【问题标题】:Extra argument error (I don't understand it)额外的参数错误(我不明白)
【发布时间】:2016-11-13 17:28:37
【问题描述】:

我之前的问题:https://stackoverflow.com/questions/38228368/i-dont-understand-this-error-extra-argument-error-in-call?noredirect=1#comment63957616_38228368

我试图从

更改我的代码
        var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

到

        var urlData: NSData?

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

但我仍然收到一条错误消息,提示“调用中的额外参数 'returnResponse'”。有人可以帮我解决这个问题吗?我也在这一行得到“调用中的额外参数'错误'”

    let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary

【问题讨论】:

  • 去掉error: &error参数
  • 删除sendSynchronousRequest调用结束时的{}
  • 旁注:sendSynchronousRequest 已弃用。使用NSURLSession 和一个异步任务。
  • @vadian 如何将其更改为 NSURLSession?我对 swift 比较陌生。
  • 我写了一个答案。

标签: ios json swift xcode swift2


【解决方案1】:

尝试如下声明可能对您有所帮助

let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers) as NSDictionary

【讨论】:

    【解决方案2】:

    您的代码非常错误。您正在使用不必要的error: &error 参数,并在sendSynchronousRequest 的末尾删除{}。 顺便说一句,sendSynchronousRequest 已弃用,请使用 NSURLSession

    所以代码应该是这样的:

    let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
    

    【讨论】:

    • 我最终得到了这个错误:调用可以抛出,但它没有标记为'try'并且错误没有被处理
    • @GeorgeWisten 所以听错误并使用try。阅读有关错误处理的语言指南。
    【解决方案3】:

    我建议使用这个现代 API

    NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
      if error != nil {
        print(error!)
      } else {
        do {
          let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as! [String:AnyObject]
          print(jsonData)
          // parse jsonData here and then update the UI
        } catch let error as NSError {
          print(error.localizedDescription)
        }
      }
    }.resume()
    

    在 Swift 中不要使用 Foundation 集合类型(NSArray、NSDictionary),除非你别无选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      相关资源
      最近更新 更多