Search code examples
iosios8writetofile

Cannot writeToFile toFullPath in iOS 8 issue


I have an issue that I cannot save in iOS 8 while it is working fine in iOS 7. Please where would be my issue?

.h       
    NSMutableArray *selected;


.m
    - (void)saveSelected
    {
        if (![selected writeToFile:[SettingVO toFullPath:@"selected"] atomically:YES])
        {
            NSLog(@"Could not save selected!!! %@", selectedParitems);
        }
    }

Update: I have include toFullPath method and I debugged it. I found that with iOS 7 it is not passing throw if fileMgr and working fine while with iOS 8 it returns nil. I hope this helps.

+ (NSString *)toFullPath:(NSString *)path
{
    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    NSURL *url = [NSURL fileURLWithPath:bundlePath];
    NSMutableArray *components = [NSMutableArray arrayWithArray:[url pathComponents]];
    [components removeLastObject];
    [components addObject:@"Documents"];
    [components addObject:@"data"];

    NSString *fullPath = [NSString pathWithComponents:components];

    NSFileManager *fileMgr = [NSFileManager defaultManager];
    if ( ![fileMgr fileExistsAtPath:fullPath isDirectory:NULL] )
    {
        if ([fileMgr createDirectoryAtPath:fullPath withIntermediateDirectories:NO attributes:nil error:nil])
        {
            //--N-SLog(@"+ Items directory created.");
        }
        else
        {
            //--N-SLog(@"- Couldn't create Items directory!!!");
            return nil;
        }
    }

    return [fullPath stringByAppendingPathComponent:path];
}

Solution

  • Don't use the bundle path if you want to find a writable location. That points to the application, which is read-only.

    Use...

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths firstObject];
    if (path) {
        //  ...
    }
    

    ...to get the base document path.