get the value form mySQL to swift by PHP - php

i have the php file that return json_encode value and when i go to the http address they give me the value but
i cant get the value form the server side to my apps i have try many time but its not get it
func loadData() {
let url = NSURL(string: "http://example.com/getExpo.php")
let request = NSMutableURLRequest(URL: url!)
// modify the request as necessary, if necessary
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if error != nil {
// Display an alert message
print(error)
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
if (json != nil) {
//let userId = parseJSON["userId"] as? String
// Display an alert message
let userMessage = json!["id"] as? String
print(userMessage)
} else {
// Display an alert message
let userMessage = "Could not fetch Value"
print(userMessage)
}
} catch {
print(error)
}
}).resume()
}
any one can help , thank you !!

Your JSON response is an array of dictionaries:
[{"id":"115","expoName":"aziz","expoDetails":"aziz","expoPhone":"aziz","expoLocation":"aziz"}]
But you're trying to cast it as a Dictionary:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
The solution of course is to cast it as an array:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
Better use Swift types if you can:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String:AnyObject]]
Then for example you can use a loop:
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String:AnyObject]] {
for item in json {
let userMessage = item["id"] as? String
}
}

Related

failed when doing JSON Serialization in iOS, but the API is OK when it is accessed via browser

I am trying to retrieve data from my own API, if i try to connect to my API using chrome browser, it gives JSON data back like this
{"id":"52","username":"aasad23","fullname":"aasad
laksana","email":"aasad#gmail.com","avatar":"/Applications/XAMPP/xamppfiles/htdocs/Twitter/Avatar/52/avatar.jpg"}
but, when I tried to access the API through my iOS app, it gives an error while doing JSON serialization, it give an error:
the data couldn’t be read because it isn’t in the correct format
what does it mean the correct format?
I have checked that the code error in this line
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
Thats why the catch error is activated and give that error message.
here is the full code of this task
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error == nil {
do {
// json containes $returnArray from php
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// declare new parseJSON to store json
guard let parsedJSON = json else {
print("Error while parsing")
return
}
print(parsedJSON)
// get id from $returnArray["id"] in PHP - parseJSON["id"]
let id = parsedJSON["id"]
// successfully uploaded
if id != nil {
// save user information yang berasal dari server
UserDefaults.standard.set(parsedJSON, forKey: "parsedJSON")
} else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = parsedJSON["message"] as! String
self.showAlert(alertTitle: "opppps", alertMessage: message, actionTitle: "OK")
})
}
// JSON serialization error
} catch {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error.localizedDescription
self.showAlert(alertTitle: "Sorry", alertMessage: message, actionTitle: "OK")
})
}
// error when connecting to server
} else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error!.localizedDescription
self.showAlert(alertTitle: "oppps", alertMessage: message, actionTitle: "OK")
})
}
})
}.resume()
}
try
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
rather than
try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

Parse JSON Data to UIPickerView in Swift

I have a UIPickerview which represents countries and i am trying to get its data from MYSQL database but i couldnt handle the coming data from PHP file. I couldnt find any Swift solution so thats why i am here.
//its the default values of pickerview
var pickOption = ["one", "two", "three", "seven", "fifteen"]
func getCountries() {
let url:NSURL = NSURL(string: "http:/domain.com/getCountriesLong.php")!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
let task = session.downloadTaskWithRequest(request) {
(
let location, let response, let error) in
guard let _:NSURL = location, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
let urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)
guard let _:NSString = urlContents else {
print("error")
return
}
//all result is here
//print(urlContents)
//string to NSData conversion
let data = urlContents.dataUsingEncoding(NSUTF8StringEncoding)
do {
//parse NSData to JSON
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
//pickOption = json["countryName"]
//pickOption = json
} catch {
print("error serializing JSON: \(error)")
}
}
task.resume()
}
Here is the PHP
$menuData = $db->get_results("SELECT countryName FROM countries ORDER BY countryName ASC");
echo json_encode($menuData);
How can i use coming data as value of my UIPickerView ?
I found the solution. instead of using pickOption = json["countryName"] i have declared new array. Here it is;
var arr = [String]()
for name in json as! [AnyObject] {
if let country = name["countryName"] as? String {
arr.append(country)
}
}
self.pickOption = arr

JSON option to allow fragments not set

I can see this question has been asked before but can't find that anyone has accepted an answer anywhere. My error is:
NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.
let myUrl = NSURL(string: "http://www.example.com/xxx.php")
let request = NSMutableURLRequest(URL:myUrl!);
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST";
let postString = "email=\(useremail)&pass=\(userpassword)&username=\(username)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = session.dataTaskWithRequest(request) { (data, response, error) in
// if error
if error != nil {
print("error=\(error)")
return
}
var json: NSDictionary? = nil
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
} catch {
print("error=\(error)")
}
if let parseJSON = json {
let resultvalue = parseJSON["status"] as? String
print("result: \(resultvalue)")
var isuserregistered:Bool = false;
if(resultvalue=="Success") { isuserregistered = true; }
var messagetodisplay:String = parseJSON["message"] as! String!;
if(!isuserregistered)
{
messagetodisplay = parseJSON["message"] as! String!;
}}
I am trying to send email, pass, username, and successfully presenting my alert and changing view controller. but I am yet to hit database. It's PHP and MYSQL via url.
try changing this line
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
to this
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? NSDictionary

Parsing JSON without Object name

Here's the usual JSON I see:
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
But I am trying to parse this format of JSON, without the object ("employees" from the example above):
[{"id":"1","company":"1","facility":"2","starttime":"1454936400","complete_time":"1454979600","scheduled_hours":"12"},{"id":"3","company":"1","facility":"2","starttime":"1455021660","complete_time":"1455061660","scheduled_hours":"12"}]
Here's the code that I'm trying to use:
let requestURL: NSURL = NSURL(string: url)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let stations = json[1] as? [[String: AnyObject]] {
print(json)
for station in stations {
if let name = station["company"] as? String {
print(name)
}
}
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
But I am not able to output any of the values from JSON data. How do I do it? I am very new in Swift and XCode.
Or if I can format my data to look like the first JSON, would it be alright? The data is being returned as an array from an SQL query.
UPDATE: When I print(json[1]) it only prints the second set. I think I'm getting closer.
NSJSONSerialization.JSONObjectWithData can be tricky because it can return either an Array aka [AnyObject] or a Dictionary aka [String: AnyObject].
Then you have to test what the result is :
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let json = jsonData as? [[String: AnyObject]] {
// json starts with an array
for value in json {
// loop through array
}
} else if let json = jsonData as? [String: AnyObject] {
// json starts with a key
for (key, value) in json {
// loop through dictionary key/values
}
} else {
// This json is broken
}
1-check that statusCode condition is true(200 or "200"?)
2-print data before try catch
if (statusCode == 200) {
print(data)
do{
......
}
3- print json object
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print(json)
and
4-check json[1] same as [[String: AnyObject]]

How to Parse a JSON with Swift on IOS, sent from a PHP service script?

I'm having trouble parsing a JSON, sent from a PHP script, on IOS using swift. I just started learning IOS development this week and also had never worked with JSON before so any help would be greatly appreciated on parsing this correctly. I'm sending a result from a mysql query as a JSON to the app. Here is my swift code and the error log in which you can see the object received by the http service.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let secondViewController:VC2 = segue.destinationViewController as! VC2
let myUrl = NSURL(string: "myscriptaddress");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "condition=" + String(currentval);
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
secondViewController.mystring = "getting ready"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Success")
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error can't parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
And now the error log:
Error could not parse JSON: Optional([{"unidad":"sanfrancisco","capacidad":"15","uso":"5","telefono":"num"},{"unidad":"pediatricouniversitario","capacidad":"15","uso":"5","telefono":"num"},{"unidad":"sanjorge","capacidad":"15","uso":"7","telefono":"num"},{"unidad":"himacaguas","capacidad":"20","uso":"4","telefono":"num"},{"unidad":"himabayamon","capacidad":"20","uso":"8","telefono":"num"},{"unidad":"sanlucas","capacidad":"10","uso":"8","telefono":"num"},{"unidad":"auxiliomutuo","capacidad":"15","uso":"11","telefono":"num"}])
Its failing to unwrap the JSON data as a dictionary type. The JSON string provided is an array of objects.
Try this in your JSONObjectWithData call:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String : AnyObject]]

Categories