1. 程式人生 > >Swift 網路資料請求與處理最常用第三方

Swift 網路資料請求與處理最常用第三方

一: Swift 網路資料請求與處理最常用第三方 

    又有時間出來裝天才了,還是在學swift,從中又發現一些問題,這兩天上網找部落格看問題弄的真的心都累。部落格一篇寫出來,好多就直接照抄,就沒有實質性的把問題解決了,只是在發表的部落格數量上 + 1 !!真心沒意思。。

    看看在Swift中是在怎樣請求資料,解析資料載入圖片這些的,也使我們最基本最常見的用法了,先說說這幾個三方庫: 

    第一個: Alamofire  (它的原作者就是AFNetworking的原作者,這個就不多說了,你要知道AFNetworking有多重要,多好用,它就有多重要好用!)

    Git地址:https://github.com/Alamofire/Alamofire

    第二個: SwiftyJSON  一個解析JSON資料的三方庫,使用swift寫的,中間幫你省去swift的各種可選值的操作,很簡便(推薦!)

    Git地址:  https://github.com/SwiftyJSON/SwiftyJSON

    第三個: Kingfisher   (一個圖片載入的國產庫。重點是國產的的支援!)

    Git地址:https://github.com/onevcat/Kingfisher/releases

    說說他們匯入時候的問題,其實三方我們用的時候,可能匯入的時候會有問題,能用的反倒不會說不會用怎樣,匯入時候的問題各種各樣,五花八門的!比起那些手動匯入三方的我真的是你強烈建議推薦  Cocoapods ! 它的安裝使用在前面我的部落格裡面有些過,是最新安裝的方法,我的也是不久前安裝的,有需要的可以去看一下:地址--->  http://www.cnblogs.com/taoxu/p/4964395.html

   然後呢,再給大家一個建議,匯入時候多去 Git 上面看看原作者的詳細的匯入過程,以及可能會出現的一下問題!在匯入的過程中,一定要注意你自己工程的最低版本要求和三方庫的最高版本要求之間的差異,這個很容易忽略導致錯誤!我把自己的 cocoapods 的終端輸入命令展示出來,確保是沒問題,可行的!我寫的例子專案最低版本是 8.0 。

 

platform :ios, '9.0'

use_frameworks!

pod 'Alamofire''~> 3.3'

 

platform :ios, '9.0'

use_frameworks!

pod 'SwiftyJSON','~> 2.3.1'

 

platform :ios, '8.0'

use_frameworks!

pod 'Kingfisher''~> 2.4'

二:完整程式碼示例用法

import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
 
// 相當於資料模型model
class itemsModel: NSObject {
     
    var cover_image_url = ""
    var title  = ""
    var likecount = ""
     
}
 
class giftSaycontroller: UIViewController,UITableViewDelegate,UITableViewDataSource {
     
    @IBOutlet weak var gifttableview: UITableView!
    
    // 資料來源
    var dataArray = [itemsModel]()
 
    override func viewDidLoad() {
        super.viewDidLoad()
         
        gifttableview.delegate = self
        gifttableview.dataSource = self
         
        self.DownLoadData()
         
        // Do any additional setup after loading the view.
   
    }
     
    // MARK: 下載解析資料
    func DownLoadData() -> Void {
        
        Alamofire.request(.GET, "http://api.liwushuo.com/v2/channels/104/items?ad=2&gender=2&generation=2&limit=20&offset=0").responseJSON {
            (response)   in
             
            // 有錯誤就列印錯誤,沒有就解析資料
            if let Error = response.result.error
            {
               print(Error)
            }
            else if let jsonresult = response.result.value {
                // 用 SwiftyJSON 解析資料
                let JSOnDictory = JSON(jsonresult )
                let data =  JSOnDictory["data"]["items"].array
                for dataDic in  data!
                {
                     
                    let model =  itemsModel()
                    //  ?? 這個符號,我怕有初學者忘記了的提醒一下,A ?? B  這是一個 NIL合併運算子,它的作用是如果 A 不是NIL 就返回前面可選型別引數 A 的確定值, 如果 A 是NIL 就返回後面 B 的值!A和B之間型別的注意點我就不說了,忘記了去看書,,哈哈哈
 
                    model.cover_image_url = dataDic["cover_image_url"].string ?? ""
                    model.title =  dataDic["title"].string ?? ""
 
                    let  numString = String(format:"%d",dataDic["likes_count"].intValue ?? 0)
                    model.likecount = numString
                    self.dataArray.append(model)
                     
                }
                 
                self.gifttableview.reloadData()
 
                //print(jsonresult)
 
            }
        }
    }
     
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         
        return self.dataArray.count
     
    }
     
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
         
        let cell:giftTabelViewcell = tableView .dequeueReusableCellWithIdentifier("Gifsayidentifile") as! giftTabelViewcell
        let model = self.dataArray[indexPath.row]
        cell.likeNumberLabel.text = model.likecount
         
        // 這個就是用到 Kingfisher
        cell.backGroundImage.kf_setImageWithURL(NSURL(string: model.cover_image_url)!)
        return cell
         
    }
     
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
         
        print(indexPath.row)
         
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
     
 
    /*
    // MARK: - Navigation
 
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
 
}