【问题标题】:Swift - Dispatch Queues and the U/I running seriallySwift - 调度队列和 U/I 串行运行
【发布时间】:2019-06-06 08:31:54
【问题描述】:

我有一个辅助 LaunchScreenViewController 用于具有一些动画同时收集三种背景数据的应用程序。

一切正常,但 DispatchQueues.async 的运行顺序是随机的。但是,如果我将它们更改为 DispatchQueues.sync 一切都以正确的顺序发生,但运行速度如此之快(即使有睡眠)你看不到动画。

这需要 .sync 但我如何控制 U/I 以便我可以看到动画? (此处显示为,例如 self.subLogo1View.isHidden = true)

代码如下:

// Queuing Variables    
var semaphore    = DispatchSemaphore(value: 1)    
var semaphoreSub = DispatchSemaphore(value: 1)

override func viewDidLoad() {
    super.viewDidLoad()
    DispatchQueue.global().async {
        self.semaphore.wait()
        self.gatherData()
        self.semaphore.signal()
    }

    DispatchQueue.global().async {
        self.semaphore.wait()
        self.checkNetworkAvailability()
        self.semaphore.signal()
    }

    DispatchQueue.global().async {
        self.semaphore.wait()
        self.checkSomething()
        self.semaphore.signal()
    }   
}


func gatherData() {
    DispatchQueue.main.async {
        self.semaphoreSub.wait()
        print ("1")
        self.subLogo1View.isHidden = true
        self.subLogo1View.setNeedsDisplay()
        self.semaphoreSub.signal()
    }
}

func checkNetworkAvailability() {
    DispatchQueue.main.async {
        self.semaphoreSub.wait()
        print ("2")
        self.subLogo2View.isHidden = true
        self.subLogo2View.setNeedsDisplay()    
        self.semaphoreSub.signal()
    }
}

func checkSomething() {
    DispatchQueue.main.async {
        self.semaphoreSub.wait()
        print ("3")
        self.subLogo3View.isHidden = true
        self.subLogo3View.setNeedsDisplay()
        self.semaphoreSub.signal()
    }
}

【问题讨论】:

  • 动画的代码在哪里?你最好尝试使用完成/回调来做事。
  • Psuedo - 在第三段中提到 - “这需要 .sync 但我如何控制 U/I 以便我可以看到动画?(此处显示为,例如 self.subLogo1View。 isHidden = true)" 检查回调 - 谢谢。
  • 闭包做到了。

标签: swift semaphore dispatch-queue


【解决方案1】:

与其用一堆信号量手动序列化你的闭包,不如使用一个自定义的serial队列。动画,用户UIView.animate

类似这样的:

func gatherData() {
    DispatchQueue.main.async {  // or sync, depending on your animation needs
        print ("1: gather Data")
        UIView.animate(withDuration: 0.5) { 
            self.subLogo1View.alpha = 0  // instead of isHidden
        }
    }
}

func viewDidLoad() {
    var mySerialQueue = DispatchQueue (label:"my.serial")
    mySerialQueue.async {
        self.gatherData()
    }
    mySerialQueue.async {
        self.checkNetworkAvailability()
    }
    // ...
}

【讨论】:

  • 非常感谢 - 当我做适当的动画时,我会听从你的建议 - 再次,非常感谢。
猜你喜欢
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多