gpt4 book ai didi

ios - 如何在 Playground 下载图像后更新 UIImageView

转载 作者:行者123 更新时间:2023-11-29 12:04:44 24 4
gpt4 key购买 nike

我在 Playground 玩耍,试图更好地理解异步图像下载和设置。

我正在使用 NSURLSession DataTask,并且我的图像数据很好——我可以使用 Playground 的 Quick Look 来确认这一点。

我也是用XCPlayground框架把页面设置为无限期执行,currentPage的liveView就是目标imageView。

然而,仍然缺少一些东西,而且实时 View 没有正确更新。有任何想法吗?我想要做的是归结为以下代码。您可以在屏幕截图中看到 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

The state of the Playground

最佳答案

鉴于 NSURLSession 不会在主队列上运行其完成处理程序,您应该自己将 View 的更新分派(dispatch)到主队列:

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

关于ios - 如何在 Playground 下载图像后更新 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35448165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com