· 9 years ago · Dec 22, 2016, 07:58 AM
1request.addValue("0C896F8C-D3CE-BD08-FF1D-2B087CE77B00", forHTTPHeaderField: "application-id")
2request.addValue("9D9A2BCD-F272-16E8-FF01-CD5AFD8CC300", forHTTPHeaderField: "secret-key")
3
4let request = NSMutableURLRequest(url: NSURL(string:"/v1/users/login") as! URL)
5 let session = URLSession.shared
6 request.httpMethod = "POST"
7 let params = ["name":"mm", "password":"mm"] as Dictionary<String, String>
8
9 request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
10 request.addValue("0C896F8C-D3CE-BD08-FF1D-2B087CE77B00", forHTTPHeaderField: "application-id")
11 request.addValue("9D9A2BCD-F272-16E8-FF01-CD5AFD8CC300", forHTTPHeaderField: "secret-key")
12 request.addValue("application/json", forHTTPHeaderField: "Content-Type")
13 request.addValue("REST", forHTTPHeaderField: "application-type")
14
15 request.addValue("application/json", forHTTPHeaderField: "Accept")
16
17 let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
18 print("Response: (response)")
19 let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
20 print("Body: (strData)")
21
22 let json = try! JSONSerialization.jsonObject(with: data!, options: .mutableLeaves)
23 print(json)
24 //JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
25
26 // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
27 if(error != nil) {
28 // print(err!.localizedDescription)
29 let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
30 print("Error could not parse JSON: '(jsonStr)'")
31 }
32 else {
33 // The JSONObjectWithData constructor didn't return an error. But, we should still
34 // check and make sure that json has a value using optional binding.
35 if let parseJSON = json as? NSDictionary { // Okay, the parsedJSON is here, let's get the value for 'uccess' out of it
36 let success = parseJSON["success"] as? Int
37 print("Succes: (success)")
38 }
39 else
40 {
41 // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
42 let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
43 print("Error could not parse JSON: (jsonStr)")
44 }
45 }
46 })
47
48 task.resume()