使用json解析来开发一个微信热门精选客户端。当你学会了这个之后,你应该可以开发一个天气app或者新闻客户端。
测试版本:Xcode7.3
1.效果图
2.步骤
我们需要用到Alamofire、SwiftyJSON、ProgressHUD,下载完成后先把Alamofire.xcodeproj导入到项目中
然后点击项目名称->General,添加依赖库Alamofire.framework,记得选择ios
把SwiftyJSON.swift和ProgressHUD文件夹导入到项目中,最终如图。
由于要涉及到上网,需要在Info.plist添加
然后设置桥接头文件,新建一个BridgeHeader.m文件,点击项目名称->Build Settings->Objective-C Bridging Header
新建一个表格控制类RootTableViewController.swift,敲入代码
// RootTableViewController.swift
// XYWeiXinArticles
// Created by 酸奶 on 16/5/20.
// Copyright © 2016年 Color. All rights reserved.
import UIKit
import Alamofire
class RootTableViewController: UITableViewController {
//标题
var newsTitle = Array()
//图片
var newsImage = Array()
//文章网址
var newsUrl = Array()
override func viewDidLoad() {
super.viewDidLoad()
//去除多余横线
self.tableView.tableFooterView = UIView()
//修改返回按钮的颜色
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
getData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return newsTitle.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
//为了使文字全部显示
cell.textLabel?.numberOfLines = 3
//字体大小
cell.textLabel?.font = UIFont.systemFontOfSize(12)
cell.textLabel?.text = newsTitle[indexPath.row]
cell.imageView?.image = newsImage[indexPath.row]
//以下为控制cell的图像大小保持一致的一种方法
let itemSize = CGSizeMake(80, 80)
UIGraphicsBeginImageContext(itemSize);
let imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
cell.imageView?.image?.drawInRect(imageRect)
cell.imageView?.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return cell
}
//Alamofire 解析json获取数据
func getData() {
ProgressHUD.show("加载中")
//这里的key仅用作演示,还请大家申请后使用自己的key,在这里可以申请:http://api.huceo.com/#wxnew
let url = "http://api.huceo.com/wxnew/?key=26ab33a5283646be3cd3902d5954cc32&num=10"
Alamofire.request(.GET,url).responseJSON { (response) in
if let value = response.result.value {
let json = JSON(value)
let jsonList = json["newslist"]
for (_,subJson):(String, JSON) in jsonList {
self.newsTitle.append(subJson["title"].stringValue)
self.newsUrl.append(subJson["url"].rawValue as! String)
let imageUrl = subJson["picUrl"].rawValue
let url = NSURL(string: imageUrl as! String)
let image = UIImage(data: NSData(contentsOfURL: url!)!)
self.newsImage.append(image!)
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
ProgressHUD.showSuccess("成功")
}
}
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
//跳转传网址
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showWeb" {
let indexPath = self.tableView.indexPathForSelectedRow as NSIndexPath!
let controller = segue.destinationViewController as! WKWebViewController
controller.newsUrl = newsUrl[indexPath.row]
}
}
}
然后新建一个显示网页的类WKWebViewController.swift
// WKWebViewController.swift
// XYWeiXinArticles
// Created by 酸奶 on 16/5/20.
// Copyright © 2016年 Color. All rights reserved.
import UIKit
import WebKit
class WKWebViewController: UIViewController,WKNavigationDelegate,WKUIDelegate {
//获取设备宽高
let screenWidth = UIScreen.mainScreen().bounds.width
let screenHeight = UIScreen.mainScreen().bounds.height
var newsUrl = String()
var webview = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
//状态栏高度
let statusHeight = UIApplication.sharedApplication().statusBarFrame.height
//导航栏高度
let navHeight = self.navigationController!.navigationBar.frame.height
//两者之和
let totalHeight = statusHeight + navHeight
//webview高度
let webHeight = screenHeight - totalHeight
//注意这里的y和高度的设置,否则显示网页有问题
webview = WKWebView(frame: CGRectMake(0, 0, screenWidth, webHeight))
let request = NSURLRequest(URL: NSURL(string: newsUrl)!)
webview.loadRequest(request)
self.webview.navigationDelegate = self
self.webview.UIDelegate = self
self.view.addSubview(webview)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//处理js提示框
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "好", style: .Default, handler: { (_) -> Void in
completionHandler()
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
至此一个简单的微信热门精选客户端完成!