Files and Storage

RSS for tag

Ask questions about file systems and block storage.

Pinned Posts

Posts under Files and Storage tag

170 Posts
Sort by:
Post not yet marked as solved
3 Replies
528 Views
I've implemented the NSFilePresenter protocol in a Mac app (Catalina 10.15.3 Xcode 10.15.3) to watch a directory.Most protocol methods get called correctly, but some don't get called at all. For some there are (cumbersome) alternatives, but if, for example a file is immediately deleted in Finder using option+command+del, the NSFilePresenter delegate never receives any callback. Is there a workaround to trigger the callbacks?final class FileController: NSObject, NSFilePresenter { ... init() { presentedItemURL = // Some directory NSFileCoordinator.addFilePresenter(self) } func accommodatePresentedItemDeletion(completionHandler: @escaping (Error?) -> Void) { // Never gets called completionHandler(nil) } func presentedSubitemDidAppear(at url: URL) { // Never gets called } func presentedSubitemDidChange(at url: URL) { // Does get called } }
Posted Last updated
.
Post not yet marked as solved
0 Replies
88 Views
Hello! I tried several times to restore an old version of a TextEdit file, but the "revert to" option doesn't work/keeps getting stuck on the loading phase and I have to force the app to quit. Everything is saved on my iCloud and I usually update the same files using to different computers (iMac and MacBook pro). Is there a solution or another way to recover the old version? My MacBook pro is currently update to Monterey 12.4 Thank you!
Posted
by w000zy.
Last updated
.
Post not yet marked as solved
6 Replies
254 Views
Hi. I want to make a planner app that has the date and location of the project. Only I have a problem. I used a "DatePicker" so that the date is counted. Only I do not know how to save and display the selected date. In general I have problems to save and reload the content of the variables and texfielders etc. I thought that these contents are automatically saved on the end device of the user. I have read that there are methods like "UserDefaults", "CoreData" or "AppStorage". Have been reading stuff about this forever. But I can't get this to work. I hope someone would like to donate their time to help. Greetings Janik
Posted Last updated
.
Post not yet marked as solved
1 Replies
117 Views
I want to figure out whether a file (for which I have the absolute path) is a local file (on a disk device connected to my machine) or a remote file (connected over network). For the same what I have done is, I opened the file and then did a fstat on it (I know, I could have done without opening the file using stat, but that is okay). Now from fstat, I am looking at dev_t     st_dev;     /* ID of device containing file */   and figuring the major and minor version of the st_dev.   Now, what information which I have on Linux, about the different possible values of major version / minor version are present in devices.txt https://www.kernel.org/doc/Documentation/admin-guide/devices.txt   And the values match also (on Linux), for example for a local file (whether on hard disk/external hard disk or pen drive), I am getting major Version as 8.   What I want to know is, does Mac has similar devices.txt file? If yes, please provide the link/path.   If not, then what values can I assume right now, which will mean, file is remote?
Posted Last updated
.
Post not yet marked as solved
1 Replies
114 Views
My app stores 3D models in the app's Documents folder. After the 15.5 update or one of the updates around then, the folder seems to only allow 34MB before refusing to let me write to the folder, regardless of how much memory is left on the phone. This has caused a critical problem, because the same file is being uploaded to my web service, due to the file not being over-written. Any idea what happened here?
Posted
by SSISteve.
Last updated
.
Post not yet marked as solved
0 Replies
1.8k Views
Modern versions of macOS use a file system permission model that’s far more complex than the traditional BSD rwx model, and this post is my attempt at explaining that new model. If you have a question about this, post it here on DevForums, tagging your thread with Files and Storage so that I see it. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" On File System Permissions Modern versions of macOS have four different file system permission mechanisms: Traditional BSD permissions Access control lists (ACLs) App Sandbox Mandatory access control (MAC) The first two were introduced a long time ago and rarely trip folks up. The second two are newer, more complex, and specific to macOS, and thus are the source of some confusion. This post is my attempt to clear that up. Error Codes App Sandbox and the mandatory access control system are both implemented using macOS’s sandboxing feature. When a file system operation fails, check the error to see whether it was blocked by this sandboxing feature. If an operation was blocked by BSD permissions or ACLs, it fails with EACCES (Permission denied, 13). If it was blocked by something else, it’ll fail with EPERM (Operation not permitted, 1). If you’re using Foundation’s FileManager, these error are reported as Foundation errors, for example, the NSFileReadNoPermissionError error. To recover the underlying error, get the NSUnderlyingErrorKey property from the info dictionary. App Sandbox File system access within the App Sandbox is controlled by two factors. The first is the entitlements on the main executable. There are three relevant groups of entitlements: The com.apple.security.app-sandbox entitlement enables the App Sandbox. This denies access to all file system locations except those on a built-in allowlist (things like /System) or within the app’s containers. The various “standard location” entitlements extend the sandbox to include their corresponding locations. The various “file access temporary exceptions” entitlements extend the sandbox to include the items listed in the entitlement. The second factor is dynamic sandbox extensions. The system issues these extensions to your sandbox based on user behaviour. For example, if the user selects a file in the open panel, the system issues a sandbox extension to your process so that it can access that file. The type of extension is determined by the main executable’s entitlements: com.apple.security.files.user-selected.read-only results in an extension that grants read-only access. com.apple.security.files.user-selected.read-write results in an extension that grants read/write access. These dynamic sandbox extensions are tied to your process; they go away when your process terminates. To maintain persistent access to an item, use a security-scoped bookmark. See Security-Scoped Bookmarks and Persistent Resource Access. If you have access to a directory — regardless of whether that’s via an entitlement or a dynamic sandbox extension — then, in general, you have access to all items in the hierarchy rooted at that directory. This does not overrule the MAC protection discussed below. For example, if the user grants you access to ~/Library, that does not give you access to ~/Library/Mail because the latter is protected by MAC. Finally, the discussion above is focused on a new sandbox, the thing you get when you launch a sandboxed app from the Finder. If a sandboxed process starts a child process, that child process inherits its sandbox from its parent. For information on what happens in that case, see the Note box in Enabling App Sandbox Inheritance. IMPORTANT The child process inherits its parent process’s sandbox regardless of whether it has the com.apple.security.inherit entitlement. That entitlement exists primarily to act as a marker for App Review. App Review requires that all main executables have the com.apple.security.app-sandbox entitlement, and that entitlements starts a new sandbox by default. Thus, any helper tool inside your app needs the com.apple.security.inherit entitlement to trigger inheritance. However, if you’re not shipping on the Mac App Store you can leave off both of these entitlement and the helper process will inherit its parent’s sandbox just fine. The same applies if you run a built-in executable, like /bin/sh, as a child process. When the App Sandbox blocks something, it typically generates a sandbox violation report. For information on how to view these reports, see Viewing Sandbox Violation Reports. To learn more about the App Sandbox, see the App Sandbox Design Guide and related documents (most notably the Entitlement Key Reference). For information about how to embed a helper tool in a sandboxed app, see Embedding a Command-Line Tool in a Sandboxed App. Mandatory Access Control Mandatory access control (MAC) has been a feature of macOS for many releases, but it’s become a lot more prominent since macOS 10.14. There are many flavours of MAC but the ones you’re most likely to encounter are: Full Disk Access (since 10.14) Files and Folders (since 10.15) Data Vaults (see below) Mandatory access control, as the name suggests, is mandatory; it’s not an opt-in like the App Sandbox. Rather, all processes on the system, including those running as root, as subject to MAC. Data Vaults are not a third-party developer opportunity. See this post if you’re curious. In the Full Disk Access and Files and Folders case users grant a program a MAC privilege using System Preferences > Security & Privacy > Privacy. Some MAC privileges are per user (Files and Folders) and some are system wide (Full Disk Access). If you’re not sure, run this simple test: On a Mac with two users, log in as user A and enable the MAC privilege for a program. Now log in as user B. Does the program have the privilege? If a process tries to access an item restricted by MAC, the system may prompt the user to grant it access there and then. For example, if an app tries to access the desktop, you’ll see an alert like this: “AAA" would like to access files in your Desktop folder. [Don’t Allow] [OK] To customise this message, set properties in your Info.plist. See the Files and Folders topic on this page. This system only displays this alert once. It remembers the user’s initial choice and returns the same result thereafter. This relies on your code having a stable code signing identity. If your code is unsigned, or signed ad hoc (“Signed to run locally” in Xcode parlance), the system can’t tell that version N+1 of your code is the same as version N, and thus you’ll encounter excessive prompts. Note For information about how that works, see TN3127 Inside Code Signing: Requirements. The Files and Folders prompts only show up if the process is running in a GUI login session. If not, the operation is allowed or denied based on existing information. If there’s no existing information, the operation is denied by default. On managed systems the site admin can use the com.apple.TCC.configuration-profile-policy payload to assign MAC privileges. For testing purposes you can reset parts of TCC using the tccutil command-line tool. For general information about that tool, see its man page. For a list of TCC service names, see the posts on this thread. Note TCC stands for transparency, consent, and control. It’s the subsystem within macOS that manages the privileges visible in System Preferences > Security & Privacy > Privacy. TCC has no API surface, but you see its name in various places, including the above-mentioned configuration profile payload and command-line tool, and the name of its accompanying daemon, tccd. While tccutil is an easy way to do basic TCC testing, the most reliable way to test TCC is in a VM, restoring to a fresh snapshot between each test. If you want to try this out, crib ideas from Testing a Notarised Product. The MAC privilege mechanism is heavily dependent on the concept of responsible code. For example, if an app contains a helper tool and the helper tool triggers a MAC prompt, we want: The app’s name and usage description to appear in the alert. The user’s decision to be recorded for the whole app, not that specific helper tool. That decision to show up in System Preferences under the app’s name. For this to work the system must be able to tell that the app is the responsible code for the helper tool. The system has various heuristics to determine this and it works reasonably well in most cases. However, it’s possible to break this link. I haven’t fully research this but my experience is that this most often breaks when the child process does something ‘odd’ to break the link, such as trying to daemonise itself. Scripting MAC presents some serious challenges for scripting because scripts are run by interpreters and the system can’t distinguish file system operations done by the interpreter from those done by the script. For example, if you have a script that needs to manipulate files on your desktop, you wouldn’t want to give the interpreter that privilege because then any script could do that. The easiest solution to this problem is to package your script as a standalone program that MAC can use for its tracking. This may be easy or hard depending on the specific scripting environment. For example, AppleScript makes it easy to export a script as a signed app, but that’s not true for shell scripts. TCC and Main Executables TCC expects its bundled clients — apps, app extensions, and so on — to use a native main executable. That is, it expects the CFBundleExecutable property to be the name of a Mach-O executable. If your product uses a script as its main executable, you are likely to encounter TCC problems. To resolve these, switch to using a Mach-O executable. Revision History 2021-04-26 Added an explanation of the TCC initialism. Added a link to Viewing Sandbox Violation Reports.  Added the TCC and Main Executables section. Made significant editorial changes. 2022-01-10 Added a discussion of the file system hierarchy. 2021-04-26 First posted.
Posted
by eskimo.
Last updated
.
Post not yet marked as solved
1 Replies
252 Views
How do I get updates about the file name change from the NSDocument window title? I noticed that despite file being property registered as a file presenter (by default), none of presentedItemDidChange, presentedSubitemDidChange, or presentedItemDidMove is called despite filename updates on the filesystem. the presentedItemURL does update value at some point. My subclass has autosave enabled, which makes title editing possible. override class var autosavesInPlace: Bool { true } [object Object]
Posted Last updated
.
Post not yet marked as solved
3 Replies
309 Views
I'm working on a MacOS application built in Unity3D. I'm using a native file browser plugin to open native MacOS file dialogs for selecting files. In order to generate PDFs, my app relies on using Chromium's Headless/command line functionality. On Windows, I can easily get the path to the included Microsoft Edge as that's standard, but on Mac, unless I guess and check (which I already do), there isn't a way to guarantee a Mac user has a Chromium-based browser installed. So I intend on allowing the user to set the path manually by selecting the .app file with a file dialog. But even when I specify .app to be a valid extension, they still don't appear selectable. I assume this is some sort of MacOS-specific limitation or default permissions, though I can't find much info on this online. Using C#/DotNet s there any way of allowing this behavior as needed? For some more info: I'm just running the application using System.Diagnostics.Process.Start() with command line arguments. Based on my experiments searching for Google Chrome (though Edge or Opera are just as usable), the path I'm looking for is: /Applications/ {{APP NAME}}.app/Contents/MacOS/{{APP NAME}} Because Contents isn't accessible by most users, I figured I would just automatically go in and grab the binary with the correct name once I have the path to the .app file. I know I could include some lightweight version of ChromeDriver with my app, but I'd rather keep everything as self-contained as possible, especially as so many people already have Chrome (or Opera, Edge, etc) installed. The challenge is that not everyone has it installed in the same place, hence my need to make it customizable. Any ideas or help would be appreciated! Thanks!
Posted Last updated
.
Post not yet marked as solved
19 Replies
13k Views
To solve a dependency tangle on an app, I’m trying to write a simple command line tool that would display all the dependencies of a given app or library, and output it in a format suitable for post-processing by graphviz. The idea here is to collect and lay out the output of the otool -L utility, recursively called on all the dependencies of the target app/lib. Unfortunately, when I try otool -L with, say, otool itself, I get this: Dev > otool -L /usr/bin/otool /usr/bin/otool: /usr/lib/libxcselect.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1292.0.0) Fine. But now: otool -L /usr/lib/libxcselect.dylib /Library/Developer/CommandLineTools/usr/bin/objdump: error: '/usr/lib/libxcselect.dylib': No such file or directory Oops. Indeed, /usr/lib seems mostly empty, and most of what lies inside are links on missing (I assume: invisible) libs. So my question is: where are all the libs gone, and it is possible to bring them back to the surface?
Posted Last updated
.
Post marked as solved
2 Replies
303 Views
So I created a program without selecting “use core data” and realized after trying to make a persistence data storage that it helps very much so I created a new program and selected it this time and copied everything over. It provided a file called “Persistence” and the contentView file had a bunch of stuff already filled in (Also something called the title of the program). I have the data I need saved to the persistent data storage narrowed down to a singular array, but none of the videos I found online showed this version of xcode that supplied a “Persistence” file when using core data so I’m unsure how to use it. I will provide the contentView and Persistence file for context. The array I need saved is called mainList in contentView. ContentView: import SwiftUI import CoreData struct ContentView: View {     var mainList = [RecipeList(),RecipeList(),RecipeList(),RecipeList(),RecipeList()]          @Environment(\.managedObjectContext) private var viewContext     @FetchRequest(         sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],         animation: .default)     private var items: FetchedResults<Item>     var body: some View {         NavigationView {             List {                 ForEach(items) { item in                     NavigationLink {                         Text("Item at \(item.timestamp!, formatter: itemFormatter)")                     } label: {                         Text(item.timestamp!, formatter: itemFormatter)                     }                 }                 .onDelete(perform: deleteItems)             }             .toolbar {                 ToolbarItem(placement: .navigationBarTrailing) {                     EditButton()                 }                 ToolbarItem {                     Button(action: addItem) {                         Label("Add Item", systemImage: "plus")                     }                 }             }             Text("Select an item")         }     }     private func addItem() {         withAnimation {             let newItem = Item(context: viewContext)             newItem.timestamp = Date()             do {                 try viewContext.save()             } catch {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 let nsError = error as NSError                 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")             }         }     }     private func deleteItems(offsets: IndexSet) {         withAnimation {             offsets.map { items[$0] }.forEach(viewContext.delete)             do {                 try viewContext.save()             } catch {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 let nsError = error as NSError                 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")             }         }     } } private let itemFormatter: DateFormatter = {     let formatter = DateFormatter()     formatter.dateStyle = .short     formatter.timeStyle = .medium     return formatter }() struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)     } } Persistence: import CoreData struct PersistenceController {     static let shared = PersistenceController()     static var preview: PersistenceController = {         let result = PersistenceController(inMemory: true)         let viewContext = result.container.viewContext         for _ in 0..<10 {             let newItem = Item(context: viewContext)             newItem.timestamp = Date()         }         do {             try viewContext.save()         } catch {             // Replace this implementation with code to handle the error appropriately.             // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.             let nsError = error as NSError             fatalError("Unresolved error \(nsError), \(nsError.userInfo)")         }         return result     }()     let container: NSPersistentCloudKitContainer     init(inMemory: Bool = false) {         container = NSPersistentCloudKitContainer(name: "ReciStorage")         if inMemory {             container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")         }         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 /*                  Typical reasons for an error here include:                  * The parent directory does not exist, cannot be created, or disallows writing.                  * The persistent store is not accessible, due to permissions or data protection when the device is locked.                  * The device is out of space.                  * The store could not be migrated to the current model version.                  Check the error message to determine what the actual problem was.                  */                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })         container.viewContext.automaticallyMergesChangesFromParent = true     } } Image showing the thing named the title of the program that I’m certain is relevant to the persisting data storage: Also I’m unsure what I need to replace those comments with and what subclasses I should add to existing swift files like “codable” for example. Any help would be greatly appreciated.
Posted Last updated
.
Post not yet marked as solved
0 Replies
165 Views
I have a cloud storage app. Right now, saving files into it creates my app's folder in On my iPhone. Is it possible to have my app's folder outside of it, in Files app's Locations list? Just like I have other cloud providers like Dropbox, OneDrive etc(see image).
Posted
by faris997.
Last updated
.
Post not yet marked as solved
3 Replies
360 Views
I have a very simple program, which works python kivy. In that program I read and write json files. Everything is fine with every simulator in Xcode Version 13.4. However when I connect my Phone it can read the json file but can't write in it. It says; `File "/Users/batuhan/programs/kivy-ios/2800-ios/YourApp/main.py", line 429, in secom PermissionError: [Errno 1] Operation not permitted: '/private/var/containers/Bundle/Application/C2508051-03DA-40EC-8587-A40D8B922055/2800.app/YourApp/savelist1.json' 2022-05-19 20:14:09.322995+0300 2800[3486:1776834] Application quit abnormally! 2022-05-19 20:14:09.416628+0300 2800[3486:1776834] Leaving` As I understand so far it is all about build settings in Xcode. Because as MacBook user I can write in that json file in simulator and everything works perfect. I need to give permission to write json file for every user, staff or everyone. I am just a beginner in Xcode, I think it is related with those settings; The json file is in same directory with main.py
Posted Last updated
.
Post marked as solved
3 Replies
372 Views
Hi, I’m required to identify file content type (e.g. - tell you that a file is in PDF format, even if the user forced its name to end with .docX, .txt, or even removed it altogether. In other words - identify file type by its real contents. I need to do this fast, for lots of files.  I searched in vain through the MacOS different APIs/Frameworks, from LaunchServices, via MDLS, NSWorkspace, NSURL, and NSFileManager — to no avail. These all provide wonderful APIs for identifying file types - but miserably report the file type as “Microsoft Word” if its filename extension has been set to “.doc” or “.docx”, no matter the content. I then found the ‘file’ command-line in Terminal which does EXACTLY what I want, and reports the correct type every time (well maybe it fails somethings, but I haven’t seen it fail once so far.) Reading ‘man file’ I leaned that it examines a file in 3 stages. stat(2) to start with (identifying Unix things like pipes, sockets, symbolic links etc.) then, it works using some 'unix style' thing called “magic number” mechanism, that employs a “compiled magic file” /usr/share/file/magic.mgc containing “binary signatures” or special “magic numbers” at known offsets that allow quick identification of file formats. Tiny hacking into this file using ’strings’ command I found a rather huge list of formats identifiable by MacOS out of the box - plus - according to man page of file , you should be able to add more “magic” files yourself! However, I wouldn't want to spawn a 'file' command process every time I need to identify a file. I'd rather call some code, or framework from within my process. (This process is of high sensitivity - it is an "Endpoint Security Client" and has lots of restrictions. Is there any public API (Cocoa, Unix, Posix, Core-Foundation, anything!) that will use this "Magic" mechanism to tell me the type of a file? Thank you very much.
Posted
by suMac.
Last updated
.
Post not yet marked as solved
1 Replies
192 Views
I'm trying to get information about the current Mission Control Spaces, specifically the current space number. I can access this info by using "defaults read com.apple.spaces". The problem is that this info only seems to update when a new space is created or deleted. So if you read this and then change the current space or open a new window, that file will still be set to the previous space until a new space is created or deleted, which would then update the file. I can't see any other way to get this information. Is there any non-intrusive way to force the OS to update this plist file on demand (without relaunching the dock or Finder)? Or is there any other way to get the current space number any other way? Thanks
Posted
by coderkid.
Last updated
.
Post marked as solved
2 Replies
229 Views
Hello community! I created an app with a golang shared library which runs a mkdir command at start. The app is working properly on emulator but not on physical device, looks like the emulator is properly sandboxing (wrapping) the shared library but in my iPhone I get a permission denied error (probably due to the app trying to write on File system) How can I reproduce the same sandboxing approach on my physical iPhone as in the emulator? Below you can see how the path for each looks like: Emulator installation path(All goo here): /Users/simbadmarino/Library/Developer/CoreSimulator/Devices/E6258FFC-CA3F-4B7F-BAAE-DDF717096A91/data/Containers/Data/Application/6BA771DD-BE68-454A-926E-A525188CBE38/.btfs Phone installation path(Permission errors here): /private/var/mobile/Containers/Data/Application/CB3B300F-07D8-4641-A6FA-4F584D4C6530/.btfs
Posted Last updated
.
Post marked as solved
3 Replies
263 Views
Hi, I wanted to know what level of NSFileProtection is provided by default in iOS in the user's documents directory of application container. Basically, if I am creating a file in this location - NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); What level of protection among NSFileProtectionType is provided? `
Posted Last updated
.
Post not yet marked as solved
3 Replies
455 Views
In my app, I want to expose the documents directory of the app in files app. I have set UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace to YES in info.plist. This works perfectly while using iOS 14 simulator. But the same does not work on iOS 15 simulator. What is the fix for this issue?
Posted Last updated
.
Post not yet marked as solved
3 Replies
290 Views
Hello, I am trying to get a FileHandle for a specific file on an external hard disk. My app is sandboxed and in order to be able to get a FileHandle I am showing a NSOpenPanel so the user can grant permission to access this disk. After the user has granted permissions, I use the following code to get the handle: guard let readDescriptor = try? FileDescriptor.open(readUrl.path, FileDescriptor.AccessMode.readWrite) else { return } I get the following error when this code runs: The operation couldn’t be completed. Operation not permitted What I don't understand is the fact that this code only fails on disks that have the MS-DOS file system. I have tested various USB sticks, SD cards and external hard drives. It works fine for the APFS, but once I format the device as MS-DOS, the code fails. Has anyone any idea why that is? Regards, Sascha
Posted
by inexcitus.
Last updated
.