URL(字符串:)不能调用非函数类型'String'的值

Tom*_*y K 2 url nsurl swift swift3

我有以下代码,但我收到一个错误.

if let userImageURL = user.image {
    let url = URL(string: userImageURL)
}
Run Code Online (Sandbox Code Playgroud)

我该如何创建网址?URL(string:)应该拿一个String不是吗?那是什么userImageURL.

编辑:这是我正在尝试实现的代码示例.即使在这个例子中,我也得到了同样的错误catPictureURL

let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")!

// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)

// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
    // The download has finished.
    if let e = error {
        print("Error downloading cat picture: \(e)")
    } else {
        // No errors found.
        // It would be weird if we didn't have a response, so check for that too.
        if let res = response as? HTTPURLResponse {
            print("Downloaded cat picture with response code \(res.statusCode)")
            if let imageData = data {
                // Finally convert that Data into an image and do what you wish with it.
                let image = UIImage(data: imageData)
                // Do something with your image.
            } else {
                print("Couldn't get image: Image is nil")
            }
        } else {
            print("Couldn't get response code for some reason")
        }
    }
}

downloadPicTask.resume()
Run Code Online (Sandbox Code Playgroud)

Gop*_*vra 10

你需要像这样制作URL的对象

let url = Foundation.URL(string:"your_url_string")
Run Code Online (Sandbox Code Playgroud)


pka*_*amb 6

就我而言,这是一个命名空间问题。

命名的变量URL与标准URL类型混淆。

Foundation.URL在您的代码中使用或重命名URL变量。

struct NamespaceTest {

    let exampleURL = "http://example.com/"

    var URL: URL {

        // ERROR: Cannot call value of non-function type 'URL'
        return URL(string: exampleURL)!

        // OK
        return Foundation.URL(string: exampleURL)!
    }

}
Run Code Online (Sandbox Code Playgroud)


小智 2

遇到同样的问题,仍然无法解决。感觉像是 Xcode 8 的 bug,因为根据苹果的网站,它应该可以工作(参考:苹果的 URL 参考

无论如何,我为此使用了一个解决方法:

let imageUrl = NSURL(string: "www.apple.com") as! URL
Run Code Online (Sandbox Code Playgroud)