I am implementing the following Swift method in F#:
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()
}
I have implemented it in the following way:
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()
My only problem is that I need the code:
this.Image <- image
to run on the main thread as it updates the UI. In Swift, this is achieved with the block:
DispatchQueue.main.async {...}
however, I have no idea how to do this in F#.