NSFileManager
's URLForDirectory is how you can find the location of things like the user's Documents directory. The domain is what domain, like NSDocumentDirectory, NSUserDomainMask will give you the URL to the iOS sandbox for your app's user files. appropriateForURL
is is advanced - mainly of use if you're going to be doing an atomic swap of files.
In Swift 4:
let fm = FileManager() do { let documentDirectoryURL = try fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) // use documentDirectoryURL } catch { // handle error as you see fit }ObjC:
NSFileManager *fm = [NSFileManager defaultManager]; NSError *error; NSURL *localDocumentDirectory = [fm URLForDirectory: NSDocumentDirectory inDomain: NSUserDomainMask appropriateForURL: nil create: YES error: &error]; if (localDocumentDirectory == nil) { // never compare error == nil NSLog (@"could not url for directory, dude - %@", error); }(looking how to do it with paths? )
NSURL *mediaDirectory = ...; NSArray *contents = [fm contentsOfDirectoryAtURL: mediaDirectory includingPropertiesForKeys: @[] options: 0 error: &error]; if (contents == nil) { NSLog (@"could not contents of %@ - %@", mediaDirectory, error); return nil; }There's also
enumeratorAtURL:includingPropertiesForKeys:...
that gives you back a directory enumerator.NSString *filename = @"/my/original/file/name"; NSString *tildeFilename; tildeFilename = [NSString stringWithFormat: @"%@~", filename]; // remove it first, otherwise the move will fail [defaultManager removeFileAtPath: tildeFilename handler: nil]; // now rename the file [defaultManager movePath: filename toPath: tildeFilename handler: nil];If you want to stick the tidle before the file extension (so the finder could open
ook~.tiff
), try this:
NSString *pathExtension = [filename pathExtension]; if (!pathExtension) { tildeFilename = [filename stringByAppendingString: @"~"]; } else { tildeFilename = [NSString stringWithFormat: @"%@~.%@", [filename stringByDeletingPathExtension], pathExtension]; }(Thanks to Peter Hosey for this one)
NSFileManager *defaultManager; defaultManager = [NSFileManager defaultManager]; [defaultManager removeFileAtPath: tildeFilename handler: nil];The handler is an object that will be sent message, like
fileManager:shouldProceedAfterError:
if something goes wrong during the removal.NSString *filename = @"/this/is/my/file/name"; NSData *data = // get NSData from somewhere, like NSPropertyListSerialization [data writeToFile: filename atomically: NO];