2013-09-05 32 views
7

Używam LinkedIn w mojej aplikacji na iOS. Chcę zapisać token dostępu do przyszłego użytku.Jak zapisać token dostępu LinkedIn za pomocą zestawu SDK iOS?

Token jest typu innego niż nieruchomości, którego nie można zapisać bezpośrednio pod numerem NSUserDefaults. Próbowałem za pomocą NSKeyedArchiver do tego, ale mam wyjścia:

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

Tekst tokena nadchodzi ale wartości idą zerowa.

Fragment kodu 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; 
} 

Próbowałem też zapisać w ten sposób, ale wynik jest taki sam:

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

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

Czy jest coś wron? g z moim kodowaniem lub tokenem dostępu potrzebujesz specjalnej techniki do zapisania? Proszę zasugerować.

+0

Można zapisać token dostępu bezpośrednio do użytkownika defaults.No potrzebie zarchiwizuj go –

+0

Dziękuję za odpowiedź. Gdy zapisuję ustawienia domyślne, otrzymuję komunikat [NSUserDefaults setObject: forKey:]: Próba wstawienia wartości niestateczności "" klasy "OAToken". Zauważ, że słowniki i tablice na listach właściwości muszą również zawierać tylko wartości właściwości. – Imran

+0

nie zapisuj obiektu OAToken bezpośrednio zapisz treść odpowiedzi tak jak ja i kiedy chcesz użyć tokena dostępu, zainicjuj go za pomocą reponseBody thi sway i użyj tokena dostępu 'self.accessToken = [[NSUserDefaults standardUserDefaults] valueForKeyPath: @ "accessToken"]; [[OAToken alloc] initWithHTTPResponseBody: self.accessToken] ' –

Odpowiedz

10

tak ocaliłem. Pracował dla me.Hope pomaga

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

    }]; 
} 

użycie zapisane responseBody w ten sposób

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

mam nadzieję, że jestem jasne, tym razem

+0

Dzięki za odpowiedź. Odległa godzina, kiedy wchodzimy do aplikacji Czy da token dostępu podczas wywoływania: self.accessToken = [[OAToken alloc] initWithHTTPResponseBody: responseBody]; ponieważ zapisujemy treść odpowiedzi (łańcuch). – Imran

+0

od następnego czasu powinieneś przyjąć łańcuch ResponseBody z NSUserDa] efaults, a następnie utworzyć OAToken object.responseBody będzie przechowywany będzie dostępny aż do odinstalowania twojej aplikacji –

+0

Pozwól mi wyjaśnić jako name accessToken Conflicts. 'self.accessToken = [[OAToken alloc] initWithHTTPResponseBody: responseBody];' w tym wierszu accessToken jest instancją OAToken i 'self.accessToken = [[NSUserDefaults standardUserDefaults] valueForKeyPath: @" accessToken "]; w tym wierszu accessToken jest NSString . –

Powiązane problemy