【问题标题】:Extra argument 'error' in call with NSURLConnection使用 NSURLConnection 调用时的额外参数“错误”
【发布时间】:2016-05-25 22:41:33
【问题描述】:

我收到错误“额外参数”错误“调用中”我的代码是:

var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

【问题讨论】:

  • 在现代 Swift 中,带有 NSError 参数的 Objective-C 方法被替换为抛出错误但不接受 NSError 参数的 Swift 方法。例如。 do { var urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) } catch { print(error) }.
  • 如果你在 Stack Overflow 上搜索“extra argument error”,你会看到很多关于这个主题的其他问题。例如。 stackoverflow.com/q/33470527/1271826 用于不同的 API 调用,但由于不使用 Swift error handling 导致完全相同的错误。

标签: json swift2 ios9


【解决方案1】:

Swift 不再使用作为参数传入的错误变量。改用 do/catch 块:

var urlData: NSData?
let request = NSURLRequest() // Presumably declared already
var response: NSURLResponse? // Presumably declared already

do {
    urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
}
catch let error as NSError {
    print("Error: \(error.localizedDescription)")
}

另请注意,sendSynchronousRequest 已被弃用,您应该将其更改为 dataTaskWithRequest(request: NSURLRequest) -> NSURLSessionDataTask

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多