2017-03-01 105 views
0

我有我的應用程序頁面視圖控制器,而這個頁面視圖控制器有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

回答

0

事實上,你有多個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

它找字典?或不? –

相關問題