Im sending a Post message to my database with swift. But how do i handle the data from that response? My variable responseString looks like this now. I want to get each parameter and work with them.
Optional([{"id":"9","name":"hallow","strasse":"street","tel_nr":"123456789","kommentar":"comment"}])
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost/getByName.php")!)
request.HTTPMethod = "POST"
let postString = "name=hallow"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
Your php is returning an array containing a dictionary, so you'd have to access it like
if let responsedict = response.first {
print(responsedict["id"])
}// prints 9
(if you know there's going to be no other elements returned first is ok...or change how your data is sent back).
You could take it one step further and parse the response in to a model e.g.
let person = Person(id: response.first?["id"], name: response.first?["name"], etc)
print("id \(person.id)")
//id 9
Related
I am trying to learn JSON parsing. I have written an API in Laravel, which returns status : 200 in response. What I did is this:
guard let url = URL(string: "http://localhost/workon-api/public/api/register") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let newUser = User.init(name: "Rob", email: "abc#gmail.com", password: "12345678")
do {
let jsonBody = try JSONEncoder().encode(newUser)
request.httpBody = jsonBody
} catch { }
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let json = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
print(json)
} catch {}
}.resume()
Now, I am getting this error: Invalid top-level type in JSON write and app's crashing. After searching, I used this:
let json = try JSONSerialization.jsonObject(with: data, options: [])
And, it works. Why the previous method is not working? And, I get a response like this if I try to return the collected userInfo.
status = "{\"name\":\"Rob\",\"email\":\"abc#gmail.com\",\"password\":\"12345678\"}";
Why are back-slashes there? Are these okay? And, what is Gzip data? I know I am asking a lot, but I need to understand this. Thanks in advance.
P.S. : Here is the User Model.
struct User: Encodable {
let name : String?
let email : String?
let password : String?
}
First of all the backslashes are virtual. The framework adds them to be able to print double quotes within a literal string.
Secondly dataTask returns serialized JSON Data so to get a dictionary or array from the data you have to call jsonObject(with.
let object = try JSONSerialization.jsonObject(with: data)
print(object)
I´m newbie in Swift and I have some problems with parsing JSON using Swift 3 code.
This is my JSON (extract):
[
{
"COD_USUARIO":"4",
"0":"4",
"USUARIO":"PIEDAD",
"1":"PIEDAD",
"CLAVE":"MU\u00d1OZ",
"2":"MU\u00d1OZ",
"ACTIVO":"1",
"3":"1",
"FECHA_ALTA":"2010-12-07 00:00:00",
"4":"2010-12-07 00:00:00",
"FECHA_BAJA":null,
"5":null,
"CIF":null,
"6":null,
"TELEFONO_CASA":"",
"7":"",
"TELEFONO_MOVIL":"",
"8":"",
"EMAIL_TRABAJO":"",
"9":"",
"EMAIL_PARTICULAR":"",
"10":"",
"COLOR":"16777215",
"11":"16777215",
"ADMINISTRADOR":"0",
"12":"0",
"COD_PERSONA":"9",
"13":"9",
"IMPRESORA_ETIQUETAS":"",
"14":"",
"IMP_JUSTIFICANTES":"",
"15":"",
"VER_SESIONES":"0",
"16":"0",
"COD_EMPRESA":"0",
"17":"0",
"FECHA_TRABAJO":null,
"18":null,
"MEMORIZAR_FECHA":"0",
"19":"0",
"AVISOS_PAGOS":"0",
"20":"0",
"AVISOS_COBROS":"0",
"21":"0",
"AVISOS_DIAS":"0",
"22":"0",
"AVISOS_CONTRATOSC":"0",
"23":"0",
"24":"0"
}
]
And this is my code (extract):
let url = URL(string : "http://192.168.0.252:6996/datos/policlinica/webservices/valida.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let paramToSend = "usu=" + user + "&pass=" + pwd
request.httpBody = paramToSend.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
guard let _:Data = data else{
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print (json) //I can see my json in console
let cod_persona = json["COD_USUARIO"]
print (cod_persona)
//error: Type 'Any' has no subscript members
} catch {
print ("error")
return
}
})
task.resume()
I have tried many examples of the internet, but I can not read a specific JSON data. For example, I would like to read the "COD_USUARIO" field and save the data in a variable, but I can not get it to work well for me.
Any advice on this theme or what am I doing wrong (sure many things)
I think your problem is that your json contains array objects, so I would call it like:
json[0]["COD_USUARIO"]
Because COD_USUARIO is in the first array of the json.
First off, I know, there are a lot of questions on this topic, but I still don't get it.
Inside my iOS app, I want to post a string to a file on my server. I found many ways to do that online and went with the following:
func postBookingNumber() {
var request = URLRequest(url: URL(string: "http://myServerURL.com/booking-number.txt")!)
request.httpMethod = "POST"
let postString = "date=\(Date())&booking-number=\(self.getBookingNumber())" //returns string with format: "01"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
Now, the file on the server is currently emtpy, until I post something to it. My plan was to either append the new booking number string to the file, OR downloading the file, appending the new booking number string to it and replacing the online version with the one I just edited inside my app.
Questions
Does the code above & my strategy make any sense?
How do I handle the "date=\(Date())&booking-number=\(self.getBookingNumber())" request on the server side?
Can I go with HTML or do I have to use JS? PHP?
I'm an absolute beginner when it comes to server stuff, so please be kind :)
Thanks in advance!
I'm using API and getting json data with SwiftyJSON. I need an add token for the API. How can I do this with SwiftyJson?
My code :
let jsonData = (NSData(contentsOfURL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)! as NSData)
var readableJSON = JSON(data: jsonData, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
Normally I'm adding token with this code when I use Swift's JSON :
let url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
Are you making a post/put with this data? Thats would make sense.
I suppose you already have made the request to get the readable data "jsonData" contains that. Since you ndicate you dont have the json data already this would probably work.
var url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
if error == nil {
var readableJSON = JSON(data: data, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
url.HTTPBody = try! name.rawData()
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
//do something with his response from getting the data
})
} else {
print(error)
}
})
This is kind of a hacky way of doing it but I think its what you are going for
I want to use donation payment with my custom website.
There is a URL I should connect to and pass 2 value with the name "sku" & "device_id".
As asnwer the web gives me a value with name of "status" and a paycode with a value like this "726287618769179".
If "status" equals "READY_TOPAY" I should go to next url+paycode and
then user can fill card number and password and etc.
I use this code to connect and communicate with the web:
let DID = UIDevice.currentDevice().identifierForVendor!.UUIDString
print("Device ID is : \(DID)")
let url = NSURL (string: "https://qqqq.com/rest-api/pay-request");
let requestObj = NSURLRequest(URL: url!);
webView.loadRequest(requestObj);
let request = NSMutableURLRequest(URL: NSURL(string: "https://qqqq.com/rest-api/pay-request")!)
request.HTTPMethod = "POST"
let postString = "mypayid&device_id=\(DID)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
if (responseString?.UTF8String.) {
print("YESsssss")
}
}
task.resume()
The problem is I get the first JSON answer like this:
responseString = Optional({"error":false,"status":"READY_TO_PAY","pay_code":"4443697552108","prd_status":1})
I don't know what to do with this!
How should I tell if "status" equals "READY_TO_PAY" go to next url+paycode?
Instead of making a String from your JSON data with NSString(data: data!, encoding: NSUTF8StringEncoding), decode the JSON data to a dictionary, and access its contents by safely subscripting:
if let json = try? NSJSONSerialization.JSONObjectWithData(data!, options: []) {
if let content = json as? [String:AnyObject],
status = content["status"] as? String,
payCode = content["pay_code"] as? String {
print(status)
print(payCode)
}
}
Now you can easily compare status with "READY_TO_PAY" and take necessary actions.