Naga Krishnamraju Naga Krishnamraju - 4 months ago 34
iOS Question

Converting Android post request to iOS swift using NSURLSession

I'm trying to convert my Android post request to iOS (Swift). Currently, this is the Android code:

JSONObject json = new JSONObject();
json.put("major", Major);
json.put("minor", Minor);
json.put("uuid", UUID);
json.put("userid", id);

int TIMEOUT_MILLISEC = 10000; // = 10 seconds

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

HttpPost request = new HttpPost("http://" + ipAddress + ":8080/");
request.setHeader("Content-Type", "application/json");


request.setEntity(new ByteArrayEntity(
json.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);


This works perfectly fine.
However, when I try to convert it to Swift, the server doesn't receive anything even though I know that it's executing the request.

Swift:

var request = NSMutableURLRequest(URL: NSURL(string: URLString)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var params = ["major": "1", "minor": "2", "uuid": "00000000-1111-2222-3333-444444444444", "userid": "3"] as Dictionary<String, String>


request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.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 {
let success = json["success"] as? Int
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
}
} catch let parseError {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
}
}


Any help or direction would be nice. Thanks.

Answer

task.resume() after block will do the job

Comments