Oauth Consumer - LinkedIN UPDATE STATUS - iphone

I try to develop a app that use OauthConsumer for connection with LinkedIN.
All work fine, I can extract the user data but when I want to update User status I've status error 401 with message [unauthorized].
I've the access token, this is the code:
NSURL *url = [NSURL URLWithString:#"https://api.linkedin.com/v1/people/~/current-status"];
OAMutableURLRequest *request1 = [[OAMutableURLRequest alloc] initWithURL:url
consumer:consumer
token:accToken//
realm:nil //
signatureProvider:nil] ; //
NSLog(#"mytoken%#",[request1 token]);
[request1 setHTTPMethod:#"PUT"];
[request1 setHTTPBodyWithString:#"<?xml version=''1.0'' encoding=''UTF-8'?><current-status>is setting their status using the LinkedIn API.</current-status>"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request1
delegate:self
didFinishSelector:#selector(status:didFinishWithData:)
didFailSelector:#selector(status:didFailWithError:)];
Any ideas??? Plese help me!!!!!! :(
tnx

OK, the rigth code is the next:
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request1 = [[OAMutableURLRequest alloc] initWithURL:url
consumer:consumer
token:accToken
realm:nil
signatureProvider:nil];
NSLog(#"mytoken%#",[request1 token]);
[request1 setHTTPShouldHandleCookies:NO];
[request1 setValue:#"text/xml;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request1 setHTTPMethod:#"POST"];
[request1 prepare];
[request1 setHTTPBody:[NSData dataWithContentsOfFile:[NSString stringWithFormat:#"%#/status.xml", [[ NSBundle mainBundle] resourcePath]]]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
[connection start];

Related

Share on Linkedin in Objective c based on new LInkedin API (Not a que)

set share permission w_share while login.
NSString *url = [NSString stringWithFormat:#".../oauth2/authorization?response_type=code&client_id=%#&redirect_uri=%#&state=svhgktyjuid&scope=r_basicprofile+r_emailaddress+w_share",linked_in_api_key,call_back_url];
- (void)shareImp
{
NSString *message = [NSString stringWithFormat:#"share This on Linkedin"];
NSMutableDictionary *contentDic=[[NSMutableDictionary alloc] init];
[contentDic setValue:logoURL forKey:#"submitted-image-url"];
[contentDic setValue:#"https://itunes.apple.com/..." forKey:#"submitted-url"];
[contentDic setValue:message forKey:#"title"];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc]
initWithObjectsAndKeys:
#"anyone",#"code",nil], #"visibility",
[NSString stringWithFormat:#"I have a new APP! And I got it in a snap!"] ,#"comment",contentDic,#"content",nil];
NSString *updateString = [update JSONString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token=%#",_accessToken]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"json" forHTTPHeaderField:#"x-li-format"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBodyWithString:updateString];
[urlRequest setHTTPMethod:#"POST"];
//allocate a new operation queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//Loads the data for a URL request and executes a handler block on an
//operation queue when the request completes or fails.
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
NSLog(#"response...%#",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
}
Thank you..Hope this will help you.

LinkedIn starter kit not sharing content to wall If add content dictionary?

I have written code to post content to linkedIn wall and it is working fine if I remove content dictionary from update dictionary. See the below code containing post data:
- (IBAction)postUpdate
{
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
NSDictionary *content=[[NSDictionary alloc] initWithObjectsAndKeys:#"http://www.celebs101.com/wallpapers/Bruce_Lee/421101/Bruce_Lee_Wallpaper.jpg",#"submitted-image-url",#"http://www.youtube.com/watch?v=GoZ2Be2zLq8",#"submitted-url",#"Post Image and Video testing",#"title",#"Posted Description",#"description",nil];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc]
initWithObjectsAndKeys:
#"anyone",#"code",nil], #"visibility",
#"Test posting to linkedIn", #"comment",content,#"content",nil];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *updateString = [update JSONString];
[request setHTTPBodyWithString:updateString];
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:)];
}
Post data comes in didfinishSelector is :
data after posting is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<error>
<status>401</status>
<timestamp>1356601471318</timestamp>
<request-id>MFW58DCKE9</request-id>
<error-code>0</error-code>
<message>[unauthorized]. OAU:0onill9cburx|3c05c306-aad8-4d07-a2a1-2430aa21b54a|*01|*01:1356601465:Ji7pimMqrXp3RHCNJLv8iKZsklk=</message>
</error>
I don't know why so? please help..
Thanks in Advance..
I have solved it
working code to post on LinkedIn as follows:
- (IBAction)postUpdate
{
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
NSMutableDictionary *contentDic=[[NSMutableDictionary alloc] init];
[contentDic setValue:#"http://www.celebs101.com/wallpapers/Bruce_Lee/421101/Bruce_Lee_Wallpaper.jpg" forKey:#"submitted-image-url"];
[contentDic setValue:#"http://www.linkedin.com" forKey:#"submitted-url"];
[contentDic setValue:[NSString stringWithFormat:#"A title for your share"] forKey:#"title"];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc]
initWithObjectsAndKeys:
#"anyone",#"code",nil], #"visibility",
#"Test posting to linkedIn",#"comment",contentDic,#"content",nil];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *updateString = [update JSONString];
NSLog(#"json string is %#",updateString);
[request setHTTPBodyWithString:updateString];
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:)];
}
- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data after posting is %#",myString);
}
- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
If you are getting that type of error:
So it may be because of post url in "submitted-url" key.
So an easy way to do this first make the post_url for "submitted-url" short using this link( http://tinyurl.com/api-create.php?url=post_url). And then use this short post_url for "submitted-url" value. This can be a solution of your problem.
Sometimes long url for "submitted-url" key cause a that kind of problem.

How to post an image to a LinkedIn account using Objective-C code on iOS?

I am able to post the comment to LinkedIn but not able to post the image. This is the code for posting the comment:
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:self.consumer
token:self.accessToken
callback:nil
signatureProvider:nil];
NSString *postedStr = self.textView.text;
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc]
initWithObjectsAndKeys:
#"anyone",#"code",nil], #"visibility",
postedStr, #"comment", nil];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *updateString = [update JSONString];
[request setHTTPBodyWithString:updateString];
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:)];
// [self.view addSubview:linkedinView];
[request release];
Any suggestion really appreciated!
try this bellow code may be its help you:-
-(void)postUpdateHERE
{
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:[self getConsumer]
token:self.accesstoken
callback:nil
signatureProvider:nil];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc]
initWithObjectsAndKeys:
#"anyone",#"code",nil], #"visibility",
#"comment goes here", #"comment",
[[NSDictionary alloc]
initWithObjectsAndKeys:
#"description goes here",#"description",
#"www.google.com",#"submittedUrl",
#"title goes here",#"title",
#"http://economy.blog.ocregister.com/files/2009/01/linkedin-logo.jpg",#"submittedImageUrl",nil],#"content",
nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
[request setValue:#"application/xml" forHTTPHeaderField:#"Content-Type"];
NSString *updateString = [update JSONString];
[request setHTTPBodyWithString:updateString];
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:)];
}
i found this from bellow stackover flow answer:-
Can't share using OAuth Starter Kit for LinkedIn
EDIT:-
For TamilKing comment reply. you can get image URL of you currunt Location using Google API. First you need to get you currunt Location Image Like:-
NSString *staticMapUrl = [NSString stringWithFormat:#"http://maps.google.com/maps/api/staticmap?markers=color:red|%f,%f&%#&sensor=true",lat, log,#"zoom=12&size=114x116"]; //That above staticMapURl NSlog is :http://maps.google.com/maps/api/staticmap?markers=color:red|1.282130,103.803131&zoom=12&size=114x116&sensor=true
That given you current Location image for example:-
Now you have to convert this above NSString to NSURL like
NSURL *mapUrl = [NSURL URLWithString:[staticMapUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
and use this url that you want to share in to LinkedIn. hope that helps you.
You may need to do more, but for sure you'll need to set the length...
[request setValue:[NSString stringWithFormat:#"%d", updateString.length] forHTTPHeaderField:#"Content-Length"];

Timeout doesn't work properly in the NSMutableURLRequest. But, why?

NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:#"application/x-www-form-urlencoded;charset=utf-8" forKey:#"Content-Type"];
[headers setValue:#"text/html" forKey:#"Accept"];
[headers setValue:#"no-cache" forKey:#"Cache-Control"];
[headers setValue:#"no-cache" forKey:#"Pragma"];
[headers setValue:#"close" forKey:#"Connection"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:TIMEOUT_REQUEST];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
[self createConnectionWithRequest:request delegate:delegate];
My TIMEOUT_REQUEST=30 seconds , but sometimes i'm waiting for 80 seconds before I'll get didFailWithError. But, why?

OAuthConsumer and Twitpic

I'm trying to post images to TwitPic using OAuthConsumer. I keep receiving a 401 "Could not authenticate you (header rejected by twitter)." error.
I am also making use of the Twitter+OAuth library to handle the login and posting regular tweets, and then saving the token and token secret for using with TwitPic.
This is the code I am using the construct the request:
NSURL *twitpicUrl = [NSURL URLWithString:#"http://api.twitpic.com/2/upload.json"];
NSString* realm = #"http://api.twitter.com/";
OAToken* oaToken = [[OAToken alloc] initWithKey:savedToken secret:savedTokenSecret];
OAConsumer* oaConsumer = [[OAConsumer alloc] initWithKey:kOAuthConsumerKey secret:kOAuthConsumerSecret];
OAMutableURLRequest *request = [[[OAMutableURLRequest alloc] initWithURL:twitpicUrl consumer:oaConsumer
token:oaToken realm:realm signatureProvider:nil] autorelease];
[request prepare];
[request setHTTPMethod:#"POST"];
[request setValue:#"https://api.twitter.com/1/account/verify_credentials.json" forHTTPHeaderField:#"X-Auth-Service-Provider"];
NSString* authorizeHeader = [request valueForHTTPHeaderField:#"Authorization"];
[request setValue:authorizeHeader forHTTPHeaderField:#"X-Verify-Credentials-Authorization"];
And if I print out my headers, this is what I get (excluding the unused Authorization header):
"X-Auth-Service-Provider" = "https://api.twitter.com/1/account/verify_credentials.json";
"X-Verify-Credentials-Authorization" = "OAuth realm=\"http%3A%2F%2Fapi.twitter.com%2F\", oauth_consumer_key=\"JOvwW7mtZUjRXZRInkQI7w\", oauth_token=\"293217559-pD0HL0oE6TZSkU35mPnc7kia325oPDgMfQMTVArK\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"ctmCK35JFwx8qs8lQj0AYB6sUr4%3D\", oauth_timestamp=\"1304580843\", oauth_nonce=\"7EBE3EB0-641A-40EA-A57C-8D071B5E647F\", oauth_version=\"1.0\"";
The error I receive is:
Error: The operation couldn’t be completed. (NSURLErrorDomain error -1012.)
{"errors":[{"code":401,"message":"Could not authenticate you (header rejected by twitter)."}]}
I have excluded some detail here, specifically appending the post data, mainly because I don't think it's relevant to the error. If you think otherwise let me know and I'll update the question.
Can anyone help?
Update: Here is the code that I am now using successfully
In header:
#define kVerifyCredentialsUrl #"https://api.twitter.com/1/account/verify_credentials.json"
#define kTwitPicUrl #"http://api.twitpic.com/2/upload.json"
Implementation:
//prepare the verify credentials header
NSURL* serviceUrl = [NSURL URLWithString:kVerifyCredentialsUrl];
NSString* realm = #"http://api.twitter.com/";
OAToken* token = [[OAToken alloc] initWithKey:tokenKey secret:tokenSecret];
OAConsumer* consumer = [[OAConsumer alloc] initWithKey:kOAuthConsumerKey secret:kOAuthConsumerSecret];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:serviceUrl consumer:consumer token:token realm:realm signatureProvider:nil];
[request setHTTPMethod:#"GET"];
[request prepare];
NSDictionary* headerDictionary = [request allHTTPHeaderFields];
NSString* oAuthHeader = [NSString stringWithString:[headerDictionary valueForKey:#"Authorization"]];
[request release];
request = nil;
//prepare the full request
serviceUrl = [NSURL URLWithString:kTwitPicUrl];
request = [[OAMutableURLRequest alloc] initWithURL:serviceUrl consumer:consumer token:token realm:realm signatureProvider:nil];
[request setHTTPMethod:#"POST"];
[request setValue:kVerifyCredentialsUrl forHTTPHeaderField:#"X-Auth-Service-Provider"];
[request setValue:oAuthHeader forHTTPHeaderField:#"X-Verify-Credentials-Authorization"];
//add the content and start the request
UIImage* imageToUpload = [UIImage imageNamed:#"test.png"];
NSData *data = UIImagePNGRepresentation(imageToUpload);
ASIFormDataRequest *asiRequest = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:kTwitPicUrl]] autorelease];
[asiRequest addRequestHeader:#"X-Auth-Service-Provider" value:kVerifyCredentialsUrl];
[asiRequest addRequestHeader:#"X-Verify-Credentials-Authorization" value:oAuthHeader];
[asiRequest setPostValue:#"Message here" forKey:#"message"];
[asiRequest setPostValue:kTwitPicAPIKey forKey:#"key"];
[asiRequest setData:data forKey:#"media"];
[asiRequest setDidFinishSelector:#selector(requestDone:)];
[asiRequest setDidFailSelector:#selector(requestWentWrong:)];
[asiRequest setDelegate:self];
[asiRequest startAsynchronous];
Try this :
NSURL *serviceURL = [NSURL URLWithString:#"https://api.twitter.com/1/account/verify_credentials.json"];
OAMutableURLRequest *oRequest = [[OAMutableURLRequest alloc] initWithURL:serviceURL
consumer:consumer_
token:accessToken_
realm:#"http://api.twitter.com/"
signatureProvider:nil];
[oRequest setHTTPMethod:#"GET"];
[oRequest prepare];
NSDictionary * headerDict = [oRequest allHTTPHeaderFields];
NSString * oauthHeader = [NSString stringWithString:[headerDict valueForKey:#"Authorization"]];
[oRequest release];
// Prepare the POST request
oRequest = nil;
serviceURL = nil;
serviceURL = [NSURL URLWithString:#"http://api.twitpic.com/2/upload.json"];
oRequest = [[OAMutableURLRequest alloc] initWithURL:serviceURL
consumer:consumer_
token:accessToken_
realm:#"http://api.twitter.com/"
signatureProvider:nil];
[oRequest setHTTPMethod:#"POST"];
[oRequest setValue:#"https://api.twitter.com/1/account/verify_credentials.json" forHTTPHeaderField:#"X-Auth-Service-Provider"];
[oRequest setValue:oauthHeader forHTTPHeaderField:#"X-Verify-Credentials-Authorization"];
You should also make this change in OAMutableURLRequest.m at the end of the method - (void)prepare:
NSString *oauthHeader = [NSString stringWithFormat:#"OAuth realm=\"%#\", oauth_consumer_key=\"%#\", %#oauth_signature_method=\"%#\", oauth_signature=\"%#\", oauth_timestamp=\"%#\", oauth_nonce=\"%#\", oauth_version=\"1.0\"%#",
[realm URLEncodedString],
[consumer.key URLEncodedString],
oauthToken,
[[signatureProvider name] URLEncodedString],
[signature URLEncodedString],
timestamp,
nonce,
extraParameters];
if(![self valueForHTTPHeaderField:#"X-Verify-Credentials-Authorization"])
[self setValue:oauthHeader forHTTPHeaderField:#"Authorization"];
It may also be a problem with twitter right now.
My code using OAMutableURLRequest like yours, has been working fine for ages, and today I keep getting the 401 error code. Searching twitter you will find more people having this problem recently.
This is what you can read now in the api status page:
We are currently experiencing elevated
error rates. There may be intermittent
issues loading twitter.com and Twitter
clients. We are aware of the problem
and taking action. Thanks for your
patience!
Twitter API Status