开始用Swift开发iOS 10 - 21 使用WKWebView和SFSafariViewController

上一篇开始用Swift开发iOS 10 - 20 使用Tab Bar Controller 和 拆分Storyboard学习了工具栏和Storyboard的拆分,这一篇学习怎么在app中显示网页内容。由于原书中使用了的网站在国内不好访问,我就用了我的简书、博客、Github代替🙂。

设计about view

  • 下载图片拖进Assets.xcasset

  • 打开about.storyboard,拖进一个Image View到table view header,height为190,imageabout-logocontent modeAspect fit。选择table view cell,identifierCellstyleBasic

  • 新建AboutTableViewController继承至UITableViewController,关联about中的table view controller。

  • AboutTableViewController,添加:

      var sectionTitles = ["Leave Feedback", "Follow Us"]
      var sectionContent = [["Rate us on App Store", "Tell us your feedback"], ["Jianshu", "Blog", "Github"]]
      var links = ["//www.greatytc.com/u/efce1a2a95ab", "http://andyron.com", "https://github.com/andyRon"]
    

table view的相关代理协议方法实现,这次使用俩个section,tableView(_:titleForHeaderInSection:)是获取section的title方法。

    override func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitles.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sectionContent[section].count
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionTitles[section]
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        
        cell.textLabel?.text = sectionContent[indexPath.section][indexPath.row]
        
        return cell
    }
  • 移除Tableview下面分割线,在viewDidLoad中添加:

    tableView.tableFooterView = UIView(frame: CGRect.zero)
    

用Mobile Safari打开Web

可直接给出网址,通过Mobile Safari打开网站,UIApplication.shared.open(_:options:completionHandler:)

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        switch indexPath.section {
        case 0:
            if indexPath.row == 0 {
                if let url = URL(string: "http://www.apple.com/itunes/charts/paid-apps/") {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            }
        default:
            break
        }
        // 取消被选中状态
        tableView.deselectRow(at: indexPath, animated: false)
    }

使用WKWebView载入Web

使用使用WKWebView载入Web的例子

if let url = URL(string: "http://andyron.com") {
    let request = URLRequest(url: url)
    webView.load(request)
}

直接载入本地html文件的例子:

let url = URL(fileURLWithPath: "about.html")
let request = URLRequest(url: url)
webView.load(request)
  • about.storyboard中拖进一个新的View Controller,用来展示Web内容。使用ctrl-drag建立Show类型的segue,identifiershowWebView
  • 新建WebViewController继承至UIViewController,关联上面的用来显示Web内容的View Controller。
  • WebViewController.swift中添加import WebKit,变量var webView: WKWebView!
  • 更新 viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()

        if let url = URL(string: "http://andyron.com") {
            let request = URLRequest(url: url)
            webView.load(request)
        }
    
    }
  • 添加loadView,这个方法会在viewDidLoad之前调用创建WKWebView
override func loadView() {
    webView = WKWebView()
    view = webView
}
  • 更新AboutTableViewController中的tableView(_didSelectRowAtIndexPath:)
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        switch indexPath.section {
        case 0:
            if indexPath.row == 0 {
                if let url = URL(string: "http://www.apple.com/itunes/charts/paid-apps/") {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            } else if indexPath.row == 1 {
                performSegue(withIdentifier: "showWebView", sender: self)
    
            }     
        default:
            break
        }
        // 取消被选中状态
        tableView.deselectRow(at: indexPath, animated: false)
    }
  • 由于自从iOS 9之后,出于安全考虑,默认只能访问HTTPS的网站,如果需要访问HTTP的网站,就需要在plist文件中添加许可:

使用SFSafariViewController载入Web

AboutTableViewController.swift中加入import SafariServices,然后更新tableView(_didSelectRowAtIndexPath:),只用通过url创建一个SFSafariViewController对象,然后使用present方法展示就可以了。

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        switch indexPath.section {
        case 0:
            if indexPath.row == 0 {
                if let url = URL(string: "http://www.apple.com/itunes/charts/paid-apps/") {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            } else if indexPath.row == 1 {
                performSegue(withIdentifier: "showWebView", sender: self)
    
            }
        case 1:
            if let url = URL(string: links[indexPath.row]) {
                let safariController = SFSafariViewController(url: url)
                present(safariController, animated: true, completion: nil)
            }
        default:
            break
        }
        // 取消被选中状态
        tableView.deselectRow(at: indexPath, animated: false)
    }

代码

Beginning-iOS-Programming-with-Swift

说明

此文是学习appcode网站出的一本书 《Beginning iOS 10 Programming with Swift》 的一篇记录

系列文章目录

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,246评论 4 61
  • 前两天,有朋友问了个问题:如果一个男人买奶粉的钱都没有,你会和他在一起吗? 在现实中我们更可能会爱上和自己差不多的...
    在写字的路上遇见自己阅读 182评论 0 0
  • 人生就像一场旅程,列车的每次停靠都会上来一波人也会下去一波人。我们身边的人却不过只是过客而已。 虽然我挺认同这个观...
    漂流晶阅读 517评论 0 1
  • 今天在简书上拜读了韩大爷的一篇文章《你的人格完善成都决定着你的发展高度》,感慨良久,在此记录下自己的一些想...
    疯木头阅读 352评论 0 2
  • NodeSchool 上有一大堆免费的课程。其中,Node.js 的入门课程是 Learn you Node。想成...
    知行社阅读 633评论 1 13