ios – Unable to write file on physical device but the simulator works fine


I am trying to write a file to a folder (outside of the app) on iOS. I am using a UIDocumentPickerViewController to pick a folder, and creating a file under it. I’m basically following the official doc:

guard folderUrl.startAccessingSecurityScopedResource() else {
  print("Failed to obtain access to folder \(folderUrl)")
  return
}
defer { folderUrl.stopAccessingSecurityScopedResource() }

let fileUrl = folderUrl.appendingPathComponent("HelloWorld.txt")
guard fileUrl.startAccessingSecurityScopedResource() else {
  print("Failed to obtain access to file \(fileUrl)")
  return
}
let fileData = "Hello World".data(using: .utf8)
try! fileData?.write(to: fileUrl)

fileUrl.stopAccessingSecurityScopedResource()

This all seems to work fine on a simulator. I can pick “On My iPhone” folder and the write is successful. However, when I try to run it on a physical device, it fails at fileUrl.startAccessingSecurityScopedResource().

What’s even weirder is that, if I ignore the guard and continue with try! fileData?.write(to: fileUrl), it doesn’t throw an exception. It simply doesn’t write anything to the folder.

The URLs I’m getting:

Simulator:

file:///Users/deling/Library/Developer/CoreSimulator/Devices/9173F102-09C7-474E-9040-6595CCBC9C4B/data/Containers/Shared/AppGroup/F13FAF79-B86B-496B-90C2-EA8D6F30FE53/File%20Provider%20Storage/

Physical iPhone:

file:///private/var/mobile/Containers/Shared/AppGroup/05C3ECD9-2601-4FD5-B2BD-D785A66DB952/File%20Provider%20Storage/

Any suggestions? Thanks.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img