我想从我的应用程序中的 URL 加载图像,所以我首先尝试使用 Objective-C 并且它工作,但是,使用 Swift,我有一个编译错误:
‘imageWithData’ 不可用:使用对象构造 ‘UIImage(data:)’
我的功能:
@IBOutlet var imageView : UIImageView override func viewDidLoad() { super.viewDidLoad() var url:NSURL = NSURL.URLWithString("http://myURL/ios8.png") var data:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil) imageView.image = UIImage.imageWithData(data)// Error here }
在 Objective-C 中:
- (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:(@"http://myURL/ios8.png")]; NSData *data = [NSData dataWithContentsOfURL:url]; _imageView.image = [UIImage imageWithData: data]; _labelURL.text = @"http://www.quentinroussat.fr/assets/img/iOS%20icon's%20Style/ios8.png"; }
有人可以解释一下为什么imageWithData:它不适用于 Swift,我该如何解决这个问题。
imageWithData:
Xcode 8 或更高版本 - Swift 3 或更高版本
同步:
if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) { imageView.contentMode = .scaleAspectFit imageView.image = image }
异步:
使用完成处理程序创建一个方法以从您的 url 获取图像数据
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) { URLSession.shared.dataTask(with: url, completionHandler: completion).resume() }
创建下载图像的方法(启动任务)
func downloadImage(from url: URL) { print("Download Started") getData(from: url) { data, response, error in guard let data = data, error == nil else { return } print(response?.suggestedFilename ?? url.lastPathComponent) print("Download Finished") // always update the UI from the main thread DispatchQueue.main.async() { [weak self] in self?.imageView.image = UIImage(data: data) } } }
用法:
override func viewDidLoad() { super.viewDidLoad() print("Begin of code") let url = URL(string: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")! downloadImage(from: url) print("End of code. The image will continue downloading in the background and it will be loaded when it ends.") }
扩展名 :
extension UIImageView { func downloaded(from url: URL, contentMode mode: ContentMode = .scaleAspectFit) { contentMode = mode URLSession.shared.dataTask(with: url) { data, response, error in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let image = UIImage(data: data) else { return } DispatchQueue.main.async() { [weak self] in self?.image = image } }.resume() } func downloaded(from link: String, contentMode mode: ContentMode = .scaleAspectFit) { guard let url = URL(string: link) else { return } downloaded(from: url, contentMode: mode) } }
imageView.downloaded(from: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")