XCode json数据处理、通过图片URL获取UIImage、通过URL显示网页

url【设为http://blabla.com/title.json】获取的json数据如下 ,[ { "title" : _ , "pubDate" : _, "image" : _, "link" : _} ]    title 为新闻的标题名称,pubDate 为新闻发布时间,image 新闻logo图标的网址,link 为新闻详细内容的网址。实现表单显示新闻标题、新闻发布时间、新闻缩略图,点击cell跳转显示link链接的网页内容

[{"title":"越来越Metro化的Bing Maps","pubDate":"2012-03-15 03:09:39 GMT","image":"http://course.gdou.com/images/jsondemo/1.gif","link":"http://course.gdou.com/JSONDemo/json/1.htm"},
{"title":"[截图]电信4s背后的忧伤:全员营销","pubDate":"2012-03-15 03:09:01 GMT","image":"http://course.gdou.com/images/jsondemo/2.gif","link":"http://course.gdou.com/JSONDemo/json/2.htm"},
{"title":"微软bing地图启用新图形界面","pubDate":"2012-03-15 03:08:06 GMT","image":"http://course.gdou.com/images/jsondemo/3.gif","link":"http://course.gdou.com/JSONDemo/json/3.htm"},
{"title":"圣何塞将会在市区推出免费Wi-Fi","pubDate":"2012-03-15 03:07:57 GMT","image":"http://course.gdou.com/images/jsondemo/4.gif","link":"http://course.gdou.com/JSONDemo/json/4.htm"},
{"title":"Galaxy S III官方照首曝","pubDate":"2012-03-15 03:00:44 GMT","image":"http://course.gdou.com/images/jsondemo/5.gif","link":"http://course.gdou.com/JSONDemo/json/5.htm"},
{"title":"诺基亚获批自家的“滑动”解锁专利","pubDate":"2012-03-15 02:46:52 GMT","image":"http://course.gdou.com/images/jsondemo/6.gif","link":"http://course.gdou.com/JSONDemo/json/6.htm"},
{"title":"有关于程序员的漫画四幅:要钱还是要命?","pubDate":"2012-03-15 02:22:13 GMT","image":"http://course.gdou.com/images/jsondemo/7.gif","link":"http://course.gdou.com/JSONDemo/json/7.htm"},
{"title":"英国将平板电脑等纳入CPI测算范围","pubDate":"2012-03-15 02:20:52 GMT","image":"http://course.gdou.com/images/jsondemo/8.gif","link":"http://course.gdou.com/JSONDemo/json/8.htm"},
{"title":"[视频]微软展示新触摸屏技术","pubDate":"2012-03-15 02:20:43 GMT","image":"http://course.gdou.com/images/jsondemo/9.gif","link":"http://course.gdou.com/JSONDemo/json/9.htm"},
{"title":"诺基亚Lumia 710广告整版登录澳大利亚报纸","pubDate":"2012-03-15 02:19:33 GMT","image":"http://course.gdou.com/images/jsondemo/10.gif","link":"http://course.gdou.com/JSONDemo/json/10.htm"},
{"title":"陶宏开炮轰《征途》升级送现金:一身铜臭味","pubDate":"2012-03-15 02:19:00 GMT","image":"http://course.gdou.com/images/jsondemo/11.gif","link":"http://course.gdou.com/JSONDemo/json/11.htm"},
{"title":"开源代码库Github受开发者欢迎 用户超140万","pubDate":"2012-03-15 02:17:24 GMT","image":"http://course.gdou.com/images/jsondemo/12.png","link":"http://course.gdou.com/JSONDemo/json/12.htm"},
{"title":"吐槽Ivy Bridge:因为它有四大不足","pubDate":"2012-03-15 02:11:15 GMT","image":"http://course.gdou.com/images/jsondemo/13.gif","link":"http://course.gdou.com/JSONDemo/json/13.htm"},
{"title":"新一代iPad网上预订攻略","pubDate":"2012-03-15 02:07:36 GMT","image":"http://course.gdou.com/images/jsondemo/14.gif","link":"http://course.gdou.com/JSONDemo/json/14.htm"},
{"title":"谷歌搜索将进行重大升级 网页上直接回答问题","pubDate":"2012-03-15 01:54:24 GMT","image":"http://course.gdou.com/images/jsondemo/15.gif","link":"http://course.gdou.com/JSONDemo/json/15.htm"},
{"title":"新款iPad或拉动苹果股价涨至700美元","pubDate":"2012-03-15 01:52:57 GMT","image":"http://course.gdou.com/images/jsondemo/16.gif","link":"http://course.gdou.com/JSONDemo/json/16.htm"},
{"title":"雨林木风Windows7 SP1、Windows XP SP3截至2012年3月补丁包","pubDate":"2012-03-15 01:49:24 GMT","image":"http://course.gdou.com/images/jsondemo/17.gif","link":"http://course.gdou.com/JSONDemo/json/17.htm"},
{"title":"苹果市值继续前进 已超过整个美国的零售业总值","pubDate":"2012-03-15 01:42:57 GMT","image":"http://course.gdou.com/images/jsondemo/18.png","link":"http://course.gdou.com/JSONDemo/json/18.htm"}]

           


Apple 只允许访问HTTPS 而禁止访问 HTTP 协议所致(HTTPS可忽略这一步),为访问HTTP 协议,必须在 Info.plist 文件中添加App Transport Security Settings  键值

course.gdou.com->blabla.com


对于数据存储需要一个类,定义为newMessage,四个变量都是String类型,分别对应新闻图片的Url、新闻标题、时间、新闻网页链接。

//
//  newMessage.swift
//  SecondHomeWork
//
//  Created by Dude on 2018/12/13.
//  Copyright © 2018年 Dude. All rights reserved.
//

import Foundation
import UIKit

class newMessage : NSObject {
    var newImage : String?
    var newTitle : String?
    var newDate : String?
    var newLink : String?
    
    
    
    init(newImage: String, newTitle: String, newDate: String, newLink : String) {
        self.newImage = newImage
        self.newTitle = newTitle
        self.newDate = newDate
        self.newLink = newLink
    }
    
}

建一个tableviewcontroller的控制器来控制表单,我取名myTableViewController。storyboard新建一个tableview,class为myTableViewController,prototype Cells选择subtitle(选择custom可以自己定制cell样式),因为subtitle样式的cell有textlable、detailtextlable以及imageView满足需求,所以可以不定制。这里注意cell的identifier,我这里是mycell,需要与之后myTableViewController里面cell的类型定义一致。点击表单之后是现实网页,添加一个View,在界面上添加WebKitView,WebView好像是弃用了,这里用到的基本用法一致。在View对应的Controller里面关联WebKitView,取名为aWebView。然后就基本没storyBoard什么事了。对哦Controller添加一个newMessage类型的变量来记录对应的信息。

//
//  myTableViewController.swift
//  SecondHomeWork
//
//  Created by Dude on 2018/12/13.
//  Copyright © 2018年 Dude. All rights reserved.
//

import UIKit


class myTableViewController: UITableViewController {
    
    //    for message of all cell
    //    newMessage(newImage:String, newTitle:String, newDate:String, newLink:String)
    var news = [newMessage]()    

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //*************************************
        //    MARK : get json - data by URL
        //-------------------------------------
        let url :URL = URL(string: "http://blabla/titles.json")!
        let data = try! Data(contentsOf: url)
        do{    //    apart data to newMessage, and append to news
            let arr : Array<Dictionary<String, String>>? = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String: String]]
            for each in arr!{
                var eachItem : [String : String] = each as [String : String]
                let newItem : newMessage = newMessage(newImage: (eachItem["image"]!), newTitle: (eachItem["title"]!), newDate: (eachItem["pubDate"]!), newLink: (eachItem["link"]!))
                self.news.append(newItem)
            }
        }catch let error as Error?{
            print("error=\(error!.localizedDescription)")
            
        }
        //*************************************

        

        self.refreshControl = UIRefreshControl()
        //set the title for pull request
        self.refreshControl!.attributedTitle = NSAttributedString(string:"更新数据…")
        //call he refresh function
        
        
        //    myTableViewController~~
self.refreshControl!.addTarget(self,action:#selector(myTableViewController.actionRefresh(_:)),for:UIControl.Event.valueChanged)
        self.tableView.addSubview(self.refreshControl!)


        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source


    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        //*********************
        //    not 0 here
        //*********************
        return 1
    }


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        //*********************
        //    not 0 here
        //*********************
        return self.news.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        //*****************************************************************
        //    mycell is the indentifier I define for the cell in storyboard
        //    if you choose the custom and design a yourself, replace the classtype UITableViewCell to the class you named
        //*****************************************************************        
        let callIndentifier = "mycell"
        
        let cell = tableView.dequeueReusableCell(withIdentifier: callIndentifier, for: indexPath) as UITableViewCell
        
        let onenew : newMessage = news[indexPath.row]
        
        cell.textLabel!.text = onenew.newTitle
        cell.detailTextLabel!.text = onenew.newDate
        
        //*************************
        //    get the image by it's URL
        //*************************
        let data : Data = try! Data.init(contentsOf: URL(string: onenew.newImage!)!)
        let image : UIImage = UIImage(data: data)!
        let sacleSize = CGSize(width: 30, height: 30)
        UIGraphicsBeginImageContextWithOptions(sacleSize, false, 0.0)
        image.draw(in: CGRect(x: 0, y: 0, width: sacleSize.width, height: sacleSize.height))
        let resizedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        cell.imageView!.image=resizedImage
        //        cell.imageView!.image = img
//
//        cell.imageView?.image = image

        // Configure the cell...

        return cell
    }
    
    
    //    remember link the action and the prepare func
    override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
//        print("prepare")
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
        let viewController:ViewController = segue.destination as! ViewController
        let indexPath:IndexPath=self.tableView.indexPathForSelectedRow!
        viewController.newItems = self.news[(indexPath as NSIndexPath).row]
        
    }
    @IBAction func actionRefresh( _ sender:AnyObject){
        // add code to refresh table data
        print("refresh...")
        (sender as! UIRefreshControl).endRefreshing()
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
//
//  ViewController.swift
//  SecondHomeWork
//
//  Created by Dude on 2018/12/13.
//  Copyright © 2018年 Dude. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController {

    //************
    //    newItems for message of this View, actually what I need is just the URL of Web 

    //************    
    @IBOutlet weak var aWebView: WKWebView!
    var newItems : newMessage?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        // navigation bar color
        self.navigationController!.navigationBar.barTintColor = UIColor.gray
        // text color in navigation bar
        self.navigationController!.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
        // text color in back button
        self.navigationController!.navigationBar.tintColor = UIColor.black

        //******************
        //    show Web by URL
        //******************
        let url:URL = URL(string:newItems!.newLink!)!
        let data:Data = try! Data(contentsOf: url)
        let webContent:String = NSString(data: data, encoding:String.Encoding.utf8.rawValue)! as String
        
        aWebView!.loadHTMLString(webContent, baseURL:URL(string:"http://blabla/"))
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

遇到的bug

1. All interface orientations must be supported unless the app requires full screen

    在设置genarl的deployment info勾选Require full screen

2. NSUnknowKeyException     [UITableViewCell]: this class is not key value coding-compliant for the key newDate

    因为一开始cell的style是custom,关联了两个label一个是newTitle一个是newDate,后来换成了subtitle,因为删除干净了,但是关联在cell端没去除,从storyboard右侧栏找到cell的属性设置,找到关联然后删掉,参考:http://www.cnblogs.com/qiyer/p/7798138.html

3. Unable to dequeue a cell with indentifier Cell

     一开始在storyboard那里给cell取名为mycell,然后就忘了,在myTableViewController里面代码讲callIndentifier 的值该成一致

let callIndentifier = "mycell"
        
        let cell = tableView.dequeueReusableCell(withIdentifier: callIndentifier, for: indexPath) as UITableViewCell

猜你喜欢

转载自blog.csdn.net/weixin_41948344/article/details/85006061
今日推荐