美文网首页全栈开发
swift网络请求之Alamofire

swift网络请求之Alamofire

作者: MichaelDing | 来源:发表于2019-08-26 16:37 被阅读0次

什么是Alamofire? github开源框架

传统的Objective-C的开发者,一定非常熟悉AFNetworking这个网络框架。在苹果推出的Swift之后,AFNetworking的作者专门用Swift来编写一个类似AFNetworking的网络框架,称为Alamofire
下面我们分别从搭建,使用等不同场景,结合项目来分析下Alamofire的网络请求

Alamofire的导入

Alamofire我们使用cocopods导入方式:

cd /Users/charles/Desktop/DCApp 
pod init

podfile里面配置如下

 pod 'Alamofire'

终端执行pod install

Alamofire的项目的使用

在我们封装的RequestCenter文件导入Alamofire

import UIKit
import MBProgressHUD
import Alamofire
import ObjectMapper

Alamofire的请求方式

  1. 获取服务器资源: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对返回的数据进行解析,需在podfile文件中导入ObjectMapper

 pod 'ObjectMapper'

model的映射如下:

//儿童信息Model
class ChildInforModel: Mappable {
    var bindId = ""//绑定id
    var fatherName = ""
    var fatherPhone = ""
    required init?(map: Map) {
    }
    func mapping(map: Map) {
        bindId <- map["a"]
        fatherName <- map["b"]
        fatherPhone <- map["c"]
 }
}

有没有很方便?
2 . 提交资源到服务器:(请求参数为字典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 . 提交资源到服务器:(请求参数为字典转化为字符串,再经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)
}}

字典转字符串:

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
}

请求返回的字符串转字典数组

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
}

应用层数据处理:

    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" {
}

至此常见的几种网络请求完成!是不是很简单,喜欢的话点个赞吧!

相关文章

网友评论

    本文标题:swift网络请求之Alamofire

    本文链接:https://www.haomeiwen.com/subject/yrtdectx.html