将NSURLConnection更改为NSURLSession以上载图像

时间:2014-02-06 11:19:19

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

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

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主体,但没有运气。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:-1)

 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__);
}