Linked in Share not working in my app - ios

Hi I want share text in LinkedIn through my app. My code is below here...
This method when I click the btn linkedIn share..
- (void)linkedBtnEvent
{
if(oAuthLoginView != nil) {
oAuthLoginView.delegate = nil;
oAuthLoginView = nil;
}
oAuthLoginView = [[OAuthLoginView alloc] initWithNibName:nil bundle:nil];
oAuthLoginView.delegate=self;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(loginViewDidFinish:)
name:#"loginViewDidFinish"
object:self.oAuthLoginView];
[self presentViewController:self.oAuthLoginView animated:YES completion:nil];
}
This are the method to handle share after login..
-(void) loginViewDidFinish:(NSNotification*)notification
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self profileApiCall];
}
- (void)profileApiCall
{
NSURL *url = [NSURL URLWithString:#"https://api.linkedin.com/v1/people/~"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(profileApiCallResult:didFinish:)
didFailSelector:#selector(profileApiCallResult:didFail:)];
}
- (void)profileApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSDictionary *profile = [responseBody objectFromJSONString];
if ( profile )
{
NSLog(#"%#", [[NSString alloc] initWithFormat:#"%# %#",
[profile objectForKey:#"firstName"], [profile objectForKey:#"lastName"]]);
}
// The next thing we want to do is call the network updates
[self networkApiCall];
}
- (void)profileApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
- (void)networkApiCall
{
NSURL *url = [NSURL URLWithString:#"https://api.linkedin.com/v1/people/~/network/updates?scope=self&count=1&type=STAT"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(networkApiCallResult:didFinish:)
didFailSelector:#selector(networkApiCallResult:didFail:)];
}
- (void)networkApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
if (isSharedLinked)
{
NSLog(#"Shared Successfully");
linkedBtn.enabled = NO;
}
else
{
isSharedLinked = YES;
[self performSelector:#selector(postTextLinkedIn) withObject:nil afterDelay:1];
}
}
- (void)networkApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
- (void)postTextLinkedIn
{
NSURL *url = [NSURL URLWithString:#"https://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc]
initWithObjectsAndKeys:
#"anyone",#"code",nil], #"visibility",
#"Wow its working... Share the text in Linked In", #"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:)];
}
- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
// The next thing we want to do is call the network updates
[self networkApiCall];
}
- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
It shows no error it always haow it share successfully in LinkedIn but no text share in that..
Please help me to fix this issue... I cant figure what mistake I done..

You need to add "rw_nus" in "scope". This only permit the app to share updates... This is your mistake otherwise all your code correct man..
- (void)requestTokenFromProvider
{
OAMutableURLRequest *request =
[[[OAMutableURLRequest alloc] initWithURL:requestTokenURL
consumer:self.consumer
token:nil
callback:linkedInCallbackURL
signatureProvider:nil] autorelease];
[request setHTTPMethod:#"POST"];
OARequestParameter *nameParam = [[OARequestParameter alloc] initWithName:#"scope"
value:#"r_fullprofile+r_contactinfo+r_emailaddress+r_network+r_basicprofile+rw_nus"];
NSArray *params = [NSArray arrayWithObjects:nameParam, nil];
[request setParameters:params];
OARequestParameter * scopeParameter=[OARequestParameter requestParameter:#"scope" value:#"r_fullprofile r_contactinfo r_emailaddress r_network r_fullprofile rw_nus"];
[request setParameters:[NSArray arrayWithObject:scopeParameter]];
OADataFetcher *fetcher = [[[OADataFetcher alloc] init] autorelease];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(requestTokenResult:didFinish:)
didFailSelector:#selector(requestTokenResult:didFail:)];
}
Replace this is in your oAuthloginView.m

You can use a great lib for LinkedIn sharing: https://www.cocoacontrols.com/controls/linkedin-share
or directly from GitHub: https://github.com/pmilanez/MIS-Linkedin-Share
It is covered with MIT License and can be used in commercial project as well.
Hope this helps.

Related

Payu money Payment GateWay Integration

I am trying to integrate payu money payment gateway in my app.
Payumoney collect all information and done transaction and return back to my custom defined url webpage.
My problem is how to get the response code after successful transaction from payu money gateway?
int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:#"%d%#",i,[NSDate date]]];
NSString *txnid1 = [strHash substringToIndex:20];
NSLog(#"tnx1 id %#",txnid1);
// NSString *key = #"JBZaLc";
// NSString* salt = #"GQs7yium";
NSString *key = #"gtKFFx";
NSString* salt = #"eCwWELxi";
NSString *amount = dataMoney.usrAmount;
NSString *productInfo = #"App Products Info ";
NSString *firstname = dataMoney.usrName;
NSString *email = dataMoney.usrEmail;
NSString *phone = dataMoney.usrMobile;
NSString *surl = #"https://dl.dropboxusercontent.com/s/dtnvwz5p4uymjvg/success.html";
NSString *furl = #"https://dl.dropboxusercontent.com/s/z69y7fupciqzr7x/furlWithParams.html";
NSString *hashValue = [NSString stringWithFormat:#"%#|%#|%#|%#|%#|%#|||||||||||%#",key,txnid1,amount,productInfo,firstname,email,salt];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,surl,furl,hash, nil] forKeys:[NSArray arrayWithObjects:#"txnid",#"key",#"amount",#"productinfo",#"firstname",#"email",#"phone",#"surl",#"furl",#"hash", nil]];
__block NSString *post = #"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:#""]) {
post = [NSString stringWithFormat:#"%#=%#",key,obj];
}else{
post = [NSString stringWithFormat:#"%#&%#=%#",post,key,obj];
}
}];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://test.payu.in/_payment"]]];
// change URL for live
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[web_view_PayU loadRequest:request];
#define Merchant_Key #"your merchant key "
#define Salt #"your salt key"
#define Base_URL #"https://secure.payu.in"
> //this base url in case of origional payment key's if you want to integarate with
test key's write base Url can check in payumoney Faq
**
#define Success_URL #"https://www.google.co.in/"
#define Failure_URL #"http://www.bing.com/"
#define Product_Info #"Denim Jeans"
#define Paid_Amount #"1549.00"
#define Payee_Name #"Suraj Mirajkar"
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
[self setTitle:#"Make A Payment"];
[self initPayment];
}
- (void)viewDidLoad {
[super viewDidLoad];
activityIndicatorView = [[UIActivityIndicatorView alloc] init];
activityIndicatorView.center = self.view.center;
[activityIndicatorView setColor:[UIColor blackColor]];
[self.view addSubview:activityIndicatorView];
}
-(void)initPayment {
int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:#"%d%#",i,[NSDate date]]];// Generatehash512(rnd.ToString() + DateTime.Now);
NSString *txnid1 = [strHash substringToIndex:20];
strMIHPayID = txnid1;
NSString *key = Merchant_Key;
NSString *amount =[[NSUserDefaults standardUserDefaults]
stringForKey:#"orderprice"];
//NSString *amount = Paid_Amount;
NSString *productInfo = Product_Info;
NSString *firstname = Payee_Name;
NSString *email = [NSString stringWithFormat:#"suraj%d#yopmail.com",i];
//ADD A fake mail For Payment for testing purpose
// Generated a fake mail id for testing
NSString *phone = #"9762159571";
NSString *serviceprovider = #"payu_paisa";
NSString *hashValue = [NSString stringWithFormat:#"%#|%#|%#|%#|%#|%#|||||||||||%#",key,txnid1,amount,productInfo,firstname,email,Salt];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,Success_URL,Failure_URL,hash,serviceprovider
, nil] forKeys:[NSArray arrayWithObjects:#"txnid",#"key",#"amount",#"productinfo",#"firstname",#"email",#"phone",#"surl",#"furl",#"hash",#"service_provider", nil]];
NSLog(#"%#",parameters);
__block NSString *post = #"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:#""]) {
post = [NSString stringWithFormat:#"%#=%#",key,obj];
} else {
post = [NSString stringWithFormat:#"%#&%#=%#",post,key,obj];
}
}];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/_payment",Base_URL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[_webviewPaymentPage loadRequest:request];
[activityIndicatorView startAnimating];
}
-(NSString *)createSHA512:(NSString *)string {
const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:string.length];
uint8_t digest[CC_SHA512_DIGEST_LENGTH];
CC_SHA512(data.bytes, (CC_LONG)data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++) {
[output appendFormat:#"%02x", digest[i]];
}
return output;
}
#pragma UIWebView - Delegate Methods
-(void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"WebView started loading");
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[activityIndicatorView stopAnimating];
if (webView.isLoading) {
return;
}
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(#"WebView finished loading with requestURL: %#",requestURL);
NSString *getStringFromUrl = [NSString stringWithFormat:#"%#",requestURL];
if ([self containsString:getStringFromUrl :Success_URL]) {
[self performSelector:#selector(delayedDidFinish:) withObject:getStringFromUrl afterDelay:0.0];
} else if ([self containsString:getStringFromUrl :Failure_URL]) {
// FAILURE ALERT
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Sorry !!!" message:#"Your transaction failed. Please try again!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alert.tag = 1;
[alert show];
}
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[activityIndicatorView stopAnimating];
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(#"WebView failed loading with requestURL: %# with error: %# & error code: %ld",requestURL, [error localizedDescription], (long)[error code]);
if (error.code == -1009 || error.code == -1003 || error.code == -1001) { //error.code == -999
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Oops !!!" message:#"Please check your internet connection!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alert.tag = 1;
[alert show];
}
}
- (void)delayedDidFinish:(NSString *)getStringFromUrl {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:strMIHPayID forKey:#"Transaction_ID"];
[mutDictTransactionDetails setObject:#"Success" forKey:#"Transaction_Status"];
[mutDictTransactionDetails setObject:Payee_Name forKey:#"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:#"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:#"Paid_Amount"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
});
}
#pragma UIAlertView - Delegate Method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.tag == 1 && buttonIndex == 0) {
// Navigate to Payment Status Screen
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:Payee_Name forKey:#"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:#"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:#"Paid_Amount"];
[mutDictTransactionDetails setObject:strMIHPayID forKey:#"Transaction_ID"];
[mutDictTransactionDetails setObject:#"Failed" forKey:#"Transaction_Status"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
}
}
- (BOOL)containsString: (NSString *)string : (NSString*)substring {
return [string rangeOfString:substring].location != NSNotFound;
}
- (void)navigateToPaymentStatusScreen: (NSMutableDictionary *)mutDictTransactionDetails {
dispatch_async(dispatch_get_main_queue(), ^{
PaymentStatusViewController *paymentStatusViewController = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:#"PaymentStatusScreenID"];
paymentStatusViewController.mutDictTransactionDetails = mutDictTransactionDetails;
[self.navigationController pushViewController:paymentStatusViewController animated:YES];
});
}
Important Note : you can check your Merchant key and Salt in seller Dashboard after Login ... Go To my account and check your merchant key and salt

I have integrated google plus in my IOS App , Now how can i get profile detail of logged in user?

I have integrated google plus in my ios app ,I am able to get access token.I have used authentication flow to integrate google plus.So now after getting access token how can i get user profile details like username, email id, profile pic etc?
My code to get access token is as below:
-(IBAction)btnGooglePlusClicked:(UIButton *)sender
{
IBwebView.hidden = FALSE;
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CALL_BACK_URL,GOOGLE_PLUS_SCOPE,GOOGLE_PLUS_VISIBLE_ACTIONS];
[IBwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CLIENT_SECRET,GOOGLE_PLUS_CALL_BACK_URL];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSLog(#"verifier %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
I feel the the method you are using will not help to get the profile detail.
I suggest to use the proper method which ensures the best results.
Please check this out : https://developers.google.com/+/mobile/ios/
This will surely help you to get required outcome.

app crashes on NSURLCONNECTION when multiple request

Hey guyz I have this issue regarding the NSUrlConnection where I initiate a request like this
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:URL_PACKAGE,2]]];
Communication *comm = [[Communication alloc] initWithUrlRequest:request];
comm.request_name = request_name;
comm.delegate = self;
[comm startAsynchronous];
[request release];
and then the response getting code is fine but as you can see I have created a communication class to make the connection and when I request with difference web services it
- (Communication *) initWithUrlRequest:(NSMutableURLRequest *)url_request {
self.request = url_request;
return self;
}
-(void)dealloc {
[super dealloc];
}
- (void) startAsynchronous {
responseData = [[NSMutableData data] retain];
NSLog(#"%#",[request URL]);
downloadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
[responseData setLength:0];
if ( [[self delegate] respondsToSelector:#selector(communication:didReceiveResponse:RequestName:)] ) {
[self.delegate communication:self didReceiveResponse:response RequestName:self.request_name];
}
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
[responseData appendData:data];
if ( [[self delegate] respondsToSelector:#selector(communication:didReceiveData:RequestName:)] ) {
[self.delegate communication:self didReceiveData:data RequestName:self.request_name];
}
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error {
[self.delegate communication:self didFailWithError:error RequestName:self.request_name];
NSLog(#"%#", error);
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection {
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
[responseData release];
responseString = [responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"+" withString:#" "];
responseString = [responseString stringByReplacingOccurrencesOfString:#"null" withString:#"\"\""];
[self.delegate communication:self didFinishWithString:responseString RequestName:self.request_name];
}
The error is
2013-07-30 13:55:46.994 Ipad Qld[3982:c07] *** -[Requests respondsToSelector:]: message sent to deallocated instance 0xa16b310

how to upload the audio songs into server using ios?

I am beginner iOS apps developer .I have tried following link codes.It's playing good but I need selected audio file path and how to upload to server in selected audio,kindly help out.Audio code Reference url
-(IBAction)clickFileuploadbtn:(id)sender;
{
NSLog(#"2");
picker1 =
[[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker1.delegate = self;
picker1.allowsPickingMultipleItems = YES;
picker1.prompt = NSLocalizedString (#"Add songs to play", "Prompt in media item picker");
// The media item picker uses the default UI style, so it needs a default-style
// status bar to match it visually
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault animated: YES];
[self presentModalViewController: picker1 animated: YES];
[picker1 release];
// [Uploads FileUpload];
}
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[self dismissModalViewControllerAnimated: YES];
NSLog(#"%# %d",mediaItemCollection,mediaItemCollection.count);
NSArray *newMediaItem= [mediaItemCollection items];
MPMediaItem *item=[[newMediaItem objectAtIndex:0] retain];
[self uploadMusicFile:item];
}
- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
{
[self dismissModalViewControllerAnimated: YES];
NSLog(#"cancel");
}
- (void) uploadMusicFile:(MPMediaItem *)song
{
NSURL *url = [song valueForProperty: MPMediaItemPropertyAssetURL];
// Given some file path URL: NSURL *pathURL
// Note: [pathURL isFileURL] must return YES
NSString *path = [NSString stringWithFormat:#"%#",url];
NSLog(#"path %#",path);
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
NSLog(#"data %#" ,data);
NSString *audioName = #"myAudio.caf";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.176:1001/api?type=iphoneupload"]];
[request addData:data withFileName:audioName andContentType:#"audio/caf" forKey:#"audioFile"];
[request setDelegate:self];
[request setTimeOutSeconds:500];
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
}
- (void)uploadRequestFinished:(ASIHTTPRequest *)request
{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
NSData *webData = [[NSData alloc] initWithData:[request responseData]];
NSString *strEr = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"strEr %#",strEr);
}
- (void) uploadRequestFailed:(ASIHTTPRequest *)request
{
NSLog(#"responseStatusCode %i",[request responseStatusCode]);
NSLog(#"responseString %#",[request responseString]);
NSError *error = [request error];
NSLog(#"error %#",error);
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
}

Unable to post on tumblr from iOS OAuth1.0, OAConsumer client

I am trying to integrate "tumblr" into my application.I am able to get the access token successfully. But, when I try to post, I am getting the following error
{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}
I am using the OAuthConsumer client for iOS, which I have pulled if from MGTwitterEngine.
This is what I have tried.
#import "ViewController.h"
#define consumer_key #"u9iZvT8KIlrTtUrh3vUeXXXXXXXXXXXXXAfgpThGyom8Y6MKKCnU"
#define consumer_secret #"xfA10mQKmALlpsnrFXXXXXXXXXXXXXXXXXXXXXXXXXX"
#define request_token_url #"http://www.tumblr.com/oauth/request_token"
#define access_token_url #"http://www.tumblr.com/oauth/access_token"
#define authorize_url #"http://www.tumblr.com/oauth/authorize?oauth_token=%#"
#define base_url #"http://api.tumblr.com/v2/user/XXXXXXXXXXXXX.tumblr.com/info"
#define user_info #"http://api.tumblr.com/v2/user/info"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (IBAction)postIt:(id)sender
{
NSURL *postURL = [NSURL URLWithString:#"http://api.tumblr.com/v2/blog/xxxxxxxx.tumblr.com/post"];
OAMutableURLRequest *oRequest = [[OAMutableURLRequest alloc] initWithURL:postURL
consumer:self.consumer
token:self.accessToken
realm:nil
signatureProvider:nil];
[oRequest setHTTPMethod:#"POST"];
[oRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
OARequestParameter *statusParam = [[OARequestParameter alloc] initWithName:#"body"
value:#"Sample Body"];
OARequestParameter *statusParam2 = [[OARequestParameter alloc] initWithName:#"type"
value:#"text"];
NSArray *params = [NSArray arrayWithObjects:statusParam,statusParam2, nil];
[oRequest setParameters:params];
OAAsynchronousDataFetcher *fetcher = [OAAsynchronousDataFetcher asynchronousFetcherWithRequest:oRequest
delegate:self
didFinishSelector:#selector(sendStatusTicket:didFinishWithData:)
didFailSelector:#selector(sendStatusTicket:didFailWithError:)];
NSLog(#"URL = %#",[oRequest.URL absoluteString]);
[fetcher start];
}
- (void)didReceiveAccessToken:(OAServiceTicket *)ticker data:(NSData *)responseData
{
}
- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error {
// ERROR!
}
- (void)sendStatusTicket:(OAServiceTicket *)ticker didFinishWithData:(NSData *)responseData
{
if (ticker.didSucceed) {
NSLog(#"Success");
}
NSString *responseBody = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSLog(#"Description = %#",responseBody);
}
- (void)sendStatusTicket:(OAServiceTicket *)ticker didFailWithError:(NSError *)error
{
NSLog(#"Error = %#",[error localizedDescription]);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (IBAction)login:(id)sender
{
self.consumer = [[OAConsumer alloc] initWithKey:consumer_key secret:consumer_secret];
NSURL *url = [NSURL URLWithString:request_token_url];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:self.consumer
token:nil // we don't have a Token yet
realm:nil // our service provider doesn't specify a realm
signatureProvider:nil]; // use the default method, HMAC-SHA1
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(requestTokenTicket:didFinishWithData:)
didFailSelector:#selector(requestTokenTicket:didFailWithError:)];
}
- (void)requestTokenTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
if (ticket.didSucceed)
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
self.accessToken= [[OAToken alloc] initWithHTTPResponseBody:responseBody];
NSURL *author_url = [NSURL URLWithString:[ NSString stringWithFormat:authorize_url,self.accessToken.key]];
OAMutableURLRequest *oaR = [[OAMutableURLRequest alloc] initWithURL:author_url consumer:nil token:nil realm:nil signatureProvider:nil];
UIWebView *webView =[[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
[[[UIApplication sharedApplication] keyWindow] addSubview:webView];
webView.delegate=self;
[webView loadRequest:oaR];
}
}
// This is to get oAuth_verifier from the url
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *url = [[request URL] absoluteString];
NSString *keyOne = #"oauth_token";
NSString *keyTwo = #"oauth_verifier";
NSRange r1 =[url rangeOfString:keyOne];
NSRange r2 =[url rangeOfString:keyTwo];
if (r1.location!=NSNotFound && r2.location!=NSNotFound) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"oauth_verifier"]) {
verifier = [keyValue objectAtIndex:1];
break;
}
}
if (verifier) {
NSURL* accessTokenUrl = [NSURL URLWithString:#"http://www.tumblr.com/oauth/access_token"];
OAMutableURLRequest* accessTokenRequest =[[OAMutableURLRequest alloc] initWithURL:accessTokenUrl
consumer:self.consumer
token:self.accessToken
realm:nil
signatureProvider:nil];
OARequestParameter* verifierParam =[[OARequestParameter alloc] initWithName:#"oauth_verifier" value:verifier];
[accessTokenRequest setHTTPMethod:#"POST"];
[accessTokenRequest setParameters:[NSArray arrayWithObjects:verifierParam,nil]];
OADataFetcher* dataFetcher = [[OADataFetcher alloc] init];
[dataFetcher fetchDataWithRequest:accessTokenRequest
delegate:self
didFinishSelector:#selector(requestTokenTicketForAuthorization:didFinishWithData:)
didFailSelector:#selector(requestTokenTicket:didFailWithError:)];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)requestTokenTicketForAuthorization:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data
{
if (ticket.didSucceed)
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
self.accessToken = [self.accessToken initWithHTTPResponseBody:responseBody];
accessText=self.accessToken.key;
accessSecret=self.accessToken.secret;
}
else
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"Response = %#",responseBody);
}
}
- (void)requestTokenTicket:(OAServiceTicket *)ticket didFailWithError:(NSError *)error
{
NSLog(#"Error = %#",[error localizedDescription]);
}
#end
Whats the mistake I am making here? Why I am getting that error? Did I follow the steps properly?
Please XXX out your consumer_key and consumer_secret to avoid unwanted use of them.
Code wise there are a few things you might want to look for here.
Are you able to use an oauth 'GET' request such as "http://api.tumblr.com/v2/user/info"?
If you can receive a successful 'GET' request then your access token is valid and you can look at how you're sending your post parameters.
Make sure you are passing in your parameters as HTTP Body as well as signature parameters. Correct parameter ordering is likely provided by the library.
NSString *postbody = #"body=myBodyText&type=text";
[oRequest setHTTPBody:[postbody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:TRUE]];

Resources