2017-12-29 7 views
1

11 초 동안 gif를 표시 한 다음 내 로그인 페이지를 표시하는 introViewController에 대한 DispatchQueue가 있습니다 ... 또한 소개를 건너 뛰고 로그인을 표시하는 버튼이 있습니다. 그것을 클릭하면 여전히 실행중인 시간과 내가 앱에서 탐색 할 때 시간이 끝나면 로그인으로 돌아갑니다.신속하게 dispatchQueue를 중지하는 방법

이 내 클래스 내가 버튼을 클릭하면 시간을 중지 할 어떻게

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) 

} 

} 

?

답변

0

는하지만 DispatchQueue보다는 Timer를 사용하여 수행중인 작업을 고려할 것입니다.

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) 
    } 
} 
+0

이것은 더 간단하고 더 잘 작동합니다! –

0

대기열을 중지하지 마십시오. 대신, 당신이 파견 한 작업이 실행되기 시작하면 컨텍스트가 변경된 경우 해당 컨텍스트를 확인하고 올바른 작업을 수행해야합니다.

+0

그래서 타이머를 사용해야합니다. –

+0

실제로 DispatchQueue 내부의 블록을 취소하기위한 API가 있습니다. 아래 내 대답을 참조하십시오 –

4

이 경우 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)  
    } 
} 
+1

감사합니다, 완벽한 작품! –