【发布时间】:2014-09-29 19:25:41
【问题描述】:
我需要将视频文件从我的应用上传到服务器。我尝试通过[AFHTTPRequestOperationManager post:parameters:success:failure] 这样做,但不幸的是不断收到请求超时。我现在正在尝试类似于 Creating an Upload Task from the AF Docs.
我阅读了on SO 和AF Docs 关于setSessionDidReceiveAuthenticationChallengeBlock: 并尝试实现整个上传问题如下:
__block ApiManager *myself = self;
// Construct the URL
NSString *strUrl = [NSString stringWithFormat:@"%@/%@", defaultUrl, [self getPathForEndpoint:endpoint]];
NSURL *URL = [NSURL URLWithString:strUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];
// Build a session manager
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
// Set authentication handler
[manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
*credential = myself.credentials;
return NSURLSessionAuthChallengeUseCredential;
}];
// Create the upload task
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
[myself endpoint:endpoint returnedFailure:error];
} else {
[myself endpoint:endpoint returnedSuccess:responseObject];
}
}];
// and run with it
[uploadTask resume];
myself.credentials 对象之前已设置为具有正确的用户名和密码。每当此请求触发时,我都会收到 401 unauthorised 作为响应。我尝试将NSLog(@"CHALLENGE") 放在上面的挑战块中,但它似乎从未被调用,因此 AFNetworking 没有给我提供凭据的方法。我知道这在服务器端运行良好,因为我已经使用 Postman 对其进行了测试。
如何让 AFNetworking 让我通过此上传任务为 HTTP 基本身份验证提供凭据?
【问题讨论】:
标签: objective-c upload afnetworking-2 basic-authentication