General:
DevForums tags: Files and Storage, Finder Sync, File Provider, Disk Arbitration, APFS
File System Programming Guide
On File System Permissions DevForums post
File Provider framework
Finder Sync framework
App Extension Programming Guide > App Extension Types > Finder Sync
Disk Arbitration Programming Guide
Mass Storage Device Driver Programming Guide
Device File Access Guide for Storage Devices
Apple File System Guide
TN1150 HFS Plus Volume Format
Extended Attributes and Zip Archives
File system changes introduced in iOS 17 DevForums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
File Provider
RSS for tagAllow other apps to access the documents and directories stored and managed by your containing app using File Provider.
Posts under File Provider tag
74 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hi everyone,
I am a beginner in iOS/Swift programming. I'm trying to develop a mobile application that allows to mount a network drive in the iphone Files application via the WebDav protocol.
I saw on the internet that WebDav is no longer implemented in iOS because considered deprecated by apple.
To accomplish this task, I decided to separate responsibilities as follows:
Framework:
WebDav (responsible for communication with the WebDav server)
FileProviderExtension:
FileBridge (Responsible for bridging the gap between the WebDav Framework and the iOS Files app)
Main App
I also have an AppGroup that includes the main application and the fileproviderextension
Initially, to measure the feasibility and complexity of this task, I'd like to make a simplistic version that simply displays the files on my drive in the Files app, without necessarily being able to interact with them.
FileProviderExtension.swift:
import FileProvider
import WebDav
class FileProviderExtension: NSObject, NSFileProviderReplicatedExtension {
private var webDavService: WebDavService?
required init(domain: NSFileProviderDomain)
{
super.init()
self.webDavService = WebDavService(baseURL: URL(string: "https://www.mydrive.com/drive")!)
}
func invalidate() {
// TODO: cleanup any resources
}
func item(for identifier: NSFileProviderItemIdentifier,
request: NSFileProviderRequest,
completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void) -> Progress {
let progress = Progress(totalUnitCount: 1)
Task {
do {
if let items = try await webDavService?.propfind(path: identifier.rawValue, depth: 1),
let item = items.first(where: { $0.itemIdentifier == identifier }) {
completionHandler(item, nil)
} else {
completionHandler(nil, NSError(domain: NSCocoaErrorDomain,
code: NSFileNoSuchFileError,
userInfo: nil))
}
} catch {
completionHandler(nil, error)
}
}
return progress
}
func fetchContents(for itemIdentifier: NSFileProviderItemIdentifier,
version requestedVersion: NSFileProviderItemVersion?,
request: NSFileProviderRequest,
completionHandler: @escaping (URL?, NSFileProviderItem?, Error?) -> Void) -> Progress {
let progress = Progress(totalUnitCount: 1)
Task {
do {
guard let service = webDavService else {
throw WebDavError.invalidResponse
}
let data = try await service.get(fileAt: itemIdentifier.rawValue)
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(itemIdentifier.rawValue)
try data.write(to: tempURL)
completionHandler(tempURL, nil, nil)
} catch {
completionHandler(nil, nil, error)
}
}
return progress
}
func createItem(basedOn itemTemplate: NSFileProviderItem, fields: NSFileProviderItemFields, contents url: URL?, options: NSFileProviderCreateItemOptions = [], request: NSFileProviderRequest, completionHandler: @escaping (NSFileProviderItem?, NSFileProviderItemFields, Bool, Error?) -> Void) -> Progress {
// TODO: a new item was created on disk, process the item's creation
completionHandler(itemTemplate, [], false, nil)
return Progress()
}
func modifyItem(_ item: NSFileProviderItem, baseVersion version: NSFileProviderItemVersion, changedFields: NSFileProviderItemFields, contents newContents: URL?, options: NSFileProviderModifyItemOptions = [], request: NSFileProviderRequest, completionHandler: @escaping (NSFileProviderItem?, NSFileProviderItemFields, Bool, Error?) -> Void) -> Progress {
// TODO: an item was modified on disk, process the item's modification
completionHandler(nil, [], false, NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:]))
return Progress()
}
func deleteItem(identifier: NSFileProviderItemIdentifier, baseVersion version: NSFileProviderItemVersion, options: NSFileProviderDeleteItemOptions = [], request: NSFileProviderRequest, completionHandler: @escaping (Error?) -> Void) -> Progress {
// TODO: an item was deleted on disk, process the item's deletion
completionHandler(NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:]))
return Progress()
}
func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier,
request: NSFileProviderRequest) throws -> NSFileProviderEnumerator {
return FileProviderEnumerator(enumeratedItemIdentifier: containerItemIdentifier,
service: webDavService)
}
}
Here's the code I use to initialize my domain in the main app files:
fileprivate func registerFileProviderDomain() {
let domainIdentifier = NSFileProviderDomainIdentifier("FileProviderExtension Bundle Identifier")
let domain = NSFileProviderDomain(identifier: domainIdentifier,
displayName: "My Drive")
NSFileProviderManager.add(domain) { error in
NSFileProviderManager.add(domain) { error in
if let error = error {
print("Error cannot add domain file provider : \(error.localizedDescription)")
} else {
print("Success domain file provider added")
}
}
}
I can't get rid of the Error :
Error cannot add domain file provider : The operation couldn’t be completed. Invalid argument.
I don't know what I'm missing
Please help me understand
When running a Mac Catalyst app that uses DocumentGroup, the app fails to display the document content. The document picker works as expected, but creating a new document or opening an existing one results in an empty window. This issue occurs regardless of whether “Optimize for Mac” or “Scale iPad” is selected.
Steps to Reproduce:
1. Download the sample project provided by Apple for building a document-based app in SwiftUI.
2. Delete the macOS version of the project.
3. Add a Mac Catalyst version of the app.
4. In the Mac Catalyst settings, select “Optimize for Mac” (the bug also appears if it is “Scale iPad”).
5. Run the project on macOS.
Expected Result:
The app should correctly display the content of the document when creating or opening it.
Actual Result:
The app opens an empty window when a new document is created or an existing one is opened.
Impact:
We have received multiple 1-star reviews, and our retention has dropped by two-thirds due to this issue.
Environment: Xcode 16.1; macOS 15.1 & 15.2 (on 15.0 it works fine)
Has anyone experienced the same issue? I filed multiple reports so far.
Hi,
With UIDocumentPickerViewController, there is a directoryURL property that says we can use to 'specify the starting directory for the document picker'. But it's not clear how to get the directory of a folder in iCloud Drive / Files app. How can I get the 'root' directory for a user's iCloud Drive or Dropbox folder, or the Downloads folder on their device, that I could pass to this directoryURL to make it easier for the user to pick their files?
Thanks.
We use File Provider Extension in our main app, and it is working fine.
We always call "NSFileProviderManager.add(_:completionHandler:)" function to start the extension, and "NSFileProviderManager.disconnect(reason:options:completionHandler:)" to temporarily quit the extension with the reason which will be shown in the Finder at the top of the FP domain folder.
But sometimes, when the main app calls the above functions, the following issue cases occur, and the extension does not start/stop:
The completionHandler function doesn't get called (As we noticed, we waited for 2 minutes. Then, we restarted the main app.)
One of the following errors returned: i) "The application cannot be used right now", ii) "Couldn't communicate with the helper application", iii) "No valid file provider found with identifier"
Here, the important thing is that restarting the main app once or twice clears the issue, and the extension starts.
But it is frustrating to restart the app each time we get this issue.
We want to know the following things:
Why and when do the above issues occur?
Why do they occur only sometimes, and how does the app restart clear the issue?
How do we resolve them without restarting the main app?
This has become a critical issue, so a detailed explanation would be greatly appreciated. TIA.
iPhone 15pro iOS 18.2
Downloaded files cannot be located anywhere in Files, only by accessing Downloads in Safari. I have tried setting download folder to various locations, iCloud, Phone, Google Disk, but nothing is stored.
Has an invisible cache or temp folder been introduced? If so, it is a total fail:
When press-holding any file in Safari download, the normal file action options (Quick Look, share, store to Files, etc) are not available.
When clicking any file it opens any of several apps that has this file type associated with it, and there is no way to change the default app or disable the forced opening of an app.
I tried deleting the app opening .csv (in this case OneDrive), and another irrelevant app opened. There seems to be a hierarchy of apps-file types, and it has no logic to it.
in Chrome behaviour is as expected.
Chrome vs. Safari screen recordings: https://shorturl.at/my3Oy
Dear Apple engineers,
Is it possible to make a fileprovider cloud volume mount path independent of the user's home folder in order to have constant path across desktop clients when files are referenced / placed by applications like Adobe Creative Cloud ?
Ideally mount or link the fileprovider cloud volume under /Volumes
Thanks,
I am using a Mac Catalyst with SwiftUI for our document-based app with DocumentGroup. The issue is that when we create a new document or open an existing one, the opened view is completely blank. It is only blank/empty when the "Optimzie for Mac" is checked. If it is "Scaled t oMatch iPad", then it works well.
Xcode 16.1
macOS 15.1
struct DocumentGroupTestApp: App {
var body: some Scene {
DocumentGroup(newDocument: WritingAppDocument()) { file in
TestView() // it is empty when it gets opened. It does not work if the option "Optimize for Mac" is checked. If it is scale iPad, then it works.
}
}
}
struct TestView: View {
var body: some View {
Text("Hello, World!")
}
}
Hello,
I'm seeing a strange error on another user's device where the SwiftUI file importer doesn't do anything at all. When selecting multiple files and hitting "open", the importer just freezes. Here's a video showing the problem: https://streamable.com/u5grgy
I'm unable to replicate on my own device, so I'm not sure what could be going on. I have startAccessingSecurityScopedResource and stopAccessingSecurityResource everywhere I access a file from fileImporter as well.
Delete the Documents path of the app
Will the files or folders in the documentDirectory path or applicationSupportDirectory path disappear or be deleted when the OS is updated?
I know that sometimes all the files in the cachesDirectory path are deleted when the OS is updated or the device is rebooted.
Sometimes, users of my app report that all the files in the documentDirectory path or applicationSupportDirectory path are deleted or disappear, or all the files are deleted and initialized.
I thought that the files or folders in the documentDirectory path or applicationSupportDirectory path were not affected by the OS update, but am I wrong?
I’m developing a file provider extension for macOS; I’m working with xcode 16 and macOS Sequoia.
I created an host application via xcode with a simple button “Add domain” that triggers the following code:
let domain = NSFileProviderDomain(identifier: NSFileProviderDomainIdentifier(rawValue: "me.piranef.fileprovider"), displayName: "piranef") NSFileProviderManager.add(domain) { theError in NSLog(">>> ERROR: \(theError?.localizedDescription ?? "No error")") }
Note: I provide the link to the whole project on GitHub below.
Finally I added via xcode a file provider target:
At this point everything should be ok to run a simple stub application that once running add a piranef file provider visible under any file manager window in finder.
But the following error appears:
No file provider was found with the identifier “me.piranef.MyFileProviderTester”
My suspect is that despite the target has been created by xcode, some setup in some .plist or .entitlement file must be changed manually or some tricky key added to make the file provider extension visible to the hosting application.
I tried to manually change some setup that appeared logical for me like:
The product bundle identifier in the target -> build settings of the extension:
App Groups in the .entitlements file of the extension that seems set to a placeholder file, set to the same value of the host application:
An hint I got reading the readme file of the FruitBasket sample application (by Apple) is to embed without signing the extension into the main app: Done! It’s ok!
To give all possible information I uploaded the whole project into my github profile at: https://github.com/fpiraneo/fileproviderstub/
Any hint is welcome; I already googled or searched in StackOverflow or even asked ChatGPT for help but with no results.
Even other users are experiencing the same issue and posting on StackOverflow with no answers:
"Error adding File Provider domain: No valid file provider found with identifier ‘MyApp.FinderExtensionHost’ on MacOS” on StackOverflow
On some systems we are running into situations where we have an existing domain, but it remains in a stuck state where the domain exists but when attempting to interact with the domain to establish an XPC connection we get:
=Error Domain=NSFileProviderInternalErrorDomain Code=0 "No valid file provider found from URL file:///Users/User/Library/CloudStorage/ProviderName-ProviderName." UserInfo={NSLocalizedDescription=No valid file provider found from URL file:///Users/User/Library/CloudStorage/Provider-Provider.
Nothing that I've been able to do on an affected user account allows our app's domain to be added without facing errors. If we switch to a different user profile the domain is added and we can establish an XPC connection without any issues.
So far I have tried:
Removing the domain via NSFileProviderManager.removeAllDomains()
Navigating to the domain in locations with the app uninstalled and deleting via the prompt within the Finder window
Removing the plugin using: pluginkit -r /Applications/AppName.app/Contents/PlugIns/ProviderName.appex
Removing the group container folder for the app from ~/Library/Group Containers and the app's data from ~/Library/Application Support/FileProvider/
I recognize that there is a profile (https://developer.apple.com/bug-reporting/profiles-and-logs/?platform=macos&name=Icloud) for additional logging, but having an end user install this is cumbersome. While I have encountered similar behavior myself I observed unix exception error 17 using console streaming logs though I can't be sure my issue is identical to the customers until we try and repeat the results on their systems with console streaming. macOS 15 has, deliberately, removed some of the options available in fileproviderctl to remove domains. If a fileProvider domain is in a bad state, how are we supposed to remove it? Relying only on NSFileProviderManager calls isn't helpful if these calls fail.
Hi, so as I understand it is not possible to know what all possible sources of files are available on iOS using some api call (by sources I mean smb shares connected, iCloud, gdrive, etc), the only paths I can get are the app sandbox, app group container and the same on iCloud. I can get the list of mount points in macOS using getmntinfo(), app/group sandbox and apart from these whatever standard locations I have given access to to my sandboxed app. Are there other paths that I can get?
I want to know how I can determine the volume given a user picks a file using a file picker. Say, they picked 10 files from gdrive and another 5 from local storage. If I encounter some errors on the files from gdrive I want to stop working on all 10 of them but to do that I need to be able to determine that that are on this particular volume. Is there a way to do this programmatically?
Ex: gdrive on iOS : "/private/var/mobile/Containers/Shared/AppGroup/6208BBEE-24BF-4CC9-A9ED-846F987C0442/File Provider Storage/39822865/1P8WD1tWEaq81ZB_DodTTZhXm0p00QaF7/test.txt"
on MacOS:
"/Users/username/Library/CloudStorage/GoogleDrive-useremailid/My Drive"
Hi,Regarding FileProvider, I know it has a permission authorization pop-up to control whether to open the FileProvider extension in the application settings
But when I first used it, the switch was turned off by default. I noticed that some applications can pop up an authorization pop-up to prompt the user to turn on this permission
I would like to ask what API this authorization pop-up is displayed through
I expect the authorization pop-up window to pop up as shown in the following picture
Thanks
Hello, I would like to know why my FileProvider. apex application cannot run on a Mac OS 12.0 computer after I compiled it on Mac OS 4.5.
I have changed the macOS Deployment Target and Minimum Deployment in the XCode configuration file to 11.0, but it still cannot run
The error is as follows:
2024-09-23 10:10:24.264067+0800 0xab312 Error 0x0 83438 0 O+Connect: (libFileProviders Manager. dylib) [com. oplus. DeviceSpace: FileProviders Manager] Unable to add domain, error: Error Domain=NSFileProviders Error Domain Code=-2001 "The application is currently unavailable. UserInfo={NSLocalizedDescription=The application is currently unavailable.}
I want to know what this error means and how to solve it
Hi Team,
I am trying to explore ESF events specifically generated by cloudsync extensions built on File Provider framework.
Brief:
I have high-level understanding of how various cloud vendors have provided their extensions to sync data from cloud/remote storage to local filesystem (and vice-versa). e.g.iCloudDriveFileProvider (icloud), DFSFileProviderExtension (google drive).
There are 2 ESF AUTH events for file provider I can see namely: ES_EVENT_TYPE_AUTH_FILE_PROVIDER_MATERIALIZE ,
ES_EVENT_TYPE_AUTH_FILE_PROVIDER_UPDATE.
and respectively their NOTIFY events.
Observation:
Observed that these events are generally triggered by fileproviderd process during download scenario i.e. syncing files from cloud/remote storage to local file system. i.e. 'materialize' for new file creation and 'update' for updating existing file.
Question/Problem:
Is there a correct way to find which cloud provider has triggered this download event? i.e. weather it is iCloudDriveFileProvider or DFSFileProviderExtension (there is this instigator field in Materialize event struct, but could not find similar for Update event.
Are there similar ESF events for upload scenario? (I have fair understanding of how file-to-upload is copied to temp location and then uploaded by respective extensions to remote storage, but then they work with original files clone created in their temp location, so the AUTH events generated by this extension will wont reveal the original file name even if I am able to get the Fileprovider name)
To Summarize: Basically I am looking for ESF event that will be triggered during upload scenario that can also let me know original file name as well the cloudprovider extension process name. As of now 'fileproviderd' process name is obtained from filesystem ESF events like AUTH_OPEN etc.
Hello,
If a user allows access to, for example, Removable Volumes (TCC permission) to the main app, does these permissions will be inherited by a bundled Finder Extension from the main app?
More specific, I have an app that bundles a Finder Extension and both the main app and the bundled extension need access to Removable Volumes. Only the main app can request it, since the main app is the only that can prompt the user. If the user allows, will the bundled extension also receive the permissions?
If not, is there any workaround?
Regards.
Hello,
I developed a file provider extension that can access files from multiple locations. With the new macOS Sequoia I cannot access files from volumes, here is the error from Console:
Refusing TCCAccessRequest for service kTCCServiceSystemPolicyRemovableVolumes from extension Sub:{com.app.ext}Resp:{TCCDProcess: identifier=com.app.ext-Driver, pid=26706, auid=501, euid=501, binary_path.... Driver}, extension point disallows prompting
I added "Privacy - Removable Volumes Usage Description" values for both the main app and extension Info.plist, I click Allow on the alert, but still I receive this error message.
Any solution?
Thank you.
Hi
I am using PhotosPicker and SwiftData with iOS17.0.
I released my own app using codes of two above. No problem came up right until I upgraded my iphone to iOS 18.0 17th of September 24. A single post pokes the similar problem. SwiftData and PhotosPikcer. He or She said it was about SwiftData Model Insert something. But, I was able to use other methods that use SwiftData, so insert Model setup isn't my problem.
But when tapping a photo to get a photo from PhotosPicker makes the ui goes down, and navigate back. Weird. iIt doesnt crash but when I tap a photo, the debug message [ERROR] Could not create a bookmark: NSError: Cocoa 4097 "connection to service named com.apple.FileProvider" comes up and the view navigates back.
The selecting a photo itself doesnt include any SwiftData related methods, it only does loadTransferable thing and shows the photo on the screen.
I cannot understand it. it only happened when I upgraded to iOS 18.0. AND Then i debugged the prob with Xcode 16.0 nothing but the unexpected message appears and not many posts are up here or google. Can you help me?
Things I tried:
Check any use of the PhotosPickerItem anywhere else. -> No where.
Use try await loadTransferable
Changed the form of initiating PhotosPikcer View
Debugging every line -> Nothing appeared.
PhotosPicker(selection: $currentImage, matching: .images, photoLibrary: .shared()) {
Text("")
}
.frame(height: 360)
.photosPickerStyle(.inline)
.photosPickerAccessoryVisibility(.hidden, edges: .bottom)
.photosPickerDisabledCapabilities(.selectionActions)
.onChange(of: currentImage) { _, newImage in
// SomeLogic
}
.ignoresSafeArea(edges: .bottom)
.transition(.move(edge: .bottom).combined(with: .opacity))
When users share a file with my app I am having trouble 5-10% of the time obtaining the file meta data, specifically creation and modified time and size.
Using SwiftUI with the code below..
.onOpenURL { url in
var fileSize: Int64 = 0
var creationTime: Date = Date(timeIntervalSince1970: 0)
var modificationTime: Date = Date(timeIntervalSince1970: 0)
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: url.path)
fileSize = fileAttributes[FileAttributeKey.size] as? Int64 ?? 0
creationTime = fileAttributes[FileAttributeKey.creationDate] as? Date ?? Date(timeIntervalSince1970: 0)
modificationTime = fileAttributes[FileAttributeKey.modificationDate] as? Date ?? Date(timeIntervalSince1970: 0)
<SNIPPED CODE no other tries though and not involving above variables>
} catch {
// quite confident I am ending up here because variables after the above code aren’t being set and there are no other try blocks,
// so FileManager.default.attributesOfItem(atPath: url.path) must be throwing….
}
<SNIPPED CODE>
To attempt to resolve this, I added in a 0.5 second wait cycle if creationTime == 0 and modificationTime == 0 , so if obtaining both metadata fails, wait 0.5 seconds and try again, try this a max of 3 times and then give up. I don’t know how often I am entering this code (didn’t instrument the app for it), but am still getting times when metadata comes back blank which means this code wasn’t successful after 3 tries.
I assume the file would only become visible and sharable with my app after it has completed being written by the original app/process. Perhaps it hasn’t finalized yet? Is there a way to detect this so I can tell the user in my share screen to wait and try again?
I am assuming that the file has finished writing though since when I read the data from the file contents, it’s good data and complete even when metadata failed.
I will be instrumenting the above code in my next app version, just hoping to fix it right now since users are emailing saying my app is broken.
Thanks!
How can I read a dataless file from within the same or another FileProvider extension?
When I pass the visible URL to AVAsset from AVFoundation, it throws the following error:
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x15b01b1e0 {Error Domain=NSPOSIXErrorDomain Code=11 "Resource deadlock avoided"}, NSLocalizedFailureReason=An unknown error occurred (11), AVErrorFailedDependenciesKey=(
"assetProperty_Tracks"
), NSURL=file:///Users/<<username>>/Library/CloudStorage/<<file-path>>, NSLocalizedDescription=The operation could not be completed}
The code snippet works fine if executed as a separate Swift process.
I'm using AVAsset with AVAssetExportSession to export a subset of the file being read. So I can't use NSFileProviderManager.requestDownloadForItem(withIdentifier:, requestedRange:) because I don't know the offset range required by the AVFoundation library.