2016-12-09 6 views
0

내 응용 프로그램은 백그라운드 모드로 들어갈 때 호출되는 함수를 가지고있다. 사용자가 앱을 다시 여는 경우 스레드를 중지하고 싶습니다. 지금까지 노력하고있는 것은 아무것도 없습니다. 이 NSThread를 어떻게 중지합니까?

여기에 지금까지 내 코드입니다 :

class Neversleep { 
    private static var callback : (()->Void)? 
    private static var thread: NSThread? 

    static func start(callback:()->Void) { 
     self.callback = callback 

     Neversleep.thread = NSThread(target: self, selector: #selector(Neversleep.task), object: nil) 
     Neversleep.thread?.start() 

    } 

    static func stop() { 
     print("NEVERSLEEP:STOP") 
     Neversleep.thread?.cancel() 

    } 

    @objc static func task() { 

     while (true) 
     { 
      sleep(3); 
      print("we are still running!") 
      callback?() 
     } 
    } 
} 

I 앱 위임의 DidEnterBackground 방법에서) Neversleep.start (호출합니다.

내가 willEnterForeground에서 Neversleep.stop()를 호출하고 있습니다 ...하지만 그것은 스레드를 중지 아니에요.

나는 내가 여기에 뭔가를 분명 누락 확신 해요. 근데 뭐? 자동으로 스레드를 죽이지 않는 스레드에서 cancel를 호출

답변

1

. 스레드의 실제 본문은 스레드가 취소 될 때 수행중인 작업을 중지해야합니다. 이 같은

업데이트합니다 task 기능 :

@objc static func task() { 
    while (!NSThread.currentThread.cancelled) 
    { 
     sleep(3); 
     print("we are still running!") 
     callback?() 
    } 
} 

더블 currentThreadcancelled에 대한 실제 메서드 및 속성 이름을 확인합니다. Swift 2에서 이름이 무엇인지 확실하지 않습니다.

sleep으로 인해 스레드가 취소 된 후에도 callback으로 다시 한 번 전화 할 가능성이 높습니다. 마법처럼 일했다

@objc static func task() { 
    while (!NSThread.currentThread.cancelled) 
    { 
     sleep(3); 
     print("we are still running!") 
     if (!NSThread.currentThread.cancelled) { 
      callback?() 
     } 
    } 
} 
+0

: 당신과 함께이 문제를 해결할 수 있습니다. 정말 고맙습니다. – bflora2