Html 将 NSData 加载到 UIWebView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9475768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading NSData into a UIWebView
提问by Greg
In my web browser, I am trying to load a UIWebView
with NSData
obtained from a NSURLConnection
. When I try to load it into the UIWebView
, instead of the site, it comes up with the HTML plain text.
在我的网页浏览器,我试图加载UIWebView
与NSData
从获得的NSURLConnection
。当我尝试将它加载到UIWebView
, 而不是站点时,它会出现 HTML 纯文本。
Here is my code:
这是我的代码:
in viewDidLoad:
在 viewDidLoad:
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.msn.com"]];
[NSURLConnection connectionWithRequest: request delegate:self];
later in the code:
稍后在代码中:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
webdata = [NSMutableData dataWithData: data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[webview loadData:webdata MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL:nil];
}
回答by Inder Kumar Rathore
You are not appending data that you are receiving. Use this piece of code
您没有附加您正在接收的数据。使用这段代码
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if (webdata == nil) {
webdata = [[NSMutableData alloc] init];
}
[webdata appendData:data];
}
This method might be called once or more times depending upon your data length. So instead of assigning new data to your ivar, append your data to it so that you have the full response not the last packet of data received.
------------------------------------------------------------------------------------------------------------------------------------
Updated
Or use like this.
根据您的数据长度,此方法可能会被调用一次或多次。因此,不要将新数据分配给您的 ivar,而是将您的数据附加到它,以便您获得完整的响应,而不是收到的最后一个数据包。
-------------------------------------------------- -------------------------------------------------- --------------------------------
更新
或这样使用。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
webdata = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webdata appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[mWebView loadData:webdata MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL:nil];
}