一:服务器返回网页需要展示的内容
//
// ViewController.swift
// WangYiDetailNews
//
// Created by fe on 2017/7/24.
// Copyright © 2017年 fe. All rights reserved.
import UIKit
class ViewController: UIViewController {
//https://c.m.163.com/nc/article/CQ3TQBMR0529A78E/full.html
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let str : String = "https://c.m.163.com/nc/article/CQ3TQBMR0529A78E/full.html"
self.webView.backgroundColor = UIColor.clear
loadData(str: str)
}
func loadData(str:String) -> Void {
let url : URL = URL.init(string: str)!
let request : URLRequest = URLRequest.init(url: url)
let con = URLSessionConfiguration.default;
let urlSession : URLSession = URLSession.init(configuration: con, delegate: self, delegateQueue: OperationQueue.main)
let dataTask = urlSession.dataTask(with: request) { (data:Data?, response:URLResponse?, error:Error?) in
if error == nil{
//let dataStr = String.init(data: data!, encoding: String.Encoding.utf8)
//print(dataStr ?? "没有数据")
let jsionData = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary<String, Any>
self.dealNewsData(jsonData: jsionData!)
}else{
print(error?.localizedDescription ?? "没有错误")
}
}
dataTask.resume()
}
//处理从网易新闻拿到的数据并显示
func dealNewsData(jsonData:Dictionary<String, Any>) -> Void {
//1.取出所有的数据
let allData = jsonData["CQ3TQBMR0529A78E"] as! Dictionary<String, Any>
//print(allData)
//2.取出body中的内容
var bodyHtml = allData["body"] as! String
//3.取出标题
let title = allData["title"] as! String
//4.取出时间
let time = allData["ptime"] as! String
//5.取出来源
let source = allData["source"] as! String
//6.取出所有图片对象
let img = allData["img"] as! [[String:Any]]
//7.遍历数组中的每一个对象
for i in 0..<img.count {
//7.1取出单独的图片对象
let imgItem = img[i]
//7.2取出占位标签
let ref = imgItem["ref"] as! String
//7.3取出src
let src = imgItem["src"] as! String
//7.4取出图片标题
let imgTitle = imgItem["alt"] as! String
//7.5拼接图片html
let imgHtml = "<div class=\"all-img\"><img src = \"\(src)\"><div>\(imgTitle)</div></div>"
//7.6替换body中的ref
bodyHtml = bodyHtml.replacingOccurrences(of: ref, with: imgHtml)
}
//8.编辑头部html
let titleHtml = "<div id = \"mainTitle\">\(title)</div>"
//9.创建子标题html
let subTitle = "<div id = \"subTitle\"><span class = \"time\">\(time)</span>\(source)<span></span></div>"
//10.加载css路径
let css = Bundle.main.url(forResource: "index", withExtension: "css")
//11.创建link标签
let csshtml = "<link href = \"\(css!)\" rel = \"stylesheet\">"
//12.加载js路径
let js = Bundle.main.url(forResource: "index", withExtension: "js")
//13.创建js标签
let jshtml = "<script type=\"text/javascript\" src=\"\(js!)\"></script>"
//14.拼接html
let html = "<html><head>\(csshtml)</head><body>\(titleHtml)\(subTitle)\(bodyHtml)\(jshtml)</body></html>"
//print(html)
self.webView.loadHTMLString(html, baseURL: nil)
}
}
extension ViewController : URLSessionDelegate{
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//let host : String = challenge.protectionSpace.host
//print(host)
let credential : URLCredential = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
completionHandler(URLSession.AuthChallengeDisposition.useCredential , credential)
return
}
///访问相册
func visitPhotoLibrary() -> Void {
let photoVC = UIImagePickerController()
photoVC.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(photoVC, animated: true, completion: nil)
}
}
extension ViewController:UIWebViewDelegate{
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//1.取出请求的字符串
let requestString = request.url!.absoluteString as NSString
//2.判断处理
let URLHeader = "zyf:///"
let range = requestString.range(of: URLHeader)
let location = range.location
if location != NSNotFound {
let method = requestString.substring(from: range.length)
print(method)
let sel = NSSelectorFromString(method)
self.perform(sel)
}
return true
}
}
二:创建本地css文件,控制网页样式
body{
}
img{
width:100%;
}
#mainTitle{
text-align:center;
font-size:20px;
margin-bottom:5px;
}
#subTitle{
color : gray;
text-align:center;
}
.time{
margin-right:20px;
margin-bottom:5px;
}
.all-img{
color:gray;
text-align:center;
margin:8px 0;
}
三:创建本地js文件,处理网页交互,调用移动端原生API
window.onload = function(){
var allImg = document.getElementsByTagName("img");
//alert(allImg.length);
//遍历数组
for(var i=0;i<allImg.length;i++){
//取出图片对象
var img = allImg[i];
img.id = i;
//监听点击
img.onclick = function(){
window.location.href = 'zyf:///visitPhotoLibrary';
}
}
var img = document.createElement('img');
img.src = 'http://pic.qiantucdn.com/58pic/16/00/52/11J58PICD3S_1024.jpg!/fw/780/watermark/url/L3dhdGVybWFyay12MS4zLnBuZw==/align/center';
document.body.appendChild(img);
}