什么是Alamofire? github開(kāi)源框架
傳統(tǒng)的Objective-C的開(kāi)發(fā)者,一定非常熟悉AFNetworking這個(gè)網(wǎng)絡(luò)框架昆婿。在蘋果推出的Swift之后,AFNetworking的作者專門用Swift來(lái)編寫(xiě)一個(gè)類似AFNetworking的網(wǎng)絡(luò)框架蜓斧,稱為Alamofire
下面我們分別從搭建,使用等不同場(chǎng)景,結(jié)合項(xiàng)目來(lái)分析下Alamofire的網(wǎng)絡(luò)請(qǐng)求
Alamofire的導(dǎo)入
Alamofire我們使用cocopods導(dǎo)入方式:
cd /Users/charles/Desktop/DCApp
pod init
podfile里面配置如下
pod 'Alamofire'
終端執(zhí)行pod install
Alamofire的項(xiàng)目的使用
在我們封裝的RequestCenter文件導(dǎo)入Alamofire
import UIKit
import MBProgressHUD
import Alamofire
import ObjectMapper
Alamofire的請(qǐng)求方式
- 獲取服務(wù)器資源:GET
let para:[String:Any] = ["syskey":"xxx","moduleKey":"xxx",qtype":qtype,"page":page,"size":size,"username":username]
let header = ["Accept": "*/*", "X-Requested-With": "APP"]
Alamofire.request("\(BasePath)/api/question/list", method: HTTPMethod.get, parameters: para, encoding: URLEncoding.default, headers: header).responseJSON { (dataResponse) in
print(dataResponse)
if dataResponse.value != nil
{
let values = dataResponse.result.value as! NSDictionary
let messageDic = values["message"]as! NSDictionary
let questionContentArr = messageDic["questionContent"] as! [[String : Any]]
if questionContentArr.count != 0 {
for dict in questionContentArr
{
let model = Mapper<ChildInforModel>().map(JSON: dict as! [String:AnyObject])
self.childrenModelArray.append(model!)
}
}
在這里我們使用ObjectMapper對(duì)返回的數(shù)據(jù)進(jìn)行解析,需在podfile文件中導(dǎo)入ObjectMapper
pod 'ObjectMapper'
model的映射如下:
//兒童信息Model
class ChildInforModel: Mappable {
var bindId = ""http://綁定id
var fatherName = ""
var fatherPhone = ""
required init?(map: Map) {
}
func mapping(map: Map) {
bindId <- map["a"]
fatherName <- map["b"]
fatherPhone <- map["c"]
}
}
有沒(méi)有很方便?
2 . 提交資源到服務(wù)器:(請(qǐng)求參數(shù)為字典POST)
let appid = UserDefaults.standard.value(forKey: "appid") as! String
let token = UserDefaults.standard.value(forKey: "token") as! String
let RT = GlobalCenter.sharedInstance().recordTimeString()
let sig = GlobalCenter.sharedInstance().sha1Str(str: "token=\(token)&ski=\(ski)&RT=\(RT)")
let para:[String:Any] = ["token":token,"ski":ski,"appid":appid,"RT":RT,"sig":sig]
let header = ["Accept": "*/*", "X-Requested-With": "APP"]
Alamofire.request("\(BasePath)/v7/client/loginSyetems", method: HTTPMethod.post, parameters: para, encoding: URLEncoding.default, headers: header).responseJSON { (dataResponse) in
print(dataResponse)
}
3 . 提交資源到服務(wù)器:(請(qǐng)求參數(shù)為字典轉(zhuǎn)化為字符串仓蛆,再經(jīng)base64編碼)
let para:[String:Any] = ["method":"queryInfo","condition":["no":studentNo]
let requestPara = ["":Base64Encoding(plainString: dicValueString(para)!)]
let header = ["Accept": "*/*", "X-Requested-With": "APP","Content-Type":"application/json;charset=utf-8"]
Alamofire.request("\(BasePath)", method: HTTPMethod.post, parameters: requestPara, encoding: JSONEncoding.default, headers: header).responseString { (dataResponse) in
ssPrint(dataResponse.result)
if dataResponse.result.isSuccess {
let value = Base64Decoding(encodedString: dataResponse.result.value!.replacingOccurrences(of: "\"", with: ""))
completionHandler(value)
}}
字典轉(zhuǎn)字符串:
func dicValueString(_ dic:[String : Any]) -> String?{
let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
let str = String(data: data!, encoding: String.Encoding.utf8)
return str
}
字符串base64編碼
func Base64Encoding(plainString:String)->String
{
let plainData = plainString.data(using: String.Encoding.utf8)
let base64String = plainData?.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
return base64String!
}
返回的字符串解碼:
func Base64Decoding(encodedString:String)->String
{
if encodedString.contains("status:404") || encodedString.contains("status:400"){
return ""
}
let decodedData = NSData(base64Encoded: encodedString, options: NSData.Base64DecodingOptions.init(rawValue: 0))
let decodedString = NSString(data: decodedData! as Data, encoding: String.Encoding.utf8.rawValue)! as String
return decodedString
}
請(qǐng)求返回的字符串轉(zhuǎn)字典數(shù)組
func stringValueArr(_ str: String) -> [[String : Any]]?{
let data = str.data(using: String.Encoding.utf8)
if let dict = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String : Any]] {
return dict
}
return nil
}
應(yīng)用層數(shù)據(jù)處理:
let dataArray = stringValueArr(value)
print("dataArray:",dataArray!)
3 . 圖片(表單)上傳
let appid = UserDefaults.standard.value(forKey: "appid") as! String
let jwt = UserDefaults.standard.value(forKey: "jwt") as! String
let sig111 = sha1Str(str: "appid=\(appid)&NI=\(userId)&RT=\(RT)")
Alamofire.upload(
//同樣采用post表單上傳
multipartFormData: { multipartFormData in
multipartFormData.append(appid.data(using: String.Encoding.utf8)!, withName: "appid")
multipartFormData.append(jwt.data(using: String.Encoding.utf8)!, withName: "jwt")
multipartFormData.append(sig.data(using: String.Encoding.utf8)!, withName: "sig111")
multipartFormData.append(newImage.pngData()!, withName: "file", fileName: "userPic.png", mimeType: "image/png")
},to: "\(BasePath1)/api/v1/updatePhotos",encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
//json處理
upload.responseJSON { response in
//解包
guard let values = response.result.value else { return }
if String(describing: (values as! NSDictionary)["code"]!) == "0" {
}
至此常見(jiàn)的幾種網(wǎng)絡(luò)請(qǐng)求完成!是不是很簡(jiǎn)單,喜歡的話點(diǎn)個(gè)贊吧!