iOS:从 url 加载图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10972555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS: load an image from url
提问by cyclingIsBetter
I need to load an image from a url and set it inside an UIImageView; the problem is that I don't know the exact size of the image, then how can I show the image correctly?
我需要从 url 加载图像并将其设置在 UIImageView 中;问题是我不知道图像的确切大小,那么如何正确显示图像?
回答by fbernardo
Just use the size property of UIImage, for example:
只需使用 UIImage 的 size 属性,例如:
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
CGSize size = img.size;
回答by yegor256
In swift:
迅速:
var url = NSURL.URLWithString("http://www.example.com/picture.png")
var data = NSData(contentsOfURL : url)
var image = UIImage(data : data)
image.size // if you need it
回答by theDC
In swift regarding using optionals:
快速关于使用选项:
var url:NSURL? = NSURL(string: imageString)
var data:NSData? = NSData(contentsOfURL : url!)
var image = UIImage(data : data!)
回答by Ashok R
IN SWIFT 3.0
在 Swift 3.0
The main thread must be always remain free so it serves the user interface and user interactions.
主线程必须始终保持空闲状态,以便为用户界面和用户交互提供服务。
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
private func fetchImage() {
let imageURL = URL(string: "https://i.stack.imgur.com/9z6nS.png")
var image: UIImage?
if let url = imageURL {
//All network operations has to run on different thread(not on main thread).
DispatchQueue.global(qos: .userInitiated).async {
let imageData = NSData(contentsOf: url)
//All UI operations has to run on main thread.
DispatchQueue.main.async {
if imageData != nil {
image = UIImage(data: imageData as! Data)
self.imageView.image = image
self.imageView.sizeToFit()
} else {
image = nil
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
fetchImage()
}
}
回答by Krishna Thakur
To download Asynchronous image with Kingfisher library you can follow this step,url :https://github.com/onevcat/Kingfisher:
要使用 Kingfisher 库下载异步图像,您可以按照此步骤操作,网址:https: //github.com/onevcat/Kingfisher:
func imageFromUrl(_ urlString: String) {
if let url = URL(string: urlString) {
ImageDownloader.default.downloadImage(with: url, options: [], progressBlock: nil) {
(image, error, url, data) in
DispatchQueue.main.async {
self.imageView.image = image
}
}
}
}
You can also download image with default URLSession.shared.dataTask
您还可以使用默认 URLSession.shared.dataTask 下载图像
func imageFromUrl(_ urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) {(data,response,error) in
if let imageData = data as Data? {
if let img = UIImage(data: imageData){
DispatchQueue.main.async {
self.imageView.image = img
}
}
}
}
}
}
回答by Bary Levy
SWIFT 5.0 + fetch on background
SWIFT 5.0 + 后台获取
private func fetchImage(_ photoURL: URL?) {
guard let imageURL = photoURL else { return }
DispatchQueue.global(qos: .userInitiated).async {
do{
let imageData: Data = try Data(contentsOf: imageURL)
DispatchQueue.main.async {
let image = UIImage(data: imageData)
self.userImageView.image = image
self.userImageView.sizeToFit()
self.tableView.reloadData()
}
}catch{
print("Unable to load data: \(error)")
}
}
}
回答by John Pitts
One common mistake in displaying an image downloaded from json or a url is the problem of queues. ALL UI-related things need to be done in the main queue, so if you forgot this, even perfect code (above answers are good) won't display your image on occasion. To call the mainQueue, use code like this, and note that calling main queue might need to be done seperately in the called imageDisplay function:
显示从 json 或 url 下载的图像的一个常见错误是队列问题。所有与 UI 相关的事情都需要在主队列中完成,因此如果您忘记了这一点,即使是完美的代码(以上答案都很好)有时也不会显示您的图像。要调用mainQueue,使用这样的代码,并注意调用main queue可能需要在被调用的imageDisplay函数中单独完成:
dispatch_async(dispatch_get_main_queue(), ^{
self.nameLabel.text = self.pokemon.name;
[self displayImage]; //CALLS FUNCTION
self.abilitiesTextView.text = @"loves SwiftUI";
});
- (void)displayImage {
NSString *imageURLString = [NSString stringWithFormat: self.pokemon.sprite];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURLString]];
dispatch_async(dispatch_get_main_queue(), ^{
self.spriteImageView.image = [UIImage imageWithData: imageData];
});
// NOTE: important for newer versions of XCode/Obj-C...
//[imageData release]; With ARC ("automated release..."), release method is forbidden, it's already done for you.
}