我将项目从Obj-c转换为Swift 3,我无法从Web方法中读取JSON响应。据我所知,代码看起来像是它的Obj-c对应物的良好转换,但是JSONSerilaization遇到了麻烦。
我会发布旧的Obj-c,但它分布在几个NSURLConnection委托方法中。如果需要我可以发布这个吗?
斯威夫特3:
// Set up the URL request
var getString : String = "https://TheWebMethod"
guard let url = URL(string: getString) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on Method")
print(error)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let result = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
print("The result is: " + result.description)
guard let resultTitle = result["title"] as? String else {
print("Could not get title from JSON")
return
}
print("The title is: " + resultTitle)
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
通过浏览器运行时的JSON输出示例:
[{"id":"3","Initials":"TL","FullName":"Tony Law","LoginName":"test","Password":"password","EmailAddress":"myemailaddress","MobileTelNo":"0123456789","SecToken":"Secret"}]