Getting bundle file references / paths at app launch

后端 未结 4 1960
走了就别回头了
走了就别回头了 2021-01-03 18:18

Suppose I have an arbitrary set of files included in the Main App Bundle. I would like to fetch the file URLs for those at launch and store them somewhere. Is this possible

4条回答
  •  一整个雨季
    2021-01-03 19:07

    You can get the URL of a file in the main bundle using

    NSString *path = [[NSBundle mainBundle] pathForResource:@"SomeFile" ofType:@"jpeg"];
    NSURL *url = [NSURL fileURLWithPath:path];
    

    You can write this URL to, for example, a property list file in the Documents directory:

    NSString *docsDir = [NSSearchForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *plistPath = [docsDir stringByAppendingPathComponent:@"Files.plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[url absoluteString] forKey:@"SomeFile.jpeg"];
    [dict writeToFile:plistPath atomically:YES];
    

    If you don't know the names of the files and you just want to list all the files in the bundle, use

    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
    for (NSString *fileName in files) {
        NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
        NSURL *url = [NSURL fileURLWithPath:path];
        // do something with `url`
    }
    

提交回复
热议问题