2010-08-25 16 views

Respuesta

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

Gracias por su ayuda :) –

+0

¡Funciona perfecto! No puedo imaginar que "dataWithContentsOfURL" esté en su método estático. Estoy usando Xamarin por cierto. – Howard

+0

¿Puedo agotar el tiempo de visualización de la imagen? cuando la conexión a Internet es lenta, la aplicación se puede bloquear, así que quiero agregar el tiempo de espera @nszombie –

1

Descargue la imagen a una ruta local en su dispositivo y luego obtenga un UIImage del imageWithContentsOfFile y utilícelo para configurar la imagen en el UIImageView. Recuerde limpiar su archivo de imagen en algún momento.

0

Puede hacer lo que se describe here, o puede usar NSURLConnection para descargar los datos de imagen y crear el UIImage para configurarlo en UIImageView. Personalmente prefiero usar NSURLConnection para descargar la imagen de forma asincrónica.

1

Después de descargar la imagen que necesita también para colocarlo como una subvista desde un punto de vista, así:

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 desea descargar la imagen en el fondo, y luego otra vez en el hilo principal, puede hacerlo de esta manera:

- (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

He aquí un fragmento de código para aquellos que deseen utilizar iOS nueva suite de 7 clases de NSURLSession:

// 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 respuesta aceptada es bastante vieja y mala práctica de todos modos. Esta es la respuesta correcta (con el manejo de errores adecuado, por supuesto;)). –

0

La misma respuesta puede tener aquí

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

puede probar el estilo moderno mcd (Xcode 8.0 o superior):

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) 
    } 
} 

También puede reemplazar la primera DispatchQueue con 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() 
Cuestiones relacionadas