Getting Image from URL Objective C

前端 未结 5 1778
甜味超标
甜味超标 2020-12-04 08:13

I\'m trying to get an image from an URL and it doesn\'t seem to be working for me. Can someone point me in the right direction?

Here is my code:

NSUR         


        
5条回答
  •  情歌与酒
    2020-12-04 08:17

    the accepted answer asynchronous version worked very slow in my code. an approach using NSOperation worked light years faster. the code provided by Joe Masilotti --> objective - C : Loading image from URL? (and pasted below):

    -(void) someMethod {
        // set placeholder image
        UIImage* memberPhoto = [UIImage imageNamed:@"place_holder_image.png"];
    
        // retrieve image for cell in using NSOperation
        NSURL *url = [NSURL URLWithString:group.photo_link[indexPath.row]];
        [self loadImage:url];
    }
    
    - (void)loadImage:(NSURL *)imageURL
    {
        NSOperationQueue *queue = [NSOperationQueue new];
        NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                            initWithTarget:self
                                            selector:@selector(requestRemoteImage:)
                                            object:imageURL];
        [queue addOperation:operation];
    }
    
    - (void)requestRemoteImage:(NSURL *)imageURL
    {
        NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
        UIImage *image = [[UIImage alloc] initWithData:imageData];
    
        [self performSelectorOnMainThread:@selector(placeImageInUI:) withObject:image waitUntilDone:YES];
    }
    
    - (void)placeImageInUI:(UIImage *)image
    {
        [self.memberPhotoImage setImage:image];
    }
    

提交回复
热议问题