我正在尝试创建一个在运行时在imageView中加载图像的函数。 你能帮忙让它发挥作用吗?
这里有完整的代码:( Swift 3)
import Foundation
import UIKit
extension UIImageView {
public func imageFromUrl(_ urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
let session = URLSession.shared
session.dataTask(with: request, completionHandler: {data, response, error -> Void in
if let imageData = data as Data? {
self.image = UIImage(data: imageData)
}
})
}
}
}
答案 0 :(得分:0)
您可能错过了恢复(resume()
)数据任务。
extension UIImageView {
public func imageFromUrl(_ urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
let session = URLSession.shared
session.dataTask(with: request, completionHandler: {data, response, error -> Void in
if let imageData = data as Data? {
self.image = UIImage(data: imageData)
}
}).resume()
}
}
}