Search code examples
objective-cfacebookparse-platformstackmob

Can't create Facebook user with access token


I am writing a method which gets the facebook user records from my db on Parse and then recreates the records on StackMob. When I call createUserWithFacebookToken it returns this error:

[48887:c07] Error Domain=HTTP Code=401 "The operation couldn’t be completed. (HTTP error 401.)" UserInfo=0xa6a9e60 {error=Login failed: }

- (IBAction)fetchAllUsers:(id)sender {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.parse.com/1/users/"]];
    [request setValue:@"XXXX" forHTTPHeaderField:@"X-Parse-Application-Id"];
    [request setValue:@"XXXX" forHTTPHeaderField:@"X-Parse-Master-Key"];

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError");
    NSLog(@"Connection failed: %@", [error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading");
    NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    NSArray *allUsers = [res objectForKey:@"results"];
    // show all values
    for (int i=0;i<allUsers.count;i++) {
        id value = [allUsers objectAtIndex:i];
        NSString *username = [value objectForKey:@"username"];
        NSDictionary *authData = [value objectForKey:@"authData"];
        NSDictionary *facebook = [authData objectForKey:@"facebook"];
        NSString *accessToken = [facebook objectForKey:@"access_token"];
        if (accessToken) {
            NSDictionary *aUser = [NSDictionary dictionaryWithObjectsAndKeys:accessToken, @"accessToken", username, @"username", nil];
//            [_userInfo addObject:aUser];

            NSLog(@"%@", aUser);
            [self processTheUser:aUser];
        }
    }
}

- (void)processTheUser:(NSDictionary *)user {
    [self.client createUserWithFacebookToken:[user valueForKey:@"accessToken"] username:[user valueForKey:@"username"] onSuccess:^(NSDictionary *result) {
        NSLog(@"%@", result);
    } onFailure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

Solution

  • Problem solved! I was working on users with a expired access_token. I simply get the valid ones and all is ok!