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

时间:2017-02-14 05:56:52

标签: swift url swift3 nsurl

我有以下代码但我收到错误。

if let userImageURL = user.image {
    let url = URL(string: userImageURL)
}

我该如何创建网址? 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()

3 个答案:

答案 0 :(得分:7)

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

let url = Foundation.URL(string:"your_url_string")

答案 1 :(得分:2)

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

名为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)!
    }

}

答案 2 :(得分:0)

遇到同样的问题,仍然无法解决所有问题。 感觉像Xcode 8的错误,因为根据苹果公司的网站它应该有效(参考:Apple's URL reference

无论如何,我使用了一种解决方法:

let imageUrl = NSURL(string: "www.apple.com") as! URL