我有以下代码但我收到错误。
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()
答案 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