Can I load a UIImage from a URL?
You can do it this way (synchronously, but compact):
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]]];
A much better approach is to use Apple's LazyTableImages to preserve interactivity.
How to load UIImage from url?
You can try that for SwiftUI:
import SwiftUI
struct RemoteImage: View {
private enum LoadState {
case loading, success, failure
}
private class Loader: ObservableObject {
var data = Data()
var state = LoadState.loading
init(url: String) {
guard let parsedURL = URL(string: url) else {
fatalError("Invalid URL: \(url)")
}
URLSession.shared.dataTask(with: parsedURL) { data, response, error in
if let data = data, data.count > 0 {
self.data = data
self.state = .success
} else {
self.state = .failure
}
DispatchQueue.main.async {
self.objectWillChange.send()
}
}.resume()
}
}
@StateObject private var loader: Loader
var loading: Image
var failure: Image
var body: some View {
selectImage()
.resizable()
}
init(url: String, loading: Image = Image(systemName: "photo"), failure: Image = Image(systemName: "multiply.circle")) {
_loader = StateObject(wrappedValue: Loader(url: url))
self.loading = loading
self.failure = failure
}
private func selectImage() -> Image {
switch loader.state {
case .loading:
return loading
case .failure:
return failure
default:
if let image = UIImage(data: loader.data) {
return Image(uiImage: image)
} else {
return failure
}
}
}
}
Then use it in your view:
struct ContentView: View {
let jsonURL = "https://cf.geekdo-images.com/thumb/img/sD_qvrzIbvfobJj0ZDAaq-TnQPs=/fit-in/200x150/pic2649952.jpg"
var body: some View {
RemoteImage(url: jsonURL)
.aspectRatio(contentMode: .fit)
.frame(width: 200)
}
}
iPhone: How to get a UIImage from a url?
NSURL *url = [NSURL URLWithString:@"http://example.com/image.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[[UIImage alloc] initWithData:data] autorelease];
However, this isn't asynchronous.
Loading/Downloading image from URL on Swift
Xcode 8 or later • Swift 3 or later
Synchronously:
if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) {
imageView.contentMode = .scaleAspectFit
imageView.image = image
}
Asynchronously:
Create a method with a completion handler to get the image data from your url
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
Create a method to download the image (start the task)
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)
}
}
}
Usage:
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:
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)
}
}
Usage:
imageView.downloaded(from: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")
UIImageView, Load UIImage from remote URL
You are using wrong method to create URL. Try URLWithString
instead of fileURLWithPath
. fileURLWithPath
is used to get image from local file path not from internet url.
or
do {
let url = URL(string: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")
let data = try Data(contentsOf: url)
self.imageView.image = UIImage(data: data)
}
catch{
print(error)
}
Load UIImage from URL in iOS
Use AFnetworking
where you can set placeholder image also if the url is not correct. This is more efficient when you are loading images in a tableview or a collection view.
Import UIImageView+AFNetworking.h
#import "UIImageView+AFNetworking.h"
and us the following code:
NSString *url1=@"http://www.fnordware.com/superpng/pnggrad16rgb.png";
[self.image setImageWithURL:[NSURL URLWithString:url1] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
You can download it from gitHub
How to display Image from a url in SwiftUI
iOS 15 update:
you can use asyncImage in this way:AsyncImage(url: URL(string: "https://your_image_url_address"))
more info on Apple developers document:
AsyncImage
Using ObservableObject (Before iOS 15)
first you need to fetch image from url :
class ImageLoader: ObservableObject {
var didChange = PassthroughSubject<Data, Never>()
var data = Data() {
didSet {
didChange.send(data)
}
}
init(urlString:String) {
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
DispatchQueue.main.async {
self.data = data
}
}
task.resume()
}
}
you can put this as a part of your Webservice class function too.
then in your ContentView struct you can set @State image in this way :
struct ImageView: View {
@ObservedObject var imageLoader:ImageLoader
@State var image:UIImage = UIImage()
init(withURL url:String) {
imageLoader = ImageLoader(urlString:url)
}
var body: some View {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width:100, height:100)
.onReceive(imageLoader.didChange) { data in
self.image = UIImage(data: data) ?? UIImage()
}
}
}
Also, this tutorial is a good reference if you need more
Swift4: UIImage from URL
Did you try copying and pasting that URL into a browser and see if the image really does exist?
Also your use of "!" everywhere is asking for a crash. Only use "!" when you are absolutely sure that what you are unwrapping is not going to be nil.
guard let stores = stores else { return cell }
guard indexPath.row < stores.count else { return cell }
if let url = URL( string:stores[indexPath.row].photos.first.path)
{
DispatchQueue.global().async {
if let data = try? Data( contentsOf:url)
{
DispatchQueue.main.async {
cell.imageCell.image = UIImage( data:data)
}
}
}
}
return cell
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;
Related Topics
How to Make Xcode Put Starting Brace on New Line in Swift
Dismiss View from View Model [Modal Page]
Set a Variable to the < ("Less Than") Operator as a Function in Swift
Usage of Withmemoryrebound with Apples Swift 3 Beta 6
Name Convention for Unwrapped Value in Swift
Change Width of a Uibarbuttonitem in a Uinavigationbar in Swift
Swift Codable with Different Array Types
Swift Alamofire Add Custom Header to All Requests
How to Add Openssl to a Swift Project
Changing the Color of the Icons in a Uitextfield Inside a Uisearchbar
Swift. Is the (Absolutely) Sole Specific Advantage of Unowned Over Weak, Performance
Which Value Types in Swift Supports Copy-On-Write
Connecting Hc-05 with iPhone Se iOS(V11.0)
Swift 4.2, String Firstindex() Function Error in Xcode Playground
Swift Optionals - Why Does Var A:Int? A? = 4 Return Nil