Loading NSData into a UIWebView(将 NSData 加载到 UIWebView)
问题描述
在我的网络浏览器中,我尝试使用从 NSURLConnection
获得的 NSData
加载 UIWebView
.当我尝试将其加载到 UIWebView
中时,它会显示 HTML 纯文本,而不是站点.
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.
这是我的代码:
在 viewDidLoad:
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.msn.com"]];
[NSURLConnection connectionWithRequest: request delegate:self];
后面的代码:
-(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];
}
推荐答案
您没有附加您正在接收的数据.使用这段代码
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];
}
此方法可能会被调用一次或多次,具体取决于您的数据长度.因此,不要将新数据分配给您的 ivar,而是将您的数据附加到它,以便您获得完整的响应,而不是收到的最后一个数据包.
-----------------------------------------------------------------------------------------------------------------------------------
更新
或者像这样使用.
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.
- (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];
}
这篇关于将 NSData 加载到 UIWebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 NSData 加载到 UIWebView
基础教程推荐
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01