为什么在使用带有swift的while循环时iPhone似乎会冻结?

And*_*ris 1 freeze timelapse while-loop swift

我试图通过使用while循环每2秒拍一张照片.但是当我尝试这个时,屏幕会冻结.
这是拍摄照片的功能:

func didPressTakePhoto(){

    if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
        videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
        stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
            (sampleBuffer, error) in

            if sampleBuffer != nil {


                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                let dataProvider  = CGDataProviderCreateWithCFData(imageData)
                let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, .RenderingIntentDefault)

                let image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)

                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

                //Adds every image taken to an array each time the while loop loops which will then be used to create a timelapse.
                self.images.append(image)


            }


        })
    }


}
Run Code Online (Sandbox Code Playgroud)

为了拍照,我有一个按钮,当一个名为count的变量等于0时,将在while循环中使用该函数,但是当按下结束按钮时,该变量等于1,因此while循环结束.
这就是startPictureButton动作的样子:

@IBAction func TakeScreanshotClick(sender: AnyObject) {

    TipsView.hidden = true
    XBtnTips.hidden = true

    self.takePictureBtn.hidden = true

    self.stopBtn.hidden = false

    controls.hidden = true
    ExitBtn.hidden = true

    PressedLbl.text = "Started"
    print("started")

    while count == 0{

        didPressTakePhoto()

        print(images)
        pressed = pressed + 1
        PressedLbl.text = "\(pressed)"
        print(pressed)

        sleep(2)

    }


}
Run Code Online (Sandbox Code Playgroud)

但是当我运行它并开始游戏中时光倒流时,屏幕看起来很冷.
有谁知道如何阻止冻结发生 - 而且还要将每个图像添加到阵列 - 以便我可以将其转换为视频?

Fre*_*ame 5

问题是处理按钮(TakeScreanshotClick方法)上的点击的方法是在UI线程上运行的.因此,如果此方法永远不会退出,则UI线程会卡在其中,并且UI会冻结.

为了避免它,你可以在后台线程上运行你的循环(阅读NSOperationNSOperationQueue).有时,您可能需要从后台线程向UI线程发送一些内容(例如,UI更新的命令).

更新:Apple有一个非常好的文档(迄今为止我见过的最好).看看这个:Apple并发编程指南.