iOS: load an image from url
Just use the size property of UIImage, for example:
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
CGSize size = img.size;
In swift regarding using optionals:
var url:NSURL? = NSURL(string: imageString)
var data:NSData? = NSData(contentsOfURL : url!)
var image = UIImage(data : data!)
IN 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()
}
}
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