gpt4 book ai didi

swift - 从 Async F# 在主线程上执行代码

转载 作者:可可西里 更新时间:2023-11-01 01:58:39 24 4
gpt4 key购买 nike

我正在 F# 中实现以下 Swift 方法:

func downloadCachedImage(url : URL) {

if let cachedImage = imageCache.object(forKey: url.absoluteString as AnyObject) {
self.image = cachedImage as! UIImage
}

URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in


if (error != nil) {
print(error)
return
}

DispatchQueue.main.async {
if let downloadedim = UIImage(data: data!) {
imageCache.setObject(downloadedim, forKey: url.absoluteString as AnyObject)
self.image = downloadedim
}
}
}).resume()

}

我是这样实现的:

    member this.downloadCachedImage(url : NSUrl) = 
if imageCache.ObjectForKey(NSObject.FromObject(url.AbsoluteString)) <> null then
this.Image <- imageCache.ObjectForKey(NSObject.FromObject(url.AbsoluteString)) :?> UIImage
else
let session : NSUrlSession = NSUrlSession.SharedSession
let request : NSUrlRequest = NSUrlRequest.FromUrl(url)


let downloadTask : NSUrlSessionDataTask = session.CreateDataTask(request, fun data response error ->
if error <> null then
printfn "Error occurred"
else
let image = UIImage.LoadFromData(data)
imageCache.SetObjectforKey(image,new NSString(url.AbsoluteString))

this.Image <- image
)
downloadTask.Resume()

我唯一的问题是我需要代码:

this.Image <- image

在更新 UI 时在主线程上运行。在 Swift 中,这是通过 block 实现的:

DispatchQueue.main.async {...}

但是,我不知道如何在 F# 中执行此操作。

最佳答案

你可以试试这样回到主线程:

InvokeOnMainThread(fun _ -> ... ) 

但我认为当你从completionHandler获取数据时,它已经在主线程上了。

关于swift - 从 Async F# 在主线程上执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48520528/

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