Swift 網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求與解析
先說(shuō)說(shuō)這幾個(gè)三方庫(kù):?
第一個(gè):Alamofire(它的原作者就是AFNetworking的原作者锅知,這個(gè)就不多說(shuō)了,你要知道AFNetworking有多重要很魂,多好用,它就有多重要好用H侍帧)
Git地址:https://github.com/Alamofire/Alamofire
?? 特點(diǎn):純Swift編寫的HTTP網(wǎng)絡(luò)庫(kù)
??????????????? 鏈?zhǔn)秸?qǐng)求/響應(yīng)
????? URL/JSON/Plist格式的參數(shù)
?上傳文件/數(shù)據(jù)/流/多格式參數(shù)
?斷點(diǎn)續(xù)傳
?NSURLCredential授權(quán)
?HTTP響應(yīng)驗(yàn)證
?NSProgress&進(jìn)度閉包
? 支持環(huán)境:iOS8.0以上??xcode7.2以上
?//請(qǐng)求
? ? func request() {
? ? ? ? let url = "https://api.douban.com/v2/book/search"
? ? ? ? let param = ["tag":"Swift" , "count":"1"]
? ? ? ? Alamofire.request(.GET, url, parameters:
param).responseJSON { (response) in
? ? ? ? ? ? if let error = response.result.error {
?? ? ? ? ? ? ? print(error)
? ? ? ? ? ? }else if let value = response.result.value{
? ? ? ? ? ? ? print(value)
? ? ? ? ? }
? ? ? }
? }
? ? //下載
? ? func downLoad(){
? ? ? ? let url = "http://img.pconline.com.cn/image/photoblog/1/7/7/4/1774994/20063/28/1143511691007.JPG"
? ? ? ? print(NSHomeDirectory())
? ? ? ? Alamofire.download(.GET, url, destination:
Alamofire.Request.suggestedDownloadDestination()).progress { (readBytes, totalReadBytes, totalNeedToReadBytes) in
? ? ? ? ? ? let progress = Int(Double(totalReadBytes)/Double(totalNeedToReadBytes)
* 100)
? ? ? ? ? ? print("\(progress)%")
? ? ? ? }.response { (request,
response, data, error) in
? ? ? ? ? ? if let error = error {
? ? ? ? ? ? ? ? print(error)
? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? print("下載成功")
? ? ? ? ? }
? ? ? }
? ? }.response(queue: dispatch_get_main_queue()) { (_, _, _, error) in
? ? ? ? ? ? //返回主線程操作
? ? ? ? ? ? if let error = error {
? ? ? ? ? ? ? ? print(error)
? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? print("下載成功")
? ? ? ? ? }
? ? ? }
第二個(gè):SwiftyJSON一個(gè)解析JSON數(shù)據(jù)的三方庫(kù)牧抵,使用swift寫的,中間幫你省去swift的各種可選值的操作班利,很簡(jiǎn)便(推薦<⒙)
Git地址:https://github.com/SwiftyJSON/SwiftyJSON
用法
else if let jsonresult =
response.result.value {
? ? ? // 用 SwiftyJSON 解析數(shù)據(jù)
? ? ? ? ? ? ? ? let JSOnDictory = JSON(jsonresult)
? ? ? ? ? ? ? ? let data =?
JSOnDictory["goods_list"].array
? ? ? ? ? ? ? ? for dataDic in? data!
? ? ? ? ? ? ? ? {
? ? let model =? Model()
? ? model.hd_thumb_url = dataDic["hd_thumb_url"].string ?? ""
? ? model.goods_name =? dataDic["goods_name"].string ?? ""
? ? let? numString = dataDic["normal_price"].intValue ?? 0
? ? model.normal_price = numString
? ? self.dataArr.append(model)
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? self.tableView.reloadData()
? ? ? ? ? ? }
第三個(gè):Kingfisher(一個(gè)圖片加載的國(guó)產(chǎn)庫(kù)。重點(diǎn)是國(guó)產(chǎn)的的支持B薇辍)
用法
self.backGroundImage?.kf_setImageWithURL(NSURL(string: backGroundImageName!)!)