xcode Swift 3:无法使用类型错误的参数列表调用 dataTask

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40008365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:27:15  来源:igfitidea点击:

Swift 3: Cannot invoke dataTask with an argument list of type error

iosswiftxcodeswift3xcode8

提问by Marat

I'm beginner in iOS. I have searched web and couldn't find answer that would solve my problem. Stuck and have no idea what to do and how to search for solution.

我是iOS初学者。我在网上搜索过,但找不到可以解决我的问题的答案。卡住了,不知道该怎么做以及如何寻找解决方案。

I'm following the tutorial which is based on Swift 2. The following method is showing error.

我正在关注基于 Swift 2 的教程。以下方法显示错误。

func downloadBooks(bookTitle: String) {
    let stringURL = "GET https://www.googleapis.com/books/v1/volumes?q=\(bookTitle)"

    guard let URL = URL(string: stringURL) else {
        print("url problems")
        return
    }

    let urlRequest = NSMutableURLRequest(url: URL)
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest) { (data: Data?, response: URLResponse?, error: Error?) in

    }

    task.resume()
}

I have made all adjustments suggested by Xcode, but no further hints.

我已经做了 Xcode 建议的所有调整,但没有进一步的提示。

Moreover, original portion of code from tutorial was like this:

此外,教程中的原始代码部分是这样的:

guard let URL = NSURL(string: stringURL) else {
    print("url problems")
    return
}

Then Xcode suggested to add as URLlike below:

然后Xcode建议添加as URL如下:

let urlRequest = NSMutableURLRequest(url: URL as URL)

Both of these versions are showing no error. So what is the difference? Which one should I use?

这两个版本都没有显示错误。那么区别是什么呢?我应该使用哪一种?

I would really appreciate any help!

我真的很感激任何帮助!

回答by vadian

In Swift 3 the compiler wants native URLRequest

在 Swift 3 中,编译器想要原生的 URLRequest

let urlRequest = URLRequest(url: url) // use a lowercase variable name, URL is a native struct in Swift 3

But with your particular syntax you don't even need the request

但是使用您的特定语法,您甚至不需要请求

let task = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in ...

nor the annotations

也没有注释

let task = session.dataTask(with: url) { (data, response, error) in ...