【问题标题】:Xcode Swift 3 NSURLSession.sharedSessionXcode Swift 3 NSURLSession.sharedSession
【发布时间】:2017-05-07 05:13:58
【问题描述】:

我正在尝试将我用 swift 2 制作的基本天气应用程序更新为 swift 3 这是我的代码:

func getWeather(city: String) {

    let path = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=095711373620570aa92ee530246dc8af"
    let url = NSURL(string: path)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        print(">>>> \(data)")
    }

和 NSURLSession.sharedSession(5th line) 和 NSURLResponse(6th line) 打印出错误

【问题讨论】:

  • 尝试重写该行。 Xcode 在自动完成/建议成员时帮助您使用新语法。
  • 试过不行...
  • 提示:NSURLSession.sharedSession() -> URLSession.shared
  • 谢谢它的工作,但 NSURLResponse 仍然给出错误
  • 删除 NS 前缀。请改用 Data、URLResponse、Error。

标签: xcode swift3 xcode8 nsurlsession nsurl


【解决方案1】:

不要在完成处理程序签名中注释类型并使用 Swift 3 本机结构:

func getWeather(city: String) {

    let path = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=095711373620570aa92ee530246dc8af"
    let url = URL(string: path)
    let session = URLSession.shared
    let task = session.dataTask(with:url!) { (data, response, error) -> Void in
        print(">>>> \(data)")
    }

【讨论】:

    【解决方案2】:

    Swift 3 更新

    URLSession.shared.dataTask()

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-19
    • 2017-02-08
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多