dispatch与NSURLRequest配合实现图片下载

来源:互联网 发布:java ssm框架面试重点 编辑:程序博客网 时间:2024/06/05 10:17


这里是功能实现:

typedef     void (^GCDBlock2_Obj_Obj)                (id object1,id object2);

@implementation   GCDHelper 


- (void) gcdImageWithURLString:(NSString *) URLString completion:(GCDBlock2_Obj_Obj) completion

{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

        

        NSMutableURLRequest *request = [[NSMutableURLRequestalloc] init];

        [request setURL:[NSURLURLWithString:URLString]];

        [request setHTTPMethod:@"GET"];

        NSData *returnData = [NSURLConnectionsendSynchronousRequest:request

                                                   returningResponse:nil

                                                               error:nil];

        [request release];

        

        UIImage *image  = [UIImageimageWithData:returnData];

        

        if (image)

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

                completion(image, URLString);

            });

        } else

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

                completion(defaultImage, URLString);

            });

        }

    });

}

@end


//这里是使用方法

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{

//    http://localhost:8888/Imgs/img0.png

//    http://theme.blogcn.com/wp-content/themes/coffee-desk/images/rsscoffee.PNG

    

    NSString *imgURLStr = nil;

    if ((indexPath.row %2) == 0)

    {

        imgURLStr = @"http://localhost:8888/Imgs/img0.png";

    } else

    {

        imgURLStr = @"http://localhost:8888/Imgs/img1.png";

    }

    

    GCDHelper *hp = [GCDHelpernew];

    [hp gcdImageWithURLString:imgURLStr

                   completion:^(id object1,id object2) {

                    

                       dispatch_async(dispatch_get_main_queue(), ^{

                           UITableViewCell *cell = [self.tableViewcellForRowAtIndexPath:indexPath];

                           [(UIImageView *)[cellviewWithTag:10] setImage:(UIImage *)object1];

                       });

                   }];

}


原创粉丝点击