OAuthTokenRequest using STTwitterAPI fails - objective-c

Using following code to get OAuth token but it always fails with error
Your credentials do not allow access to this resource
I have taken following code sample from
https://github.com/nst/STTwitter/blob/master/demo_cli/reverse_auth/main.m
Even I have allowed Read and Write access in application settings at
https://apps.twitter.com/app/XXXX/permissions
STTwitterAPI *twitter = [STTwitterAPI twitterAPIWithOAuthConsumerName:nil consumerKey:#"MY CONSUMER KEY" consumerSecret:#"MY CONSUMER SECRET"];
[twitter postReverseOAuthTokenRequest:^(NSString *authenticationHeader) {
STTwitterAPI *twitterAPIOS = [STTwitterAPI twitterAPIOSWithFirstAccount];
[twitterAPIOS verifyCredentialsWithSuccessBlock:^(NSString *username) {
[twitterAPIOS postReverseAuthAccessTokenWithAuthenticationHeader:authenticationHeader successBlock:^(NSString *oAuthToken, NSString *oAuthTokenSecret, NSString *userID, NSString *screenName) {
NSLog(#"REVERSE AUTH OK");
} errorBlock:^(NSError *error) {
NSLog(#"ERROR, %#", [error localizedDescription]);
}];
} errorBlock:^(NSError *error) {
NSLog(#"ERROR");
}];
} errorBlock:^(NSError *error) {
NSLog(#"ERROR");
}];
Any help, where I am going wrong.

Related

CKDiscoverAllContactsOperation not fetching contacts

I am using CKDiscoverAllContactsOperation but its not working fine for me.
-(void)queryForAllUsers: (void (^)(NSArray *records))completionHandler {
CKDiscoverAllContactsOperation *op = [[CKDiscoverAllContactsOperation alloc] init];
[op setUsesBackgroundSession:YES];
op.queuePriority = NSOperationQueuePriorityNormal;
[op setDiscoverAllContactsCompletionBlock:^(NSArray *userInfos, NSError *error) {
if (error) {
NSLog(#"An error occured in %#: %#", NSStringFromSelector(_cmd), error);
//abort();
} else {
NSLog(#"Number of records in userInfos is: %ld", (unsigned long)[userInfos count]);
dispatch_async(dispatch_get_main_queue(), ^(void){
completionHandler(userInfos);
});
}
}];
[self.container addOperation:op];
}
The container which I'm using is publicCloudDatabase.
The search only works if different users activate the app, approved to be Discoverable and have the other person's iCloud email address in their Contacts.
You should use the discoverAllContactUserInfosWithCompletionHandler on the container like this:
[self.container discoverAllContactUserInfosWithCompletionHandler:^(NSArray *userInfos, NSError *error) {
..
}
this function will only return the contacts that can be linked to an iCloud account and the person has also started up your app.

how to partial download a file from google drive use objective c?

I wanna download a big file from google drive use objective,and I use the google-api-objectivec-client-read-only lib.But when I download the big file,I see the memory boom up.
For example,the file's size is 589M,the program's memory more than 600M.So I wannna partial download the file from google drive.
My code:
-(void)getFileMetadataWithService:(NSString *)fileId
{
GTLQuery *query = [GTLQueryDrive queryForFilesGetWithFileId:fileId];
[service executeQuery:query
completionHandler:^(GTLServiceTicket *ticket, GTLDriveFile *file,
NSError *error) {
if (error == nil) {
NSLog(#"Title: %#", file.title);
NSLog(#"Description: %#", file.descriptionProperty);
NSLog(#"MIME type: %#", file.mimeType);
NSLog(#"download url:%#",file.downloadUrl);
NSLog(#"export link:%#",file.exportLinks);
[self downloadFileContentWithService:#"example"
file:file];
} else {
NSLog(#"An error occurred: %#", error);
}
}];
}
-(void)downloadFileContentWithService:(NSString *)loaclpath
file:(GTLDriveFile *)file
{
NSLog(#"download file");
if (file.downloadUrl != nil)
{
NSLog(#"begin download");
GTMHTTPFetcher *fetcher =[service.fetcherService fetcherWithURLString:file.downloadUrl];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil) {
[data writeToFile:#"/Users/mycomputer/Desktop/a.mov" atomically:YES];
[data writeToFile:#"/Users/mycomputer/Desktop/b.mov" atomically:YES];
[data writeToFile:#"/Users/mycomputer/Desktop/c.mov" atomically:YES];
NSLog(#"download ok");
} else {
NSLog(#"An error occurred: %#", error);
}
}];
}
else
{
}
}
How to modify the method to partial download a file from google drive?
OK,I fix it up.It is so easy.
I modify the code as:
-(void)downloadFileContentWithService:(NSString *)loaclpath
file:(GTLDriveFile *)file
{
NSLog(#"download file");
if (file.downloadUrl != nil)
{
NSLog(#"begin download");
GTMHTTPFetcher *fetcher =[service.fetcherService fetcherWithURLString:file.downloadUrl];
fetcher.downloadPath = #"/Users/KarlDoenitz/Desktop/download/bisaishipin.mov";
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil) {
NSLog(#"download ok");
} else {
NSLog(#"An error occurred: %#", error);
}
}];
}
else
{
}
}

Rubymotion and Objective C getter blocks

I'm pretty new to RubyMotion and I've just hit a wall.
I'm trying to do some LinkedIn oauth work and I need to convert the following to RubyMotion
client = LIALinkedInHttpClient.clientForApplication(application, presentingViewController:nil)
client getAuthorizationCode:^(NSString * code) {
[self.client getAccessToken:code success:^(NSDictionary *accessTokenData) {
NSString *accessToken = [accessTokenData objectForKey:#"access_token"];
[self.client getPath:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~?oauth2_access_token=%#&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation * operation, NSDictionary *result) {
NSLog(#"current user %#", result);
} failure:^(AFHTTPRequestOperation * operation, NSError *error) {
NSLog(#"failed to fetch current user %#", error);
}];
} failure:^(NSError *error) {
NSLog(#"Quering accessToken failed %#", error);
}];
} cancel:^{
NSLog(#"Authorization was cancelled by user");
} failure:^(NSError *error) {
NSLog(#"Authorization failed %#", error);
}];
Could anyone possibly point me in the write direction?
The less-typing way using Ruby 2.0's stabby lambdas looks like this:
client.getAuthorizationCode -> (code) {
NSLog "Success"
}, cancel: ->
NSLog "Auth was cancelled"
}, failure: -> (error) {
NSLog "Auth failed"
}
Here's an idea of how you'd use Objective-C blocks in RubyMotion:
client.getAuthorizationCode(lambda { |code|
}, cancel: lambda {
}, failure: lambda { |error|
})
I believe you can use the lambda shorthand -> or Proc if you prefer. See the RubyMotion docs for more info. They demonstrate using do and end to begin and finish the block, but for this purpose, I prefer braces.

Native Facebook/iOS6 integration: Cocoa error 3840 when trying to get profile picture

I am currently using only Social.framework (no FacebookSDK) and getting starting with requesting and getting access to basic user data. Here's all the code I have (with a few properties declared outside, as you'll notice). Everything works fine in terms of getting the right permissions, but I'm getting the following output error when asking for user's profile picture:
2013-01-27 21:28:44.324 TestApp[9230:1a703] Account saved to accountStore
2013-01-27 21:28:45.002 TestApp[9230:1d603] (null)
2013-01-27 21:28:45.003 TestApp[9230:1d603] Request error: The operation couldn’t be completed. (Cocoa error 3840.)
And here is the code:
- (IBAction)btnFbLoginPressed:(id)sender
{
ACAccountType *fbAccountType = [self.accountStore accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierFacebook];
NSArray *permissions = #[#"email"];
self.requestAccessOptions = #{ACFacebookAppIdKey:FB_API_KEY, ACFacebookPermissionsKey:permissions, ACFacebookAudienceKey:ACFacebookAudienceOnlyMe};
[self.accountStore requestAccessToAccountsWithType:fbAccountType options:self.requestAccessOptions completion:^(BOOL granted, NSError *e) {
if (granted && e == nil) {
NSArray *readPermissions = #[#"user_photos"];
NSDictionary *readAcccessOptions = #{ACFacebookAppIdKey:FB_API_KEY, ACFacebookPermissionsKey:readPermissions, ACFacebookAudienceKey:ACFacebookAudienceOnlyMe};
[self.accountStore requestAccessToAccountsWithType:fbAccountType options:readAcccessOptions completion:^(BOOL granted, NSError *e) {
if (granted && e == nil) {
NSArray *accounts = [self.accountStore accountsWithAccountType:fbAccountType];
self.facebookAccount = [accounts lastObject];
[self.accountStore saveAccount:self.facebookAccount withCompletionHandler:^(BOOL success, NSError *error) {
if (error != nil || !success) {
NSLog(#"Error saving account to accountStore: %#", error.localizedDescription);
} else {
NSLog(#"Account saved to accountStore");
}
}];
NSString *uid = [NSString stringWithFormat:#"%#", [[self.facebookAccount valueForKey:#"properties"] valueForKey:#"uid"]];
NSString *url = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture", uid];
NSURL *profilePictureURL = [NSURL URLWithString:url];
SLRequest *profilePictureRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:profilePictureURL parameters:nil];
profilePictureRequest.account = self.facebookAccount;
[profilePictureRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *e)
{
NSDictionary *responseDataDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&e];
NSLog(#"%#", responseDataDictionary);
if (e != nil) {
NSLog(#"Request error: %#", e.localizedDescription);
} else {
}
}];
} else {
NSLog(#"Read permissions request error: %#", e.localizedDescription);
}
}];
} else {
NSLog(#"Basic permissions request error: %#", e.localizedDescription);
}
}];
}
You can see that the reponseDataDictionary is null and something happens when parsing the data. I noticed a couple of other threads on SO about the same error code, but no luck so far. My guess is that either 1) there's something wrong with my Facebook code, or 2) I'm parsing the data incorrectly. Any help's appreciated!
Note: I would like to stick to using the Social/Account frameworks only.
UPDATE: Slight modification thanks to a suggestion in the comments.
Changed code:
[profilePictureRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *e)
{
NSLog(#"Request error value: %#", e.localizedDescription);
NSError *jsonError = nil;
NSDictionary *responseDataDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&jsonError];
NSLog(#"Response data dictionary value: %#", responseDataDictionary);
if (jsonError != nil) {
NSLog(#"Serialization error: %#", jsonError.localizedDescription);
} else {
NSLog(#"Serialization successful");
}
}];
Output:
2013-01-28 18:55:16.265 TestApp[9565:1ae03] Account saved to accountStore
2013-01-28 18:55:17.640 TestApp[9565:1b503] Request error value: (null)
2013-01-28 18:55:17.640 TestApp[9565:1b503] Response data dictionary value: (null)
2013-01-28 18:55:17.642 TestApp[9565:1b503] Serialization error: The operation couldn’t be completed. (Cocoa error 3840.)
The profilePictureRequest is returning an image and not JSON. Use + (CIImage *)imageWithData:(NSData *)data to convert the response to an image.

Why can't I access the facebook friends list after reopening a session in ios

I am upgrading to the facebook 3.0 sdk for ios. Things went well, until I tried to open an existing session after relaunching the application. I am trying to access the list of friends for the facebook user.
if ([[FBSession activeSession] isOpen]) {
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//do something here
}];
}else{
[[self session] openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if ([self isValid]) {
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//log this error we always get
NSLog(#"%#",error);
//do something else
}];
}
}];
}
However I get this error:
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x1d92ff40 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:HTTPStatusCode=400}
I've found that if I use the FBSession reauthorize method it allows me to complete the request without error, but it also means I must show UI or switch apps every time we relaunch the application which is unacceptable. Any suggestions on what I should be doing differently?
I was not setting the session on the request after logging in. Simple mistake.
[[self session] openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if ([self isValid]) {
//I should have been doing this
request.session = [FBSession activeSession];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//log this error we always get
NSLog(#"%#",error);
//do something else
}];
}
}];