2013-01-08 41 views
1

我正在啓動一個請求,該請求將內部重定向返回給HTML。爲什麼didReceiveData函數沒有被第二次調用?我正在嘗試下載一個JSON文件。 (使用iOS6)NSURLConnection連接:didReceiveData:在重定向後不被調用

- (void) testdownload{ 
     NSURL *url = [NSURL URLWithString:@"https://***]; 
     NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
     NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
     [connection start]; 
    } 

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d{ 

     NSString *tmpdata = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding]; 
     NSLog(@"data: %@", tmpdata); 
    } 

當我使用一個UIWebView的重定向將被處理和JSON文件將被顯示。使用此功能玩沒有工作:使用

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse{ 
    return request; 
} 
+0

http://stackoverflow.com/questions/1446509/handling-redirects-correctly-with-nsurlconnection –

回答

1

試試這個代碼,而不是:

- (NSURLRequest *)connection: (NSURLConnection *)inConnection 
      willSendRequest: (NSURLRequest *)inRequest 
      redirectResponse: (NSURLResponse *)inRedirectResponse; 
{ 
    if (inRedirectResponse) { 
     NSMutableURLRequest *r = [[request mutableCopy] autorelease]; // original request 
     [r setURL: [inRequest URL]]; 
     return r; 
    } else { 
     return inRequest; 
    } 
} 

Learn more on this SO question

+0

thx,但我tr之前ied這個東西,它仍然無法正常工作。在調用「didreceiveData」函數之前,會調用「willSendRequest」函數兩次。它是否正確? – tuvok

+0

@tuvok林不知道,檢查鏈接替代問題的更多信息 – MCKapur

+0

我認爲問題是,該網頁重定向與此: tuvok

0

我用這個來代替現在的(但不是真的好聽):

- (IBAction)redirectTest:(id)sender { 

     NSURL *url = [NSURL URLWithString:@"http://billstclair.com/html-redirect.html"]; 
     _request = [NSURLRequest requestWithURL:url]; 

     UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectNull]; 
     webview.delegate = self; 
     [webview loadRequest:_request]; 
     [self.view addSubview:webview]; 

    } 


    - (void)webViewDidFinishLoad:(UIWebView *)webView{ 

     NSString *content = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"]; 
     NSLog(@"content: %@",content); 
    } 
相關問題