我有一个 ROR 应用程序,其 API 由 Devise + simple_token_authentication 保护 - 一切正常。现在我正在使用 NSURLSession 构建一个 iOS 应用程序来访问 API 并处理身份验证,这就是我遇到麻烦的地方。
在加载时,我调用以下方法从服务器检索数据。据我了解,在获得未经授权的 401 时应该调用 didReceiveChallenge 代表,但没有任何反应。我对iOS相当陌生,我可能做错了,但我希望有人能帮助我解决这个问题。谢谢!:)
- (void)fetch:(id)sender {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
config.HTTPAdditionalHeaders = @{ @"Accept":@"application/json"};
self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURLSessionTask *dataTask = [self.session dataTaskWithURL:[NSURL URLWithString:@"http://localhost:3000/api/v1/tasks"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle response
NSLog(@"data %@", data);
}];
[dataTask resume];
}
即使在收到 401 标头后,也不会调用此方法。
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
NSString *user = @"email";
NSString *password = @"secretpass";
NSLog(@"didReceiveChallenge");
// should prompt for a password in a real app but we will hard code this baby
NSURLCredential *secretHandshake = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceForSession];
// use block
completionHandler(NSURLSessionAuthChallengeUseCredential,secretHandshake);
}