Search code examples
iosobjective-cplistnsdatansurl

Plist From URL to NSMutableArray


I have the code below:

//Find device directory
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString  *documentsDirectory = [paths objectAtIndex:0];
            //Define file name
            NSString * fileName = [file objectForKey: (id) kCFFTPResourceName];
            //File path to file
            NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,fileName];
            //Download Plist from server and write to 'filePath'
            [[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://url.net/directory/%@",[file objectForKey: (id) kCFFTPResourceName]]]] writeToFile:filePath atomically:YES];
            //Load Plist from directory
            NSURL *url = [NSURL URLWithString:filePath];
            //Load Data into Array
            mapDetails = [[NSMutableArray alloc ] initWithContentsOfURL:url];

            NSLog(@"Here is the Dict %@",mapDetails);

My issue is, is that array is being returned as 'nil', what's my issue??

I've tried various combinations and still can't get the strings in the PLIST into an NSMutableArray.


Solution

  • [noSpaces stringByReplacingOccurrencesOfString:@"plist" withString:@""]; returns a new NSString. It doesn't change noSpaces.

    Change these two lines:

    [noSpaces stringByReplacingOccurrencesOfString:@"plist" withString:@""];
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:noSpaces withExtension:@"plist"];
    

    to:

    NSURL *url = [[NSBundle mainBundle] URLForResource:[noSpaces stringByReplacingOccurrencesOfString:@".plist" withString:@""] withExtension:@"plist"];
    

    Update: why don't you use filePath to read the content to NSMutableArray?

    NSURL *url = [NSURL URLWithString:filePath];
    

    Note:

    1) [[NSBundle mainBundle] URLForResource: withExtension:] is used to find resource built into your application. 2) If the content of the file is not be able to parsed to an array, you'll still get nil.

    This assumes the file location is correct. If what you do is load the remote URL and save the content to a plist file, then read it, you should make sure 1) the content is saved to the file successfully, 2) the path to load it is correct, 3) file content could be parsed to array.