【问题标题】:Change NSURLConnection to NSURLSession for uploading images将 NSURLConnection 更改为 NSURLSession 以上传图片
【发布时间】:2014-03-03 07:28:26
【问题描述】:

我目前在后台将图像上传到这样的服务器(名称在服务器上更改为更好的名称)。

buildURL = [buildURL  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageData = UIImageJPEGRepresentation(imageToUpload, 1.0);     //change Image to NSData

if (imageData != nil)
{
    NSString *filenames = [NSString stringWithFormat:@"imagename"];      //set name here
    NSLog(@"%@", filenames);
    NSString *urlString = buildURL;

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"filenames\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[filenames dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    // setting the body of the post to the reqeust
    [request setHTTPBody:body];
    // now lets make the connection to the web

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
            {

                NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"Returned From Image Upload : %@",returnString);
            }];

}

这很好用,我可以在后台看到图像完成没有问题。问题是我想将其更改为使用 NSURLSession 和委托 didSendBodyData 以便我可以监控上传。

我找到了大量关于下载的信息,但没有找到关于上传的信息。我试图用请求来做到这一点,但完成块永远不会发生..我也尝试过使用 uploadTaskWithStreamedRequest 但我无法让委托发生......

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

    NSURLSessionDataTask *uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                          {
                                              NSLog(@"Image Uploaded ------------");
                                          }];

    [uploadTask resume];

我还发现了这个StackOverflow 19985353,它似乎突出了一些问题,但我真的可以用一些示例代码来做。如果有帮助,则从 imagePicker 中挑选图像。

我也在这里StackOverflow 19099448 尝试了这两个答案,但它们都没有奏效,再次该块从未执行。我在 NSURLSession 上做错了什么,可能是一个框架!我还注意到我不知道我尝试使用但没有运气的 HTTP 正文。

【问题讨论】:

  • 这可能对你有帮助:Tutorial
  • @67cherries 我经历了这个,但仍然没有快乐。我已经尝试了所有示例,但我无法让 Delegates 和/或 Blocks 运行。也没有错误...
  • 你在使用多线程吗?
  • @67cherries 大多数情况下没有。此时背景中应该没有任何事情发生。有人认为这适用于 iOS6 吗?
  • @67cherries Nope 在 iOS6 中不起作用,真的没有任何错误或警告......

标签: image cocoa-touch file-upload nsurlconnection nsurlsession


【解决方案1】:

好吧,我没有意识到 Session 只适用于 iOS7 及更高版本。为此我做了一个测试,如果是iOS6,那么我使用NSURLConnection。问题是我无法从中获得进度状态(会话我有一个上传栏)。

如果有人对使用 NSURLConnection 的上传进度条有任何想法,那么我很想听听。

【讨论】:

  • Apple 文档在清单 2-3 下谈到了 here
  • 听起来您找到了答案,并在问另一个问题。如果是这样,您应该接受这个(您的)答案,并在NSURLConnection 期间开始另一个关于更新的 SO 问题。
【解决方案2】:
 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:_urlToUpload];// create request
    [request setHTTPMethod:@"POST"];// request type
     [request setTimeoutInterval:60];
    [request setValue:@"application/octet-stream" forHTTPHeaderField: @"Content-Type"];// content type
  NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];// configuration
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];// session

    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:file completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { }

Use the delegates


#pragma mark -
#pragma mark Session Upload Delegate Methods
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
    float status = (double)totalBytesSent / (double)totalBytesExpectedToSend;
    [[MTFileStreamer sharedFileStreamer] setCurrentStatus:status];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response
        newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler {
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler {
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

【讨论】:

  • 您能否上传必要的字段,这对初学者来说非常混乱假设我有一个 api 和密钥“图像”接下来要做什么?
猜你喜欢
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
相关资源
最近更新 更多