REQUEST_DENIED on ios google map api - iphone

I am using
-(void) getRouteData :(double)startPointLatitude :(double)startPointLongitude :(double)stopPointLatitude :(double)stopPointLongitude{
NSString *url = #"http://maps.apple.com/maps/api/directions/json?";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:15];
NSString *postString;
postString = [#"" stringByAppendingFormat: #"origin=%f,%f&destination=%f,%f&sensor=true&mode=driving", startPointLatitude, startPointLongitude, stopPointLatitude, stopPointLongitude];
NSLog(#"%#%#",url, postString);
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
Boolean isDataGet = false;
if (theConnection) {
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *result = [NSString stringWithFormat:#"%#", [self hexToString:data]];
NSLog(#"result = %#", result);
}
}
to draw path initial and final points on google map but I am getting
{
"routes" : [],
"status" : "REQUEST_DENIED"
}
Also when I add api key it does not work either. (I have enabled places API too)

I solved problem by this function
-(void) getRouteData :(double)startPointLatitude :(double)startPointLongitude :(double)stopPointLatitude :(double)stopPointLongitude{
NSString* apiUrlStr = [NSString stringWithFormat:#"http://maps.google.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true&mode=driving", startPointLatitude, startPointLongitude, stopPointLatitude, stopPointLongitude];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:apiUrlStr]];
[request setTimeoutInterval:15];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
Boolean isDataGet = false;
if (theConnection) {
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *result = [NSString stringWithFormat:#"%#", [self hexToString:data]];
NSLog(#"result = %#", result);
}
}

Related

how to call webservice in xcode by GET Method?

I have this link :
function new_message($chat_id,$user_id,$message,$recipient_ids)
http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2%2C7
return chat_log_id
Can anyone please explain me how to call webserive by this get method or give me the
solution .
what i did with my code is below :
-(void)newMessage{
if ([self connectedToWiFi]){
NSString *urlString = [NSString stringWithFormat:#"www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/1,1,2"];
NSLog(#"urlString is %#", urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *requestURL = [NSURL URLWithString:urlString];
[request setURL:requestURL];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"ERROR = %#",error.localizedDescription);
if(error.localizedDescription == NULL)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> succ %#",returnString);
[delegate ConnectionDidFinishLoading:returnString : #"newMessage"];
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> fail %#",returnString);
[delegate ConnectiondidFailWithError:returnString : #"newMessage"];
}
}];
}
}
how can i handle this ?
Thanks in advance .
I am not sure from your post whether or not you want to "post" or "get." However, gauging from the fact that you set your method to post, and that you are creating something new on your server, I am assuming you want to post.
If you want to post you can use my wrapper method for a post request.
+ (NSData *) myPostRequest: (NSString *) requestString withURL: (NSURL *) url{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:15.0];
NSData *requestBody = [requestString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
return responseData;
}
Where request string is formatted like this:
NSString * requestString = [[NSString alloc] initWithFormat:#"username=%#&password=%#", userInfo[#"username"], userInfo[#"password"]];
This will also shoot back the response data which you can turn into a string like this.
responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
If you are trying to grab data from the server in json format...
+ (NSArray *) myGetRequest: (NSURL *) url{
NSArray *json = [[NSArray alloc] init];
NSData* data = [NSData dataWithContentsOfURL:
url];
NSError *error;
if (data)
json = [[NSArray alloc] initWithArray:[NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error]];
//NSLog(#"get results: \n %#", json);
return json;
}
Pls change ur code like this
-(void)newMessage{
NSString *urlString = [NSString stringWithFormat:#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/27" ];
NSLog(#"urlString is %#", urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *requestURL = [NSURL URLWithString:urlString];
[request setURL:requestURL];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"ERROR = %#",error.localizedDescription);
if(error.localizedDescription == NULL)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> succ %#",returnString);
[self parseStringtoJSON:data];
//[delegate ConnectionDidFinishLoading:returnString : #"newMessage"];
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> fail %#",returnString);
// [delegate ConnectiondidFailWithError:returnString : #"newMessage"];
}
}];
}
-(void)parseStringtoJSON:(NSData *)data{
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"chat id %#",[dict objectForKey:#"chat_log_id"]);
}
u will get the JSON response string as result if u hit that url. If u r familiar with json parsing, u can get the value based on key.
see this link: How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

HTTP Post method php and ios

i'm facing a big problem,
I want to send data to my server, my data is a string.
I do not want to use Get method because the string might be very long, so i want to use POST method but everything goes, wrong, if someone can help me he'll be my hero :)
Here is my php code :
<?php include("config.inc.php");
if (isset($_POST['contentInterro']) && $_POST['contentInterro'] !="" ) {
//$id_user = $_POST['contentInterro'];
//$db->sql_query("INSERT INTO interrogations VALUES(DEFAULT, '$id_user')");
echo "succes";
}else{
echo "This is an error";
}
?>
Here is my app code :
NSData *postData = [stringToPost2 dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *requestPost = [[NSMutableURLRequest alloc] init];
NSURL *urlPost = [NSURL URLWithString:#"http://buzznapps.fr/FDF/postInterrogation.php"];
[requestPost setURL:urlPost];
[requestPost setHTTPMethod:#"POST"];
[requestPost setValue:#"lol" forHTTPHeaderField:#"contentInterro"];
NSError *errorURL;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:requestPost returningResponse:&response error:&errorURL];
NSString *str = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Str = %#",str);
I always get an error, and i've search the web i do not know how to get this data !
Thanks for any help.
#define TIMEOUT_INTERVAL 60
#define CONTENT_TYPE #"Content-Type"
#define URL_ENCODED #"application/x-www-form-urlencoded"
#define GET #"GET"
#define POST #"POST"
-(NSMutableURLRequest*)getNSMutableURLRequestUsingGetMethodWithUrl:(NSString*)url
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
[req setHTTPMethod:GET];
return req;
}
-(NSMutableURLRequest*)getNSMutableURLRequestUsingPOSTMethodWithUrl:(NSString *)url postData:(NSString*)_postData
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
[req setHTTPMethod:POST];
[req addValue:URL_ENCODED forHTTPHeaderField:CONTENT_TYPE];
[req setHTTPBody: [_postData dataUsingEncoding:NSUTF8StringEncoding]];
return req;
}
#try
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *_postData = [NSString stringWithFormat:#"user_name=%#&password=%#",#"user_name",#"password"];
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"error==%#==",[error localizedDescription]);
}
else
{
NSError *errorInJsonParsing;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorInJsonParsing];
if(errorInJsonParsing) //error parsing in json
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"error in json==%#==",[error localizedDescription]);
}
else
{
//do some operations
}
}
}];
}
#catch(NSException *exception)
{
NSLog(#"error in exception==%#==",[exception description]);
}
same way it works for the get method, just call the
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingGetMethodWithUrl:_url]; instead of NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];

newby IOS: unable to redirect url

This is my first IOS project. Having a tough time getting login to work. The site has a meta_refresh to another url. I've tried to send another request to the url in the meta_refresh but then the app just hangs. I'm sure that I'm doing something wrong but I'm using XCode 4.4 so a lot of the NSURLConnection delegate methods have been deprecated.
Here's what I'm doing:
NSString *urlAsString = baseURL;
urlAsString = [urlAsString stringByAppendingString:#"?user[login]=username"];
urlAsString = [urlAsString stringByAppendingString:#"&user[password]=password"];
urlAsString = [urlAsString stringByAppendingString:#"&origin=splash"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"POST"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if([data length] > 0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
NSRange obj = [html rangeOfString:#"http-equiv=\"refresh\""];
NSInteger len = obj.length;
} else if([data length] == 0 && error == nil) {
NSLog(#"No data was returned.");
} else {
NSLog(#"Error happened = %#", error);
}
Here's what I'm getting:
Another question is that I've read that I should use asynchronous connection. The trouble is that I need the data scraped from the site to display on the screen. If I display the screen before the data is returned, then I won't have any data -- or am I not understanding how this works?
Thanks.
--Tony
I think that maybe you're a mixing stuff. You're setting a string url with GET values and then you set the HTTPMethod to POST and I don't know if that is going to work fine.
Here's a code that I have to send values with POST:
NSString *post = [NSString stringWithFormat:#"&user_login=%#&user_password=%#&origin=%#,username,password, splash];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:baseURL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

How to send a Get request in iOS?

I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as
[requestObject setHTTPMethod:#"GET"];
Tell me what could be the problem. Also provide me the code if you have.
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response1 =
[NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSString *getString = [NSString stringWithFormat:#"parameter=%#",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:#"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https:yoururl"]];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
Make sure your requestObject is of type NSMutableURLRequest.
Simply call and use:
(void)jsonFetch{
NSURL *url = [NSURL URLWithString:#"http://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *data = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSError *erro = nil;
if (data!=nil) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro ];
if (json.count > 0) {
for(int i = 0; i<10 ; i++){
[arr addObject:[[[json[#"feed"][#"entry"] objectAtIndex:i]valueForKeyPath:#"im:image"] objectAtIndex:0][#"label"]];
}
}
}
dispatch_sync(dispatch_get_main_queue(),^{
[table reloadData];
});
}];
[data resume];
}

Google Reader Token Request giving 403 error

I am trying to get the token from google reader for my iPhone project. I am able to get the Authorization but when I request for the token, I get a 403 Forbidden
Below is my code implementation. Any help would be appreciated.
//The tokenStorer contains the Authorization key
NSString *tokenStorer = [[NSUserDefaults standardUserDefaults]valueForKey:#"authKey"];
NSLog(#"%#", tokenStorer);
NSDictionary *cookieDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host",
#"iReader", #"User-Agent",
#"gzip, deflate", #"Accept-Encoding",
tokenStorer, #"Authorization",
nil
];
//#"Auth", NSHTTPCookieName, tokenStorer, NSHTTPCookieValue, #"./google.com", NSHTTPCookieDomain, #"/", NSHTTPCookiePath, nil];
//NSHTTPCookie *authCookie = [NSHTTPCookie cookieWithProperties:cookieDictionary];
//Google token url "http://www.google.com/reader/api/0/token?client=clientName"
NSURL *url=[[NSURL alloc] initWithString:GOOGLE_READER_TOKEN_URL];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:cookieDictionary];
NSData *reciveData;
NSURLResponse *response;
NSError *error;
reciveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSMutableURLRequest *tokenRequest= [[NSMutableURLRequest alloc] initWithURL:url];
NSString *trial = [[NSString alloc]initWithData:reciveData encoding:NSASCIIStringEncoding];
NSLog(#"%# %d",trial, response);
[url release];
The below code solved my problem:
-(id)queryLoginDetails {
//authKey returns the authorization key
NSString *tokenStorer = [[NSUserDefaults standardUserDefaults]valueForKey:#"authKey"];
NSLog(#"%#", tokenStorer);
NSString *auth = [[NSString alloc] initWithString:
[NSString stringWithFormat:#"GoogleLogin auth=%#", [tokenStorer substringToIndex:[tokenStorer length]-1]]];
NSDictionary *createHeader = [[NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host", #"iReader", #"User-Agent", #"gzip, deflate", #"Accept-Encoding", auth, #"Authorization", nil]retain];
NSURL *url =[NSURL URLWithString:GOOGLE_READER_TOKEN_URL];
NSData *recieveData;
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:createHeader];
NSURLResponse *response;
NSError *error;
recieveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSString *myString = [[NSString alloc]initWithData:recieveData encoding:NSASCIIStringEncoding];
return myString;
}