【发布时间】:2014-01-04 11:21:04
【问题描述】:
我的iOS 项目中有以下代码,我想转换为使用NSURLSession 而不是NSURLConnection。我正在查询一个使用基于令牌的HTTP Authentication 方案的REST API,但我找不到如何执行此操作的示例。
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"Username"];
NSString *token = //GET THE TOKEN FROM THE KEYCHAIN
NSString *authValue = [NSString stringWithFormat:@"Token %@",token];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
if ([NSURLConnection canHandleRequest:request]){
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[NSURLConnection sendAsynchronousRequest:request queue:self.fetchQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200){
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil];
//Process the data
}
}
}];
}
【问题讨论】:
-
您使用什么请求方法,GET 或 POST 发送身份验证数据?
标签: ios objective-c ios7 nsurlsession