【问题标题】:Put variable values in an asynchronous function in Swift将变量值放入 Swift 中的异步函数中
【发布时间】: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 函数
  • arr nil 在哪里? (或者你的意思是它是 0,因为它不是可选的)。您是否尝试在网络操作完成之前访问arr

标签: ios swift xcode swift4


【解决方案1】:

您必须在块外和块执行之前使用/打印arr 值。 尝试在完成块内移动打印语句

ImageDownload(url: urll!) { (value) in
  // value = Image Height
  DispatchQueue.main.async {
    arr = value
    print("\(arr)")
  }
}

我的意思是仅在分配arr 之后执行您的操作 您也可以使用arr 中的didSet

var arr = 0 {
  didSet {
    // Add your code here you want to execute after value assignment to `arr` 
    print("\(arr)")
  }
}

【讨论】:

  • 我没有完全解决,但我找到了一些方向。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 1970-01-01
相关资源
最近更新 更多