I'm having trouble getting data to write to disk on iOS, using Swift 3 and Xcode 8.3 (8E162). Tested on iPhone5, iPhone6 plus and iPhone7, all running iOS10.3, to no avail.
In my view class, I declare:
var takePhoto: AVCapturePhotoOutput!
and an IBAction that calls:
takePhoto.capturePhoto(with: settings, delegate: self)
When the IBAction is triggered (button tap), the capturePhoto()
and its delegate are called. I make an attempt to write out the file, which doesn't work. Adding the image to the current view does work, so I know the captured image buffer is good.
func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
// Create file path using FileManager
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let filename = documentsURL?.appendingPathComponent("photo.jpg")
// Try write out the file
do{
let writeToFile = try dataImage.write(to: filename!, options: .atomic)
print("WRITING out file", writeToFile)
}
catch {
print("ERROR writing out file")
}
// Check if the file was created
if FileManager.default.fileExists(atPath: (filename?.absoluteString)!) {
print("YAY! Image " + (filename?.absoluteString)! + " exists")
}
else {
print("BOO! The file doesn't exist: " + (filename?.absoluteString)!)
}
// Add the image to the current view
let viewImage = UIImageView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
viewImage.image = UIImage(data: dataImage)
viewImage.contentMode = .scaleAspectFit
self.view.addSubview(viewImage)
}
The write()
doesn't throw
, and the fileExists
fails
WRITING out file ()
BOO! The file doesn't exist:
file:///var/mobile/Containers/Data/Application/1E77951B-BEA5-48AD-ADD3-5DCB289A94C0/Documents/photo.jpg
What am I missing?