Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save LinkedIn Access Token using iOS SDK?

I am using LinkedIn in my iOS app. I want to save the access token for the future use.

The token is of non property type which cannot be saved in NSUserDefaults directly. I tried using NSKeyedArchiver for this but I got the output:

Token===oauth_token "(null)" oauth_token_secret "(null)" oauth_verifier "(null)"

The text in the token is coming but the values are coming null.

Code snippet 1 :

-(void)saveData :(LOAToken *)token
{
    NSFileManager *filemgr;
    NSString *docsDir;
    NSArray *dirPaths;

    filemgr = [NSFileManager defaultManager];

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(
                                                   NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the data file
    NSString *dataFilePath = [[NSString alloc] initWithString: [docsDir
                                                                stringByAppendingPathComponent: @"data.archive"]];

    [NSKeyedArchiver archiveRootObject:
     token toFile:dataFilePath];
}


-(LOAToken *)GetToken
{
    NSFileManager *filemgr;
    NSString *docsDir;
    NSArray *dirPaths;

    filemgr = [NSFileManager defaultManager];

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(
                                                   NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the data file
    NSString *dataFilePath = [[NSString alloc] initWithString: [docsDir
                                                                stringByAppendingPathComponent: @"data.archive"]];

    // Check if the file already exists
    if ([filemgr fileExistsAtPath: dataFilePath])
    {
        LOAToken *token;

        token = [NSKeyedUnarchiver
                     unarchiveObjectWithFile: dataFilePath];

        return token;
    }

    return NULL;
}

I also tried to save like this but the result is same:

Token===oauth_token "(null)" oauth_token_secret "(null)" oauth_verifier "(null)"

Code snippet 2 :

NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:self.accessToken];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:myEncodedObject forKey:@"myEncodedObjectKey"];
    [defaults synchronize];

   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   NSData *myEncodedObject = [defaults objectForKey:@"myEncodedObjectKey"];
            LOAToken *obj = (LOAToken *)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];

Is there anything wrong with my coding or Access Token need some special technique to save?Please Suggest.

like image 488
Imran Avatar asked Sep 05 '13 12:09

Imran


1 Answers

this is how I saved. It worked for me.Hope it helps

- (void)accessTokenResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
    NSDictionary *dict;
    NSString *responseBody = [[NSString alloc] initWithData:data
                                               encoding:NSUTF8StringEncoding];
    BOOL problem = ([responseBody rangeOfString:@"oauth_problem"].location != NSNotFound);
   if (problem)
   {
        DLog(@"Request access token failed.");
        DLog(@"%@",responseBody);
        dict = [NSDictionary dictionaryWithObjectsAndKeys:@"0",@"success",@"Request access token failed.",@"reason", nil];
   }
   else
   {
       self.accessToken = [[OAToken alloc] initWithHTTPResponseBody:responseBody];
       [[NSUserDefaults standardUserDefaults] setObject:responseBody forKey:@"accessToken"];//save here
       [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"TokenRefreshDate"];//save here
       [[NSUserDefaults standardUserDefaults] synchronize];
       dict = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"success",@"Login Successful",@"reason", nil];
   }
   // Notify parent and close this view
   [[NSNotificationCenter defaultCenter] postNotificationName:@"loginViewDidFinish" object:self userInfo:dict];
   [self dismissViewControllerAnimated:YES completion:^{

   }];
 }

use saved responseBody in this way

self.accessToken = [[NSUserDefaults standardUserDefaults] valueForKeyPath:@"accessToken"];
NSURL *url = [NSURL URLWithString:@"http://api.linkedin.com/v1/people/~/connections:(id,first-name,last-name,headline,maiden-name,picture-url,formatted-name,location,positions,public-profile-url,specialties,num-connections,industry)"];

OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
                                                                   consumer:self.consumer
                                                                      token:[[OAToken alloc] initWithHTTPResponseBody:self.accessToken]
                                                                   callback:nil
                                                          signatureProvider:nil];

[request setValue:@"json" forHTTPHeaderField:@"x-li-format"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
                         delegate:self
                didFinishSelector:@selector(connectionsApiCallResult:didFinish:)
                  didFailSelector:@selector(connectionsApiCallResult:didFail:) withId:0];

I hope I am clear this time

like image 52
Pratyusha Terli Avatar answered Sep 22 '22 08:09

Pratyusha Terli