gpt4 book ai didi

ios - Swift 延迟加载属性 Alamofire 请求

转载 作者:搜寻专家 更新时间:2023-10-31 22:49:31 24 4
gpt4 key购买 nike

我正在尝试使用 Alamofire 请求延迟加载属性 (UIImage)。这就是我所在的位置:

public lazy var theImage: UIImage = MyCalass.loadImage { (imageTest) -> Void in
return imageTest
}

class public func loadImage(completion: (imageTest: UIImage) -> Void){
Alamofire.request(.GET, "http://pathtoimage/image.jpg").response { (request, response, data, error) in
var tempImage = UIImage(data: data!, scale:1)
completion(imageTest: tempImage!)
}
}

错误:“()”无法转换为“UIImage”

最佳答案

嘿伙计,用 GCD 很容易解决...

像这样构建一个类:

class AsynchImageLoader {
class func loadImageAsync (imageURL: NSURL, completionHandler: (downloadedImage: UIImage?) -> Void) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
if let imageData: NSData = NSData(contentsOfURL: imageURL) {
if let imageImage: UIImage = UIImage(data: imageData) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(downloadedImage: imageImage)
})
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(downloadedImage: nil)
})
}
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(downloadedImage: nil)
})
}
})
}
}

然后像这样加载你的图片...

let imageView: UIImageView = UIImageView()
AsynchImageLoader.loadImageAsync(NSURL(string: "yourURL")!, completionHandler: { (downloadedImage) -> Void in
imageView.image = downloadedImage
})

downloadedImage 可以是 nil,如果出现问题...否则您可以将其放入您的 View 、数组或任何您想要的...

顺便说一下...惰性修饰符并不意味着图像加载为“惰性/异步”...在 Swift 中,您可以将某些东西声明/初始化为惰性,这意味着它将在其初始化时声明类,但在您第一次尝试在代码中访问它之前不久,它会首先被初始化……这可能是任何时候,甚至永远不会:-)

或者从这里更改您的代码...

public lazy var theImage: UIImage = MyCalass.loadImage { (imageTest) -> Void in
return imageTest
}

为此...

var theImage: UIImage? 
MyCalass.loadImage { (imageTest) -> Void in
theImage = imageTest
}

关于ios - Swift 延迟加载属性 Alamofire 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906204/

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