OAuth Refresh Token Process for salesforce SDK - ios

Can anyone help me with refreshing token on saleforce.
NSDictionary *fields = #{#"grant_type" : #"refresh_token",
#"refresh_token": oauth[#"refreshToken"],
#"client_id": coordinator.credentials.clientId,
#"format": #"json"
};
SFRestRequest *request = [SFRestRequest requestWithMethod:SFRestMethodPOST path:[NSString stringWithFormat:#"%#/services/oauth2/token",[SFAccountManager loginHost]] queryParams:fields];
request.endpoint = [NSString stringWithFormat:#"%#/services/oauth2/authorize", [SFAccountManager loginHost]];
[[SFRestAPI sharedInstance] sendRESTRequest:request failBlock:^(NSError *e) {
NSLog(#"Error %#", e);
} completeBlock:^(NSDictionary* dict) {
NSLog(#"dict");
}];
This is what i am trying to do, but i am getting the following error:
Error Domain=NSURLErrorDomain Code=404 "The operation couldn’t be completed. (NSURLErrorDomain error 404.)" UserInfo=0x7993c670 {Transfer-Encoding=Identity, Content-Type=text/html;charset=UTF-8, Date=Thu, 13 Nov 2014 15:23:36 GMT}
I am not sure what is going wrong.
FYI: Understanding the OAuth Refresh Token Process
This is the request:
endpoint: test.salesforce.com/services/oauth2/authorize
method: POST
path: test.salesforce.com/services/oauth2/token
queryParams: {"grant_type":"refresh_token","refresh_token":"5AsdfdfssdBuiV6yFNukUqDSMUH1tnk39L.x0GFcdqdMhpmQUTu.wv1BNndfglD3SxEZIFUev4i8T2KLkcCOK","format":"json","client_id":"3MVG9dPGzsddfssfdsOQG3p9KW.2hh3Bh5BeEsdfsRlDhxcybG.YRTQC0C0XayvzEw.5.umftLwJpYjYVDE6xgSCgXo"}

I stopped using Salesforce and NSURL Kit instead i use AFHTTPREQUEST
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"password" forKey:#"grant_type"];
[dict setObject:#"xxx" forKey:#"client_id"];
[dict setObject:#"xxx" forKey:#"client_secret"];
[dict setObject:#"your user" forKey:#"username"];
[dict setObject:#"password" forKey:#"password"];
[dict setObject:#"json" forKey:#"format"];
[manager POST:#"https://test.salesforce.com/services/oauth2/token" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
}];

Related

How to send json data in the Http request using AFNetworking

I have to pass data like json format to the server
{"email":"abc#gmail.com","password":"abc"}
and i have used this code but data is not pass to the server please help me..
NSDictionary *dict1=#{#"email": #"biren123#gmail.com"};
NSDictionary *dict2=#{#"password": #"biren"};
services *srv=[[services alloc]init];
NSString *str=#"http://emailsending.in/setting_saver_api/";
NSString *method=#"login.php";
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:dict1 forKey:#"email"];
[dict setValue:dict2 forKey:#"password"];
[srv postToURL:str withMethod:method andParams:dict completion:^(BOOL success, NSDictionary *responseObj)
{
NSLog(#"res :%#",responseObj);
NSLog(#"%d",success);
NSLog(#"Successfully..................");
}];
you can check your link at
https://www.hurl.it/
1)give your http link
2)select your method type "Get" or "Post"
3)add the parameters
and check the response.If you get the same response contact your backend team.
Try this.
1) Convert your dictionary into json using NSJSONSerialization and store it in NSdata.
NSData * incidentData = [NSJSONSerialization dataWithJSONObject: params options:0 error:&err];
2) Post the NSdata containing json to your server
Try this,if this helps
NSString *str = #"http://emailsending.in/setting_saver_api/";
NSString*method = #"login.php";
services *srv=[[services alloc]init];
NSMutableDictionary *dict1 = [NSMutableDictionary dictionary]; [dict1 setValue:#"biren123#gmail.com" forKey:#"email"];
NSMutableDictionary *dict2 = [NSMutableDictionary dictionary]; [dict2 setValue:#"biren" forKey:#"password"];
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:dict1 forKey:#"email"];
[dict setValue:dict2 forKey:#"password"];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:str parameters:dict success:^(NSURLSessionDataTask
*task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
//here is place for code executed in success case
} failure:^(NSURLSessionDataTask *task, NSError *error) {
//here is place for code executed in error case
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error while sending POST"
message:#"Sorry, try again."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
NSLog(#"Error: %#", [error localizedDescription]); }];

Afnetworking request get time out on iPhone 5 , iPhone 6 and iPhone 6+ but works on iPhone 4

I have the following URL:
http://beta.bemembr.com/en/webservice/abc123/members/login/email/******/password/****
And this piece of code:
NSString *path = [NSString stringWithFormat:#"en/webservice/%#/members/login/email/%#/password/%#",apiKey,login,pass];
NSLog(#"PATH IS %#",path);
[manager GET:path parameters:nil success:^(NSURLSessionDataTask *task, id responseObject)
{
NSDictionary *json = (NSDictionary *)responseObject;
NSLog(#"JSON IS %#",json);
int status = [[json valueForKey:#"status"] intValue];
if(status == 200){
compblock(YES);
}else{
compblock(NO);
}
}failure:^(NSURLSessionDataTask *task, NSError *error)
{
// Failure
NSLog(#"Failure: %#", error);
compblock(NO);
}];
This is working on an iPhone4 but fails on iPhone 5, iPhone6 and iPhone 6+
This is the error I got:
Failure: Error Domain=NSURLErrorDomain Code=-1001 "The operation couldn’t be completed. (NSURLErrorDomain error -1001.)" UserInfo=0x7f8951c5c7b0 {NSErrorFailingURLStringKey=http://beta.bemembr.com/en/webservice/abc123/members/login/email/*****/password/*****, NSUnderlyingError=0x7f8951c82220 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1001.)", NSErrorFailingURLKey=http://beta.bemembr.com/en/webservice/abc123/members/login/email/*****/password/*****}
Can anybody help me?
Thanks !
Try avoiding the username and password component of your URL, and try something like this instead.
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://examplewebsite.com]];
[client setAuthorizationHeaderWithUsername:#"username" password:#"password"];
Use AFNetworking: [AFNetworking2.0] https://github.com/AFNetworking/AFNetworking
Add UIKit+AFNetworking and AFNetworking folder into your project.
and add this code in the file you want to use AFNetworking:
#import "AFnetworking.h"
#import "UIKit+AFNetworking.h"
And use this code:
-(void)login
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"some_url" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
Since you are passing parameters within the URL String, set it to nil: parameters:nil

How to make a POST request in iOS?

I am trying to figure out how to make use of AFNetworking 2.0. I am trying to POST a login with a username and password.
This is my current attempt but something is not working as it does not get sent.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"loginName": #"password"};
[manager POST:#"http://xxxx.com/login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSLog(#"Data saved");
MainViewController *mainView = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
mainView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController: mainView animated:YES completion:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSString *error_msg = (NSString *) error;
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}];
}
} #catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Sign in Failed." :#"Error!" :0];
}
However nothing is happening, just keep getting this printout:
2014-04-16 20:14:09.903 Slidedrawer[9279:60b] Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8e78bd0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
The response will be in JSON. Anyone know what I need to edit in the code or how to fix it?
JSON: {
"_id" = 533cb1c453769a02008c2d55;
name = dddd;
picture = "/img/users/default.jpg";
}
How do I access the above returned JSON, trying to pick apart each returned property to a string or integer etc...
Try this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"userName": username, #"password": password};
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format
[manager POST:#"http://asd.com/login.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
}];
For parsing the response use this the responseObject as NSDictionary:
NSString *userName = [responseObject objectForKey:#"userName"];
NSString *password = [responseObject objectForKey:#"password"];
Hope this helps.. :)
You may find Send Nested JSON using AFNetworking for the answer.
The error Error Domain=NSCocoaErrorDomain Code=3840 is received invalid JSON object from the server. It is probably caused by the server's improper handling your missing parameters . Your parameters dictionary has only one key object loginName.

handling the Response with the AFNetworking 2

i am really new to IOS development. i want to develop an application which is dealing with some web services and display in a table view. somehow i found a 3rd party library for do the networking stuffs [AFNetworking 2]. below is my code to get the json response for any given url and parameters.
-(NSDictionary*)getWebServiceResponce:(NSString *)url :(NSDictionary *)object
{
// NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
__block NSDictionary* result=Nil;
__block NSString* person=Nil;
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:url
parameters:object
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
person = [responseObject[#"d"]objectForKey:#"PersonId"];
// [self returnedResponce:responseObject];
result = (NSDictionary *) responseObject[#"d"];
NSLog(#"RESULT: %#", result);
NSLog(#"personm: %#", person);
[operation waitUntilFinished];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
//result = [error];
}
];
return result;
}
this code works perfectly.. but my point is when i put some breakpoints to check what are the values i got for several variables, it shows null. but my log shows the entire json response.
and i want to return my response object as a dictionary. because i want to do some process with the response.. can some one help me with this ?
The problem is that result is nil when it gets returned. AFNetworking uses ObjC's awesome blocks, they get executed asynchronously. Read more about it here.
You should include a callback block in your getWebServiceResponce method. I've thrown together a bit of code but you should really read more about blocks.
-(void)webServiceResponceForURL:(NSString *)url dictionary:(NSDictionary *)object success:(void (^)(NSDictionary *responseObject))success {
// NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
__block NSDictionary* result=Nil;
__block NSString* person=Nil;
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:url
parameters:object
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
person = [responseObject[#"d"]objectForKey:#"PersonId"];
// [self returnedResponce:responseObject];
result = (NSDictionary *) responseObject[#"d"];
NSLog(#"RESULT: %#", result);
NSLog(#"personm: %#", person);
//We are executing the block as soon as we have the results.
if (success) {
success(responseObject);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
//result = [error];
}
];
}
Edit:
[self webServiceResponceForURL:#"foo://foo" dictionary:nil success:^(NSDictionary *responseObject) {
//your code here
}
[self webServiceResponceForURL:#"foo://foo" dictionary:nil success:^(NSDictionary *responseObject) {
//your code here
}
Here you will got complete responseObject in form NSDictionary. You can assign responseObject to instance variable. Now This instance Variable will be used at point time. in your case, it will passed on button event.

Problems with AFNetworking 2.1.0

I hope this hasn't been asked here...I've done quite a bit of searching on this site but am not really getting anywhere I've been using ASIHTTPRequest to get JSON data, but am now trying to migrate to AFNetworking 2.1.0. I'm using the following:
-(BOOL)getCoordsForAddress:(NSString*) inputAddress {
responseString = [[NSString alloc] init];
// retrieve and urlencode address
NSString *encodedAddress = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)inputAddress, NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8);
// build the geocoding URL
NSString *getLatLonUrl = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=false", encodedAddress];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://maps.googleapis.com"]];
manager.securityPolicy.allowInvalidCertificates = YES;
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager GET:getLatLonUrl
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
responseString = [responseObject objectForKey:#"results"];
NSLog(#" Success %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#" Fail %#", error);
}];
return YES;
}
However, when I execute the manager GET routine, nothing is executed, neither the Success or Failure messages are printed out. It's as if that call is getting ignored. What am I doing wrong? Thanks for any assistance!!!

Resources