基于swift3.0的网络请求

2017-04-13 11:57
基于swift3.0的网络请求
 //MARK: - 发送请求
    func  request(httpUrl: String, httpArg: String) {
            //初始化请求
            let req = NSMutableURLRequest(url: NSURL(string: httpUrl + "?" + httpArg)! as URL)
            //设置请求超时
            req.timeoutInterval = 5
            //设置请求方式
            req.httpMethod = "GET"
            req.cachePolicy=NSURLRequest.CachePolicy.returnCacheDataElseLoad
            req.addValue("29d8f8163b8ad4894b3fa4db401bade8", forHTTPHeaderField: "apikey")

            let session=URLSession.shared
            let dataTask=session.dataTask(with: req as URLRequest) { (data, response, error) in


                if error != nil{
                    //如果请求过程出错
                    self.loadMoreBtn?.setTitle("加载失败,点击重试", for: UIControlState.normal)
                    self._aiv.stopAnimating()
                    self.loadMoreBtn?.isHidden=false
                }else{

                    let content = NSString(data: data!,                  encoding: String.Encoding.utf8.rawValue)

                    print(content)
                    //下次请求的页码加一
                    self.i=self.i+1



                        do{
                            let dict0:NSDictionary=try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                            let dict1:NSDictionary=dict0["showapi_res_body"]as! NSDictionary
                            let dict2:NSDictionary=dict1["pagebean"]as! NSDictionary
                            let array:NSArray=dict2["contentlist"] as! NSArray
                            //数据转模型
                            let conArray=Contents.ContentsWhithArray(array: array) as NSArray
                            //添加到数据源中
                            for con in conArray{
                                self.message.add(con)
                            }
                        }catch{
                            //解析出现异常

                        }



                    //回到主线程更新tableView
                    DispatchQueue.main.async(execute: {
                        self.tableView.reloadData()
                        self._aiv.stopAnimating()
                        self.loadMoreBtn?.isHidden=false
                        self.loadMoreBtn?.setTitle("点击加载更多", for: UIControlState.normal)

                    })


                }


            }
            //发送请求
            dataTask.resume()
        }