美文网首页
从url异步获取图片

从url异步获取图片

作者: 白雪天枫 | 来源:发表于2018-08-22 20:00 被阅读15次

如果要从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;

        }

    }];

处理比较好

相关文章

网友评论

      本文标题:从url异步获取图片

      本文链接:https://www.haomeiwen.com/subject/yztuiftx.html