3

Hi im new to swift and I to want run a function in the background, my problem is that once the function is running the hole app freezes I can't use the interface until the function end.

StartStream is a button that will call the function self.StreamCam for streaming the camera and then it will move the current view to CAMView to see the camera interface.

here's what I used to call the the function :

@IBAction func StartStream(sender: UIButton) {

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
   let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

   let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("CAMView") as! CAM

   let seconds = 2.0
   let delay = seconds * Double(NSEC_PER_SEC)
   let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

   dispatch_after(dispatchTime, dispatch_get_main_queue(), {
        self.StreamCam(self.session)
   })

   dispatch_async(dispatch_get_main_queue(), {
       self.presentViewController(nextViewController, animated:true, completion:nil)});
   });

}

Any suggestions?

Ky -
  • 30,724
  • 51
  • 192
  • 308
Michel Kansou
  • 2,851
  • 4
  • 13
  • 22
  • Go through this link May it Helps http://stackoverflow.com/questions/24056205/how-to-use-background-thread-in-swift – Sanju Dec 24 '15 at 13:23
  • Your solution work but it work only on the simulator when i use the app on my iPhone the streaming video freezes if i use safari of the iPhone the stream work fine why it freezes only on my iPhone app ? – Michel Kansou Dec 24 '15 at 13:50

1 Answers1

4

You're breaking the golden rule of messing with UI objects outside the main thread. Never, ever do that. Perform work in the background and update your UI on the main queue. UI / view controllers / storyboard stuff is not thread safe.

In your case, you're trying to load a view / view controller assembly from a storyboard on a background queue. This is your problem.

Joshua Nozzi
  • 60,946
  • 14
  • 140
  • 135