使用swift做一个小的应用,调用showapi来显示笑话。
1.使用pod装第三方库,Alamofire请求http数据,SnapKit代码布局,SwiftJSON解析json;
pod文件:
platform :ios,'8.0'
use_frameworks!
target 'JokeText' @H_403_13@do
pod 'Alamofire','~> 3.0'
pod 'SwiftyJSON',:git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
pod 'SnapKit','~> 0.17.0'
@H_403_13@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
@H_403_13@class Request {
@H_403_13@var appId: Int
@H_403_13@var timestamp: String {
@H_403_13@return NSDate.currentDate("yyyyMMddHHmmss")
}
@H_403_13@var signMethod = "md5"
@H_403_13@var resGzip = 0
@H_403_13@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))
@H_403_13@let sortedParams = allParams.sort{$0.0 < $1.0}
@H_403_13@var str = ""
@H_403_13@for item @H_403_13@in sortedParams {
str += (item.0 + item.1)
}
str += secret.lowercaseString
@H_403_13@return str.md5()
}
func url(mainUrl: String,sign: String) -> String {
@H_403_13@var url = mainUrl + "?"
@H_403_13@for param @H_403_13@in self.allParams {
url += "\(param.0)=\(param.1)&"
}
url += "showapi_sign=\(sign)"
@H_403_13@return url
}
}
//
// JokeTextRequest.swift
// JokeText
//
// Created by tutujiaw on 15/11/11.
// Copyright © 2015年 tujiaw. All rights reserved.
//
import Foundation
@H_403_13@class JokeTextRequest : Request {
@H_403_13@var time: String = ""
@H_403_13@var page: Int = 0
@H_403_13@var maxResult: Int = 0
@H_403_13@var url: String {
@H_403_13@let params = [("time",self.time),("page",String(self.page)),("maxResult",String(self.maxResult))]
@H_403_13@let sign = super.sign(params,secret: "c7288cbf5a0941598e3ab326c27f9668")
@H_403_13@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
@H_403_13@struct JokeItem {
@H_403_13@var title = ""
@H_403_13@var text = ""
@H_403_13@var ct = ""
}
class Response {
@H_403_13@static @H_403_13@let sharedManager = Response()
@H_403_13@var resCode = -1
@H_403_13@var resError = ""
@H_403_13@var allNum = 0
@H_403_13@var allPages = 0
@H_403_13@var currentPage = 0
@H_403_13@var maxResult = 0
@H_403_13@var contentList = [JokeItem]()
func setData(@H_403_13@object: AnyObject) {
@H_403_13@let json = JSON(@H_403_13@object)
self.resCode = json["showapi_res_code"].@H_403_13@int ?? -1
self.resError = json["showapi_res_error"].@H_403_13@string ?? ""
@H_403_13@let bodyJson = json["showapi_res_body"]
self.allNum = bodyJson["allNum"].@H_403_13@int ?? 0
self.allPages = bodyJson["allPages"].@H_403_13@int ?? 0
self.currentPage = bodyJson["currentPage"].@H_403_13@int ?? 0
self.maxResult = bodyJson["maxResult"].@H_403_13@int ?? 0
@H_403_13@if self.currentPage == 1 {
self.contentList = [JokeItem]()
}
@H_403_13@if @H_403_13@let contentList = json["showapi_res_body"]["contentlist"].array {
@H_403_13@for content @H_403_13@in contentList {
guard @H_403_13@let title = content["title"].@H_403_13@string,@H_403_13@let text = content["text"].@H_403_13@string,@H_403_13@let ct = content["ct"].@H_403_13@string @H_403_13@else {
@H_403_13@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! {
@H_403_13@let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
@H_403_13@let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
@H_403_13@let digestLen = Int(CC_MD5_DIGEST_LENGTH)
@H_403_13@let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!,strLen,result)
@H_403_13@let hash = NSMutableString()
@H_403_13@for i @H_403_13@in 0..<digestLen {
hash.appendFormat("%02x",result[i])
}
result.destroy()
@H_403_13@return String(format: hash as String)
}
}
日期格式化
extension NSDate {
static func currentDate(dateFormat: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale.currentLocale()
@H_403_13@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 @H_403_13@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 @H_403_13@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 @H_403_13@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 @H_403_13@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)