如何使用iOS SDK保存LinkedIn访问令牌?

我在我的iOS应用程序中使用LinkedIn.我想保存访问令牌以供将来使用.

令牌属于非属性类型,无法直接保存在NSUserDefaults中.
我尝试使用NSKeyedArchiver,但我得到了输出

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

令牌中的文本即将到来,但值将为空.

代码段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,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;
}

我也尝试像这样保存,但结果是一样的:

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

代码段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];

我的编码或访问令牌有什么问题需要一些特殊技术来保存吗?请建议.

解决方法

这就是我拯救的方式.它对我有用.希望它有所帮助
- (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",@"Login Successful",nil];
   }
   // Notify parent and close this view
   [[NSNotificationCenter defaultCenter] postNotificationName:@"loginViewDidFinish" object:self userInfo:dict];
   [self dismissViewControllerAnimated:YES completion:^{

   }];
 }

以这种方式使用保存的responseBody

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];

我希望这次我很清楚

相关文章

背景 前端时间产品经理决定使用百度统计,使得 工程B 中原统计sdk-友盟统计,需要被去除。之前尝试去除...
结论: alloc负责分配内存和创建对象对应的isa指针; init只是返回alloc生成的对象。 所以alloc后,多次...
更新 如果UI愿意把启动图切割成n份,按一定约束在launchscreen.storyboard中进行排版,启动图效果会更好...
最近在看一本书《Effective OC 2.0》,今天看到有个tip是OC适中循环各自优劣性,作者最终推荐此块循环。...
// // ViewController.m // paintCodeTestOC //gif // Created by LongMa on 2019/7/25. // #import &a...
背景介绍 一般情况下,出于省电、权限、合理性等因素考虑,给人的感觉是很多奇怪的需求安卓可以实现,但...