我试图通过使用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)
}
})
}
}
要拍照,我有一个按钮,当一个名为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)
}
}
但是当我跑步并开始游戏中时光倒流时,屏幕看起来很冷 有谁知道如何阻止冻结发生 - 而且还要将每个图像添加到一个数组中 - 以便我可以将其转换为视频?
答案 0 :(得分:5)
问题是处理按钮(TakeScreanshotClick
方法)上的点击的方法是在UI线程上运行的。因此,如果此方法永不退出,则UI线程会卡在其中,并且UI会冻结。
为了避免它,你可以在后台线程上运行你的循环(阅读NSOperation
和NSOperationQueue
)。有时,您可能需要从后台线程向UI线程发送一些内容(例如,UI更新的命令)。
更新:Apple拥有非常出色的文档(迄今为止我所看到的最好)。看看这个:Apple Concurrency Programming Guide。
答案 1 :(得分:3)
您正在主UI线程上调用sleep命令,从而冻结所有其他活动。
另外,我看不到你设置count = 1的位置? while循环不会永远持续吗?