ios - How to handle JSON returned from HTTP GET request - Swift? -
this code :
let myurl = nsurl(string:"hostname/file.php"); let request = nsmutableurlrequest(url:myurl!); request.httpmethod = "get"; nsurlsession.sharedsession().datataskwithrequest(request, completionhandler: { (data:nsdata?, response:nsurlresponse?, error:nserror?) -> void in dispatch_async(dispatch_get_main_queue()) { if(error != nil) { //display alert message return } { let json = try nsjsonserialization.jsonobjectwithdata(data!, options: .mutablecontainers) as? nsdictionary if let parsejson = json { /* when app reach here , enter catch , out */ let userid = parsejson["id"] as? string print(userid) if(userid != nil) { nsuserdefaults.standarduserdefaults().setobject(parsejson["id"], forkey: "id") nsuserdefaults.standarduserdefaults().setobject(parsejson["name"], forkey: "name") nsuserdefaults.standarduserdefaults().synchronize() } else { // display alert message print("error") } } } catch { print(error) } } }).resume()
my app getting json php file parse array database json , return using echo
, return following 2 rows :
[{"id":"1","name":"cit","adminstrator_id":"1"},{"id":"2","name":"helpdesk","adminstrator_id":"1"}]
when print description of json
nil
i tried cast json
nsarray
, when print first json[0]
first row when tried cast result of json[0]
nsdictionary still i'll nil
when app reach if statement if let parsejson = json
enter catch , it's not printing error , don't know why ?
this php code :
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "mydb"; // create connection $conn = new mysqli($servername, $username, $password, $dbname); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } $sql = "select * department"; $result = $conn->query($sql); $rows = array(); if ($result->num_rows > 0) { // output data of each row while($r = $result->fetch_assoc()) { $rows[] = $r; } $conn->close(); echo json_encode($rows); } else { $conn->close(); echo "0 results"; } ?>
so problem in request or handling request ?
the json array of [string:string]
dictionaries.
in json string []
represents array , {}
represents dictionary.
an urlrequest not needed because get
default mode. .mutablecontainers
not needed either because values read.
consider json returns multiple records. code prints values id
, name
.
let myurl = nsurl(string:"hostname/file.php")! nsurlsession.sharedsession().datataskwithurl(myurl) { (data, response, error) in if error != nil { print(error!) } else { { if let json = try nsjsonserialization.jsonobjectwithdata(data!, options: []) as? [[string:string]] { entry in json { if let userid = entry["id"], name = entry["name"] { print(userid, name) } } } else { print("json not array of dictionaries") } } catch let error nserror { print(error) } } }.resume()
Comments
Post a Comment