1

我正在启动一个请求,它给我返回带有重定向的 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;
}
4

2 回答 2

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

了解有关此 SO 问题的更多信息

于 2013-01-08T13:54:44.713 回答
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);
    }
于 2013-01-09T10:00:23.323 回答