如何在swift中停止dispatchQueue

Kev*_*izu 1 swift dispatch-queue

我有一个用于introViewController的DispatchQueue,它显示一个11秒的gif然后显示我的登录页面......但是还有一个跳过介绍并显示登录的按钮.当我点击它时,仍在运行的时间和当我在应用程序中导航时,在时间结束时返回登录.

这是我的班级

class GifClass: UIViewController {

@IBOutlet weak var gifImage: UIImageView!
@IBOutlet weak var skipButton: UIButton!


override func viewDidLoad() {
    super.viewDidLoad()

    gifImage.loadGif(name: "promed")

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(11)) {

        self.performSegue(withIdentifier: "introLogin", sender: self)
    }

}


@IBAction func skip(_ sender: Any) {


    performSegue(withIdentifier: "introLogin", sender: self)

}

}
Run Code Online (Sandbox Code Playgroud)

如何点击按钮停止时间?

Dan*_*all 11

为此,您可以使用DispatchWorkItem.这是参考:

https://developer.apple.com/documentation/dispatch/dispatchworkitem

这是一个如何在代码中使用它的示例:

class GifClass: UIViewController {

    @IBOutlet weak var gifImage: UIImageView!
    @IBOutlet weak var skipButton: UIButton!

    private var workItem: DispatchWorkItem? // Create a private DispatchWorkItem property

    override func viewDidLoad() {
        super.viewDidLoad()

        gifImage.loadGif(name: "promed")

        workItem = { // Set the work item with the block you want to execute
            self.performSegue(withIdentifier: "introLogin", sender: self)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(11), execute: workItem!)
    }

    @IBAction func skip(_ sender: Any) {
        workItem?.cancel() // Cancel the work item in the queue so it doesn't run
        performSegue(withIdentifier: "introLogin", sender: self)    
    } 
}
Run Code Online (Sandbox Code Playgroud)


cae*_*sss 3

我不确定这里是否有最佳实践,但我会考虑使用计时器而不是 DispatchQueue 来完成您正在做的事情。

class GifClass: UIViewController {

    @IBOutlet weak var gifImage: UIImageView!
    @IBOutlet weak var skipButton: UIButton!

    var timer = Timer()

    override func viewDidLoad() {
        super.viewDidLoad()

        gifImage.loadGif(name: "promed")

        timer = Timer.scheduledTimer(timeInterval: 11, target: self, selector: #selector(timerAction), userInfo: nil, repeats: false)
    }

    @objc func timerAction() {
        performSegue(withIdentifier: "introLogin", sender: self)
    }

    @IBAction func skip(_ sender: Any) {
        timer.invalidate()
        performSegue(withIdentifier: "introLogin", sender: self)
    }
}
Run Code Online (Sandbox Code Playgroud)