Writing permission for generated pdf : swift on 11.3 only

I am getting error while generating pdf on iOS 11.3. It's working fine with iOS 11.2.

CGDataConsumerCreateWithFilename: failed to open `/note.pdf' for writing: Operation not permitted.
deflateEnd: error -3: (null).

Pdf is generated well but when I try to access it to upload, it generates error. Code for the same is :

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

let fileURL:URL = documentsURL.appendingPathComponent("note.pdf")

do {
   try FileManager.default.createDirectory(atPath: fileURL.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
   NSLog("Unable to create directory \(error.debugDescription)")
}

UIGraphicsBeginPDFContextToFile((fileURL.path as NSString).lastPathComponent as String?, CGRectZero, nil);

The last line generates error.

Any help would be highly appreciated.

1 answer

  • answered 2018-04-17 08:01 a.masri

    You are saving the file in root directory , You can not do this, try this

     let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    
                let fileURL:URL = documentsURL.appendingPathComponent("note.pdf")
    
                do {
                    try FileManager.default.createDirectory(atPath: fileURL.path, withIntermediateDirectories: true, attributes: nil)
                } catch let error as NSError {
                    NSLog("Unable to create directory \(error.debugDescription)")
                }
    
                UIGraphicsBeginPDFContextToFile(fileURL.appendingPathComponent("note.pdf").path, CGRect.zero, nil);
    

    Which will get and according to what you are doing you will create a folder note.pdf and then save the file note.pdf inside it