Pri*_*ess 3 get http xcode7 swift2
我是xcode编程的新手,我正在尝试在Swift 2中实现一个发出HTTP Get请求的App.升级xcode 7后显示错误:
Cannot convert value of type
'(NSData!, response: NSURLResponse!, err: NSError!) -> ()'
to expected argument type
'(NSData?, NSURLResponse?, NSError?) -> Void'
Run Code Online (Sandbox Code Playgroud)
(此代码段使用swift 1.2的旧错误处理.)任何人都可以帮助我,请问如何在Swift 2.0中实现它.
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler:loadedData)
task.resume()
}
func loadedData(data:NSData!, response:NSURLResponse!, err:NSError!){
if(err != nil)
{
print(err?.description)
}
else
{
var jsonResult: NSDictionary = NSDictionary()
let httpResponse = response as! NSHTTPURLResponse
print("\(httpResponse.statusCode)")
if (httpResponse.statusCode == 200)
{
jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
print(jsonResult)
self.performSegueWithIdentifier("SuccessSignin", sender: self)
}
else if (httpResponse.statusCode == 422){
print("422 Error Occured...")
}
}
}
Run Code Online (Sandbox Code Playgroud)
方法签名已更改(参数现在是选项).此外,你必须使用try封闭在一个do catch块.并避免使用强制尝试(使用!)但更喜欢捕获可能的错误,并使用if let安全解包选项.例:
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
print(error!.description)
} else {
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
do {
if let data = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
print(jsonResult)
self.performSegueWithIdentifier("SuccessSignin", sender: self)
}
} catch let JSONError as NSError {
print(JSONError)
}
} else if (httpResponse.statusCode == 422) {
print("422 Error Occured...")
}
} else {
print("Can't cast response to NSHTTPURLResponse")
}
}
}
task.resume()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3909 次 |
| 最近记录: |