I have implemented the google place search API in IOS and enabled the API in the developer console and used the below code but its shows error that "This IP, site or mobile application is not authorized to use this API key. Request received from IP address 122.173.223.114, with empty refer"
After regenerate the API key its shows API key is expired and after sometime its shows the same above errors. Please help someone.
-(void) queryGooglePlaces: (NSString *) googleType {
// Build the url string to send to Google. NOTE: The kGOOGLE_API_KEY is a constant that should contain your own API key that you obtain from Google. See this link for more info:
// https://developers.google.com/maps/documentation/places/#Authentication
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%#&types=%#&sensor=true&key=%#", appDel.objLocationManager.location.coordinate.latitude, appDel.objLocationManager.location.coordinate.longitude, [NSString stringWithFormat:#"%i", appDel.currenDist],googleType, kGOOGLE_API_KEY];
//Formulate the string as a URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responseData {
//parse out the json data
if (responseData==nil) {
}else{
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* places = [json objectForKey:#"results"];
//Write out the data to the console.
NSLog(#"Google Data: %#", json);
}
}
I did it with use of AFNetworking class Try this one,
#define kGoogleAutoCompleteAPI #"https://maps.googleapis.com/maps/api/place/autocomplete/json?key=%#&input=%#"
-(void)getAutoCompletePlaces:(NSString *)searchKey
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// set request timeout
manager.requestSerializer.timeoutInterval = 5;
NSString *url = [[NSString stringWithFormat:kGoogleAutoCompleteAPI,GoogleDirectionAPI,searchKey] stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSLog(#"API : %#",url);
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSDictionary *JSON = responseObject;
predictions = [NSMutableArray array];
// success
AutomCompletePlaces *places = [AutomCompletePlaces modelObjectWithDictionary:JSON];
[arrSuggestionData removeAllObjects];
if (!arrSuggestionData) {
arrSuggestionData = [NSMutableArray array];
}
for (Predictions *pred in places.predictions)
{
[arrSuggestionData addObject:pred.predictionsDescription];
}
[self.Tbl_suggestion reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
Related
I'm attempting to obtain elements extracted from a dictionary and convert them to doubles. The data is being pulled from JSON and seems to be extracted into a type of array (not sure which type). Is there a way to obtain the numbers listed below individually out of the array? Please let me know if you need more information.
NSDictionary *parameters = #{#"username":savedUser,#"password":savedPass};
NSURL *URL = [NSURL URLWithString:#"testwebsite"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:URL.absoluteString parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSError *error = nil;
JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
if (error) {
NSLog(#"Error serializing %#", error);
}
NSLog(#"%#",JSON);
NSString *price = [NSString stringWithFormat:#"%#",[JSON valueForKey:#"UnitPrice"]];
price= [price stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"Price: %#",price);
[transactionTotals addObject:price];
[self createGraph:100];
}
failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"Error1: %#", [error debugDescription]);
NSLog(#"Error2: %#", [error localizedDescription]);
}];
}
#catch (NSException *exception)
{
NSLog(#"%#",exception);
}
Log (UnitPrice values I need individually extracted):
Dictionary output:
2016-07-03 22:52:21.330 T2PApp[2272:658440] (
{
OrderDetailID = 3;
ProductName = Oranges;
UnitPrice = "399.99";
date = "2016-06-09T21:45:06";
},
{
OrderDetailID = 7;
ProductName = Oranges;
UnitPrice = 1000;
date = "2016-06-13T22:15:47.107";
}
)
Extracted UnitPrice output (still not completely extracted):
2016-07-03 22:52:21.330 T2PApp[2272:658440] Price: (
399.99,
1000
)
I think what you need is digging out the data from the objects in array. It not about the JSON.
There is many way to do it, but not one simply way to dig it out.
For example, create a new array, and traverse the target array, put the property you need into the new array.
It is basically like that.
In your code, maybe the code below will work.
NSLog(#"%#",JSON);
NSMutableArray *priceArr = [NSMutableArray array];
NSArray *arr = nil;
if ([JSON isKindOfClass:[NSArray class]]) {
arr = (NSArray *)JSON;
for (NSDictionary *dic in arr) {
NSString *price = [NSString stringWithFormat:#"%#",[dic valueForKey:#"UnitPrice"]];
price= [price stringByReplacingOccurrencesOfString:#"\"" withString:#""];
[priceArr addObject:price];
}
}
priceArr is what you need.
I am trying to redo some code to use AFNetworking. I have this method below:
-(NSArray *)GetTableDataOfPhase:(NSString *)phase
{
NSString *phaseRequestString = [NSString stringWithFormat:#"%#?jobNo=%#",kIP,phase];
NSURL *JSONURL = [NSURL URLWithString:phaseRequestString];
NSURLResponse* response = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if(data == nil)
return nil;
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
return tableArray;
}
and right now I am trying to alter it so it still returns an array, I have tried doing this:
-(NSArray *)GetTableDataOfPhase:(NSString *)phase
{
NSString *phaseRequestString = [NSString stringWithFormat:#"%#?jobNo=%#",kIP,phase];
NSURL *JSONURL = [NSURL URLWithString:phaseRequestString];
NSURLResponse* response = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSData* data = [NSURLConnection sendSynchronousRequest:responseObject returningResponse:&response error:nil];
if(data == nil)
return nil;
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[operation start];
return tableArray;
}
but I got this error:
/Users/jamessuske/Documents/My Programs/SSiPad(Device Only)ios7/SchedulingiPadApplication/Classes/LHJSonData.m:168:46: Incompatible block pointer types sending 'void *(^)(AFHTTPRequestOperation *, id)' to parameter of type 'void (^)(AFHTTPRequestOperation *, id)'
and this warning:
/Users/jamessuske/Documents/My Programs/SSiPad(Device Only)ios7/SchedulingiPadApplication/Classes/LHJSonData.m:170:97: Sending 'NSURLResponse *const *' to parameter of type 'NSURLResponse **' discards qualifiers
This is how I am calling it:
- (void)GetRequest
{
//refresh table view
[dataSource.editedCellHolder removeAllObjects];
[dataSource.cellHolder removeAllObjects];
[dataSource.cellHolderDisplay removeAllObjects];
NSArray *tableData = [dataSource.areaData GetTableDataOfPhase:[NSString stringWithFormat:#"%#%#",areaPickerSelectionString,unitPickerSelectionString]];
if(tableData == nil)
[self CustomAlert:#"Data was not recieved from the server, please check internet/VPN settings, Or contact Software Vendor for assistance."];
[dataSource PopulateTableData:tableData];
[indicatorView stopAnimating];
[indicatorView removeFromSuperview];
[loadingView removeFromSuperview];
loadingView = nil;
indicatorView =nil;
[NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:#selector(DisplayTable) userInfo:nil repeats:NO];
}
A couple of things:
Using AFNetworking, you should entirely lose the NSURLConnection request.
Likewise, the default responseSerializer does the JSON parsing for you, so you can lose the NSJSONSerialization parsing. AFNetworking does all of that for you.
Likewise, don't build URL parameters manually, but rather again let AFNetworking do that for you. By default, AFNetworking uses a requestSerializer that will build the request for you.
Your old method ran synchronously, which is generally a bad idea. Instead, you should use asynchronous patterns (e.g. a completionHandler block).
So, pulling all of this together, it probably looks like:
- (void)getTableDataOfPhase:(NSString *)phase completionHandler:(void (^)(NSArray *resultsObject, NSError *error))completionHandler
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"jobNo" : phase};
[manager GET:kIP parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
completionHandler(responseObject, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completionHandler(nil, error);
}];
}
And you'd call it like so:
[self getTableDataOfPhase:#"..." completionHandler:^(NSArray *resultsObject, NSError *error) {
if (resultsObject) {
// use NSArray here
} else {
NSLog(#"error = %#", error);
}
}];
// but don't try to use the `resultsObject` array here!
i have a request which returns information from a php web service. I'm having trouble adding this to a array which can be used in my UICollectionView. It seems like whatever i do i cant return the data. I think it is because i'm returning the array before i've added any objects. I've tried placing the NSLog several places, but without luck. What am i doing wrong?
When i place this NSLog(#"%d", imagesArray.count); beyond the request it returns 0.
ViewDidAppear:
-(void)viewDidAppear:(BOOL)animated {
imagesArray = [[NSMutableArray alloc] init];
[self getImages];
}
getImages method:
-(void)getImages {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:#"http://URL.COM" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSString *theTitle = [[json objectForKey:#"response"] valueForKey:#"title"];
NSString *theUrl = [[json objectForKey:#"response"] valueForKey:#"imageUrl"];
[imagesArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:
theTitle, #"title",
theUrl, #"url",
nil]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
NSLog(#"%d", imagesArray.count);
}
AFNetworking is Asynchronous, you have to place the log inside the success block. Otherwise the array will always be empty.
One good solution would be to pass a block to your getImages function like that
-(void) getImages:(void (^)(BOOL result))callback {
// your code here then you call callback(YES or NO) inside your success or failure block.
}
[self getImages:^(BOOL result){
if(result)
//we got the images, we can now display them etc.
}];
I'm using AFNetworking 2.0 to make a POST request to my web service that returns JSON data.
{
post = {
"first_name" = Joe;
"last_name" = Blogs;
"user_id" = 1;
};
},
{
post = {
"first_name" = Bill;
"last_name" = Gates;
"user_id" = 2;
};
}
Im able to print out responseObject to the console fine which displays my JSON data.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"user": #"root"};
[manager POST:#"http://192.168.0.100/webservice.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *responseString = [operation responseString];
NSError *error;
NSArray *json = [NSJSONSerialization
JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
for (NSDictionary *dictionary in json)
{
NSString *firstName = [[dictionary objectForKey:#"post"] valueForKey:#"first_name"];
NSLog(#"%#", firstName);
NSString *lastName = [[dictionary objectForKey:#"post"] valueForKey:#"last_name"];
NSLog(#"%#", lastName);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
Each "post" is going to be used for a table cell on my View Controller. Im struggling to understand how to make each post an object in an array. Any help appriciated.
UPDATE
You can use this code snipped to perform your desired functionality:
NSString *responseString = [operation responseString];
NSData *data= [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray* results = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
for (int i=0; i<results.count; i++)
{
NSDictionary *res=[results objectAtIndex:i];
NSDictionary *res2=[res objectForKey:#"post"];
[self.storesArray addObject:res2];
}
[self.tableView reloadData];
and in your CellForRowAtIndexPath method, use this code snipped to show data on your cell:
NSDictionary *res=[self.storesArray objectAtIndex:indexPath.row];
cell.firstName.text=[res objectForKey:#"first_name"];
cell.lastName.text=[res objectForKey:#"last_name"];
This NSDictionary works in key values pair style, so you can get the value of any key by just mentioning the key name and get the values of that key.
I'm developing an iOS app that includes a facebook feed of a users wall. Using the graph api with the following URL:
feedURL = [NSString stringWithFormat:#"https://graph.facebook.com/%#/feed?
access_token=%#&since=%#&until=%#",kFaceBookID,FBSession.activeSession.accessToken,
[dateRange objectForKey:#"since"], [dateRange objectForKey:#"until"]];
I get back data that only one result and a dictionary entry for paging. When I do a NSURLRequest with the "next" URL I get back 0 results. If I cut and paste that same URL into a web browser I get back 25 results. Any ideas on why?
Here is the code I am using:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *nextPageURL;
NSError *jsonError;
if (!jsonError) {
NSDictionary *rDict = [NSJSONSerialization JSONObjectWithData:_postData
options:0
error:&jsonError];
nextPageURL = [[rDict objectForKey:#"paging"]objectForKey:#"next"];
NSArray *rArray = [rDict objectForKey:#"data"];
DLog(#"Posts Dictionary = %#\n\n",rDict);
for (NSDictionary *rPost in rArray) {
FBPost *post = [[FBPost alloc]initFBPostWithDictionary:rPost];
[feedsArray addObject:post];
}
}
else
{
ALog(#"json error = %#",[jsonError localizedDescription]);
[activity stopAnimating];
NSString *errorMessage = [NSString stringWithFormat:#"Facebook status request failed with error: %#\nCheck your network connection and try again later",[jsonError localizedDescription]];
[self quit:errorMessage];
}
[feedsTable reloadData];
if (nextPageURL && [feedsArray count] < 30) {
DLog(#"Next Feed URL = %#",nextPageURL);
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:nextPageURL]];
if (![[NSURLConnection alloc] initWithRequest:request delegate:self]) {
ALog(#"Connection failed for request: %#",request);
}
}
}
I am answering my own question as I took another look at the entire logic and completely changed my approach to use [FBRequestConnection...] instead. Here is the code if anyone is interested. Note that I fetch one weeks worth of feed messages at a time to improve the tableview performance.
- (void) fetchFBFeedsForDateRange:(NSDictionary *)dateRange;
{
_postData = [[NSMutableData alloc]init];
//since, until is a decremented one week at a time date range.
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[dateRange objectForKey:#"since"], #"since",
[dateRange objectForKey:#"until"], #"until",
nil];
NSString *gPath = [NSString stringWithFormat:#"%#/feed",kFaceBookID];
[FBRequestConnection startWithGraphPath:gPath
parameters:params
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSArray *rArray = [result objectForKey:#"data"];
//DLog(#"Posts Array = %#\n\n",rArray);
for (NSDictionary *rPost in rArray) {
FBPost *post = [[FBPost alloc]initFBPostWithDictionary:rPost];
if (post.type) {
if (!post.skip) {
[feedsArray addObject:post];
}
}
}
[feedsTable reloadData];
if ([feedsArray count] < kFaceBookMaxPostsToDisplay) {
[self performSelector:#selector(fetchPreviousWeek)];
}
else
{
[activity stopAnimating];
}
}
else
{
[activity stopAnimating];
NSString *errorMessage = [NSString stringWithFormat:#"Facebook status request failed with error: %#\nCheck your network connection and try again later",[error localizedDescription]];
[self quit:errorMessage];
}
}];
}