NSFileManager Archives

How to list the contents of an NSURL

On the iOS simulator we have the luxury of peeking inside our virtual devices with the Finder. We can do this by heading over to the Finder, holding down Option and clicking Go. This will bring up the Library, in which you can navigate to Application Support / iPhone Simulator / 7.0 / Applications / […]

How to copy a file from the Main Bundle into the Documents Directory in iOS

You can do this either by using paths or NSURLs. Apple recommends using NSURLs, so here’s how it works. In this example we’re copying a file called “Amy.png” which exists in the app’s main bundle. // file URL in our bundle NSURL *fileFromBundle = [[NSBundle mainBundle]URLForResource:@”Amy” withExtension:@”png”]; // Destination URL NSURL *destinationURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:@”Amy.png”]; […]

How to delete a file

Once you have a reference to the file in question you can call the removeItemAtPath method: // get reference with path and filename NSString *filePath = [[NSString alloc]initWithFormat:@”Documents/myFile.txt”]; NSString *deleteThis = [NSHomeDirectory()stringByAppendingPathComponent:filePath]; // now delete the file [[NSFileManager defaultManager]removeItemAtPath:deleteThis error:nil]; This does not work with wildcards in the file name (for example *.jpg).

How to test if a file exists

Imagine we had a file that we’ve saved: NSString *myFile = [NSHomeDirectory() stringByAppendingPathComponent:@”Documents/myFile.txt”]; Before accessing it we can determine if it exists or not: BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[NSHomeDirectory()stringByAppendingPathComponent:myFile]];

How to save a UIImage

// let’s save our image as a JPG NSData *imageData = UIImageJPEGRepresentation(chosenImage, 1); // get our home directory and add the save path and file name NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:@”Documents/myImage.jpg”]; // then write the file to disk [imageData writeToFile:imagePath atomically:YES];