NSURLConnection连接:didReceiveData:重定向后不调用

时间:2013-01-08 13:41:02

标签: objective-c ios redirect nsurlconnection

我正在启动一个请求,它返回给我带有重定向的HTML。为什么第二次没有调用didReceiveData函数?我正在尝试下载JSON文件。 (使用iOS6)

    - (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;
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);
    }