I am developing an application which retrieves its data from a plist located on my webserver. Therefore the application is dependent on a network connection. I want the user to be able to use my application when offline and therefore I am saving a copy of the plist on the users device every time the application is loaded with network connection. From there, I read the data from the plist located on the device.
I am having troubles, though. I am starting the download of the data in didFinishLaunchingWithOptions
method of the AppDelegate. This is done like this:
if(hasConnection) { // returns TRUE or FALSE based on Apple's example on checking network reachability
NSLog(@"Starting download of data.");
// loading using NSURLConnection
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:FETCH_URL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// create the connection with the reque开发者_开发百科st
// and start loading the data
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
}
}
Then I add the data to my plist Bands.plist
in connectionDidFinishLoading
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// throw data into a property list (plist)
NSMutableArray *tmpArray = [NSPropertyListSerialization propertyListFromData:receivedData mutabilityOption:NSPropertyListMutableContainers format:nil errorDescription:nil];
NSMutableArray *plistArray = [[NSMutableArray alloc] initWithArray:tmpArray];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Bands.plist"];
[plistArray writeToFile:path atomically:YES];
[plistArray release];
// release the connection, and the data object
[connection release];
[receivedData release];
}
But when loading the application for the first time, it crashes. I believe this is due to the application trying to reach this data even though it is not yet saved. If I remove the part that tries to reach the data saved locally, I have no problem. Neither do I have a problem if I add it again and restart the application (second load).
Does anyone have an idea how to fix this issue?
It is as if my application tries to load and handle data which does not yet exist.
Simply try checking for the existence of the plist first:
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
... // read the data, etc.
}
else {
... // don't try to read it
}
Cheers,
Sascha
精彩评论