How to save file in the documents folder?

后端 未结 4 1136
半阙折子戏
半阙折子戏 2020-12-06 14:54

I am trying to save data in the documents folder on iPhone 5.1 simulator.

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDo         


        
4条回答
  •  死守一世寂寞
    2020-12-06 15:18

    Maybe because you have not created the file, the file you tested does not exist. :)

    You can do this to find the problem,

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"myData.json"];
    NSLog(@"filePath %@", filePath);
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { // if file is not exist, create it.
        NSString *helloStr = @"hello world";
        NSError *error;
        [helloStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    }
    
    if ([[NSFileManager defaultManager] isWritableFileAtPath:filePath]) {
        NSLog(@"Writable");
    }else {
        NSLog(@"Not Writable");
    }
    

提交回复
热议问题