views:

1300

answers:

1

I have a servlet that serves up a plist XML file. What's the best way to slup this into an NSDictionary? I have this basically working with:

NSDictionary* dict = [ [ NSDictionary alloc] initWithContentsOfURL:
      [NSURL URLWithString: @"http://example.com/blah"] ];

But then I have no control over the timeout; I'd rather not have my UI hang for 60 seconds just because the server (which I may not control) is having a hissy fit. I know about NSURLRequest, which will let me do the following:

NSURLRequest *theRequest=[NSURLRequest requestWithURL:
         [NSURL URLWithString: @"http://example.com/blah"
                  cachePolicy:NSURLRequestUseProtocolCachePolicy
          timeoutInterval:5 ];

But I don't quite see how to feed that to NSDictionary.

+3  A: 

You need to do this using the asynchronous methods. Start with this answer/post:

http://stackoverflow.com/questions/319463/can-i-make-post-or-get-requests-from-an-iphone-application/322573#322573

This will get you your data and place it in a varibale: responseData. Now you need to add your code to convert it to a NSDictionary in the following method:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

I've found 2 possible ways to convert NSData to NSDictionary. This way is straight from the Apple Archives and Serializations Guide.

NSString *errorStr = nil;
NSPropertyListFormat format; 

NSDictionary *dictionary = [NSPropertyListSerialization propertyListFromData: responseData
                mutabilityOption: NSPropertyListImmutable
                format: &format
                errorDescription: &errorStr];

Second:

NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSDictionary *dictionary = [string propertyList];
[string release];
Corey Floyd