网络请求第三方库AFNetworking使用 Swift

一、集成AFNetworking

用CocoaPods集成AFNetworking,打开终端按下列步骤输入命令

  1. 找到项目文件夹:

    cd 你的项目文件路径
  2. 如果没有Podfile文件,新建Podfile文件:

    touch Podfile
  3. 如果有Podfile文件,打开Podfile:

    open -e Podfile
  4. 在Podfile文件里写入AFNetworking库:

    pod 'AFNetworking', '~> 2.5.4'
  5. 安装第三方库:

    pod install
  6. 更新库:

     pod update

二、配置

在"项目名-Bridging-Header.h"文件中引入库包

#import <AFNetworking/AFNetworking.h>
#import "AFNetworking.h"

在全局文件里定义请求类

let httpRequest = AFHTTPRequestOperationManager()

三、使用

  1. get请求:url为请求地址的字符串格式,parameter传接口请求参数的json格式,data是接口返回数据集合
    httpRequest.get(url, parameters: nil, success: { (oper, data) in
                
    }) { (opeation, error) in
                
    }
  2. post请求
    httpRequest.post(url+"login/login2", parameters: ["loginAccount":zhanghao, "password":password], success: { (oper, data) -> Void in
        let dic = data as! Dictionary<String, Any>
        print(dic)
    }) { (opeation, error) -> Void in
        print(error)
    }
  3. 图片文件上传:withFileData参数为图片的Data格式,name、fileName、mimeType参数固定
    httpRequest.post(url+"oss/upload", parameters: nil, constructingBodyWith: { (formData) in formData?.appendPart(withFileData: choseImage.compressImageOnlength(maxLength: 2), name: "file", fileName: "image.png", mimeType: "image/png")}, success: { (task, responseObject) in
        print(responseObject ?? "")
        let dic = responseObject as! Dictionary<String, Any>
        print(dic)
    }, failure: { (task, error) in
        print("报错")
        self.showAwardInfo(info: "上传图片失败\(error ?? "" as! Error)")
    })

猜你喜欢

转载自blog.csdn.net/weixin_42012181/article/details/88414113
今日推荐