iOS 从url异步获取图片

来源:互联网 发布:macbook 软件 编辑:程序博客网 时间:2024/05/22 05:21

如果要从url同步获取图片,可以用如下方式:

    NSString *fileURL = @“http://xxxxx.xxxx”;    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];    image1.image = [UIImage imageWithData:data];

但是由于这种方式是同步的,如果网速不够快,它会卡住界面。所以需要使用异步方式。

我是这样做的:

    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:fileURL]];    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        UIImage *img1 = [UIImage imageWithData:data];        if (img1 == nil) {            NSLog(@"img1 == nil");        } else {            image1.image = img1;        }            }];

该异步方式实际上是用NSURLConnection 发异步请求,不是专门取图片的,只不过这里的url指向了图片。

如果有谁知道更好的方式,请不吝赐教。

0 0