如何使用Api在页面视图控制器中的所有视图控制器中下载图片?

问题描述:

我有我的应用程序页面视图控制器,而这个页面视图控制器有4个视图控制器 - 所以我必须在所有这些页面视图控制器的图像查看,我想使用JSON API下载图像,这些网页如何使用Api在页面视图控制器中的所有视图控制器中下载图片?

这是我的代码,但我在我所有的视图控制器类的复制这个代码,所以我只写他们中的一个在这里

func refreshingphoto1() { 

    let firstImageURL = URL(string: "http://img.autobytel.com/car-reviews/autobytel/11694-good-looking-sports-cars/2016-Ford-Mustang-GT-burnout-red-tire-smoke.jpg")! 

    let session = URLSession(configuration: .default) 

    // Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data. 


    let downloadPicTask = session.dataTask(with: firstImageURL) { (data, response, error) in 
     // The download has finished. 

     if error != nil { 
      print("Error downloading picture") 
      self.firstImageJson.image = UIImage(named: "1.jpg") 
     } else { 

      // No errors found. 
      // It would be weird if we didn't have a response, so check for that too. 
      if (response as? HTTPURLResponse) != nil { 

       print("Downloaded picture with response code") 

       if let imageData = data { 

        // Finally convert that Data into an image and do what you wish with it. 
        let image = UIImage(data: imageData) 
        self.firstImageJson.image = image 
        // Do something with your image. 

       } else { 


        print("Couldn't get image: Image is nil") 
        self.firstImageJson.image = UIImage(named: "1.jpg") 

       } 
      } else { 
       print("Couldn't get response code for some reason") 
       self.firstImageJson.image = UIImage(named: "1.jpg") 
      } 
     } 
    } 
    downloadPicTask.resume() 
} 
} 

**这将工作,但并不完全正确**

这里是我的故事板图片

as you see in the picture I have Page VC2 that is page view controller and four view controllers that connected to the page VC2

事实上,你有多个VC与下载图像的任务很少有关。

但是,除了缺乏抽象,您正处于正确的轨道上:使用URLSessionURLSessionTask是使用Apple API执行的正确方法。

您可能对下列内容感兴趣:要抽象的东西很多开发人员使用这个名为Alamofire第三方库,特别是你的情况AlamofireImage

例如与AlamofireImage你只需要做

let imageView = UIImageView(frame: frame) 
let url = URL(string: "https://httpbin.org/image/png")! 
let placeholderImage = UIImage(named: "placeholder")! 

imageView.af_setImage(withURL: url, placeholderImage: placeholderImage) 
+0

它找字典?或不? –