【发布时间】:2018-10-29 02:22:15
【问题描述】:
我实现了图片下载功能。
但是,我发现 UI 卡住了,而且我的功能是异步的。
"(value) in" 安全地传递值,但如果代码试图将值放入全局变量中,它将不会被执行。
代码:
var arr = 0
ImageDownload(url: urll!) // asynchronous function
{ (value) in // value = Image Height
DispatchQueue.main.async
{
arr = value
}
}
// I want use this line
print("\(arr)") // always print 0
图片下载功能:
func ImageDownload(url urll: URL, completion: @escaping (Int) -> Void)
{
let queue = DispatchQueue.global()
queue.async
{
if let imageSource = CGImageSourceCreateWithURL(urll as CFURL, nil)
{
if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?
{
let pixelHeight = imageProperties[kCGImagePropertyPixelHeight] as! Int
if pixelHeight >= 2000
{
completion(pixelHeight/6)
}
else
{
completion(pixelHeight/5)
}
}
}
}
}
请帮帮我
【问题讨论】:
-
arr 应该是强的,不是弱的,不是可选的。
-
上述代码中的每一件事都是正确的,只要确保 ImageDownload 返回的值不为零,
-
你能添加你的ImageDownload func吗
-
我添加了 ImageDownload 函数
-
arrnil在哪里? (或者你的意思是它是 0,因为它不是可选的)。您是否尝试在网络操作完成之前访问arr?