我正在尝试编写一种方法来扫描条形码,然后使用http rest调用从服务器获取一些JSON数据。 Alamofire现在不工作,我尝试了很多不同的方式。
这是我现在所拥有的:
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()
我收到一条错误消息:
致命错误:在展开Optional值时意外发现nil
(lldb)在线:let httpResponse = response as! NSHTTPURLResponse
答案 0 :(得分:0)
问题是如果NSHTTPURLResponse
为response
,强制转换为nil
将会失败(例如,如果出现某些错误导致请求无法成功发出,例如在这种情况下,URL字符串缺少http://
方案前缀;但是这可能发生在任何各种问题上,因此必须优雅地预测和处理网络错误)。当处理来自网络请求的响应时,除非您首先确认该值是有效且非nil
,否则应该刻意避免强制解包/转换。
我建议:
guard
语句安全地检查nil
值; data
不是nil
且error
是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()