html - 在 stringWithContentsOfURL cookies 之后不保存在 UIWebView 中。 iOS

标签 html ios cookies save nsurlconnectiondelegate

我想从 url 获取 html,我使用:

NSString *URLtoHTML = [NSString stringWithContentsOfURL:self.url encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:URLtoHTML baseURL:nil];

但在此之后我的 cookie 在 UIWebView 中清理。 但是如果我使用不带 stringWithContentsOfURL cookie 的加载请求保存:

[self.webView loadRequest:[NSURLRequest requestWithURL:self.url]];

我已经试过了,但是 cookies 也没有保存:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

如何获取 HTML 并使用 cookie 将其加载到 UIWebView 中?

更新: 如果我使用这种情况(两条不相关的行)cookie 也不会保存:

NSString *URLtoHTML = [NSString stringWithContentsOfURL:self.url encoding:NSUTF8StringEncoding error:nil];
[self.webView loadRequest:[NSURLRequest requestWithURL:self.url]];

stringWithContentsOfURL 不保存 cookie。怎么会这样?这很有趣 :D

最佳答案

在这种情况下 - 您从 URL 下载原始内容,并仅在 WebView 中显示此数据。 WebView 只是不知道您的 cookie。

NSString *URLtoHTML = [NSString stringWithContentsOfURL:self.url encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:URLtoHTML baseURL:nil];

在这种情况下 - 您创建连接,但再次只下载原始数据。

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

这个更接近,您只需要它 - 它是从 WebView 捕获加载的数据。

[self.webView loadRequest:[NSURLRequest requestWithURL:self.url]];
NSString *html = [self.webView stringByEvaluatingJavaScriptFromString: 
                                     @"document.body.innerHTML"];

关于html - 在 stringWithContentsOfURL cookies 之后不保存在 UIWebView 中。 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28798556/

相关文章:

php - 当我对我的 php 文件的引用仍在运行时,无法找到 style.css

javascript - 无法在 Protractor 中使用 .click() 打开日期选择器 > "Failed: element not interactable"

ios - 如何添加从启动屏幕到初始 View Controller ios 的过渡?

ios - 检测结束拖动/缩放 MKMapView

cookies - _ga cookie 中的值是什么?

javascript - css 在悬停时将隐藏更改为可见

html - 防止边距将元素推出容器

ios - UIViewAnimationOptionBeginFromCurrentState 的意外行为

sqlite - Chrome 中的加密 cookie

jquery - 为什么我的所有 jQuery cookie 都未定义?