开发�工作数据请求一般都是用第三方的框架,OC用AFNetworking,Swift用Alamofire,很少用原生。
AFNetworking
一般会在AFNetworking上简单的封装一层,暴露出get,post和文件上产三个接口
Alamofire
API用的的是APIStore
遇到的问题
问题一:http传输不符合苹果网络安全策略
**App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.**
**FAILURE: Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x7fd9d9d1d590 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text?apikey=5ac26d9bf3cb087732ceef3ff42ab3ff&page=1, NSErrorFailingURLKey=http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text?apikey=5ac26d9bf3cb087732ceef3ff42ab3ff&page=1, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}**
解决方案
在plist中添加相应的key
问题二: 少配置http头内容
解决方案:
let headers = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Accept": "application/json"]Alamofire.request(.GET,
"https://httpbin.org/get", headers: headers) .responseJSON {
response in debugPrint(response)
}
Demo
import UIKit
import Alamofire
import EVReflection
let apiKey = "5ac26d9bf3cb087732ceef3ff42ab3ff"
class testObject: EVObject {
var showapi_res_code = ""
var showapi_res_error = ""
var name = ""
var allPages = ""
var ret_code = ""
var id = ""
var text = ""
var title = ""
var type = ""
var ct = ""
var currentPage = ""
var allNum = ""
var maxResult = ""
var showapi_res_body:testObject?
var contentlist:[testObject] = []
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupData()
}
func setupData() {
let header = ["apikey":apiKey]
Alamofire.request(.GET, "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text", parameters: ["page":"1"],headers:header).responseJSON { response in
let json : [String : AnyObject] = response.result.value as! [String : AnyObject]
let object:testObject = testObject(dictionary:json )
let arr:[testObject] = (object.showapi_res_body?.contentlist)!
let test:testObject = arr[0]
print("\(test.text)")
}
}
}
判断网络状态
方案一:在UI层处理
在controller或者viewModel进行数据请求,请求不通的时候根据code值提示网络链接错误。
方案二:在网络层进行处理
在封装网络层时直接处理了,我觉得这种处理方案比较好。
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@",AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];