使用swift做一个小的应用,调用showapi来显示笑话。
1.使用pod装第三方库,Alamofire请求http数据,SnapKit代码布局,SwiftJSON解析json;
pod文件:
platform :ios,'8.0'
use_frameworks!
target 'JokeText' do
pod 'Alamofire','~> 3.0'
pod 'SwiftyJSON',:git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
pod 'SnapKit','~> 0.17.0'
end
2.打开Main.storyboard拖入一个TableView拉伸放置在合适的位置进行布局
3.关联UITableView
@IBOutlet weak var tableView: UITableView!
4.编写showapi(https://www.showapi.com/api/lookPoint/341/1)文本笑话请求,应答数据结构
1>请求:
//: Playground - noun: a place where people can play
//
// Request.swift
// JokeText
//
// Created by tutujiaw on 15/11/11.
// Copyright © 2015年 tujiaw. All rights reserved.
//
import Foundation
class Request {
var appId: Int
var timestamp: String {
return NSDate.currentDate("yyyyMMddHHmmss")
}
var signMethod = "md5"
var resGzip = 0
var allParams = [(String,String)]()
init(appId: Int) {
self.appId = appId
}
func sign(appParams: [(String,String)],secret: String) -> String {
self.allParams = appParams
self.allParams.append(("showapi_appid",String(self.appId)))
self.allParams.append(("showapi_timestamp",self.timestamp))
let sortedParams = allParams.sort{$0.0 < $1.0}
var str = ""
for item in sortedParams {
str += (item.0 + item.1)
}
str += secret.lowercaseString
return str.md5()
}
func url(mainUrl: String,sign: String) -> String {
var url = mainUrl + "?"
for param in self.allParams {
url += "\(param.0)=\(param.1)&"
}
url += "showapi_sign=\(sign)"
return url
}
}
//
// JokeTextRequest.swift
// JokeText
//
// Created by tutujiaw on 15/11/11.
// Copyright © 2015年 tujiaw. All rights reserved.
//
import Foundation
class JokeTextRequest : Request {
var time: String = ""
var page: Int = 0
var maxResult: Int = 0
var url: String {
let params = [("time",self.time),("page",String(self.page)),("maxResult",String(self.maxResult))]
let sign = super.sign(params,secret: "c7288cbf5a0941598e3ab326c27f9668")
return super.url("https://route.showapi.com/341-1",sign: sign)
}
init(time: String = NSDate.currentDate("yyyy-MM-dd"),page: Int = 1,maxResult: Int = 20) {
super.init(appId: 12078)
self.time = time
self.page = page
self.maxResult = maxResult
}
}
2>应答
//
// JokeTextResponse.swift
// JokeText
//
// Created by tutujiaw on 15/11/12.
// Copyright © 2015年 tujiaw. All rights reserved.
//
import Foundation
import SwiftyJSON
struct JokeItem {
var title = ""
var text = ""
var ct = ""
}
class Response {
static let sharedManager = Response()
var resCode = -1
var resError = ""
var allNum = 0
var allPages = 0
var currentPage = 0
var maxResult = 0
var contentList = [JokeItem]()
func setData(object: AnyObject) {
let json = JSON(object)
self.resCode = json["showapi_res_code"].int ?? -1
self.resError = json["showapi_res_error"].string ?? ""
let bodyJson = json["showapi_res_body"]
self.allNum = bodyJson["allNum"].int ?? 0
self.allPages = bodyJson["allPages"].int ?? 0
self.currentPage = bodyJson["currentPage"].int ?? 0
self.maxResult = bodyJson["maxResult"].int ?? 0
if self.currentPage == 1 {
self.contentList = [JokeItem]()
}
if let contentList = json["showapi_res_body"]["contentlist"].array {
for content in contentList {
guard let title = content["title"].string,let text = content["text"].string,let ct = content["ct"].string else {
continue
}
self.contentList.append(JokeItem(title: title,text: text,ct: ct))
}
}
}
}
3>md5计算(http://www.jb51.cc/article/p-pcleyxep-te.html)
extension String {
func md5() -> String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!,strLen,result)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x",result[i])
}
result.destroy()
return String(format: hash as String)
}
}
日期格式化
extension NSDate {
static func currentDate(dateFormat: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale.currentLocale()
return dateFormatter.stringFromDate(NSDate())
}
}
5.自定义UITableViewCell
//
// JokeViewCell.swift
// JokeText
//
// Created by tutujiaw on 15/11/14.
// Copyright © 2015年 tujiaw. All rights reserved.
//
import UIKit
import SnapKit
class JokeViewCell : UITableViewCell {
static let ID = "JOKE_VIEW_CELL_ID"
let titleLabel = UILabel()
let ctLabel = UILabel()
let contentLabel = UILabel()
override init(style: UITableViewCellStyle,reuseIdentifier: String?) {
super.init(style: style,reuseIdentifier: reuseIdentifier)
self.addSubview(titleLabel)
self.addSubview(ctLabel)
self.addSubview(contentLabel)
titleLabel.textColor = UIColor.redColor()
titleLabel.snp_makeConstraints{(make)->Void in
make.top.equalTo(self.snp_top).offset(5)
make.height.equalTo(20)
make.left.equalTo(self.snp_left).offset(5)
make.right.equalTo(ctLabel.snp_left).offset(-5)
}
ctLabel.textColor = UIColor.blueColor()
ctLabel.snp_makeConstraints{(make)->Void in
make.top.equalTo(self.snp_top).offset(5)
make.height.equalTo(titleLabel)
make.left.equalTo(titleLabel.snp_right).offset(5)
make.width.equalTo(160)
make.right.equalTo(self.snp_right).offset(-5)
}
contentLabel.snp_makeConstraints{(make)->Void in
make.top.equalTo(titleLabel.snp_bottom).offset(5)
make.bottom.equalTo(self.snp_bottom).offset(-5)
make.centerX.equalTo(self.snp_centerX)
make.width.equalTo(self).offset(-10)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
6.编写ViewController
//
// ViewController.swift
// JokeText
//
// Created by tutujiaw on 15/11/11.
// Copyright © 2015年 tujiaw. All rights reserved.
//
import UIKit
import Alamofire
import SnapKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var currentPage = 1
var isLoading = false
let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
refreshControl.addTarget(self,action: "refreshData",forControlEvents: .ValueChanged)
tableView.addSubview(refreshControl)
requestData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getColor(color:Int32) -> UIColor{
let red = CGFloat((color&0xff0000)>>16)/255
let green = CGFloat((color&0xff00)>>8)/255
let blue = CGFloat(color&0xff)/255
return UIColor(red: red,green: green,blue: blue,alpha: 1)
}
func requestData() {
print("----------\(currentPage)")
let request = JokeTextRequest(time: "2015-01-01",page: currentPage)
isLoading = true
Alamofire.request(.GET,request.url).responseJSON { response in
print(response.request?.URLString)
if response.result.isSuccess {
if let value = response.result.value {
Response.sharedManager.setData(value)
self.tableView.reloadData()
}
} else {
response.result.error
}
self.isLoading = false
self.refreshControl.endRefreshing()
}
}
func refreshData() {
currentPage = 1
requestData()
}
}
extension ViewController: UITableViewDelegate,UITableViewDataSource {
internal func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return Response.sharedManager.contentList.count
}
internal func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(JokeViewCell.ID) as? JokeViewCell
if cell == nil {
cell = JokeViewCell(style: .Subtitle,reuseIdentifier: JokeViewCell.ID)
}
let jokeItem = Response.sharedManager.contentList[indexPath.row]
cell?.titleLabel.text = jokeItem.title
cell?.ctLabel.text = jokeItem.ct.substringToIndex(jokeItem.ct.endIndex.advancedBy(-4))
cell?.contentLabel.attributedText = NSAttributedString(string: jokeItem.text,attributes: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType])
cell?.contentLabel.numberOfLines = 0
cell?.contentLabel.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds)
return cell!
}
func tableView(tableView: UITableView,heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if self.isLoading {
return
}
let space = CGFloat(10)
let y = scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom
//print("y:\(y),height:\(scrollView.contentSize.height),table height:\(self.tableView.frame.height)")
if y > scrollView.contentSize.height + space { // 滑到底部
++currentPage
if currentPage > Response.sharedManager.allPages {
currentPage = 1
}
requestData()
}
}
}
其中涉及到UITableView cell自适应高度(http://www.jb51.cc/article/p-dxbuaaev-te.html)