Forward geocoding doesnt give correct results - ios

I didn't get correct results for Forward geocoding in certain cases. When I search for some places or hotel it shows result of some others places or areas. I have got following code. I study the following link. What url should i place to get correct results.
how can we implement the following given in following site
https://developers.google.com/places/webservice/autocomplete
A request for addresses containing "Vict" with results in French:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=geocode&language=fr&key=API_KEY
A request for cities containing "Vict" with results in Brazilian
Portuguese:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=(cities)&language=pt_BR&key=API_KEY
I have implemented following but it doesn't give the results as i aspected
- (CLLocationCoordinate2D)addressLocation{
NSError *error = nil;
// NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true", SearchtextField];
// NSString *API_KEY=#"AIzaSyB27SkGBzvEYKcxvZ5nmOVWvrA-6Xqf-7A";
NSString *API_KEY=#"AIzaSyCHcqJcqZbP1XpU-WB4VfRct5hpdgqisSY";
NSString *lookUpString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?address=%#&region=np&key=%#", SearchtextField,API_KEY];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
NSArray *locationArray = [[[jsonDict valueForKey:#"results"] valueForKey:#"geometry"] valueForKey:#"location"];
NSString *statusString = [jsonDict valueForKey:#"status"];
if ([statusString isEqualToString:#"OK"])
{
locationArray = [locationArray objectAtIndex:0];
Str_Latitude= [locationArray valueForKey:#"lat"];
Str_Longitude= [locationArray valueForKey:#"lng"];
NSLog(#"LatitudeString:%# & LongitudeString:%#", Str_Latitude, Str_Longitude);
/*Google place latitude Longitude*/
Arr_LatLong = #[Str_Latitude,Str_Longitude];
[[NSUserDefaults standardUserDefaults] setValue:Str_Latitude forKey:#"Str_Latitude"];
[[NSUserDefaults standardUserDefaults] setValue:Str_Longitude forKey:#"Str_Longitude"];
[[NSUserDefaults standardUserDefaults] synchronize];
GogLatitude = [Str_Latitude doubleValue];
Goglongitude = [Str_Longitude doubleValue];
if (Bool_SearchField) {
[self getGoogleAddress];
Bool_SearchField=FALSE;
}else{
}
}else{
UIAlertView *alertview =[[UIAlertView alloc] initWithTitle:#"Address not found" message:#"make sure you enter a valid address" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertview show];
NSLog(#"Something went wrong, couldn't find address");
[self.tableView reloadData];
}
GogLocation.latitude = GogLatitude;
GogLocation.longitude = Goglongitude;
return GogLocation;
}
When i search for radission in maps.google.com it shows as below
But when i search in my app it shows different locations then what I search

You can either take use of the Region Biasing, which according to wiki, should be NP. So add &region=np at the end of your query.
Or you can use the Viewport Biasing to set the bounds of your searches.

I have done what you have asked in one of my apps, but the url is different.
I am posting the function that gets called each time i input something in a text field.
-(void) startAutocomplete{
NSString* baseUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?input=%#&key=AIzaSyDz3HAmNY8NsgIhtA8gtbH-QA08Lg9tej4&types=all", self.locationTextfield.text];
NSURL *url = [NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"Url: %#", url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError!=nil) {
[[[UIAlertView alloc] initWithTitle:nil message:connectionError.localizedDescription delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil] show ] ;
}else{
NSError *error = nil;
self.searchResult= [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//NSLog(#"result:%#",self.searchResult);
[self.tableView reloadData];
}
}];
}

Related

How to parse JSON response from Rest API

I am working on an app that will parse data from a Rest API. As I haven't done this before, I was wondering if NSScanner or NSRange would work for this. Here is an example using NSScanner for such purposes. It's a small string so it doesn't take much code, so it seemed like a quick and dirty option. Is there an easier and quicker way to do this?
- (void)GetAliasName:(NSString *)cno selector:(NSString*)selectorName completionHandler:(void (^)(NSDictionary *, NSError *))handler
{
NSMutableDictionary *d = [[NSMutableDictionary alloc] init];
[d setValue:interface forKey:#"interface"];
[d setValue:#"GetAlias" forKey:#"method"];
NSMutableDictionary *p = [[NSMutableDictionary alloc] init];
cno = [[NSUserDefaults standardUserDefaults] objectForKey:#"cno"];
[p setValue:cno forKey:#"cno"];
[p setValue:selectorName forKey:#"selector"];
[d setValue:p forKey:#"parameters"];
NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];
[self load:data completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"done");
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"GetAlias RAW response = %#", s);
if (apiConditions)
{
dispatch_async(dispatch_get_main_queue(),
^{
[hud hide:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"No network connection or no data found" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
NSLog(#"data is NIL");
});
}
else
{
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
handler(d, error);
//scans for aliasname
NSString *match = #"AliasName\": \"";
NSString *preTel;
NSString *postTel;
NSScanner *scanner = [NSScanner scannerWithString:s];
[scanner scanUpToString:match intoString:&preTel];
[scanner scanString:match intoString:nil];
postTel = [s substringFromIndex:scanner.scanLocation];
//removes newlines, characters, and whitespaces from aliasname
NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:#"}]\""];
postTel = [[postTel componentsSeparatedByCharactersInSet: trim] componentsJoinedByString: #""];
postTel = [[postTel componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString: #""];
NSLog(#"postTel: %#", postTel);
NSString *docno = [[NSUserDefaults standardUserDefaults] objectForKey:#"docno"];
//if docno is filled in, look up TR by docno
if ([docno isEqual: #""])
{
[self GetTR:(NSString*)postTel customStatus:customStatus completionhandler:^(NSDictionary *dictionary, NSError *error) {
nil;
}];
}
}];
}
There is NSJSONSerialization which is built for this.
Use it as follows:
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSString *aliasName = dictionary[#"AliasName"];
Edit
Since you already use this, and have dictionary, the only step you needed was to access dictionary with needed key(last step).

Unable to search in iTunes Store on iOS8

I'm using this code to open iTunes Store app and search for specific music:
NSString *iTunesLink = [NSString stringWithFormat:#"http://search.itunes.apple.com/WebObjects/MZSearch.woa/wa/search?entity=album&media=all&page=1&restrict=true&startIndex=0&term=TERM_NAME"];
NSURL *url = [NSURL URLWithString:iTunesLink];
[[UIApplication sharedApplication] openURL:url];
Code works fine on iOS7, by changing TERM_NAME value I can search whatever I want. The issue on iOS8 is that somehow search term is appended and prepended by ( " ) symbols. I'm using log to check what's the value of my NSURL but it looks fine.
This code worked for me:
NSString *artist = #"artist";
NSString *title = #"title";
NSOperationQueue *operationQueue = [NSOperationQueue new];
NSString *baseURLString = #"https://itunes.apple.com/search";
NSString *searchTerm = [NSString stringWithFormat:#"%# %#", artist, title];
NSString *searchUrlString = [NSString stringWithFormat:#"%#?media=music&entity=song&term=%#&artistTerm=%#&songTerm=%#", baseURLString, searchTerm, artist, title];
searchUrlString = [searchUrlString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
searchUrlString = [searchUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *searchUrl = [NSURL URLWithString:searchUrlString];
NSURLRequest *request = [NSURLRequest requestWithURL:searchUrl];
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse* response, NSData* data, NSError* error)
{
if (error)
{
NSLog(#"Error: %#", error);
}
else
{
NSError *jsonError = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError)
{
NSLog(#"JSON Error: %#", jsonError);
}
else
{
NSArray *resultsArray = dict[#"results"];
if(resultsArray.count == 0)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"917xfm" message:[NSString stringWithFormat:#"No results returned."] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
});
}
else
{
NSDictionary *trackDict = resultsArray[0];
NSString *trackViewUrlString = trackDict[#"trackViewUrl"];
if (trackViewUrlString.length)
{
NSURL *trackViewUrl = [NSURL URLWithString:trackViewUrlString];
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] openURL:trackViewUrl];
});
}
}
}
}
}];

Adding Multiple GET Requests to NSMutableArray in iOS App

The app keeps score during a game. Based off of your score, it will retrieve a quote from an online database, using a GET method and returning it in JSON format. For example, your score is 5, you get 1 quote, 10, you get 2 and so on. The view that shows the quote(s) is a UIViewController with a UITextView in it.
I have a for loop that runs based off the score, to run the same GET request over and over again, after a 1.5 second delay so the server housing the database won't reject requests made nearly simultaneously.
I create a few NSStrings and pull information from the JSON data, append it into some basic HTML code and then set that as the UITextView attributedText.
Most of the time this runs great, but every once in a while, I'll expect 2 quotes, and only get 1, or some of the quotes will wind up being the same.
Can someone tell me if there is a better way to go about doing this than how I currently am?
- (void)viewWillAppear:(BOOL)animated {
if ([textView.text isEqualToString:#""]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger getReady = [defaults integerForKey:#"after"];
self.theNumber = getReady;
for(int i = 0; i< self.theNumber; i++) {
[self performSelector:#selector(quoteView) withObject:self afterDelay:1.5 ];
}
}
}
-(void) quoteView {
NSString *bringitalltogether = #"http://url.com&type=json";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:bringitalltogether]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[request setHTTPMethod:#"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
if (code == 200){
}
else
{
UIAlertView *oops = [[UIAlertView alloc] initWithTitle:#"Oops" message:#"The network is having difficulties getting you the quote. Please check your network settings and try again later." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[oops show];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableDictionary *allResults = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
NSArray *book = [allResults valueForKey:#"bookname"];
self.bookstring = [book objectAtIndex:0];
NSArray *chapter = [allResults valueForKey:#"chapter"];
self.chapterstring = [chapter objectAtIndex:0];
NSArray *verse = [allResults valueForKey:#"verse"];
self.versestring = [verse objectAtIndex:0];
NSArray *text = [allResults valueForKey:#"text"];
self.textstring = [text objectAtIndex:0];
[self doneGotIt];
}
- (void) doneGotIt {
if (!self.theArray) {
self.theArray = [[NSMutableArray alloc] init];
}
NSString *doIt = [NSString stringWithFormat:#"%# - %# %#:%#", self.textstring, self.bookstring, self.chapterstring, self.versestring];
[self.theArray addObject:doIt];
NSString *theEnd = [self.theArray componentsJoinedByString:#"\n"];
NSString *loadHTML = [#"<head> <style type='text/css'>a > img {pointer-events: none;cursor: default;}</style></head><b><div align=\"left\"><font size=5>" stringByAppendingString:theEnd];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[loadHTML dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
textView.attributedText = attributedString;
NSLog(#"ARRAY: %#", self.theArray);
NSLog(#"String: %#", theEnd);
}
-(IBAction)finished {
[self dismissViewControllerAnimated:YES completion:nil];
textView = nil;
}
From the NSLogs I have towards the end there, sometimes the NSMutableArray contains several of the same quotes, which is why they don't show in the string, because it eliminates duplicates. My question is if there is a better way to do this that will keep these errors from occurring?
Here is some pseudo code for you
mutableArray = new NSMutableArray
while([mutableArray count] < total) {
quote = getQuote()
if([array indexOfObject:quote] != NSNotFound)
[mutableArray addObject:quote]
}
This will ensure you do not have duplicate quotes. After you have an array of valid quotes, you can then construct the string exactly how you want it.

My app is crashing when updating my table view

I am doing a database based application. My app needs to update a database table and simultaneously it needs to update the table view i.e. generated based on that particular database table.
Here's is the code i have written
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.courses.count;
}
-(void)viewWillAppear:(BOOL)animated {
self.usernameLBL.text = [NSString stringWithFormat:#"Welcome, %#", self.del.username];
[self loadCourses];
// NSLog(#"The courses count is %d", self.courses.count);
}
-(void)loadCourses {
NSString * stringUrl = [NSString stringWithFormat:"Some URL";
NSURL * uRL = [NSURL URLWithString:[stringUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:uRL];
NSError * error;
NSData * results = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
self.courses = [NSJSONSerialization JSONObjectWithData:results options:0 error:&error];
NSLog(#"The courses array count is %d", self.courses.count);
[self.tableView reloadData];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSDictionary * dict = self.courses[indexPath.row];
cell.textLabel.text = dict[#"name"];
cell.detailTextLabel.text = dict[#"id"];
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.courses = [[NSMutableArray alloc] init];
self.del = [[UIApplication sharedApplication] delegate];
NSString * strURL = [NSString stringWithFormat:"Some URL";
// NSLog(#"The username is %#", self.del.username);
NSURL * url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
// NSLog(#"The data is %#", data);
NSDictionary * result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
// NSLog(#"The error is %#", error);
// NSLog(#"The value returned is %#", result[#"image"]);
if(![result[#"image"] isEqualToString:#"empty"]){
NSString * urlLocation = result[#"image"];
self.adminIMG.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[urlLocation stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]]];
}
// Do any additional setup after loading the view.
}
- (IBAction)addNewCourse:(id)sender {
NSString * strURL = [NSString stringWithFormat:"Some URL";
NSURL * url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * results = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:results options:0 error:&error];
if([dict[#"response"] isEqualToString:#"success"]) {
NSLog(#"New course added");
UIAlertView * success = [[UIAlertView alloc] initWithTitle:#"New course added successfully" message:#"You successfully added a new course" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[success show];
}else {
NSLog(#"Course not added");
}
[self.courses removeAllObjects];
[self viewDidLoad];
[self viewWillAppear:YES];
}
And i got this error.
Error: Evaluation[13335:60b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKeyedSubscript:]: unrecognized selector sent to instance 0xb7d26d0'
I tried many solutions available on the internet but those are not working for me. Anyone can help me, please. Thanks in advance :)
your issue might be here
[self.courses removeAllObjects];
[self viewDidLoad];
[self viewWillAppear:YES];
you don't have to clear your array, try this:
function:
- (void)addCourse{
NSString * strURL = [NSString stringWithFormat:"Some URL";
NSURL * url = [NSURL URLWithString:
[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * results = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:&error];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:results
options:0 error:&error];
if([dict[#"response"] isEqualToString:#"success"]) {
NSLog(#"New course added");
UIAlertView * success = [[UIAlertView alloc]
initWithTitle:#"New course added successfully"
message:#"You successfully added a new course"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[success show];
}else {
NSLog(#"Course not added");
}
}
Your IBAction keep it simple there you don't want to fire off life cycle event from an IBAction instead call the methods you need not to mention that it is not a good idea to call viewDidLoad before viewWillAppear Method...
- (IBAction)addNewCourse:(id)sender {
[self addCourse];
[self loadCourses];
}
first you check the array data it valid or not .(put break point and check it)
and i think u got error because u still not convert integer to string .
i replace this line in to tableview cellForRowAtIndexPath:
cell.detailTextLabel.text = dict[#"id"];
to replace
cell.detailTextLabel.text =[NSString stringWithFormat:#"%d",dict[#"id"]];
Its may be very helpful to you Thanks.
I think your problem is here.. your targeting AppDelegate as self.delegate
self.del = [[UIApplication sharedApplication] delegate];
And AppDelegate runs onetime at start of application only that's why your are getting error

block not being called on the other end

i'm new to blocks, I have a class of requests with static methods to call me back on UIViewControllers with some blocks
this is the method implementation :
(putting a breakpoint on the block(something) DOES stop there, like it should)
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*callBackArray))block
{
if ([text isEqualToString:#""] || [text isEqualToString:#" "])
{
block(nil);
return;
}
NSString * key = #"someActualKeyHere";
;
NSString * finalText;
NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
[tagger setString:text];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
if ([language isEqualToString:#"he"])
{
finalText = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
else
{
finalText = [text stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
}
NSString *urlString = [NSString stringWithFormat:
#"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%#&types=geocode&sensor=true&key=%#",finalText,key];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (!responseObject && ![responseObject respondsToSelector:#selector(dataWithData:)])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving "
message:#"ERROR"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
return ;
}
NSData * responseData = [NSData dataWithData:responseObject];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSError *err;
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
this is how I call it, notice the NSLog, i put a breakpoint on it and its never called
which is exactly what I want to occur.
[Requests requestSuggestedLocationsForText:text withBlock:^(NSArray *callBackArray)
{
NSLog(#"ROFL");
}];
for the record, I have tried the same method with a different signature (without the returning variable name like so :
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*))block;
still didn't fire my breakpoint :(
I think that this:
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
Never runs because as far as I know, NSString doesn't declare JSONObjectWithData. Your break point will never hit because it will never be called.
It seems like it could just be:
NSData * responseData = [NSData dataWithData:responseObject];
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (!err) {
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
else {
block(nil);
}
The other way you convert it to a string, then back to data, why not just keep it as data?

Resources