Sarah Malik Sarah Malik - 1 month ago 14
iOS Question

Swift: Data not fetching correctly from PHP

I am creating an app, where I am fetching the data from a php. To download the data from the php, I have a func that downloads the data, submits to the model, and then retrieves it whenever needed. Now the issue is, when my data is fetched from the data base, it is not snyc appropriately and getting the same info every where. For example, Name shows the mob phone; street address also shows the same.

here is my code

func download(){

let request = NSMutableURLRequest(url: URL(string: "http://www.some-site.com")!)
request.httpMethod = "POST"

let postString = "id=\(businessID)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: (request as URLRequest), completionHandler: { data, response, error in

let responseString = String(data: data!, encoding: String.Encoding.utf8)
let r = self.convertStringToDictionary(responseString!)

for element in r! {

print("element = \(element)")

let stname = String(describing: element.first!)
let sn = stname.replacingOccurrences(of: "\"STREET_NAME\", ", with: "")


let name = String(describing: element.first!)
let n = name.replacingOccurrences(of: "\"FILE_LOCATION\", ", with: "")

let reverse = element.reversed()
let fileloc = String(describing: reverse.first!)
let f = fileloc.replacingOccurrences(of: "\"BUSINESS_NAME\", ", with: "")

self.model = ProfilePage(fileloc: f, streetname: sn, name: n)

print("Address = \(stname)")
print("Name = \(name)")
print("File Location = \(f)")

DispatchQueue.main.async {
self.setUI()
}
}

if error != nil {
print("error=\(error)")
}

})
task.resume()
}
}



but yes in my output console, i can see all the infor appropriate, its just when i run this, it shows all the info as one


Screenshots
enter image description here

enter image description here

Answer

Let me Know is this work for you,

let r = self.convertStringToDictionary(responseString!) // Make sure Your string is successfully converted as NSDictionary else use below
// let r = self.convertStringToDictionary(responseString!) as NSDictionary // if r is dictionary, then convert to NSDictionary
let stname = r["STREET_NAME"] as! String
let name = r["FILE_LOCATION"] as! String
let f = r["BUSINESS_NAME"] as! String
print("Address",stname)
print("Name",name)
print("File Location",f)

DispatchQueue.main.async {
  self.setUI()
}

If you confuse, then refer below example

let mydict = ["Hip-Hop Tamizha": 21,"Hip-Hop Tamizha":"Takkaru Takkaru","Michael Jackson":"Beat It","Taylor Swift":"Back to December","Katy Perry":"Fire Works","Selina Gomez":"Love You Like A Love Song Baby","Avril Lavigne":"Slipped Away","Eminem":"The Music Box","Akhil":"Khaab","Hip-Hop Tamizha": 21,"Akhil": 61] as NSDictionary

let hop = mydict["Hip-Hop Tamizha"] as AnyObject
let swift = mydict["Taylor Swift"] as! String
print("The Number:",hop)
print("Taylor Swift song:",swift)

output

enter image description here

UPDATE 1:

a. Delete extension of convertStringToDictionary and add this below function inside your class.

// It work for all cases. also use for all project
func contvertToDictionary(_ data:Data) ->Any // because return object may be NSDictionary or NSArray
{

let responseString = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary //as? is optional if or else

if responseString != nil
{
    return responseString!
}

else
{
    let responseString2 = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray // as! is a particulor not if or else

    return responseString2
}

}

b.Analyse this and add to your code

  override func viewDidLoad() {
    super.viewDidLoad()
   self.updateDetails()

}

func updateDetails()
{

let url = NSURL(string: "http://getmydetails.pe.hu/test/sarahdata.php") // data is on my server. I dont know how long it is live there.
let request = NSMutableURLRequest(url: url as! URL)
request.httpMethod = "POST"

let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
    guard error == nil && data != nil else
    {

        print("Error:\(error)")
        return
    }

    let httpStatus = response as? HTTPURLResponse

    if httpStatus!.statusCode == 200
    {
        if data?.count != 0
        {

            let converted = self.contvertToDictionary(data!) as! NSArray //Because we know return object is Array

            let NSarraytoDict = converted[0] as! NSDictionary //Array has only one index (i.e., index(0)) and that is a dictionary.
            print(NSarraytoDict)

            let about = NSarraytoDict["BUSINESS_NAME"] as! String // not string without space
            let fb = NSarraytoDict["FACEBOOK_URL "] as! String // The response key has one space. note this
            let phone = NSarraytoDict["STREET_NO"] as! String
            let name = NSarraytoDict["NAME "] as! String

            print("\n\(about)\n\(fb)\n\(phone)\n\(name)")

        }
        else
        {
            print("No data got from url!")

        }
    }
    else
    {

        print("error:",httpStatus)
    }
}
task.resume()   
}

c.Full code for optional

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
       self.updateDetails()
    }

    func updateDetails()
    {

        let url = NSURL(string: "http://getmydetails.pe.hu/test/sarahdata.php") // data is on my server. I dont know how long it is live there.
        let request = NSMutableURLRequest(url: url as! URL)
        request.httpMethod = "POST"

        let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
            guard error == nil && data != nil else
            {

                print("Error:\(error)")
                return
            }

            let httpStatus = response as? HTTPURLResponse

            if httpStatus!.statusCode == 200
            {
                if data?.count != 0
                {

                    let converted = self.contvertToDictionary(data!) as! NSArray //Because we know return object is Array

                    let NSarraytoDict = converted[0] as! NSDictionary //Array has only one index (i.e., index(0)) and that is a dictionary.
                    print(NSarraytoDict)

                    let about = NSarraytoDict["BUSINESS_NAME"] as! String // not string without space
                    let fb = NSarraytoDict["FACEBOOK_URL "] as! String // The response key has one space. note this
                    let phone = NSarraytoDict["STREET_NO"] as! String
                    let name = NSarraytoDict["NAME "] as! String

                    print("\n\(about)\n\(fb)\n\(phone)\n\(name)")

                }
                else
                {
                    print("No data got from url!")

                }
            }
            else
            {

                print("error:",httpStatus)
            }
        }
        task.resume()

    }

    // It work for all cases. also use for all project
    func contvertToDictionary(_ data:Data) ->Any // because return object may be NSDictionary or NSArray
    {

        let responseString = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary //as? is optional if or else

        if responseString != nil
        {
            return responseString!
        }

        else
        {
            let responseString2 = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray

            return responseString2
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
   }

}

Output 2: enter image description here