GCD 图片下载代码

-(void)downloadImageWithURL:(NSString *)URL_str
{        
    //判断传入URL是否为NSString类型
    if (![URL_str isKindOfClass:[NSString class]]) {
        return;
    }
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    NSLog(@"url_str is %@",URL_str);
    //去掉空格,并给str进行UTF8编码
    URL_str = [[URL_str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //NSString to NSURL
    NSURL *url = [NSURL URLWithString:URL_str];
    NSLog(@"NSURL is %@",url);
    dispatch_queue_t downloadQueue = dispatch_queue_create("paper image downloader", NULL);
    dispatch_async(downloadQueue, ^{
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        NSLog(@"image data is %d",[imageData length]);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (imageData) {
                [button setImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
            }

        });
        
    });
    //一定要release!
    dispatch_release(downloadQueue);
    [self.view addSubview:button];
    
}

你可能感兴趣的:(ios,gcd)