WebView和網(wǎng)頁的交互(網(wǎng)易新聞詳情篇)

新聞內(nèi)容的圖文混排的效果,網(wǎng)上有人開源一個(gè)仿網(wǎng)易新聞的代碼,本文就是簡單記錄學(xué)習(xí)其詳細(xì)頁面顯示的效果實(shí)現(xiàn);
一般網(wǎng)易詳情頁面后臺(tái)返回的數(shù)據(jù)內(nèi)容與通常的json格式,其原理:通過網(wǎng)絡(luò)請(qǐng)求獲得相關(guān)的信息,再通過手機(jī)端進(jìn)行拼HTML,然后在WebView進(jìn)行展示,此處還對(duì)文章中的圖片增加點(diǎn)擊效果,可以保存到相冊(cè)中;文章的樣式已經(jīng)存在項(xiàng)目中,直接去調(diào)用;

網(wǎng)易詳情數(shù)據(jù)

1:首先了解兩個(gè)相關(guān)的實(shí)體對(duì)象,一個(gè)是新聞的主體內(nèi)容,另外一個(gè)就是圖片的相關(guān)信息實(shí)體,所以我們需要NSURL進(jìn)行讀取網(wǎng)站

 NSURL *url = [NSURL URLWithString:@"http://c.m.163.com/nc/article/A7AQOT560001124J/full.html"];

2.進(jìn)行數(shù)據(jù)請(qǐng)求(創(chuàng)建一個(gè)- (void)showNews:(NSDictionary *)news)將所請(qǐng)求接受的數(shù)據(jù)進(jìn)行拼接

// 2.requets
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 3.發(fā)送請(qǐng)求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *news = dict[@"A7AQOT560001124J"];
        [self showNews:news];
    }];

- (void)showNews:(NSDictionary *)news
{
    // 1.取出網(wǎng)頁內(nèi)容
    NSString *body = news[@"body"];
    
    // 2.取出圖片
    NSDictionary *img = [news[@"img"] lastObject];
    NSString *imgHTML = [NSString stringWithFormat:@"<img src=\"%@\" width=\"300\" height=\"171\">", img[@"src"]];
    
    // 2.創(chuàng)建一個(gè)webView,顯示網(wǎng)頁
    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = self.view.bounds;
    [self.view addSubview:webView];
    
    // 3.拼接網(wǎng)頁內(nèi)容
    NSString *html = [body stringByReplacingOccurrencesOfString:img[@"ref"] withString:imgHTML];
    
    // 4.取出新聞標(biāo)題
    NSString *title = news[@"title"];
    // 5.取出新聞的時(shí)間
    NSString *time = news[@"ptime"];
    
    // 頭部內(nèi)容
    NSString *header = [NSString stringWithFormat:@"<div class=\"title\">%@</div><div class=\"time\">%@</div>", title, time];
    html = [NSString stringWithFormat:@"%@%@", header, html];
    
    // 鏈接mainBundle中的CSS文件
    NSURL *cssURL = [[NSBundle mainBundle] URLForResource:@"news" withExtension:@"css"];
    html = [NSString stringWithFormat:@"%@<link rel=\"stylesheet\" href=\"%@\">", html, cssURL];
    
    // 5.加載網(wǎng)頁內(nèi)容
    [webView loadHTMLString:html baseURL:nil];
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容