學習Swift 第三方網絡封裝庫Moya
Alamofire封裝庫Moya
Moya
moya 對Alamofire網絡請求庫進行了封裝,開發不需要寫網絡模型,管理等。使代碼更加簡潔。詳情訪問 Moya 項目主頁
1. 創建一個iOS Swift項目 (廢話)
這里使用cocoapods 創建Podfile文件放在項目根目錄下
Java
source 'https://github.com/CocoaPods/Specs.git' use_frameworks! pod 'Moya'
source 'https://github.com/CocoaPods/Specs.git' use_frameworks! pod 'Moya'
在項目根目錄運行
Java
pod install --verbose --no-repo-update // 不更新repo, 速度會快點
podinstall --verbose --no-repo-update // 不更新repo, 速度會快點
安裝成功
點擊 .xcworkspace 文件。啟動項目
2. 創建API管理文件 DSAPI.Swift
這里我們使用逗視的api1.引入Moya頭文件
Java
<code class="swift">import Foundation import Moya </code>
<codeclass="swift">import Foundation import Moya </code>
2.創建DS的請求方法列表 enum
Java
/** MARK: 創建DS 請求方法列表 - GetVideosByType 根據類型獲取視頻列表 */ public enum DS { case GetVideosByType(Int,Int,Int,Int) //根據類型獲取視頻列表 }
/** MARK: 創建DS 請求方法列表 - GetVideosByType 根據類型獲取視頻列表 */ public enum DS { case GetVideosByType(Int,Int,Int,Int) //根據類型獲取視頻列表 }
3.創建 MoyaProvider
Java
// MARK: - Provider setup let DSProvider = MoyaProvider<DS>()
// MARK: - Provider setup letDSProvider = MoyaProvider<DS>()
4.通過Moya 定義的 baseUrl 、 請求路徑( path )、 Http方法、 參數和目標的示例數據的協議。
擴展DS : TargetType
Java
extension DS: TargetType { // 逗視API地址 public var baseURL: NSURL { return NSURL(string: "https://api.doushi.me/v1/rest/video/")! } /// 拼接請求字符串 public var path: String { switch self { case .GetVideosByType(let vid, let count, let type,let userId): return ("getVideosByType/\(vid)/\(count)/\(type)/\(userId)") } } /// 請求方法 public var method: Moya.Method { return .GET } /// 配置參數 public var parameters: [String: AnyObject]? { switch self { default: return nil } } /// 數據 public var sampleData: NSData { switch self { case .GetVideosByType: return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)! } } }
extensionDS: TargetType { // 逗視API地址 public var baseURL: NSURL { return NSURL(string: "https://api.doushi.me/v1/rest/video/")! } /// 拼接請求字符串 public var path: String { switch self { case .GetVideosByType(letvid, letcount, lettype,letuserId): return ("getVideosByType/\(vid)/\(count)/\(type)/\(userId)") } } /// 請求方法 public var method: Moya.Method { return .GET } /// 配置參數 public var parameters: [String: AnyObject]? { switch self { default: return nil } } /// 數據 public var sampleData: NSData { switch self { case .GetVideosByType: return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)! } } }
OK 這樣創建好了DSAPI管理類,下面在tableView中實驗一把
5.創建VideosTableViewController
- 定義數據集合
Java
var repos = NSArray()
var repos = NSArray()
- 創建loadData()方法請求網絡數據
Java
/** 請求數據 */ func loadData() { DSProvider.request(DS.GetVideosByType(0, 12, 0, 1)) {(result) -> () in switch result { case let .Success(response): do { let json: Dictionary? = try response.mapJSON() as? Dictionary<String, AnyObject> if let json = json { print(json["content"] as! Array<AnyObject>) if let contents: Array<AnyObject> = json["content"] as? Array<AnyObject> { self.repos = contents } } self.tableView.reloadData() } catch { } case let .Failure(error): print(error) break } } }
/** 請求數據 */ funcloadData() { DSProvider.request(DS.GetVideosByType(0, 12, 0, 1)) {(result) -> () in switch result { case let .Success(response): do { letjson: Dictionary? = try response.mapJSON() as? Dictionary<String, AnyObject> if letjson = json { print(json["content"] as! Array<AnyObject>) if letcontents: Array<AnyObject> = json["content"] as? Array<AnyObject> { self.repos = contents } } self.tableView.reloadData() } catch { } case let .Failure(error): print(error) break } } }
- 擴展VideosTableViewController Cell增添數據
Java
extension VideosTableViewController { override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... let contentDic = repos[indexPath.row] as? Dictionary<String, AnyObject> cell.textLabel?.text = contentDic!["title"] as? String return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repos.count } }
extension VideosTableViewController { overridefunctableView(tableView: UITableView, cellForRowAtIndexPathindexPath: NSIndexPath) -> UITableViewCell { letcell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... letcontentDic = repos[indexPath.row] as? Dictionary<String, AnyObject> cell.textLabel?.text = contentDic!["title"] as? String return cell } overridefunctableView(tableView: UITableView, numberOfRowsInSectionsection: Int) -> Int { return repos.count } }
OK,點擊 Run 看一下效果吧
正確獲取到 逗視 app的視頻列表了
有沒有發現這樣寫網絡請求很爽,我們只維護 DSAPI 就可以了,添加請求方法,處理數據等。
本文例子已經上傳到github,有問題可以發送郵件iosdev#itjh.com.cn
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!