【发布时间】: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 来说明问题。 -
我已经更新了我的帖子
-
再次声明:该代码确实可以编译。