Friday, May 31, 2013

NSArray initWithContentsOfURL example in Objective C (iOS).


NSArray initWithContentsOfURL

Initializes a newly allocated array with the contents of the location specified by a given URL.

- (id)initWithContentsOfURL:(NSURL *)aURL

Parameters
aURL
The location of a file containing a string representation of an array produced by the writeToURL:atomically: method.

Return Value of [NSArray initWithContentsOfURL]
An array initialized to contain the contents specified by aURL. Returns nil if the location can’t be opened or if the contents of the location can’t be parsed into an array. The returned object might be different than the original receiver.

Discussion of [NSArray initWithContentsOfURL]
The array representation at the location identified by aURL must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects). The objects contained by this array are immutable, even if the array is mutable.

NSArray initWithContentsOfURL example.
-(void)readPlistFromServerAndSaveToDocs
{
    //save plist from server to docs:
    NSArray *tempArr1 = [[NSArray alloc]initWithContentsOfURL:
                         [NSURL URLWithString:@\"http://dl.dropbox.com/u/4082823/AppsFiles/Black/stores.plist\"]];
    NSString *error;
    NSString *rootPath =
    [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *plistPath = [rootPath stringByAppendingPathComponent:@\"stores.plist\"];
    NSArray *tmpArr = [NSArray arrayWithArray:tempArr1];
    NSData *tmpData = [NSPropertyListSerialization dataFromPropertyList:tmpArr
                                                                 format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
   
    NSLog(@\"plistPath=%@\",plistPath);
   
    if(tmpData)
    {
        [tmpData writeToFile:plistPath atomically:YES];
    }
   
    else
    {
        NSLog(@\"%@\",error);
    }
}

Example of [NSArray initWithContentsOfURL].
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.warpstudio.se/PizzaItems.plist"]];
    AFPropertyListRequestOperation *operation = [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
       
        pArray = [[NSMutableArray alloc] initWithContentsOfURL:request];
       
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
 

End of NSArray initWithContentsOfURL example article.