如何从swift2.0、xcode7.3中的http请求中获取JSON数据
我试图编写一个方法,扫描条形码,然后使用HTTPREST调用从服务器获取一些JSON数据。阿拉莫菲尔现在不工作了,我尝试了很多不同的方法 这是我现在得到的:如何从swift2.0、xcode7.3中的http请求中获取JSON数据,json,swift,http,get,Json,Swift,Http,Get,我试图编写一个方法,扫描条形码,然后使用HTTPREST调用从服务器获取一些JSON数据。阿拉莫菲尔现在不工作了,我尝试了很多不同的方法 这是我现在得到的: let getEndpoint: String = "45.55.63.218:8080/food?foodidentifier=\(code)" let requestURL: NSURL = NSURL(string: getEndpoint)! let urlRequest: NSMutableURLRequest =
let getEndpoint: String = "45.55.63.218:8080/food?foodidentifier=\(code)"
let requestURL: NSURL = NSURL(string: getEndpoint)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
do{
//let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
我收到一条错误消息:
致命错误:在展开可选值时意外发现nil
(lldb)在线:
让httpResponse=响应为!NSHTTPURLResponse
问题在于,如果响应为零,则强制转换到NSHTTPURLResponse
将失败(例如,如果有某个错误阻止请求成功发出,例如在本例中,URL字符串缺少http://
scheme前缀;但这可能发生在各种问题中的任何一个,因此必须优雅地预测和处理网络错误)。在处理来自网络请求的响应时,应小心避免强制展开/强制转换,除非您首先确认该值有效且非
nil
我建议:
- 使用
guard
语句安全地检查nil
值
- 检查
数据
是否为nil
,以及错误
是否为nil
,然后再检查状态代码
因此,这可能会产生:
let task = session.dataTaskWithRequest(urlRequest) { data, response, error in
guard data != nil && error == nil else {
print(error)
return
}
guard let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200 else {
print("status code not 200; \(response)")
return
}
print("Everyone is fine, file downloaded successfully.")
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
print(json)
} catch let parseError {
print("Error with Json: \(parseError)")
}
}
task.resume()
顺便说一下,除了需要添加方案(例如http://
或https://
),假设它只是http://
,那么您可能还需要将域添加到NSAppTransportSecurity
,如中所述。