NSURLSession执行上传任务为' curl'

时间:2016-05-06 03:04:18

标签: ios nsurlsession

这是我用来上传PDF的curl命令,它完美运行:

curl -u USERNAME:PASSWORD -T MyPDF.pdf —url https://mywebserver.com

我正在使用NSURLSession并使用委托上传任务,但我的PDF永远不会上传。

这是我的代码:

- (IBAction)upload:(id)sender {
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"https://mywebserver.com/"]];
    [request setHTTPMethod:@"POST"];

    NSString* pdfPath = [[NSBundle mainBundle] pathForResource:@"bill" ofType:@"pdf"];
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:pdfPath]];

    [uploadTask resume];
}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {

}

- (void)URLSession:(NSURLSession *)session task:(nonnull NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
    if (error) {
        NSLog(@"Error = %@", error);
    }
}

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(nonnull NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession]);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveData:(nonnull NSData *)data {
    if (data) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }

}

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error {
    if (error) {
        NSLog(@"Error = %@", error);
    }
}

2 个答案:

答案 0 :(得分:0)

如果您尝试将完成块与 NSURLSessionAuthChallengeUseCredential

一起使用会发生什么
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(nonnull NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    completionHandler(NSURLSessionAuthChallengeUseCredential, 
    [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession]);
}

一般情况下,请确保您的上传首先适用于不受保护的服务器。而不是用凭证进行测试。

答案 1 :(得分:0)

NSURLSessionAuthChallengeUseCredential具有相同的行为。