我正在尝试将我的Android发布请求转换为iOS(Swift)。当前,这是Android代码:
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);
这工作得很好。但是,当我尝试将其转换为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)
}
}
任何帮助或指示都将是不错的。谢谢。
编辑1:task.resume()从服务器获得了我的响应。但是,如果有人知道如何转换“ request.setEntity(new ByteArrayEntity(json.toString()。getBytes(“ UTF8”)));“” 在Swift中,这真的很有帮助。
您忘记添加了task.resume
吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句