Load Web-Content Asynchronously - iphone

I am trying to load web content asynchronously. I have a large amount of web calls in my viewdidappear method and my app is very unresponsive. I understand the concepts of synchronous and asynchronous loading of content, but don't know how to tell if this is being done asynchronously. The code below is simply embedded in my viewdidappear method, and I assume it is loading synchronously. How would I edit this to make it load asynchronously? Thank you all!
NSString *strURLtwo = [NSString stringWithFormat:#"http://website.com/json.php?
id=%#&lat1=%#&lon1=%#",id, lat, lon];
NSData *dataURLtwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURLtwo]];
NSArray *readJsonArray = [NSJSONSerialization JSONObjectWithData:dataURLtwo options:0
error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];

You can use NSURLConnectionDelegate:
// Your public fetch method
-(void)fetchData
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://website.com/json.php?id=%#&lat1=%#&lon1=%#",id, lat, lon]];
// Put that URL into an NSURLRequest
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
connection = [[NSURLConnection alloc] initWithRequest:req
delegate:self
startImmediately:YES];
}
Implement the delegate methods:
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[jsonData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// All data is downloaded. Do your stuff with the data
NSArray *readJsonArray = [NSJSONSerialization jsonData options:0 error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
jsonData = nil;
connection = nil;
}
// Show AlertView if error
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
connection = nil;
jsonData = nil;
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}

For asynchronous web content loading, I recommend you to use AFNetworking . It'll solve lots of your major headache of networking in future. How to do:
1) subclass AFHTTPCLient, for example:
//WebClientHelper.h
#import "AFHTTPClient.h"
#interface WebClientHelper : AFHTTPClient{
}
+(WebClientHelper *)sharedClient;
#end
//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"
NSString *const gWebBaseURL = #"http://whateverBaseURL.com/";
#implementation WebClientHelper
+(WebClientHelper *)sharedClient
{
static WebClientHelper * _sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return self;
}
#end
2) Request asynchronously your web content, put this code in any relevant part
NSString *testNewsURL = #"http://whatever.com";
NSURL *url = [NSURL URLWithString:testNewsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operationHttp =
[[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"Response: %#", szResponse );
//PUT your code here
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Operation Error: %#", error.localizedDescription);
}];
[[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];

Related

How to assign values from NSMutableDictionary to NSArray

I am doing JSON parsing and I want to show my parsed data in a UITableView.
For that, I am trying to assign parsed data from NSMutableDictionary to NSArray to show in the table view but the array returns null.
Here my array returns null value;
NSMutableDictionary *tempDict1;
NSArray *arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
// NSArray *latestrates = [[responseString JSONValue] objectForKey:#"rates"];
[responseString release];
values = [responseString JSONValue];
array = [[NSMutableArray alloc] init];
array = [values valueForKey:#"rates"];
NSLog(#"array values:--> %#",array);
tempDict1 = (NSMutableDictionary *)array;
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
NSString *subStar = #"=";
NSMutableArray *arrTitle = [[NSMutableArray alloc] init];
NSMutableArray *arrValues = [[NSMutableArray alloc] init];
[arrTitle removeAllObjects];
[arrValues removeAllObjects];
for (int i=0; i<[arr count]-1; i++)
{
[arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])-1]];
[arrValues addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
NSLog(#"arrTitle is:--> %#",arrTitle);
}
tempDict1 = (NSMutableDictionary*)[array objectAtIndex:0];
array = [values valueForKey:#"rates"];
NSLog(#"tempDict--%#",tempDict1);
[arr retain];
[tbl_withData reloadData];
}
Try editing fourth line in connectionDidFinishLoading to
values = [responseString JSONFragments];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Your data - %#",array);
Now you can get it according to data format.
EDIT
I think you also dont know how to get a webResponse.
So here is a way to get webResponse -
First set XML delegate in your ViewController.h class
and declare a NSMutableData globaly
#interface ViewController : UIViewController<NSXMLParserDelegate>
#property(nonatomic, retain)NSMutableData *responseData;
#end
Now synthesized this responseData in your ViewController.m class
#synthesize responseData = _responseData;
Now you can send request on server in viewDidLoad: method its up to you in which method you want to send it.
-(void)viewDidLoad
{
NSString *urlString = [NSString stringWithFormat:#"http://EnterYourURLHere"];
NSURL *URL = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]init];
[urlRequest setURL:URL];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-type"];
NSURLConnection *urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
if(!urlConnection)
{
[[[UIAlertView alloc]initWithTitle:#"OOoopppssS !!" message:#"There is an error occured. Please check your internet connection or try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
}
#pragma mark - Parsing delegate methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.responseData = [[NSMutableData alloc]init];
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Now parse your data here -
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Your data - %#",array);
}

how to use twitter user search api in MGTwitterengine iphone

I am using MGtwitterengine in iPhone , I want to use USER search API http://api.twitter.com/1/users/search.json?q={username} but I don't find any method for this in MGTwitterengine. how can I use this API in iphone to get users.
Thanks
Use like This :-
- (void)searchforTwUser {
OAToken *access_token = [[OAToken alloc] initWithKey:[tEngine oauthKey] secret:[tEngine oauthSecret]];
OAConsumer *aconsumer = [[OAConsumer alloc] initWithKey:kOAuthConsumerKey
secret:kOAuthConsumerSecret];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
NSString *spaceString=#" ";
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:self.searchName] invertedSet];
if ([spaceString rangeOfCharacterFromSet:set].location == NSNotFound)
{
NSString *Name = [self.searchName stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1/users/search.json?q=%#",Name]];
NSLog(#"search name 1 is ..................................... %#",url);
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:aconsumer token:access_token realm:nil
signatureProvider:nil];
[request setHTTPMethod:#"GET"];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(searchTicket:didFinishWithData:)
didFailSelector:#selector(searchTicket:didFailWithError:)];
[request release];
}
else
{
NSString *addStr = #"%20";
NSString *firstCapChar = [[searchName substringToIndex:1] capitalizedString];
NSString *cappedString = [searchName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1/users/search.json?q=%#%#",cappedString,addStr]];
NSLog(#"search name 2 is ..................................... %#",url);
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:aconsumer token:access_token realm:nil
signatureProvider:nil];
[request setHTTPMethod:#"GET"];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(searchTicket:didFinishWithData:)
didFailSelector:#selector(searchTicket:didFailWithError:)];
[request release];
}
[access_token release];
[aconsumer release];
}
- (void) searchTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dict = [response objectFromJSONString];
NSLog(#"Dict %#",dict);
[twSearchArray removeAllObjects];
if (twSearchArray != nil) {
[twSearchArray release];
twSearchArray = nil;
}
twSearchArray = (NSMutableArray *)dict;
NSLog(#"Twitter %#",twSearchArray);
self.twLoaded = YES;
[twSearchArray retain];
[self prepareSearchResults];
[response release];
}
- (void) searchTicket:(OAServiceTicket *)ticket didFailWithError:(NSData *)error {
NSLog(#"Errors is %#",error.description);
}

iPhone - How to download big amount of files

I need to download a number of files from the server. What is the best way to do it?
All documents are stored in NSMutableArray and for each documents there are two files - the document itself and its change log. So what I do is:
- (void)downloadDocuments:(int)docNumber
{
NSString *urlString;
NSURL *url;
for (int i=0; i<[items count]; i++) {
[progressBar setProgress:((float)i/[items count]) animated:YES];
urlString = [[items objectAtIndex:i] docUrl];
url = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
[self downloadSingleDocument:url];
urlString = [[items objectAtIndex:i] changeLogUrl];
url = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
[self downloadSingleDocument:url];
}
urlString = nil;
url = nil;
[self dismissModalViewControllerAnimated:YES];
}
- (void)downloadSingleDocument:(NSURL *)url
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req addValue:#"Basic XXXXXXX=" forHTTPHeaderField:#"Authorization"];
downloadConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response
{
if (conn == downloadConnection) {
NSString *filename = [[conn.originalRequest.URL absoluteString] lastPathComponent];
filename = [filename stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:filename];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
file = [[NSFileHandle fileHandleForUpdatingAtPath:filePath] retain];
if (file)
{
[file seekToEndOfFile];
}
}
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
if (conn == downloadConnection) {
if (file) {
[file seekToEndOfFile];
}
[file writeData:data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
if (conn==downloadConnection) {
[file closeFile];
}
}
And my problem is that only the last file is downloaded. Any suggestions on what I am doing wrong?
Thanks in advance for help!
The problem is that you "overwrite" the member var "downloadConnection" within your loop with a new instance of NSURLConnection (through method call downloadSingleDocument). Doing this leads to the case that the if-statements within your didReceiveResponse, didReceiveData and connectionDidFinish methods will only evaluate to true with the latest created connection. Try using a list of connections to avoid this.

How to download CSV file from server in Objective-C

I'm developing a new iPhone application, Here i have parsed a 'csv' file from local, and its working with me. When i try to download the 'csv' file from the server programmatically, it didn't workout for me. Could you please help me?
Loading data from local file (Working fine)
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * file = [[NSBundle bundleForClass:[self class]] pathForResource:#"sample" ofType:#"csv"];
NSStringEncoding encoding = 0;
NSString * csv = [NSString stringWithContentsOfFile:file usedEncoding:&encoding error:nil];
NSArray *fields = [csv CSVComponents];
NSLog(#"fields: %#", fields); //getting the result content
}
Download the file from Server (failed)
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading"); //nothing showing here
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullName = [NSString stringWithFormat:#"quotes.csv"];
NSString *fullFilePath = [NSString stringWithFormat:#"%#/%#",docDir,fullName];
[receivedData writeToFile:fullFilePath atomically:YES];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"data: %#", data); //nothing showing here
if (receivedData)
[receivedData appendData:data];
else
receivedData = [[NSMutableData alloc] initWithData:data];
}
- (void)loadDatafromURL
{
NSURL *url = [NSURL URLWithString:#"http://download.finance.yahoo.com/d/quotes.csv?s=^GSPC,^IXIC,^dji,^GSPC,^BVSP,^GSPTSE,^FTSE,^GDAXI,^FCHI,^STOXX50E,^AEX,^IBEX,^SSMI,^N225,^AXJO,^HSI,^NSEI&f=sl1d1t1c1ohgv&e=.csv"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
Implement this method:
-(void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
You'll find that you're getting an error of
Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xf663f40 {NSUnderlyingError=0xf663de0 "bad URL", NSLocalizedDescription=bad URL}
I've looked into downloading information this way before, and I think one problem you're having is that separate symbols have to be separated with a "+". Also, when pulling an index, you can't pass the "^" symbol as part of the URL. You have to replace it with "%5E".
So, add this:
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"%#", [error description]);
}
And change your URL to this:
NSString *urlString = #"http://download.finance.yahoo.com/d/quotes.csv?s=^GSPC+^IXIC+^dji+^GSPC+^BVSP+^GSPTSE+^FTSE+^GDAXI+^FCHI+^STOXX50E+^AEX+^IBEX+^SSMI+^N225+^AXJO+^HSI+^NSEI&f=sl1d1t1c1ohgv&e=.csv";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
Now it works for me! I even checked the output .csv file, and it looks good to go! One full quote per line.
If you plan on fetching more data over the network than this single csv, you could have a look at AFNetworking, it's a great library for doing network operations.
A working solution would then look a bit like this:
- (void)getCSVAsynch {
NSString *unescaped = #"http://download.finance.yahoo.com/d/quotes.csv?s=^GSPC,^IXIC,^dji,^GSPC,^BVSP,^GSPTSE,^FTSE,^GDAXI,^FCHI,^STOXX50E,^AEX,^IBEX,^SSMI,^N225,^AXJO,^HSI,^NSEI&f=sl1d1t1c1ohgv&e=.csv";
NSURL *url = [NSURL URLWithString:[unescaped stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"CSV: %#", [[NSString alloc] initWithBytes:[responseObject bytes] length:[responseObject length] encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Things go boom. %#", [error localizedDescription]);
}];
[operation start];
}

Show kml data? No,instead the Map is going to location (0,0)

I am using the code in this question NSURLConnection download large file (>40MB) to download a KML file and load the data in my MKMap using the KMLViewer of Apple.KML files are small <200KB so KMLViewer is just fine.The code provided in the question should be fine too exept the fact that when the I click the button (that should make the request of the url and then load the data in the map) the map just goes to location 0,0 ,zooming tremendously and so all I can see is a black map.What is going wrong? What should I do?
Here is the code:
(By the way, I have two connections, because one uses JSON to get Google search results for locations from a UIsearchBar.)
EDIT 1
//In the ViewController.m
-(void) searchCoordinatesForAddress:(NSString *)inAddress //for Google location search
{
NSMutableString *urlString = [NSMutableString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#?output=json",inAddress];
[urlString setString:[urlString stringByReplacingOccurrencesOfString:#" " withString:#"+"]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0]; //webData in the header file
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if ( connection = theConnection ) //theConnection is created before
{
[webData appendData:data];
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
NSArray *placemark = [results objectForKey:#"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:#"Point.coordinates"];
double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];
NSLog(#"Latitude - Longitude: %f %f", latitude, longitude);
[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
[jsonString release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#" Error in writing file %#' : \n %# ", filePath , writeError );
return;
}
NSLog(#"%#",fileURL);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error !" message:#"Error has occured, please verify internet connection.." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
-(IBAction)showKmlData:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"KMLGenerator" ofType:#"kml"];
kml = [[KMLParser parseKMLAtPath:path] retain];
NSArray *overlays = [kml overlays];
[mapview addOverlays:overlays];
NSArray *annotations = [kml points];
[mapview addAnnotations:annotations];
MKMapRect flyTo = MKMapRectNull;
for (id <MKOverlay> overlay in overlays) {
if (MKMapRectIsNull(flyTo)) {
flyTo = [overlay boundingMapRect];
} else {
flyTo = MKMapRectUnion(flyTo, [overlay boundingMapRect]);
}
}
for (id <MKAnnotation> annotation in annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
mapview.visibleMapRect = flyTo;
}
EDIT 2 I have done modifications,now it doesn't go anywhere, it crashes because it doesn't find KMLGenerator.kml file (path)
-(void)showData
{
NSString *url = /*kmlStr;*/#"http://www.ikub.al/hartav2/handlers/kmlgenerator.ashx?layerid=fc77a5e6-5985-4dd1-9309-f026d7349064&kml=1";
NSURL *path = [NSURL URLWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:path];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
theConnection = connection;
[connection release];
[request release];
}
//Search Coordinates for address entered in the searchBar
-(void) searchCoordinatesForAddress:(NSString *)inAddress
{
NSMutableString *urlString = [NSMutableString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#?output=json",inAddress];
[urlString setString:[urlString stringByReplacingOccurrencesOfString:#" " withString:#"+"]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0]; //Here i get an alert: NSData may not respond to -setLength
//webData is a NSData object.
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data]; //Here i get an alert: NSData may not respond to -appendData
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
if ( connection == theConnection ) //"theConnection" is for kml file download
{
NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#" Error in writing file %#' : \n %# ", filePath , writeError );
return;
}
NSLog(#"%#",fileURL);
}
else //it's a geocoding result
{
NSString *jsonString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
//check the Google geocode error code before looking for coordinates...
NSDictionary *statusDict = [results objectForKey:#"Status"];
NSNumber *errorCode = [statusDict objectForKey:#"code"];
if ([errorCode intValue] == 200) //200 is "success"
{
NSArray *placemark = [results objectForKey:#"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:#"Point.coordinates"];
double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];
NSLog(#"Latitude - Longitude: %f %f", latitude, longitude);
[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
}
else
{
NSLog(#"geocoding error %#", errorCode);
}
[jsonString release];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:#"Error has occured, please verify internet connection..." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (IBAction)showKmlData:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"KMLGenerator" ofType:#"kml"];
kml = [[KMLParser parseKMLAtPath:path] retain];
NSArray *annotationsImmut = [kml points];
NSMutableArray *annotations = [annotationsImmut mutableCopy];
//[mapview addAnnotations:annotations];
[self filterAnnotations:annotations];
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
mapview.visibleMapRect = flyTo;
}
It's still hard to pinpoint the cause but there are some problems with the code you posted.
First, in didReceiveData, this line is probably not what you want:
if ( connection = theConnection ) //theConnection is created before
The single = is doing an assignment instead of an equality check (which is ==).
Fixing that, however, is not the solution (the other problem is in connectionDidFinishLoading).
The didReceiveData method is not the right place to process your geocoding JSON result. The didReceiveData method can be called multiple times for a single url request. So it's possible that the geocoding results (just like the kml file) may be delivered in multiple chunks which cannot be processed individually in that method. The data in that method may be a partial stream of the complete result which will not make sense to process. You should only be appending the data to an NSMutableData object or, as an answer to the linked question suggests, write the data to a file.
The data can only be processed/parsed in the connectionDidFinishLoading method.
Since you are using the same connection delegate for both the kml file download and the geocoding, they both call the same connectionDidFinishLoading method. In that method, you are not checking which connection it is being called for.
When the geocoding url request finishes and calls connectionDidFinishLoading, that method takes whatever is in webData (possibly the geocoding results or empty data) and writes it to the kmlStr file. This is probably what causes the kml data to show "nothing".
You have to move the processing of the geocoding results to connectionDidFinishLoading and check there what connection is calling it.
For example:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
if ( connection == theConnection ) //"theConnection" is for kml file download
{
NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#" Error in writing file %#' : \n %# ", filePath , writeError );
return;
}
NSLog(#"%#",fileURL);
}
else //it's a geocoding result
{
NSString *jsonString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
//check the Google geocode error code before looking for coordinates...
NSDictionary *statusDict = [results objectForKey:#"Status"];
NSNumber *errorCode = [statusDict objectForKey:#"code"];
if ([errorCode intValue] == 200) //200 is "success"
{
NSArray *placemark = [results objectForKey:#"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:#"Point.coordinates"];
double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];
NSLog(#"Latitude - Longitude: %f %f", latitude, longitude);
[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
}
else
{
NSLog(#"geocoding error %#", errorCode);
}
[jsonString release];
}
}
(It's probably better to avoid using the same delegate for multiple connections. It would be cleaner to move the geocoding out to another class with its own connection object and delegate methods. By the way, iOS5 has geocoding built-in so you don't need to do this yourself. See the CLGeocoder class.)
I added a check for the Google error code. It's possible the address queried returns no results in which case there will be no placemark coordinates in which case the latitude and longitude will get set to zero. This is another possible cause of the map going to 0,0.
It also seems you are using the deprecated v2 Google geocoder. This is the latest one but you may want to switch to using CLGeocoder instead unless you need to support iOS4 or earlier.