Get String From Text File
- (NSString *)GetTextFile
{
NSString *urlString = @"http://mydomain.com/my_file.txt";
NSURL *url = [NSURL URLWithString:urlString];
return [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
}
The above works great, but if the iOS device has a WiFi connection but no internet connectivity or if the server is not responding it will lock up indefinately. Use the below to deal with this
Get String From Text File With Timeout
This can also be a really good do we have connectivity test in place of things like "if (![self.reachability isReachable])" which can simply lock up if there is no internect connectivity
//----- TRY AND DOWNLOAD FILE WITH TIMEOUT -----
//This avoids lockup if we have WiFi connectivity but can't reach the server for any reason
NSString *urlString = @"http://www.mydomain.com/some_file.txt";
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:3.0]; //Set timeout
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString* stringFromServer = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //autorelease];
return stringFromServer; //stringFromServer will be @"" if file could not be retrieved due to no server response, no internet connectivity or if WiFi and GSM are not connected.