将 HTML NSString 加载到 UIWebView 中

发布于 2024-09-29 03:45:33 字数 2107 浏览 0 评论 0原文

我正在做一个项目,我使用 NSURLConnection 连接到网页,以便能够监视返回的状态代码(200 OK / 404 ERROR)。如果我收到 404 作为状态代码,我想将用户发送到顶级网址 www.domain.com,如果我收到 200 状态代码,我想将页面加载到 web 视图中。我已经通过创建新请求看到了这个问题的几个实现,但我觉得这是不必要的,因为您已经在第一个请求中收到了 html,所以我只想将该 HTML 加载到 webView 中。

所以我尝试使用 [webView loadHTMLFromString: baseURL:] 但它并不总是有效,我注意到当我在 connectionDidFinnishLoading 中打印带有 html 的 NSString 时,它有时为空,当我通过在中打印 html 来监视这些情况时didReceiveData 最后一个数据包的随机数为 NULL(在 2-10 之间变化)。始终是相同的网页未加载。如果我使用 [webView loadRequest:myRequest] 将它们加载到我的 webView 中,它总是有效。我的实现看起来像这样,也许你们中的一些人可以看到我做错了什么。

我通过单击按钮创建了第一个请求。

-(IBAction)buttonClick:(id)sender
{
    NSURL *url = [NSURL URLWithString:@"http://www.domain.com/page2/apa.html"];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url]
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
    }
    else
    {

    }
}

然后,我通过将请求转换为 NSHTTPURLResponse 以便能够访问状态代码,然后根据状态代码设置 Bool 来监视 didReceiveResponse 方法中的响应代码。

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{     
    NSHTTPURLResponse *ne = (NSHTTPURLResponse *)response;
    if ([ne statusCode] == 200) {
        ok = TRUE;
    }

    [webData setLength: 0];
}

然后我检查connectionDidFinnishLoading 中的bools 值。如果我记录 html NSString 我会得到网页的源代码,所以我知道它不是一个空字符串。

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSString *html = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    NSURL *url = [NSURL URLWithString:@"http://www.domain.com/"];
    if (ok) {
        [webView loadHTMLString:html baseURL:url];
        ok = FALSE;
    }
    else {
        // Create a new request to www.domain.com
    }

}

webData 是一个实例变量,我将它加载到 didReceiveData 中,如下所示。

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

Im doing a project where I connect to a webpage using the NSURLConnection to be able to monitor the status codes that are returned (200 OK / 404 ERROR). I would like to send the user to the top url www.domain.com if I recieve 404 as status code and if i recieve as 200 status code I would like to load the page in to a webview. I have seen several implementations of this problem by creating a new request but I feel that it is unnecessary since you already received the html in the first request so i would just like to load that HTML in to the webView.

So i try to use the [webView loadHTMLFromString: baseURL:] but it doesn't always work, I have noticed that when i print the NSString with html in the connectionDidFinnishLoading it sometimes is null and when I monitor these cases by printing the html in didReceiveData a random number of the last packets is NULL (differs between 2-10). It is always the same webpages that doesn't get loaded. If I load them to my webView using [webView loadRequest:myRequest] it always works. My implementation looks like this perhaps someone of you can see what Im doing wrong.

I create my first request with a button click.

-(IBAction)buttonClick:(id)sender
{
    NSURL *url = [NSURL URLWithString:@"http://www.domain.com/page2/apa.html"];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url]
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
    }
    else
    {

    }
}

Then I monitor the response code in the didReceiveResponse method by casting the request to a NSHTTPURLResponse to be able to access the status codes and then setting a Bool depending on the status code.

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{     
    NSHTTPURLResponse *ne = (NSHTTPURLResponse *)response;
    if ([ne statusCode] == 200) {
        ok = TRUE;
    }

    [webData setLength: 0];
}

I then check the bools value in connectionDidFinnishLoading. If I log the html NSString I get the source of the webpage so i know that it isn't an empty string.

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSString *html = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    NSURL *url = [NSURL URLWithString:@"http://www.domain.com/"];
    if (ok) {
        [webView loadHTMLString:html baseURL:url];
        ok = FALSE;
    }
    else {
        // Create a new request to www.domain.com
    }

}

webData is an instance variable and I load it in didReceiveData like this.

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拒绝两难 2024-10-06 03:45:33

我假设 webData 是您的类上的实例变量。我认为您的问题是您没有将 webData 设置为从 NSURLConnection 获取的数据。尝试这样的操作:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [webData appendData:data];
}

如果这不起作用,请尝试在 NSString *html = [[NSString alloc]... 行之后添加 NSLog() ,例如so:

NSLog(@"HTML: %@", html);

这会告诉你是否获得了 HTML,以及问题是否出在你的 NSURLConnection 代码上您的UIWebView IBOutlet

I am assuming that webData is an instance variable on your class. I think your problem is that you are not setting webData to the data you are getting from the NSURLConnection. Try something like this:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [webData appendData:data];
}

If that doesn't do the trick try adding an NSLog() after the NSString *html = [[NSString alloc]... line, like so:

NSLog(@"HTML: %@", html);

That will tell you whether you are getting HTML or not and whether the problem is with your NSURLConnection code or your UIWebView IBOutlet.

中二柚 2024-10-06 03:45:33

您也混合了两种执行连接的方式 - 同步和异步。如果异步在同步之前完成,则将 webData 重新初始化为空字符串。因此,即使同步填充 webData 它也会被清除。

// you create asynchronous connection which starts downloading in background immediately
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
// you create another synchronous connection which will block until the URL is downloaded
[NSURLConnection sendSynchronousRequest:theRequest returningResponse: &responseHeader error: nil];

// assuming your theRequest is valid, theConnection is always non-nil, so this is always TRUE
if (theConnection) {
     // you reset content of webData, so if your synchronous connection has downloaded something, you throw it away here
     webData = [[NSMutableData data] retain];
} else ...

尝试删除对 sendSynchronousRequest:returningResponse:error: 的不必要/有缺陷的调用,它可能会起作用。

不管怎样 - 你在哪里用数据填充 webData ?您确实实现了 connection:didReceiveData: 并将内容附加到 webData 中,对吗?如果你没有——好吧,这就是你所看到的问题。

You are mixing two ways of performing connection - synchronous and asynchronous too. If the asynchronous finishes before the synchronous, you reinitialize webData to empty string. So even if synchronous populated webData it would be cleared.

// you create asynchronous connection which starts downloading in background immediately
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
// you create another synchronous connection which will block until the URL is downloaded
[NSURLConnection sendSynchronousRequest:theRequest returningResponse: &responseHeader error: nil];

// assuming your theRequest is valid, theConnection is always non-nil, so this is always TRUE
if (theConnection) {
     // you reset content of webData, so if your synchronous connection has downloaded something, you throw it away here
     webData = [[NSMutableData data] retain];
} else ...

Try to remove unnecessary/buggy call to sendSynchronousRequest:returningResponse:error: and it might work.

Anyway - where do you populate webData with data ? You did implement connection:didReceiveData: and append what comes into webData, right ? If you didn't - well, that's the problem you are seeing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文