Fox5150 Fox5150 - 3 months ago 21
Swift Question

Swift - Record Video With AVCaptureSession - Full memory device alert?

My Swift app uses video capture and it works well. The problem is that if the phone has low memory, the video data of the last session can't be saved.
Is it a way to receive a memory warning a few megs before the phone memory is full ? ... to give time to the app to stop recording and save the data.
Thanks !

Answer

I found an extension that gives the device free memory. It is not exactly what I was looking for, but it helps :

extension UIDevice {
    func getFreeDiskspace() -> UInt {
        guard let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last else {
            return 0
        }
        do {
            let dictionary = try NSFileManager.defaultManager().attributesOfFileSystemForPath(path)
            if let _ = dictionary[NSFileSystemSize] as? UInt,
                let freeFileSystemSizeInBytes =     dictionary[NSFileSystemFreeSize] as? UInt {
                return freeFileSystemSizeInBytes/1024/1024
            } else {
                return 0
            }
        } catch {
            return 0
        }
    }
}

For example, I noticed that my iPhone was unable to save a data file with startRecordingToOutputFileURL when the free memory goes under 230 Mb. I stop recording when the free memory is close to this limit :

if ( UIDevice.currentDevice().getFreeDiskspace() < 250 ) {

  // Do whatever you want to do here if the free disk space is under 250Mb
                
}