2010-08-25 18 views

Répondre

42
NSURL *url = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"]; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
UIImage *image = [UIImage imageWithData:data]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
+0

Merci pour votre aide :) –

+0

Fonctionne parfaitement! Impossible d'imaginer que "dataWithContentsOfURL" est dans sa méthode statique. J'utilise Xamarin en passant. – Howard

+0

Puis-je temporiser imageview? Lorsque la connexion Internet est lente, l'application peut être écrasée, donc je veux ajouter le délai d'attente @nszombie –

1

Téléchargez l'image vers un chemin d'accès local sur votre appareil puis obtenez un numéro UIImage de imageWithContentsOfFile et utilisez-le pour définir l'image dans le UIImageView. N'oubliez pas de nettoyer votre fichier image un jour.

0

Vous pouvez soit faire comme décrit here, ou vous pouvez utiliser NSURLConnection pour télécharger les données d'image et créer le UIImage pour vous définir UIImageView. Personnellement, je préfère utiliser NSURLConnection pour télécharger l'image de manière asynchrone.

1

Après avoir téléchargé l'image vous devez également placer une sous-vue d'une vue, comme ceci:

NSURL *url = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"]; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
UIImage *image = [UIImage imageWithData:data]; 

UIImageView * myImageView = [[UIImageView alloc] initWithImage:image]; 
[someOtherView addSubview:myImageView]; 
[myImageView release]; 
2

Si vous voulez télécharger l'image en arrière-plan, puis mis sur le thread principal, vous pouvez le faire comme ceci:

- (void)downloadPicture { 

     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

       NSURL *url = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"]; 

       UIImage *image = [self getPicture:url]; 

       dispatch_async(dispatch_get_main_queue(), ^{ 

        [self setPicture:image]; 

       }); 
      }); 
} 

- (UIImage *)getPicture:(NSURL *)pictureURL { 

     NSData *data = [NSData dataWithContentsOfURL:pictureURL]; 
     UIImage *image = [UIImage imageWithData:data]; 

     return image;  
} 

- (void)setPicture:(UIImage *)image { 

     UIImageView * imageView = [[UIImageView alloc] initWithFrame: 
           CGRectMake(kPictureX, kPictureY, image.size.height, image.size.width)]; 

     [imageView setImage:image]; 

     [self.view addSubview: imageView]; 

} 
2

Voici un extrait de code pour ceux qui cherchent à utiliser iOS nouvelle suite de classes NSURLSession de 7:

// Set NSURLSessionConfig to be a default session 
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 

// Create session using config 
NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 

// Create URL 
NSURL *url = [NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]; 

// Create URL request 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
request.HTTPMethod = @"GET"; 

// Create data task 
NSURLSessionDataTask *getDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

    // Okay, now we have the image data (on a background thread) 
    UIImage *image = [UIImage imageWithData:data]; 

    // We want to update our UI so we switch to the main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 

     // Create image view using fetched image (or update an existing one) 
     UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 

     // Do whatever other UI updates are needed here on the main thread... 
    }); 
}]; 

// Execute request 
[getDataTask resume]; 
+0

La réponse acceptée est assez ancienne et mauvaise pratique de toute façon. C'est la bonne réponse (avec une gestion correcte des erreurs bien sûr;)). –

0

Même réponse peut avoir ici

NSURL *urlLink = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"]; 
NSData *dataURL = [NSData dataWithContentsOfURL:urlLink]; 
UIImage *imageData = [UIImage imageWithData:dataURL]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:imageData]; 
0

vous pouvez essayer le style de GCD moderne (Xcode 8.0+):

let queue = DispatchQueue(label: "com.mydomain.queue3") 
queue.async { 
    let imageURL: URL = URL(string: "https://www.brightedge.com/blog/wp-content/uploads/2014/08/Google-Secure-Search_SEL.jpg")! 
    guard let imageData = try? Data(contentsOf: imageURL) else { 
     return 
    } 
    DispatchQueue.main.async { 
     self.imageView.image = UIImage(data: imageData) 
    } 
} 

vous pouvez également remplacer la première DispatchQueue avec URLSession.dataTask

let imageURL: URL = URL(string: "https://www.brightedge.com/blog/wp-content/uploads/2014/08/Google-Secure-Search_SEL.jpg")! 

(URLSession(configuration: URLSessionConfiguration.default)).dataTask(with: imageURL, completionHandler: { (imageData, response, error) in 

    if let data = imageData { 
     print("Did download image data") 

     DispatchQueue.main.async { 
      self.imageView.image = UIImage(data: data) 
     } 
    } 
}).resume()