0

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?

rmaddy
  • 298,130
  • 40
  • 468
  • 517
  • You didn't read the answers. You need to use `path`, not `absoluteString` to convert a file `URL` to a path string. – rmaddy Apr 04 '17 at 05:15
  • besides the issue of using absoluteString instead of the path property you should also create a new name for each picture otherwise you will always save it over and over because with the atomic property it doesn't care if the file already exists or not. it will save it anyway – Leo Dabus Apr 04 '17 at 05:16
  • Ah, you're right rmaddy. Looks like I went too far with a git revert. Thanks. – user7811985 Apr 04 '17 at 05:20
  • I rolled back your last edit because it completely negates the problem in your original question. – rmaddy Apr 04 '17 at 05:29

0 Answers0