Not able to fetch the gmail address book in iPhone - iphone

From last few days i am stuck as i am not able to access my gmail address book in my iPhone app.I searched a lot but didn't get any success.
Here is the link that i refereed
I checked this link also to access gmail contacts
In the above link it is given that you can access the contacts using this url
https://www.google.com/m8/feeds/contacts/userEmail/full
I am able to login using GData framework but didn't find anything to fetch gmail contacts.
I have a access token after successful login and i am calling this method after logging in successfully.
- (void)doAnAuthenticatedAPIFetch {
NSString *urlStr = #"https://www.google.com/m8/feeds/contacts/myEmailId#gmail.com/full";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.authToken authorizeRequest:request
completionHandler:^(NSError *error) {
NSString *output = nil;
if (error) {
output = [error description];
} else {
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded :Here I am getti
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
} else {
// fetch failed
output = [error description];
}
}
}];
}
Please guide me.

Use this URL to get gmail account address book fetching.
http://code.google.com/p/gdata-objectivec-client/wiki/GDataObjCIntroduction
And take instruction from here how to use google api.
http://johntwang.com/blog/2009/06/08/how-to-use-google-apis-with-iphone-sdk/
hope this would be work for you.

Related

How do I post images to reddit in iOS / Objective C?

I am trying to post an image to reddit; however, I only kind of know what I am doing. I am using objective c for my iphone app.
Prior to the code listed below I obtain a modhash and cookie by logging in prior to the upload and use NSLog to determine that I truly am receiving them. Then I use a JSON Parser to separate them into separate variables.
I was not sure what all of the POST argument values were supposed to be so I kind of guessed. The necessary arguments are uh, file, formid, header, ing_type, name, and sponsor.
The documentation for reddit api is http://www.reddit.com/dev/api I believe that I want to use the POST /api/upload_sr_img method...
NSURL *url = [NSURL URLWithString:#"http://www.reddit.com/api/upload_sr_img"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *httpBody = [NSString stringWithFormat:#"?uh=%#&file=%#&formid=''header=%#&img_type=%#&name=%#&sponsor=%#",modhash,UIImagePNGRepresentation(self.memeImage.image),#"test",#"png",#"Drew",#"Drew'sApp"];
[request setHTTPBody:[httpBody dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse *response = NULL;
NSError *imgError = NULL;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&imgError];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
NSDictionary *responseJson = [json valueForKey:#"json"];
NSLog(#"response is: %#",response);
NSLog(#"imgError is: %#",imgError);
NSLog(#"result is: %#",result);
NSLog(#"json is: %#",json);
NSLog(#"responseJson is: %#",responseJson);
Could use any help I can get.
Also, I was not sure if I needed to send a content-type or even what it would be.
Thanks for your help.
Check this library: https://github.com/MattFoley/MFRedditPostController
You can use the provided UI or create your own.

Getting status "REQUEST_DENIED" after fetching data from google places API

I have done that
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/search/json?location=30.722322,76.76126&radius=500&types=food&sensor=true&key=any_apiKey"]];
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",strResponse);
SBJSON *sbJason = [[SBJSON alloc] init];
NSMutableDictionary *getPlaceList = [sbJason objectWithString:strResponse];
// But i am getting this-
{
"html_attributions" : [],
"results" : [],
"status" : "REQUEST_DENIED"
}
**Is there any problem with API Key i have wrote API key given by google map. Is there any problem with api key or what please tell me here is the link of google api
Although this has been answered, I think the community could do better in explaining what ACTUALLY needs to be done in order to get this working.
I was tearing my hair out about this, it just didn't make sense to me.. I was making an iOS/Android App, so I made an iOS/Android Key...
Wrong.
With Google's Places API, your bundle identifier isn't even considered.
What you really want to do is this:
(I'm using the new User Interface)
1. Log into https://cloud.google.com/console#/project
Select your Project Name, then go into API's & Auth > APIs
Make sure you have Places API Turned on. This is the only thing that needs to be turned on for Places-API to work.
2. Go into Credentials
Click CREATE NEW KEY under Public API Access
3. Select BROWSER KEY
4. Click Create, Nothing Else
Leave the HTTP Refer box empty.
5. Use the Key Generated here
This key will allow ANY user from any device access to the API via your Developer login.
You can try it out here: (Be sure to replace YOUR_KEY_HERE with your generated Key)
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Food%20Sh&sensor=false&radius=500&location=0,0&key=YOUR_KEY_HERE
6. Enjoy
Now you can use that URL above in your Android/iOS device.
Try using the BROWSER app key, not the iOS key. You can find it here:
https://code.google.com/apis/console/
And press "API Access" on the left
The Static Maps API and the Places API each need to be enabled in the API Console for that key. Open the API console and enable access to the Places API. There is a Courtesy limit: 1,000 requests/day, after that you might need to enable billing.
https://code.google.com/apis/console/
I end up with this code.
UIActivityIndicatorView *activity=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activity.center=self.view.center;
[activity startAnimating];
[self.view addSubview:activity];
NSString *str=[[NSString alloc] init];
str=[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/textsearch/json?query=%#&sensor=true&key=YOUR_BROWSER_KEY",searchQuery];
NSMutableURLRequest *request1=[[NSMutableURLRequest alloc] init];
NSURL *url= [[NSURL alloc] initWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[request1 setURL:url];
[request1 setHTTPMethod:#"GET"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response1 =
[NSURLConnection sendSynchronousRequest:request1
returningResponse:&urlResponse error:&requestError];
dispatch_async(dispatch_get_main_queue(), ^{
if ([activity isAnimating]) {
[activity startAnimating];
[activity removeFromSuperview];
}
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:response1
options:kNilOptions
error:&error];
NSLog(#"%#",json);
self.searchArray=[json objectForKey:#"results"];
[self.tableView setDataSource:self];
[self.tableView setDelegate:self];
[self.tableView reloadData];
[self showPins:self.searchArray];
});
});

Error code -1011 when I use AFNetWorking

I am doing a service in our customer company. And I try to get some information from their server by AFNetWorking (Our customer encourage to use AFNetWorking)
I did some sample using AFNetWorking, and it's work.
But when I use one of our customer URLs to get JSON data, it failed and this is error description:
Error Domain=com.alamofire.networking.error Code=-1011
"Expected status code <NSIndexSet: 0x7e274f0>[number of indexes: 100 (in 1 ranges),
indexes: (200-299)], got 403" UserInfo=0x7b64040 {NSErrorFailingURLKey=<url_hidden_for_stackoverflow>,
NSLocalizedDescription=Expected status code <NSIndexSet: 0x7e274f0>[number of indexes: 100 (in 1 ranges), indexes: (200-299)], got 403}
I try to find out some solution, but I can't fix yet. There's my code:
NSURL *url = [NSURL URLWithString:#"http://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
//[httpClient setDefaultHeader:#"Accept" value:#"text/json"];
//NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:CONST_KEY_REGISTER_UNIQUE_KEY, CONST_API_KEY_TEXT,nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"path/to/page.json" parameters:nil];
[httpClient release];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSString *status = [JSON valueForKey:#"status"];
if ([status isEqualToString:#"OK"]) {
NSString *uniqueId = [JSON valueForKey:#"uniqueId"];
[UserSettings setWithKey:CONST_PROGRAM_UNIQUE_KEY value:uniqueId];
}
//NSString *message = [json valueForKey:#"message"];
//NSString *error = [json valueForKey:#"error"];
[[LoadingView instance] performSelectorOnMainThread:#selector(removeLoadingView) withObject:nil waitUntilDone:YES];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSString *errorString = [error description];
[[LoadingView instance] performSelectorOnMainThread:#selector(removeLoadingView) withObject:nil waitUntilDone:YES];
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
Thanks for reading, and any help or reply will be greatly appreciated.
EDIT: As DarkDust said: server deny my access. But I can get data from server by basic connection:
Here is code to get:
NSURL *url = [NSURL URLWithString:#"http://example.com/path/to/page.json"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:CONST_CONNECTION_TIMEOUT];
rssConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[self performSelectorOnMainThread:#selector(downloadStarted) withObject:nil waitUntilDone:NO];
if (rssConnection != nil) {
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
} while (!done);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// I can get text here, but it is not JSON format
NSString *content = [NSString stringWithUTF8String:[data bytes]];
}
I wonder why rssConnection can get JSON text and AFHTTPClient can not ?
As reference because of high search result via google...
For others that are looking for the possible error codes retrieved via AFNetworking, consult the apple documentation for URL Loading System Error Codes as these are the same.
NSURLErrorBadServerResponse = -1011
Returned when the URL Loading system receives bad data from the server.
This is equivalent to the “500 Server Error” message sent by HTTP servers.
The server is responding with the HTTP error code 403 which means Forbidden. It denies you access. You need to find out why, for example by reading the server logs (if you can) or asking the server administrator to help you. It might be access restrictions on the server that need to be lifted/modified.
Edit: A HTTP POST is an operation that wants to save something on the server. While the normal GET seems to work just fine according to your edited question, saving is prohibited right now. First thing to do is still examine the server configuration. Additionally, if your URL points to a script (JSP, ASP, whatever) which is the only thing that would make sense in your case you need to examine that to determine why it denies you access (if the server configuration doesn't already deny it, it must be the script).

youtube inbox problem

I'm trying to programmatically (using gdata api) retrieve incoming messages from youtube account.
My request:
NSURL *url = [NSURL URLWithString:#"http://gdata.youtube.com/feeds/api/users/my_nick/inbox"];
NSMutableURLRequest *inboxRequest = [NSMutableURLRequest requestWithURL:url];
NSString *authStr = [NSString stringWithFormat:#"GoogleLogin auth=%#", authMarker];
[inboxRequest setValue:authStr forHTTPHeaderField:#"Authorization"];
[inboxRequest addValue:#"Content-Type" forHTTPHeaderField:#"application/x-www-form-urlencoded"];
[inboxRequest setHTTPMethod:#"GET"];
NSHTTPURLResponse *response = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:inboxRequest returningResponse:&response error:nil];
NSString *responseDataString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"\n%#\n", responseDataString);
NSLog(#"\n%#\n", [inboxRequest ]);
return feed without entries... (although I can see incoming messages on the site)
here response from nslog:
<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'><id>http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox</id><updated>2011-06-16T14:45:00.475Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#videoMessage'/><title type='text'>Inbox of thisistestnick</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='alternate' type='text/html' href='http://www.youtube.com/my_messages?folder=inbox&filter=videos'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox'/><link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox/batch'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/thisistestnick/inbox?start-index=1&max-results=25'/><author><name>thisistestnick</name><uri>http://gdata.youtube.com/feeds/api/users/thisistestnick</uri></author><generator version='2.0' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage></feed>
what is wrong? pls help.
Why cant you use, gdata-objectivec lib api's rather doing your own parsing ? I havent tried retrieving 'inbox' but was fairly successful in getting the info i want. Advantages of using it are:
a) You get the info in native formats (Strings and Dictionaries), lib does the job of parsing feeds for you.
b) mainly, there wont be any parsing/api understanding errors (which i suppose is the reason for your problem).

Remotely write to a .plist file iPhone SDK

I am wondering if theres a way to remotely write to a plist file stored on my server. The directory the file is located has write access, but i cannot seem to push the new data. Heres my code:
NSString *accountURL = [NSString stringWithFormat:#"http://www.mywebsite.com//%#.plist",txtUsername.text];
NSURL *url = [NSURL URLWithString:accountURL];
NSMutableDictionary *account = [[NSMutableDictionary alloc] initWithContentsOfURL:url];
[account setObject:#"TEST" forKey:#"LastLogin"];
if ([account writeToURL:url atomically:NO]){
NSLog(#"saved");
}else{
NSLog(#"not saved");
}
The plist file exists because I can read from it with no problem. I just cannot write to the file.
On another note, is this even AppStore-friendly if the accounts will be stored on my server?
You need to parse this web service like this and need to implement the delegate methods of parser.
-(void)startParsingForLoginUser:(NSString*)UserName
{
NSString *urlString = [NSString stringWithFormat:#"http://www.mywebsite.com//%#.plist",UserName]];
NSURL *xmlURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:xmlURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]autorelease];
NSURLResponse *returnedResponse = nil;
NSError *returnedError = nil;
NSData *itemData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnedResponse error:&returnedError];
xmlParser = [[NSXMLParser alloc] initWithData:itemData];
[xmlParser setDelegate:self];
[xmlParser parse];
}
And then you would be able to write the plist file on server. Moreover, you could also use the method for parsing like POST, PUT and you can also send aSynchronousRequest to the server, that depends upon you.
Read-only is easy. As soon as you get into writing something you get into permissions for: server, application, user.
To solve your problem you need to create a web service that will authenticate the user and application, check permissions and save the file. Typically it would be a server accepting a POST or PUT from your iPhone app (similar to what browsers do for upload)