Files and Storage

RSS for tag

Ask questions about file systems and block storage.

Posts under Files and Storage tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

NSSavePanel not has the User Selected File Read/Write permission in a sandbox inherit child process
I have an application running in the sandbox which launches an application bundle using NSTask. The main app entitlements enable sandbox add the User Selected File Read/Write permission. <dict> <key>com.apple.security.app-sandbox</key> <true/> <key>com.apple.security.files.user-selected.read-write</key> <true/> </dict> The child app entitlements enable sandbox and inherit. <dict> <key>com.apple.security.app-sandbox</key> <true/> <key>com.apple.security.inherit</key> <true/> </dict> When invoke NSSavePanel *savePanel = [NSSavePanel savePanel] in the child process, system will throw the error.The error message prompt that missing the User Selected File Read/Write permission. However, I have already added this permission in the main app, and I have set up the inherit in the child-process as well. The child process cannot add the User Selected File Read/Write permission again because it add sandbox and inherit in entitlements by the doc EnablingAppSandbox . It appears that the system is not inheriting this permission for the child process. panel[60195:2499353] [OpenSavePanels] Unable to display save panel: your app is missing the User Selected File Read/Write app sandbox entitlement. Please ensure that your app's target capabilities include the proper entitlements. And the error stack. [miscellany] CLIENT ERROR: remote view delegate NSSavePanel lacks method which can react to the details of Error Domain=com.apple.ViewBridge Code=14 "(null)" UserInfo={com.apple.ViewBridge.error.hint=-[NSViewServiceMarshal bootstrap:withReply:] caught NSInternalInconsistencyException '+[NSOpenAndSavePanelService loadViewToService:isOpenPanel:appCentric:] : failed entitlements check' with backtrace ( "0 CoreFoundation __exceptionPreprocess + 242", "1 libobjc.A.dylib objc_exception_throw + 48", "2 CoreFoundation -[NSException raise] + 9", "3 com.apple.appkit.xpc.openAndSavePan com.apple.appkit.xpc.openAndSavePan + 16852", "4 AppKit -[NSViewController _loadViewIfRequired] + 72", "5 AppKit __24-[NSViewController view]_block_invoke + 27", "6 AppKit NSPerformVisuallyAtomicChange + 132", "7 AppKit -[NSViewController view] + 123", "8 ViewBridge -[NSViewServiceMarshal _bootstrap:replyData:completion:] + 1826", "9 ViewBridge -[NSViewServiceMarshal bootstrap:withReply:] + 245", "10 CoreFoundation __invoking___ + 140", "11 CoreFoundation -[NSInvocation invoke] + 305", "12 CoreFoundation -[NSInvocation invokeWithTarget:] + 70", "13 ViewBridge -[NSVB_ViewServiceImplicitAnimationDecodingProxy forwardInvocation:] + 178", "14 CoreFoundation ___forwarding___ + 756", "15 CoreFoundation _CF_forwarding_prep_0 + 120", "16 CoreFoundation __invoking___ + 140", "17 CoreFoundation -[NSInvocation invoke] + 305", "18 CoreFoundation -[NSInvocation invokeWithTarget:] + 70", "19 ViewBridge -[NSVB_QueueingProxy forwardInvocation:] + 321", "20 CoreFoundation ___forwarding___ + 756", "21 CoreFoundation _CF_forwarding_prep_0 + 120", "22 CoreFoundation __invoking___ + 140", "23 CoreFoundation -[NSInvocation invoke] + 305", "24 CoreFoundation -[NSInvocation invokeWithTarget:] + 70", "25 CoreFoundation ___forwarding___ + 756", "26 CoreFoundation _CF_forwarding_prep_0 + 120", "27 CoreFoundation __invoking___ + 140", "28 CoreFoundation -[NSInvocation invoke] + 305", "29 ViewBridge __deferNSXPCInvocationOntoMainThread_block_invoke + 142", "30 ViewBridge __wrapBlockWithVoucher_block_invoke + 37", "31 ViewBridge kNotRunningOnAppKitCompatibleThread_block_invoke + 323", "32 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12", "33 CoreFoundation __CFRunLoopDoBlocks + 398", "34 CoreFoundation __CFRunLoopRun + 2015", "35 CoreFoundation CFRunLoopRunSpecific + 560", "36 HIToolbox RunCurrentEventLoopInMode + 292", "37 HIToolbox ReceiveNextEventCommon + 657", "38 HIToolbox _BlockUntilNextEventMatchingListInModeWithFilter + 64", "39 AppKit _DPSNextEvent + 858", "40 AppKit -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1214", "41 ViewBridge __77-[NSViewServiceApplication vbNextEventMatchingMask:untilDate:inMode:dequeue:]_block_invoke + 111", "42 ViewBridge -[NSViewServiceApplication _withToxicEventMonitorPerform:] + 114", "43 ViewBridge -[NSViewServiceApplication vbNextEventMatchingMask:untilDate:inMode:dequeue:] + 151", "44 ViewBridge -[NSViewServiceApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 99", "45 AppKit -[NSApplication run] + 586", "46 AppKit NSApplicationMain + 817", "47 libxpc.dylib _xpc_objc_main + 867", "48 libxpc.dylib xpc_main + 96", "49 ViewBridge xpc_connection_handler + 0", "50 ViewBridge NSViewServiceMain + 1789", "51 com.apple.appkit.xpc.openAndSavePan main + 178", "52 dyld start + 1903" ), com.apple.ViewBridge.error.description=NSViewBridgeErrorServiceBootstrap}
1
0
560
Aug ’23
iOS 17 beta "You don’t have permission to save the file" crash on device
Issue This issue is reproducible on iOS 17 beta 4 and iOS 17.0 (21A5303d) public beta. When try to create a folder using the FileManager API, the app crashes with the following stack trace. Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “Samples” in the folder “…”." UserInfo={NSURL=file://…/Samples.app/, NSUnderlyingError=0x28100cf00 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}} What is the user impact? Users will not be able to run the app on iOS 17 Steps to Reproduce Create a new project Add the following code import SwiftUI struct ContentView: View { var body: some View { Text("Hello, world!") .onAppear { _ = makeTemporaryDirectory() } } /// Creates a temporary directory. private func makeTemporaryDirectory() -&gt; URL { try! FileManager.default.url( for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: Bundle.main.bundleURL, create: true ) } } Build and run the app. It crashes on the force try line. O/S: iOS 17 (Beta 4) / iOS 17.0 (21A5303d) Device: iPad Pro Gen 4, iPhone 11. Only happens on real device, not on the simulators
5
2
2.3k
Aug ’23
How To Load a ModelEntity from a URL?
3D assets such as models, textures, animations, etc., can significantly inflate app bundle sizes. To mitigate this, loading these assets from a remote URL is the way to go. But how does someone load a ModelEntity from a hosted URL? The current method is to load a Model3D: let url = URL(string: "my-url")! Model3D(url: url) But this does not pack all the features of a ModelEntity which can be used in a RealityView. Such as anchoring, animations, advanced gestures, etc. How do I load a remote URL into a ModelEntity?
2
0
651
Aug ’23
Force Refresh Volume to Get Current Amount of Free Bytes From File System Without Any Caches
Hello, in my app I need the current amount of free space on a certain volume. I use the following code to the this information: if let mountedVolumeURLs = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: nil) { for volumeUrl in mountedVolumeURLs { guard let values = try? self.url.resourceValues(forKeys: [.volumeTotalCapacityKey, .volumeAvailableCapacityKey]) else { continue } let totalBytes = values.allValues[.volumeTotalCapacityKey] as? UInt64 ?? 0 let freeBytes = values.allValues[.volumeAvailableCapacityKey] as? UInt64 ?? 0 // This is not always correct. } } When writing to a volume and then calling the code above, a wrong amount is returned. I suspect that there is still some cacheing going on. Is there any function that I can call to get this information from the file system without any cacheing? I guess an alternative would be to get a list of all files, get their sizes, add them up and subtract that number from the total bytes of the volume. But maybe there is a more elegant solution. I also tried something like this: let handle = try FileDescriptor.open(volumeUrl.path, .writeOnly, options: .create, permissions: .ownerReadWrite, retryOnInterrupt: true) fcntl(handle.rawValue, F_FULLFSYNC) But this did not help. I would appreciate any help. Regards
1
0
456
Aug ’23
Custom FAT16 USB volume support
There's a slightly tweaked FAT16 implementation used on some Akai samplers. I've created an emulator of one of those samplers. It supports USB volume i/o with a custom FAT16 implementation. All of this works, but currently goes via the deprecated AuthorizationExecuteWithPrivileges for achieving raw USB volume access. The mechanism I specifically rely on currently is to, with elevated privileges, change the ownership of /dev/diskN, and then with normal privileges I can open a file handle against that disk device. Yesterday I looked into migrating to SMJobBless, but it also turns out to be deprecated. Does any of the macOS SDKs support my use case? Should I look into writing a DriverKit or IOKit driver? Any tips or guidance would be appreciated. Ideally I can implement a flow where the user is only required to approve with admin privileges once and after that has raw block device access to a restricted set connected volumes -- FAT16/ms-dos volumes that have a special volume label, or a special flag set in the boot sector.
1
0
329
Aug ’23
Did macOS Sonoma add additional file read-write restrictions?
Hello, I have an app in the App Store that is your typical cleaner app. The app searches for files from deleted apps and can remove them. Under macOS Sonoma the app does no longer work. When deleting files, the following message appears in the Console: System Policy: App(1636) deny(1) file-write-unlink The app has scoped bookmarks for the folder and additionally I added Full Disk Access for my app - it still does not work? Is there another layer on top of that? The app works perfectly fine on Big Sur, Monterey and Ventura. Regards, Sascha
2
0
805
Sep ’23
Sandboxing iOS Simulator
An iOS app running in simulator has complete access to the Mac's file system: // Files in protected directory like Desktop, Documents, Calendar, etc will need additional permissions. let filesInSystem = FileManager.default.enumerator(at: .currentDirectory(), includingPropertiesForKeys: nil)?.allObjects This isn't the case when running in device as the app is sandboxed. Is the same possible when running in simulator? More specifically, is there a way to restrict access to the Mac's file system when running an app in the Simulator? This is particularly useful when trying out binaries/frameworks that are not open sourced.
1
0
1k
Sep ’23
Xcode 15 post archive script permission problems
I'm using this build script: https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution/customizing_the_notarization_workflow/customizing_the_xcode_archive_process?language=objc To create and notarize a dmg. In Xcode 15 it fails when calling /usr/bin/hdiutil create .... The fail error message is: could not access /Volumes/Bike/Bike.app - Operation not permittedhdiutil: create failed - Operation not permitted I have found that I can work around the problem by giving Xcode 15 full disk access. Is there a way that I can make my script run without having to give Xcode full disk access?
3
0
928
Sep ’23
Is there a way of accessing/viewing files in an iOS app's shared group location from a Mac?
My goal is to try and get a unified logging system set up where logging from an iOS app and its extensions (primarily a notification service extension) get written into one central repository. So I was planning on setting up CocoaLumberjack in the app and the extension to use the same file path/name, adding the group capability to the app and the extensions and specifying the shared group directory as the file path. By default, for an app, CocoaLumberjack writes its files to: var/mobile/Containers/Data/Application/05464D4A-20F6-4E1F-9DBC-3109C053A1E8/Library/Caches/Logs/ On a Mac using an application such as iExplorer the above file and be located and viewed and copied etc. For an extension, it writes them to: /var/mobile/Containers/Data/PluginKitPlugin/5542F5EA-EB3A-4728-B33E-4E57C1B7B3B4/Library/Caches/Logs/ Now if I configure Cocoalumberjack to instead write the logger file to the shared group directory, then that will be at: /private/var/mobile/Containers/Shared/AppGroup/6CD5AF2C-54C9-46EF-B831-997B1DD6664F/ However its not possible using iExplorer to access this location. Using a Mac connected to the iPhone, is there an app or tool etc., that will enable me to locate the log file if it's created in the above AppGroup location?
1
0
615
Sep ’23
macOS Sonoma 14 RC - Full Disk Access for app bundle is disabled after reboot (kTCCServiceSystemPolicyAllFiles)
Hi guys, has anyone seen this issue? When installing an application, which requires Full Disk Access (kTCCServiceSystemPolicyAllFiles), user enables this feature, but after reboot, OS automatically turns it off. Filed feedback in case it's a new issue. Any idea how to fix it? Any workaround to keep Full Disk Access enabled? Thanks.
16
0
3.5k
Dec ’23
macFUSE and autofs
I'm trying to use autofs to mount some macFUSE filesystems. However, autofs requires custom filesystems to provide /sbin/mount_* and this directory is not writable nor modifiable via synthentic.conf Using a launch agent or daemon is not desirable as there is a non-blocking delay before the filesystem gets mounted which causes a race condition. Is there any other option to let diskarbitrationd or autofs to automatically mount a macFUSE filesystem?
1
0
402
Jun ’24
Opening AirDropped files in 3rd party apps in iOS 17
Since updating to iOS 17 there doesn't seem to be a way to automatically open files AirDropped into any applications. The files get downloaded to the Files application and you can open them from there, but previously you could open them straight in another application. There doesn't seem to be any documentation to this change. Is there still a way to open AirDropped files directly in a non-Apple published application?
16
9
5.4k
Oct ’23
Change mobile data transfer
My APP is hybrid architecture, I transferred my test phone to a new phone, userdefault will be transferred, but the local storage of the front-end will not be transferred. Both(userdefault&amp;local storage) will be transferred when my colleagues transfer their personal phones. My test case Same model mobile phone Mobile phones with the same OS version Switch from a small OS version to a phone with a large OS version Switch from large OS version to mobile phone with small OS version The first three items are userdefault will be transferred, but local storage will not be transferred. The fourth item is that you will be asked to upgrade the OS version when transferring. Does anyone know any relevant information? Or are there any settings enabled?
0
0
271
Sep ’23
unable to delete file because it's never found because.
my mind is shot. core data hasn't been my cup of tea. print("saveTrigger called with trigger: \(trigger)") let encoder = JSONEncoder() let fm = FileManager.default let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let reflectionsURL = documentsDirectory.appendingPathComponent("reflections.json") let triggersDirectory = documentsDirectory.appendingPathComponent("Triggers") // Create a new reflections file if it doesn't exist if !fm.fileExists(atPath: reflectionsURL.path) { let emptyData = Data() fm.createFile(atPath: reflectionsURL.path, contents: emptyData, attributes: nil) } // Write the trigger to the reflections file do { let data = try encoder.encode(trigger) try data.write(to: reflectionsURL) print("Trigger saved to device: \(trigger)") print("Reflections file URL: \(reflectionsURL)") } catch { print("Failed to save trigger: \(error)") } // Find the trigger file with the UUID inside the file let triggerFileURL = triggersDirectory.appendingPathComponent("\(trigger.id).json") if fm.fileExists(atPath: triggerFileURL.path) { do { let data = try Data(contentsOf: triggerFileURL) let uuid = try JSONDecoder().decode(UUID.self, from: data) let uuidString = uuid.uuidString let matchingTriggerFileURL = triggersDirectory.appendingPathComponent("\(uuidString).json") if fm.fileExists(atPath: matchingTriggerFileURL.path) { try fm.removeItem(at: matchingTriggerFileURL) print("Trigger file deleted: \(matchingTriggerFileURL.lastPathComponent)") } else { print("Trigger file not found") } } catch { print("Error deleting trigger file: \(error.localizedDescription)") } } else { print("Trigger file not found") } }
6
0
567
Oct ’23
Path must be an absolute path: <> cannotCreateNode(path: "")
We are trying to save usdz file in file manager some time its saved but some time we are getting the error. Like: path.absoluteURL file:///var/mobile/Containers/Data/Application/6D14A430-47B4-45F2-9D0D-6C31588A6A03/Documents/2896837C-C7E0-4FA8-BFE2-21A59B26D801.usdz Warning: in SdfPath at line 151 of sdf/path.cpp -- Ill-formed SdfPath &lt;/2896837CC7E04FA8BFE221A59B26D801&gt;: syntax error Coding Error: in _IsValidPathForCreatingPrim at line 3338 of usd/stage.cpp -- Path must be an absolute path: &lt;&gt; cannotCreateNode(path: "/2896837CC7E04FA8BFE221A59B26D801") func saveFileLocal() { if let finalResult { let fm = FileManager.default var path = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let fileName = "(UUID().uuidString).usdz" path.appendPathComponent(fileName) do { try finalResult.export(to: path.absoluteURL) } catch{ print(error) } } } func removeFiles() { var filePath = "" let fm = FileManager.default let path = fm.urls(for: .documentDirectory, in: .userDomainMask).first! do{ let content = try fm.contentsOfDirectory(atPath: path.path) for c in content{ filePath = path.appendingPathComponent(c).absoluteString if let url = URL(string: filePath){ try fm.removeItem(at: url) } } } catch{ print(error) } }
8
0
864
Oct ’23
`Bad file descriptor` when copying using hardlink flag
When I try to link a file on macOS, I get: $ cp -l release-source/release/examples/stubs-1-pubsub.test.js . cp: ./stubs-1-pubsub.test.js: Bad file descriptor This made it seem like the copying failed, but ls shows it went fine: $ ls -li release-source/release/examples/stubs-1-pubsub.test.js stubs-1-pubsub.test.js 9825657 -rw-r--r-- 2 carlerik staff 1072 26 sep 16:24 release-source/release/examples/stubs-1-pubsub.test.js 9825657 -rw-r--r-- 2 carlerik staff 1072 26 sep 16:24 stubs-1-pubsub.test.js A related post talks about this error coming from the file system, not the cp util itself. Creating a hard link using the ln command works fine, so the error must be due to something cp does that ln does not, so I fired up the console and captured messages hoping to see something. I cannot see that I do ... Does anyone have an idea what this is caused by? System information ❯ npx envinfo --system System: OS: macOS 13.5.2 CPU: (12) arm64 Apple M2 Max Memory: 4.24 GB / 64.00 GB Shell: 5.2.15 - /opt/homebrew/bin/bash ❯ diskutil list /dev/disk0 (internal, physical): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme *2.0 TB disk0 1: Apple_APFS_ISC Container disk1 524.3 MB disk0s1 2: Apple_APFS Container disk3 2.0 TB disk0s2 3: Apple_APFS_Recovery Container disk2 5.4 GB disk0s3
3
2
1.4k
Sep ’23
I'm missing something basic here but I am unable to to get the SwiftUI function to save a new file and delete the old one
it should be creating a new file and saving it, and then deleting the original file. iv'e attempted to have it load the UUID and by the title to avoid the need to even have the correct filename.... import SwiftUI struct file1DetailView: View { var file1: file1 @Binding var showFile1: Bool var saveFile1: ((file1) -&gt; Void) @Environment(\.presentationMode) var presentationMode @State private var addFile1View: AddFile1View? var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .long return formatter } var timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeStyle = .short return formatter }() var body: some View { ZStack { ScrollView { VStack { VStack{ HStack{ Text(file1.title) .font(.largeTitle.weight(.semibold)) .foregroundColor(.BrandGreen) .disabled(true) Spacer() } Spacer() .frame(height: 5) HStack{ Text(dateFormatter.string(from: file1.date)) .foregroundColor(.BrandGreen) .font(.subheadline.weight(.light)) Text(timeFormatter.string(from: file1.date)) .foregroundColor(.BrandGreen) .font(.subheadline.weight(.light)) Spacer() } Spacer() .frame(height: 15) Text(file1.description) .foregroundColor(.BrandGreen) .disabled(true) Spacer() .frame(height: 10) } .padding() .background(Color.white) .cornerRadius(30) Spacer() } Spacer() } .background( Image("calm-gradient") .resizable() .edgesIgnoringSafeArea(.all) ) VStack { Spacer() Button("Start file1") { let newFile1 = file1(title: file1.title, description: file1.description, date: file1.date, reflectionDate: Date(), preventible: false, Option1: "", Option2: "") addFile1View = AddFile1View(id: file1.id, file1: newFile1, saveFile1: saveFile1) showFile1 = true } .frame(maxWidth: .infinity) .padding(.vertical, 15) .foregroundColor(.white) .background(Color("BrandGreen")) } } .fullScreenCover(item: $addFile1View) { view in NavigationView { view .onDisappear { showFile1 = false presentationMode.wrappedValue.dismiss() } } } } } struct AddFile1View: View, Identifiable { var id: UUID @Environment(\.presentationMode) var presentationMode @State private var preventible = false @State private var Option1 = "" @State private var Option2 = "" @State private var reflectionDate = Date() var file1: file1 var saveFile1: ((file1) -&gt; Void)? // AddFile1View initializer init(id: UUID, file1: file1, saveFile1: ((file1) -&gt; Void)?) { self.id = id self.file1 = file1 self.saveFile1 = saveFile1 } var body: some View { VStack { Toggle("Preventible", isOn: $preventible) TextField("Option1", text: $Option1) TextField("Option2", text: $Option2) DatePicker("file1 Date", selection: $reflectionDate) Button("Save") { let newFile1 = file1(title: file1.title, description: file1.description, date: file1.date, reflectionDate: reflectionDate, preventible: preventible, Option1: Option1, Option2: Option2) saveFile1?(newFile1) presentationMode.wrappedValue.dismiss() } } .navigationTitle("Add file1") } } func saveFile1(file1: file1) { let encoder = JSONEncoder() let fm = FileManager.default let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let file1sURL = documentsDirectory.appendingPathComponent("file1s.json") // Read the existing file1s from the file system var file1s: [file1] = [] if fm.fileExists(atPath: file1sURL.path) { do { let data = try Data(contentsOf: file1sURL) file1s = try JSONDecoder().decode([file1].self, from: data) } catch { print("Failed to read file1s from file system: \(error)") } } // Add the new file1 to the list file1s.append(file1) // Write the updated list back to the file system do { let data = try encoder.encode(file1s) try data.write(to: file1sURL) print("file1s saved to device: \(file1s)") print("file1s file URL: \(file1sURL)") } catch { print("Failed to save file1s: \(error)") } // Delete the old file1 file let oldFile1URL = documentsDirectory.appendingPathComponent("\(file1.id).json") if fm.fileExists(atPath: oldFile1URL.path) { do { try fm.removeItem(at: oldFile1URL) print("Deleted old file1 file: \(oldFile1URL.lastPathComponent)") } catch { print("Failed to delete old file1 file: \(error)") } } } struct file1DetailView_Previews: PreviewProvider { static var previews: some View { NavigationView { file1DetailView( file1: file1( title: "Example file1", description: "This is an example file1 description.", date: Date(), file1Date: Date(), preventible: true, Option1: "Example Option1", Option2: "Example Option2" ), showFile1: .constant(false), saveFile1: saveFile1 ) } } }
2
0
432
Sep ’23