在Swift上从URL加载/下载图像 [英] Loading/Downloading image from URL on Swift
本文介绍了在Swift上从URL加载/下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从我的应用程序中的URL加载一个图像,所以我首先尝试使用Objective-C,然而它可以使用Swift,我有一个编译错误:
I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error:
'imageWithData'不可用:使用对象构造'UIImage(数据:)'
'imageWithData' is unavailable: use object construction '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中:
In 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,我该如何解决问题。
Can someone please explain me why the imageWithData:
doesn't work with Swift, and how can I solve the problem.
推荐答案
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
}
异步:
创建一个使用完成处理程序从您的网址获取图像数据的方法
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")
DispatchQueue.main.async() {
self.imageView.image = UIImage(data: data)
}
}
}
用法:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("Begin of code")
if let url = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
imageView.contentMode = .scaleAspectFit
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: UIViewContentMode = .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() {
self.image = image
}
}.resume()
}
func downloaded(from link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloaded(from: url, contentMode: mode)
}
}
用法:
imageView.downloaded(from: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
这篇关于在Swift上从URL加载/下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文