2014-02-06 20 views
0

我当前将图像上传到服务器的背景中(名称在服务器上更改为更好)。将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身体,但没有运气。

+0

这可以帮助你:[教程](http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&ved=0CDcQFjAC&url=http%3A%2F %2Fwww.raywenderlich.com%2F51127%2Fnsurlsession-tutorial&ei = _IXzUqq3MJOMyAHhx4DwDA&usg = AFQjCNG8YRDnx7buLt1VGpFYqkoE91cXYg&bvm = bv.60799247,d.aWc) – 68cherries

+0

@ 67cherries我经历过这个但仍然没有快乐。我尝试了所有的例子,但我简单的不能让委托和/或块运行。有没有错误... –

+0

你使用多线程? – 68cherries

回答

1

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

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

+0

苹果文档谈论这[这里](https://developer.apple.com/library/mac/documentation/ Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html)。 – 68cherries

+0

听起来像你找到你的答案,并提出另一个问题。如果是这样,你应该接受这个(你的)答案,并在'NSURLConnection'期间启动另一个关于更新的SO问题。 –

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

可否请您上传必要的字段,让初学者非常困惑让我们假设我有一个API和关键“图像”接下来要做什么? – dreamBegin