【问题标题】:How to create UIImageView with image from a link?如何使用链接中的图像创建 UIImageView?
【发布时间】:2011-04-03 12:27:58
【问题描述】:

如何使用来自http://img.abc.com/noPhoto4530.gif 这样的链接的图像创建 UIImageView?

【问题讨论】:

    标签: ios iphone macos uiimageview uiimage


    【解决方案1】:
    NSURL *url = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    

    【讨论】:

    • 完美运行!无法想象“dataWithContentsOfURL”在其静态方法中。顺便说一句,我正在使用 Xamarin。
    • 我可以超时 imageview 吗?当互联网连接速度很慢时,应用程序可能会崩溃,所以我想添加超时@nszombie
    • 你应该注意这不是一个很好的解决方案,因为它阻塞了等待下载的主线程。数据的异步加载方法要好得多。
    【解决方案2】:

    对于那些希望使用 iOS 7 新的 NSURLSession 类套件的人来说,这是一个代码 sn-p:

    // Set NSURLSessionConfig to be a default session
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    // Create session using config
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    
    // Create URL
    NSURL *url = [NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"];
    
    // Create URL request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    
    // Create data task
    NSURLSessionDataTask *getDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    
        // Okay, now we have the image data (on a background thread)
        UIImage *image = [UIImage imageWithData:data];
    
        // We want to update our UI so we switch to the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
    
            // Create image view using fetched image (or update an existing one)
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    
            // Do whatever other UI updates are needed here on the main thread...
        });
    }];
    
    // Execute request
    [getDataTask resume];
    

    【讨论】:

    • 无论如何,公认的答案都是非常古老和糟糕的做法。这是正确的答案(当然有适当的错误处理;))。
    【解决方案3】:

    如果你想在后台下载图片,然后设置在主线程上,可以这样:

    - (void)downloadPicture {
    
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
                    NSURL *url = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"];
    
                    UIImage *image = [self getPicture:url];
    
                    dispatch_async(dispatch_get_main_queue(), ^{
    
                        [self setPicture:image];
    
                    });
                });
    }
    
     - (UIImage *)getPicture:(NSURL *)pictureURL {
    
            NSData *data = [NSData dataWithContentsOfURL:pictureURL];
            UIImage *image = [UIImage imageWithData:data];
    
            return image;    
    }
    
     - (void)setPicture:(UIImage *)image {
    
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:
                                   CGRectMake(kPictureX, kPictureY, image.size.height, image.size.width)];
    
            [imageView setImage:image];
    
            [self.view addSubview: imageView];
    
    }
    

    【讨论】:

      【解决方案4】:

      下载图片后,您还需要将其作为视图中的子视图放置,如下所示:

      NSURL *url = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"];
      NSData *data = [NSData dataWithContentsOfURL:url];
      UIImage *image = [UIImage imageWithData:data];
      
      UIImageView * myImageView = [[UIImageView alloc] initWithImage:image];
      [someOtherView addSubview:myImageView];
      [myImageView release];
      

      【讨论】:

        【解决方案5】:

        将图像下载到设备上的本地路径,然后从imageWithContentsOfFile 获取 UIImage,并使用它在UIImageView 中设置图像。记得有时清理你的图像文件。

        【讨论】:

          【解决方案6】:

          您可以按照here 的描述进行操作,或者您可以使用 NSURLConnection 下载图像数据并创建 UIImage 以设置给您的 UIImageView。我个人更喜欢使用 NSURLConnection 来异步下载图片。

          【讨论】:

            【解决方案7】:

            这里可以有同样的答案

            NSURL *urlLink = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"];
            NSData *dataURL = [NSData dataWithContentsOfURL:urlLink];
            UIImage *imageData = [UIImage imageWithData:dataURL];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:imageData];
            

            【讨论】:

              【解决方案8】:

              你可以试试现代 gcd 风格(xcode 8.0+):

              let queue = DispatchQueue(label: "com.mydomain.queue3")
              queue.async {
                  let imageURL: URL = URL(string: "https://www.brightedge.com/blog/wp-content/uploads/2014/08/Google-Secure-Search_SEL.jpg")!
                  guard let imageData = try? Data(contentsOf: imageURL) else {
                      return
                  }
                  DispatchQueue.main.async {
                      self.imageView.image = UIImage(data: imageData)
                  }
              }
              

              您也可以将第一个 DispatchQueue 替换为 URLSession.dataTask

              let imageURL: URL = URL(string: "https://www.brightedge.com/blog/wp-content/uploads/2014/08/Google-Secure-Search_SEL.jpg")!
              
              (URLSession(configuration: URLSessionConfiguration.default)).dataTask(with: imageURL, completionHandler: { (imageData, response, error) in
              
                  if let data = imageData {
                      print("Did download image data")
              
                      DispatchQueue.main.async {
                          self.imageView.image = UIImage(data: data)
                      }
                  }
              }).resume()
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-10-01
                • 2015-03-20
                • 2011-09-29
                相关资源
                最近更新 更多