2014-03-03 25 views
0

我想遷移到NSURLSession,以便我可以發送多個圖像到我的服務器,並停止當我得到所需的響應。但我的完成塊永遠不會被調用。如果能夠正確地進行遷移,請告訴我,謝謝。從NSURLConnection遷移到NSURLSession

這裏是我的舊代碼,工程精細

-(void) sendImgWithText:(UIImage*)img 
{ 
    NSURL *requestURL = [NSURL URLWithString:@"Some URL"]; 

    // create request 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 
    [request setHTTPShouldHandleCookies:NO]; 
    [request setTimeoutInterval:30]; 
    [request setHTTPMethod:@"POST"]; 

    NSString *boundary = @"*****"; 
    NSString *lineEnd = @"\r\n"; 
    NSString *twoHyphens = @"--"; 

    // set Content-Type in HTTP header 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 

    // post body 
    NSMutableData *body = [NSMutableData data]; 

    // add params (all params are strings) 
    // UIImage *imgColor = [UIImage imageNamed:@"9.jpg"]; 

    UIImage * imageToPost = [[UIImage alloc] init]; 
    UIImageWriteToSavedPhotosAlbum(imageToPost, nil, nil, nil); 
    NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0); 

    if (imageData) { 
     [body appendData:[[NSString stringWithFormat:@"%@%@%@", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
     // [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
     [body appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [body appendData:imageData]; 
     [body appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    } 

    [body appendData:[[NSString stringWithFormat:@"%@%@%@%@", twoHyphens,boundary, twoHyphens,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 

    // setting the body of the post to the reqeust 
    [request setHTTPBody:body]; 

    // set the content-length 
    NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

    NSLog(@"%@",requestURL); 
    NSLog(@"%f,%f",imageToPost.size.height,imageToPost.size.height); 

    // set URL 
    [request setURL:requestURL]; 
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 

這裏是版本(我得到了大部分來自其他堆棧溢出文章)

- (void) serverRequestWithImage:(UIImage *)img completion:(void (^)(id responseObject, NSError *error))completion 
{ 
    NSURL *requestURL = [NSURL URLWithString:@"Some URL"]; 

    // create request 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 
    [request setHTTPShouldHandleCookies:NO]; 
    [request setTimeoutInterval:30]; 
    [request setHTTPMethod:@"POST"]; 

    NSString *boundary = @"*****"; 
    NSString *lineEnd = @"\r\n"; 
    NSString *twoHyphens = @"--"; 

    // set Content-Type in HTTP header 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 

    // post body 
    NSMutableData *body = [NSMutableData data]; 

    UIImage * imageToPost = [[UIImage alloc] init]; 
    imageToPost = img; 

    NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0); 
    if (imageData) { 
     [body appendData:[[NSString stringWithFormat:@"%@%@%@", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
     // [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
     [body appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [body appendData:imageData]; 
     [body appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 
    } 

    [body appendData:[[NSString stringWithFormat:@"%@%@%@%@", twoHyphens,boundary, twoHyphens,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]]; 

    // setting the body of the post to the reqeust 
    [request setHTTPBody:body]; 

    // set the content-length 
    NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

    NSLog(@"%@",requestURL); 
    NSLog(@"%f,%f",imageToPost.size.height,imageToPost.size.height); 

    // set URL 
    [request setURL:requestURL]; 

    NSURLSessionTask *task = 
    [session 
    dataTaskWithRequest:request 
    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
    { 
     // report any network-related errors 
     NSLog(@"Got Response 1"); 

     if (!data) { 
      if (completion) { 
       dispatch_async(dispatch_get_main_queue(), ^{ 
        completion(nil, error); 
       }); 
      } 
      return; 
     } 

     // report any errors parsing the JSON 
     NSError *parseError = nil; 
     _responseData = [NSMutableData dataWithData:data]; 

     if (_responseData) { 
      if (completion) { 
       dispatch_async(dispatch_get_main_queue(), ^{ 
        completion(nil, parseError); 
       }); 
      } 
      return; 
     } 

     // if everything is ok, then just return the JSON object 
     if (completion) { 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       completion(_returnedData, nil); 
      }); 
     } 
    }]; 

    [task resume]; 
} 

這裏是我的電話的方法從其他類

- (IBAction)GetData:(id)sender 
{ 
    [_imageView setImage:[UIImage imageNamed:@"9.jpg"]]; 

    msg = [[Message alloc] init]; 
    [msg initData]; 
    msg.delegate=self; 
    [msg serverRequestWithImage:_imageView.image completion:^(id responseObject, NSError *error) 
    { 
     if (responseObject) { 
      // do what you want with the response object here 
      NSLog(@"Got Data"); 
     } else { 
      NSLog(@"%s: serverRequest error: %@", __FUNCTION__, error); 
     } 
    }]; 

} 
+0

確定'從線session''NSURLSessionTask *任務= [會議dataTaskWithRequest:請求completionHandler:^(NSData的*數據,NSURLResponse *響應,NSError *錯誤)'初始化? – Avt

+0

使用'NSURLSession'會自動將您的應用程序部署目標提升到ios 7.0。你確定你需要它嗎? –

+0

@Avt是的,我有一個initData方法,我從msg類調用 - (void)initData { session = [[NSURLSession alloc] init]; _returnedData = [[NSMutableData alloc] init]; } – user2067051

回答

2

項目:

  • 我沒有看到NSURLSession的初始化。這是你應該在你的問題中顯示的東西。你也可以檢查你的「發送圖像」方法session是非零。

  • 看起來你是從一個文件開始(@"9.jpg")。如果是這樣,-[NSURLSession uploadTaskWithRequest:fromFile:completionHandler:]可能會爲您節省一些麻煩。

未請求的建議,與所有的需要::)

  • 在我看來,-serverRequestWithImage:completion:是該方法的可憐的名字。它意味着它返回一個請求對象,並且不會告訴你它實際上發送了請求。積極的東西,如-uploadImage:completionHandler:可能會更好。

  • 在所有方法名稱的開頭應該是小寫字母,即-getData:

+2

我會說'fetchData:'而不是'getData:'。在方法名稱開始的'get'指示結果是通過傳遞參數中的間接方式返回的。 – Abizern

+0

同意。我試圖保持兩個建議的分離。也許'-uploadImageWithSender:'對'IBAction'的描述更爲準確。 –

+0

感謝您的諮詢!我實際上已將[NSURLSession alloc]更改爲[NSURLSession sharedURLSession],並且它工作正常!我實際上只是用一個img進行測試,通常我是從相機實時傳送圖像。 – user2067051