簡體   English   中英

在Playground下載圖片后如何更新UIImageView

[英]How to update UIImageView after downloading image in Playground

我在一個游樂場玩耍,試圖更好地了解異步圖像的下載和設置。

我正在使用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

游樂場的狀態

鑒於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

從而:

即時取景

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM