2015-10-05 49 views
0

我正在從NSURLConnection移動到NSURLSession,並且在保存URL請求值的NSMutableURLRequest時遇到問題。從NSURLConnection不兼容的指針類型遷移到NSURLSession

如何保留在NSURLSession這個信息沒有收到此錯誤的任何想法:

incompatible pointer types sending nsmutableurlrequest to parameter of type nesting * _nonull nsurl urlwithstring

我看到這條線[NSURL URLWithString:myRequest]想要一個的NSString,但如何我仍然可以通過其他信息是我的NSMutableURLRequest

NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL: myURL]; 
[acquisitionRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"]; 

NSURLSession *session = [NSURLSession sharedSession]; 
[[session dataTaskWithURL:[NSURL URLWithString:myRequest] 
      completionHandler:^(NSData *data, 
           NSURLResponse *response, 
           NSError *error) {     
      }] resume]; 

回答

0

您應該使用dataTaskWithRequest:completionHandler:代替dataTaskWithURL:completionHandler:。這樣你就可以傳遞整個請求。如果它抱怨可變,你可以複製它以擺脫可變狀態。

NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL: myURL]; 
[acquisitionRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"]; 

NSURLSession *session = [NSURLSession sharedSession]; 

[[session dataTaskWithRequest:[myRequest copy] 
      completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
       // completion stuff 
}] resume]; 
+0

謝謝BIG TIME Keith。這看起來像一個快樂的露營者沒有副本,但我會測試並在測試後批准它。再次感謝。 – Jazzmine

0

你的問題是要傳遞NSMutableURLRequest對象在使用URLWithString:其期待您通過NSString創建URL。通過myURL而不是[NSURL URLWithString:myRequest],你應該很好。

但是,我也建議使用dataTaskWithRequest:completionHandler:來代替。

0

我收到類似的問題。我無法在iOS 9上登錄,因爲NSData已被棄用。我需要更新到NSURLSession。我試圖用下面的代碼,但是 - 看起來有兩行仍然從NSData中繪製,其中我的指針是一個NSURLSession。

它加劇了系統。我如何設置接收線路與NSURLSession連接?

NSURLSession *session=[NSURLSession sharedSession]; 
    NSLog(@"response%@",response); 
    NSLog(@"Response code: %ld", (long)[response statusCode]); 

    if ([response statusCode] >= 200 && [response statusCode] < 300) 
    { 
     NSString *responseData = [[NSString alloc]initWithData:session encoding:NSUTF8StringEncoding]; 
     NSLog(@"Response ==> %@", responseData); 

     NSError *error = nil; 
     /* NSDictionary *jsonData = [NSJSONSerialization 
            JSONObjectWithData:urlData 
            options:NSJSONReadingMutableContainers 
            error:&error];*/ 
     // NSLog(@"dict%@",jsonData); 
     self.topLevelArray3 = [NSJSONSerialization JSONObjectWithData:session options:NSJSONReadingMutableContainers error:&error]; 
     for (int i=0; i<[self.topLevelArray3 count]; i++) {