2016-02-17 44 views
1

我在Playground上玩耍,試圖更好地理解異步圖像的下載和設置。如何在Playground中下載圖像後更新UIImageView

我正在使用NSURLSession DataTask,並且我有圖像數據進來 - 我可以使用Playground的Quick Look來確認這一點。

我還使用XCPlayground框架將頁面設置爲需要無限期執行,並且currentPage的liveView是目標imageView。

但是,還是有些東西丟失了,實時視圖沒有正確更新。有任何想法嗎?我想要做的是下面的代碼。你可以看到操場上的狀態截圖:

import UIKit 
import XCPlayground 

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 

let someImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 256, height: 256)) 

let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) 
session.dataTaskWithRequest(NSURLRequest(URL: NSURL(string: "http://www.stridesapp.com/strides-icon.png")!)) 
    { 
     data, response, error in 
     if let data = data 
     { 
      print(data) 
      someImageView.image = UIImage(data: data) 
     } 
    }.resume() 

XCPlaygroundPage.currentPage.liveView = someImageView 

The state of the Playground

回答

1

鑑於NSURLSession不會對主隊列運行其完成處理程序,你應該派遣視圖的更新到主隊列自己:

import UIKit 
import XCPlayground 

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 

let someImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 256, height: 256)) 

let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) 
session.dataTaskWithRequest(NSURLRequest(URL: NSURL(string: "http://www.stridesapp.com/strides-icon.png")!)) { data, response, error in 
     if let data = data { 
      print(data) 
      dispatch_async(dispatch_get_main_queue()) { 
       someImageView.image = UIImage(data: data) 
      } 
     } 
    }.resume() 

XCPlaygroundPage.currentPage.liveView = someImageView 

因此:

live view

+0

這樣做!菜鳥的錯誤。謝謝,@Rob。 – tracicot

相關問題