My current code:
SLRequest *req = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:[NSURL URLWithString:#"http://api.twitter.com/1.1/statuses/user_timeline.json"]
parameters:[NSDictionary
dictionaryWithObjects:#[user]
forKeys:#[#"screen_name"]]];
[req performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (urlResponse.statusCode == 200){
id object = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
completionBlock(object);
}else {
if (error == nil)
error = [API errorWithStatusCode:urlResponse.statusCode];
errorBlock(error);
}
}];
I did made a Application on dev.twitter.com but I don't know how to implement the tokens I got from Twitter. How can I update to 1.1 without the user asking for their Twitter account?
you need to authenticate your request to get the User Timeline, see this answer
this answer is using FHSTwitterEngine to authenticate the request and then create a search query, you can get the user_timeline instead of the search query.
Hope it helps you ^_^
Related
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.
I am able to get the user profile permissions if user has set facebook account in his iPhone settings. For this I have used following code:
if(!_accountStore)
_accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookTypeAccount = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[_accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey: #"app_id", ACFacebookPermissionsKey: #[#"email"]}
completion:^(BOOL granted, NSError *error) {
if(granted){
NSArray *accounts = [_accountStore accountsWithAccountType:facebookTypeAccount];
_facebookAccount = [accounts lastObject];
NSLog(#"Success");
[self me];
}else{
NSLog(#"go to iphone settings");
}
}];
-(void)me
{
NSURL *meurl = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:meurl
parameters:nil];
merequest.account = _facebookAccount;
[merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", meDataString);
}];
}
If user hasn't set his facebook account then control will move to else part i.e. go to iphone settings. In this else part I want to open the facebook login page so that user will be able to login in his facebook account without going to iPhone settings. SO how could we open the facebook login via SDK. Please help me out from this issue.
Thanks in advance.
In this case, if you're not using the user account (in case he/she doesn't have it set up on the iOS Settings), you need to implement the Facebook SDK (https://developers.facebook.com/ios/) on your application. It's easy, just follow these steps (https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/).
After that, you can use FBSession's method +openActiveSessionWithReadPermissions:allowLoginUI:completionHandler: to perform the user login.
To be true, in my application, I don't even try to login the user with Apple's requestAccessToAccountsWithType:options:completion:; with the newest Facebook SDK, the default behavior is:
Tries to login with the user account setup on the iOS Settings;
If no account is found, tries to open the Facebook application to request login / permissions;
If the Facebook app is not installed on the device, it opens Facebook on Safari, as a fallback.
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];
});
});
i have used oauth mechanism to let the user login via twitter in my app, on successful login it returns me the access taken, username and oauth_token_secret, i want to get the user account information from twitter like his location, date of birth, and other profile information. I have searched the Rest Api given on the twitter's official site but haven't found any such link.... so how to get the user 's account information? kindly help me.
what about this call
https://api.twitter.com/1/users/show.json?screen_name=TwitterAPI&include_entities=true
Twitter-Kit Version 3.4.0 Here is function
-(void)userVerify:(NSString *)userID{
NSString *statusesShowEndpoint = #"https://api.twitter.com/1.1/users/show.json";
NSDictionary *params = #{#"id": userID};
NSError *clientError;
// Objective-C
TWTRAPIClient *client = [[TWTRAPIClient alloc] init];
NSURLRequest *request = [client URLRequestWithMethod:#"GET" URLString:statusesShowEndpoint parameters:params error:&clientError];
if (request) {
[client
sendTwitterRequest:request
completion:^(NSURLResponse *response,
NSData *data,
NSError *connectionError) {
if (data) {
// handle the response data e.g.
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&jsonError];
NSLog(#"%#",[json description]);
self.txtViewDetails.text = [json description];
}
else {
NSLog(#"Error code: %ld | Error description: %#", (long)[connectionError code], [connectionError localizedDescription]);
self.txtViewDetails.text = [NSString stringWithFormat:#"Error code: %ld | Error description: %#", (long)[connectionError code], [connectionError localizedDescription]];
}
}];
}
else {
NSLog(#"Error: %#", clientError);
}
}
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).