我尝试将数据从我的应用程序发送到其他程序员开发的Android应用程序所使用的其他API。我使用NSJSONSerialization.dataWithJSONObject将JSON转换为NSData对象,然后将其附加到NSURLRequest,但NSData对象是JSON字符串的十六进制表示形式。根据其他开发人员的说法,他的Android代码正在以UTF-8编码创建和传输JSON对象,所以我的问题是我如何将JSON字符串作为UTF-8文本发送,或者将API作为API的最佳方式是什么?尽可能无缝地处理这两个来源?
编辑:我现在使用的代码
func postToServer() {
let endPoint: String = "http://server.com"
guard let url = NSURL(string: endPoint) else {
print("ERROR: cannot create URL")
return
}
let urlRequest = NSMutableURLRequest(URL: url)
urlRequest.HTTPMethod = "POST"
urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let loc = self.getLocation()
var content:[String: AnyObject] = ["action": "put-point", "request": ["rangeKey": self.id, "lng": loc.coordinate.longitude, "lat": loc.coordinate.latitude, "count": self.count]]
var data: NSData! = NSData()
do {
data = try NSJSONSerialization.dataWithJSONObject(content, options: NSJSONWritingOptions())
print(data)
} catch {
print ("Error")
}
urlRequest.HTTPBody = data
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler:{ data, response, error in
guard error == nil else {
print("ERROR: Cannot call Get on endpoint")
print(error)
return
}
guard let responseData = data else {
print("ERROR: Did not receive any data")
return
}
print("DATA: \(data)")
})
task.resume()
}
答案 0 :(得分:0)
您可以执行类似
的操作let jsonObj = [...]
var data = NSData()
do {
data = try NSJSONSerialization.dataWithJSONObject(jsonObj, options: .PrettyPrinted)
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
} catch {
print("error: \(error)")
}
*试过Swift 2& Xcode 7.3.1