简体   繁体   中英

Save file in iOS application directory

I have a an app in both Android and iOS, the app is supposed to download and save some files on the device with a click of a button. I manage the directories in Android, and I specify the url of the file with this :

Environment.getExternalStorageDirectory().getPath() + "/appDirectory/" + fileName

I wanted to ask what is similar way to specify this in Objective c and iOS.
Right now I use this in objective-c:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask,YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@%@", documentDirectory, @"/myfile.mp4"];

filePath will return something like this:

/var/mobile/Applications/CFEDE74F0A493-499B/Library/Documentation/myfile.mp4


is this the right way?
Thanks very much

For the most part, you've got the right idea. Apple recommends to use NSURL-based file system methods so with that in mind, you can do the following:

NSError *error = nil;
NSURL *documentDirectory = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
if (!documentDirectory) {
    // Check error
}
NSURL *fileURL = [documentDirectory URLByAppendingPathComponent:@"myfile.mp4"];

If you need an NSString-based method, you should use built-in method for appending path components instead of using stringWithFormat:

NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *fileURL           = [documentDirectory stringByAppendingPathComponent:@"myfile.mp4"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM