【问题标题】:URL(string:) Cannot call value of non-function type 'String'URL(string:) 不能调用非函数类型'String'的值
【发布时间】:2017-07-02 07:31:51
【问题描述】:

我有以下代码,但出现错误。

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()

【问题讨论】:

  • 该代码应该编译(假设user.image 的类型为String?)。请出示minimal reproducible example 来说明问题。
  • 我已经更新了我的帖子
  • 再次声明:该代码确实可以编译。

标签: swift url swift3 nsurl


【解决方案1】:

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

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

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

【讨论】:

  • 对我来说很顺利,我不知道它还没有解决什么问题,我使用了下面两行代码的确切行,它就像地狱一样工作,但是这个给我这个愚蠢的错误日志!
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2021-07-06
      • 2020-07-05
      • 2021-09-06
      • 2015-05-27
      相关资源
      最近更新 更多