如何在 Playground 下载图像后更新 UIImageView
How to update UIImageView after downloading image in Playground
我正在游乐场玩耍,试图更好地理解异步图像下载和设置。
我正在使用 NSURLSession DataTask,并且我的图像数据很好——我可以使用 Playground 的快速查看来确认这一点。
我也是用XCPlayground框架把页面设置为无限期执行,currentPage的liveView就是目标imageView。
然而,仍然缺少一些东西,实时取景没有正确更新。有任何想法吗?我想要做的是归结为以下代码。您可以在屏幕截图中看到 playground 的状态:
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
鉴于 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
因此:
我正在游乐场玩耍,试图更好地理解异步图像下载和设置。
我正在使用 NSURLSession DataTask,并且我的图像数据很好——我可以使用 Playground 的快速查看来确认这一点。
我也是用XCPlayground框架把页面设置为无限期执行,currentPage的liveView就是目标imageView。
然而,仍然缺少一些东西,实时取景没有正确更新。有任何想法吗?我想要做的是归结为以下代码。您可以在屏幕截图中看到 playground 的状态:
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
鉴于 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
因此: