Puis-je charger un UIImage depuis une URL?

J’ai une URL pour une image (obtenue de UIImagePickerController) mais je n’ai plus l’image en mémoire (l’URL a été enregistrée à partir d’une exécution précédente de l’application). Puis-je recharger l’UIImage à partir de l’URL?

Je vois que UIImage a un imageWithContentsOfFile: mais j’ai une URL. Puis-je utiliser le dataWithContentsOfURL de NSData: pour lire l’URL?

EDIT1


basé sur la réponse de @ Daniel j’ai essayé le code suivant mais ça ne marche pas …

NSLog(@"%s %@", __PRETTY_FUNCTION__, photoURL); if (photoURL) { NSURL* aURL = [NSURL URLWithSsortingng:photoURL]; NSData* data = [[NSData alloc] initWithContentsOfURL:aURL]; self.photoImage = [UIImage imageWithData:data]; [data release]; } 

Quand je l’ai couru la console montre:

 -[PhotoBox willMoveToWindow:] file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG *** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0' 

En regardant la stack des appels, j’appelle URLWithSsortingng, qui appelle URLWithSsortingng: relativeToURL:, puis initWithSsortingng: relativeToURL: puis _CFSsortingngIsLegalURLSsortingng, puis CFSsortingngGetLength, puis forwarding_prep_0 , puis forwarding , puis – [NSObject doesNotRecognizeSelector].

Des idées pourquoi mon NSSsortingng (l’adresse de photoURL est 0x536fbe0) ne répond pas à la longueur? Pourquoi dit-il qu’il ne répond pas à – [longueur NSURL]? Ne sait-il pas que param est un NSSsortingng, pas un NSURL?

EDIT2


OK, le seul problème avec le code est la chaîne de conversion d’URL. Si je codé en dur la chaîne, tout le rest fonctionne bien. Donc, quelque chose ne va pas avec mon NSSsortingng et si je ne peux pas le comprendre, je suppose que cela devrait être une question différente. Avec cette ligne insérée (j’ai collé le chemin depuis le journal de la console ci-dessus), cela fonctionne bien:

 photoURL = @"file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG"; 

Vous pouvez le faire de cette façon (de manière synchrone, mais compacte):

 UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithSsortingng:MyURL]]]; 

Une approche bien meilleure consiste à utiliser les images LazyTable de Apple pour préserver l’interactivité.

Vous pouvez essayer SDWebImage , il fournit:

  1. Chargement asynchrone
  2. Mise en cache pour une utilisation hors connexion
  3. Placez le support image pour apparaître pendant le chargement
  4. Fonctionne bien avec UITableView

Exemple rapide:

  [cell.imageView setImageWithURL:[NSURL URLWithSsortingng:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; 

obtenir DLImageLoader et essayer le code suivant

  [DLImageLoader loadImageFromURL:imageURL completed:^(NSError *error, NSData *imgData) { imageView.image = [UIImage imageWithData:imgData]; [imageView setContentMode:UIViewContentModeCenter]; }]; 

Un autre exemple typique d’utilisation de DLImageLoader, qui peut aider quelqu’un …

 PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow]; NSSsortingng *facebookImageURL = [NSSsortingng ssortingngWithFormat: @"http://graph.facebook.com/%@/picture?type=large", [aFacebookUser objectForKey:@"id"] ]; __weak UIImageView *loadMe = self.userSmallAvatarImage; // ~~note~~ you my, but usually DO NOT, want a weak ref [DLImageLoader loadImageFromURL:facebookImageURL completed:^(NSError *error, NSData *imgData) { if ( loadMe == nil ) return; if (error == nil) { UIImage *image = [UIImage imageWithData:imgData]; image = [image ourImageScaler]; loadMe.image = image; } else { // an error when loading the image from the net } }]; 

Comme je le mentionne ci-dessus, une autre grande bibliothèque à considérer est Haneke (malheureusement, elle n’est pas aussi légère).

Et la version rapide:

  let url = NSURL.URLWithSsortingng("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg"); var err: NSError? var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err) var bgImage = UIImage(data:imageData) 

Essayez ce code, vous pouvez définir le chargement de l’image avec lui, afin que les utilisateurs sachent que votre application charge une image depuis l’url:

 UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading.png"]]; [yourImageView setContentMode:UIViewContentModeScaleAspectFit]; //Request image data from the URL: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithSsortingng:@"http://yourdomain.com/yourimg.png"]]; dispatch_async(dispatch_get_main_queue(), ^{ if (imgData) { //Load the data into an UIImage: UIImage *image = [UIImage imageWithData:imgData]; //Check if your image loaded successfully: if (image) { yourImageView.image = image; } else { //Failed to load the data into an UIImage: yourImageView.image = [UIImage imageNamed:@"no-data-image.png"]; } } else { //Failed to get the image data: yourImageView.image = [UIImage imageNamed:@"no-data-image.png"]; } }); }); 

Découvrez le AsyncImageView fourni ici . Un bon exemple de code, et peut-être même utilisable «prêt à l’emploi» pour vous.

AFNetworking fournit un chargement d’image asynchrone dans un UIImageView avec un support d’espace réservé. Il prend également en charge les réseaux asynchrones pour travailler avec les API en général.

Si vous êtes vraiment , absolument sûr que le NSURL est une url de fichier, c.-à-d. [url isFileURL] est garanti pour retourner vrai dans votre cas, alors vous pouvez simplement utiliser:

 [UIImage imageWithContentsOfFile:url.path] 

La manière d’utiliser une extension Swift à UIImageView (code source ici ):

Création d’une propriété calculée pour UIActivityIndicatorView associé

 import Foundation import UIKit import ObjectiveC private var activityIndicatorAssociationKey: UInt8 = 0 extension UIImageView { //Associated Object as Computed Property var activityIndicator: UIActivityIndicatorView! { get { return objc_getAssociatedObject(self, &activityIndicatorAssociationKey) as? UIActivityIndicatorView } set(newValue) { objc_setAssociatedObject(self, &activityIndicatorAssociationKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN)) } } private func ensureActivityIndicatorIsAnimating() { if (self.activityIndicator == nil) { self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) self.activityIndicator.hidesWhenStopped = true let size = self.frame.size; self.activityIndicator.center = CGPoint(x: size.width/2, y: size.height/2); NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in self.addSubview(self.activityIndicator) self.activityIndicator.startAnimating() }) } } 

Initialiseur personnalisé et Setter

  convenience init(URL: NSURL, errorImage: UIImage? = nil) { self.init() self.setImageFromURL(URL) } func setImageFromURL(URL: NSURL, errorImage: UIImage? = nil) { self.ensureActivityIndicatorIsAnimating() let downloadTask = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in if (error == nil) { NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in self.activityIndicator.stopAnimating() self.image = UIImage(data: data) }) } else { self.image = errorImage } } downloadTask.resume() } } 

Assurez-vous d’activer ces parameters depuis iOS 9:

Les parameters de sécurité de transport d’ Apple dans Info.plist pour garantir le chargement de l’image à partir de l’URL afin de permettre le téléchargement de l’image et sa définition.

entrer la description de l'image ici

Et écrivez ce code:

 NSURL *url = [[NSURL alloc]initWithSsortingng:@"https://www.google.co.in/"]; NSData *data =[NSData dataWithContentsOfURL:url]; quickViewImage.image = [UIImage imageWithData:data];