I'm trying to fetch a json from google places with the following code:
NSString *query = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%i&types=%#&sensor=true&key=%#", center.latitude, center.longitude, rad, types, kGOOGLE_API_KEY];
NSLog(#"%#",query);
NSURL *googleRequestURL=[NSURL URLWithString:query];
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:googleRequestURL] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Error fetching data: %#",[error description]);
} else {
//To-do
}
}];
The resulting url is: https://maps.googleapis.com/maps/api/place/search/json?location=37.337566,-122.041202&radius=1000&types=accounting|bowling_alley|doctor&sensor=true&key=MY_KEY
(my key is ommitted for obsious reasons)
Which works fine from my laptop's browser, but return the error:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0x7fe47bc138f0 {NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7fe47be9dbe0 "unsupported URL"}
I tried using http instead of https (in the browser it returns a json with some error message, but still returns something) with no success.
What am I doing wrong?
This is how I got it resolved. Good Luck!
NSString *google = #"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=500&types=%#&key=%#";
NSString *link = [NSString stringWithFormat:google, coordinate.latitude, coordinate.longitude, types, GOOGLE_KEY];
NSURL *url = [NSURL URLWithString:[link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
Related
I send a registration message to the server like this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
[request setValue:API_KEY forHTTPHeaderField:#"api_key"];
NSString *dataString = [NSString stringWithFormat:#"username=%#&password=%#", username, encryptedPassword];
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
// Connection
NSURLResponse *response = nil;
NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Print results
NSLog(#"response: %#", response);
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"response: %d", [(NSHTTPURLResponse *)response statusCode]);
}
id jsonObject = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&jsonError];
NSLog(#"jsonObject: %#", jsonObject);
The connection was success, but I got the error response:
=> response: 400
=> jsonObject: {
error = "Please provide username.USERNAME:";
}
The server received a null user name, but I'm sure I pass a valid user name to http body (converted into NSData). The data contains the following info (converted back into string):
username=cc24#cc.com&password=12345678nW7wMNio0bsNBHGqY7VgSw%3D%3D
I don't what happened. But the API works fine with Android app.
I am trying to to use mail api from sendgrid.com but everytime it finishes with failure block.
Also I don't understand how to send the image as an attachment in the email. Can anybody tell me whats wrong in below code & how can I send image ? I am using below code for now
-(void)sendEmail
{
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:#"username" forKey:#"api_user"];
[params setValue:#"sdsfddf23423" forKey:#"api_key"];
[params setValue:#"test#gmail.com" forKey:#"to"];
[params setValue:#"test user" forKey:#"toname"];
[params setValue:#"Test SendGrid" forKey:#"subject"];
[params setValue:#"Test SendGrid from iOS app" forKey:#"text"];
[params setValue:#"noreply#gmail.com" forKey:#"from"];
NSURL *url = [NSURL URLWithString:#"https://sendgrid.com/api"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: url];
NSMutableURLRequest *request = [client requestWithMethod:POST path:#"/mail.send.json" parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
DLog(#"Get latest product info response : %#", response);
NSLog(#"Success");
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure");
}];
[operation start];
}
Thanks in advance.
Update
I made some changes in code & now I can send the email successfully as below
-(void)sendEmailWithoutImage
{
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"subject":#"Test SendGrid",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
[[MyAPIClient sharedAPIClient] POST:#"mail.send.json" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"Success::responseObject : %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error::Mail response : %#", error);
}];
}
But when I try to send the image as attachment then it result in 400 bad request. So I think there is some error in my file uploading block. Here is my code
-(void)sendEmailWithImage
{
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"subject":#"Test SendGrid",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
[[MyAPIClient sharedAPIClient] POST:#"mail.send.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
UIImage *image = [UIImage imageNamed:#"redWine.png"];
NSData *imageToUpload = UIImagePNGRepresentation(image);
[formData appendPartWithFileData:imageToUpload name:#"files" fileName:[NSString stringWithFormat:#"%#",#"abc.png"] mimeType:#"image/png"];
}
success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"Success::responseObject : %#", responseObject);
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
NSLog(#"Error::Mail response : %#", error);
}];
}
Can you anybody tell me whats going wrong while uploading the image ?
Thanks
Just modified your code a little. It looks like there was an issue with the parameters being sent and the URL path.
Also since you are already using AFNetworking to make your POST request, you can follow their docs and example on how to send a photo over here: http://cocoadocs.org/docsets/AFNetworking/2.0.1/
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"Test SendGrid":#"test",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
NSURL *url = [NSURL URLWithString:#"https://sendgrid.com/api/"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: url];
NSMutableURLRequest *request = [client requestWithMethod:#"POST" path:#"mail.send.json" parameters:parameters];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
// DLog(#"Get latest product info response : %#", response);
NSLog(#"Success: %#", response);
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
[operation start];
Update**
Created a Sendgrid-ios library to make it easier to send an email and photo attachment.
//create Email Object
gridmail *msg = [gridmail user:#"username" andPass:#"password"];
//set parameters
msg.to = #"foo#bar.com";
msg.subject = #"subject goes here";
msg.from = #"me#bar.com";
msg.text = #"hello world";
msg.html = #"<h1>hello world!</h1>";
//Image attachment
[msg attachImage:self.photo];
//Send email through Web API Transport
[msg sendWithWeb];
I think my problem is like the one described here but I cannot quite understand the answer.
My app requires users to enter the URL of a site that contains .pbn files. But the same URL which works manually, does not work when entered in the TextField in my app. In my example case self.urlNameInput.text is http://www.atlantaduplicatebridgeclub.com/scorepost/2013/01/20130126ana.pbn and the URL is not recognized.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlNameInput.text] cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
Depending on whether I include or exclude 'http://' I get the following error messages.
Connection failed! Error - A server with the specified hostname could not be found. http://www.atlantaduplicatebridgeclub.com/scorepost/2013/01/20130126ana.pbn
Connection failed! Error - unsupported URL www.atlantaduplicatebridgeclub.com/scorepost/2013/01/20130126ana.pbn
This seems to work just fine:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.atlantaduplicatebridgeclub.com/scorepost/2013/01/20130126ana.pbn"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *results = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Results:%#", results);
}];
In my current xcode project, I need to send parameter values to a url and need to retrieve an xml file based on the parameter values sent.
I tried the below code but it's not working:
(IBAction)myButtonClick:(id)sender
{
NSURL *oRequestURL =
[NSURL URLWithString:#"http://xyz .com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-06-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc"];
NSMutableURLRequest *oRequest = [[[NSMutableURLRequest alloc]init]autorelease];
[oRequest setHTTPMethod:#"POST"];
[oRequest setURL: oRequestURL];
NSMutableData *oHttpBody = [NSMutableData data];
[oHttpBody appendData:[#"This is HTTP Request body" dataUsingEncoding:NSUTF8StringEncoding]];
[oRequest setValue:[oHttpBody length] forHTTPHeaderField:#"Content-Length"];
NSError *oError = [[NSError alloc]init];
NSHTTPURLResponse *oResponseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:oRequest returningResponse:oResponseCode error:oError];
if ([oResponseCode statusCode]> 200) {
NSLog(#"Status code is greater than 200");
}
NSString *strResult=[[NSString alloc]initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(#"The result is %s",strResult);
}
I have searched many sites and books but could not find a solution.
Would be of great help if a link to a tutorial or some other useful resource can be provided. Appreciate your great help.
Thank You.
Hi,
I have found the solution. The code is as below. Hope it helps someone else:)
- (IBAction)myButtonPressed:(id)sender
{
NSString *urlAsString = #"http://api.abc.com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-09-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"2193141de2g7e2a34bb19bc3aa52b3b5" forHTTPHeaderField:#"X-XX-API-KEY"];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection
sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length]>0 &&
error == nil)
{
NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
}
else if ([data length]== 0 && error==nil) {
NSLog(#"Nothing was downloaded");
}
else if (error!= nil) {
NSLog(#"Error occured = %#", error);
}
}];
}
I have a Mac application that is supposed to fetch Twitter followers and friends for a given username and then, in turn, ask Twitter for the user NAMES for each of those returned UserIDs. As you can see below, I have a method that will call the Twitter API to get friends/followers (which works fine). It is the userNameForUserID:delegate: method that is causing me problems. I used to do these requests synchronously and return the NSString for the username right then. That (now commented out) line always broke, so I tried doing it with an NSURLConnection asynchronously. Still doesn't work. I don't understand why
[[NSString alloc] initWithContentsOfURL:...] works for the fetchFollowers... method, but not when I do it the EXACT SAME way in the other...
I put a break point on the line that used to alloc init the NSString with contents of URL, and when I step into it, it doesn't break, return, throw an exception, crash...nothing. It's as if that line just got stepped over (but my application is still blocked.
Any ideas? Much appreciated!
NSString * const GET_FOLLOWERS = #"https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=";
NSString * const GET_FRIENDS = #"https://api.twitter.com/1/friends/ids.json?cursor=-1&screen_name=";
NSString * const GET_USER_INFO = #"https://api.twitter.com/1/users/show.json?user_id=";
#implementation TwitterAPI
+ (void)userNameForUserID:(NSNumber *)userID delegate:(id<UserNameDelegate>)delegate
{
NSURL *url = [NSURL URLWithString:[GET_USER_INFO stringByAppendingString:[userID stringValue]]];
// NSString *JSON = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error) {
[delegate addUserNameToArray:data];
}];
}
+ (NSArray *)fetchFollowersWithUserName:(NSString *)userName
{
NSURL *url = [NSURL URLWithString:[GET_FOLLOWERS stringByAppendingString:userName]];
NSArray *followerIDs;
NSString *JSON = [[NSString alloc] initWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
if ([JSON rangeOfString:#"error"].location == NSNotFound)
followerIDs = [[JSON JSONValue] valueForKey:#"ids"];
return followerIDs;
}