2014-02-06 43 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