7

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

令牌是非属性类型,不能NSUserDefaults直接保存。我尝试使用NSKeyedArchiver它,但我得到了输出:

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

令牌中的文本即将到来,但值将变为 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, 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;
}

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

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

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

4

1 回答 1

10

我就是这样保存的。它对我有用。希望它有所帮助

- (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:^{

   }];
 }

以这种方式使用保存的 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];

我希望这次我清楚

于 2013-09-05T12:29:37.183 回答