源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Swift网络请求库Alamofire使用详解

  • 时间:2020-08-15 10:37 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Swift网络请求库Alamofire使用详解
[b]前言[/b] Alamofire是一个使用Swift开发的网络请求库,其开发团队是AFNetworking的原团队。它语法简洁,采用链式编程的思想,使用起来是相当的舒服。本质是基于NSURLSession进行封装。接下开我们就进入实战,开始学习Alamofire的使用。 [b]GET请求[/b] [b]常用的get请求示例以及请求结果[/b]
 Alamofire.request("https://httpbin.org/get", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
  if(response.error == nil){
  LLog("请求成功")
  LLog(response.result.value)
  }else{
  LLog("请求失败\(String(describing: response.error))")
  }

 }

[img]http://files.jb51.net/file_images/article/201708/2017082909340436.jpg[/img] [b]Get请求、有参数、使用Basic Auth授权访问(例如:jira)[/b]
var header:HTTPHeaders = [:]
 if let authorizationHeader = Request.authorizationHeader(user: "xxxx", password: "xxxxxx") {
  header[authorizationHeader.key] = authorizationHeader.value
 }
 // 此处的 URLEncoding.default (URLEncoding.queryString )会将parameters 拼接到url后面
 Alamofire.request("https://httpbin.org/get", method: HTTPMethod.get, parameters: ["key":"value"], encoding: URLEncoding.default, headers: header).responseJSON { (response) in
  if(response.error == nil){
  LLog("请求成功")
  LLog(response.result.value)
  }else{
  LLog("请求失败\(String(describing: response.error))")
  }

 }

[img]http://files.jb51.net/file_images/article/201708/2017082909340437.jpg[/img] [b]POST请求[/b][b]常用的post请求[/b]
Alamofire.request("https://httpbin.org/post", method: .post, parameters: ["key1":"value1","key2":"value2"], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in

   if(response.error == nil){
    LLog("请求成功")
    LLog(response.result.value)
   }else{
    LLog("请求失败\(String(describing: response.error))")
   }

  }

[img]http://files.jb51.net/file_images/article/201708/2017082909340438.jpg[/img] [b]post请求,提交json格式的数据[/b]
// JSONEncoding.default === JSONEncoding.prettyPrinted
 Alamofire.request("https://httpbin.org/post", method: .post, parameters: ["key1":"value1","key2":"value2"], encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in

   if(response.error == nil){
    LLog("请求成功")
    LLog(response.result.value)
   }else{
    LLog("请求失败\(String(describing: response.error))")
   }

  }

[img]http://files.jb51.net/file_images/article/201708/2017082909340439.jpg[/img] [b]PUT、Delete 请求 参照POST(使用区别不大)[/b] [b]UPLOAD(上传文件)[/b] [b]上传文件示例[/b]
 let data:Data = UIImageJPEGRepresentation(#imageLiteral(resourceName: "beauty.jpeg"), 0.2)!
  let url = Bundle.main.url(forResource: "beauty", withExtension: "jpeg");
  // 多文件上传
  Alamofire.upload(multipartFormData: { (formdata) in

   formdata.append(data, withName: "file", fileName: "beauty.jpeg", mimeType: "image/jpeg") 
   formdata.append(url!, withName: "file2")

  }, to: UPLOAD_URL) { (encodingResult) in

   switch encodingResult{
   case .success(let uploadFile, _, _):
    //上传进度回调
    uploadFile.uploadProgress(closure: { (progress) in
     debugPrint("上传进度\(progress)")
    })
    //上传结果回调
    uploadFile.responseString(completionHandler: { (response) in
     LLog(response.result.value)
    })

    break
   case .failure( let error):
    LLog(error);
    break
   }

  }

[img]http://files.jb51.net/file_images/article/201708/201782994911869.jpg?201772994954[/img] 备注: 想必大家也注意到上面的上传图片的代码,在append data的时候多了一个 filename的参数,在测试的时候,我发现这个参数是必须的,如果你传入的是data数据,但是如果你使用的是fileurl则可以不用这个参数,在alamofire中 会自己获取文件的名。 [img]http://files.jb51.net/file_images/article/201708/2017082909340541.jpg[/img] [img]http://files.jb51.net/file_images/article/201708/2017082909340642.jpg[/img] [b]如果我们在append data的时候,不传入文件名,在上面的代码中 headers中则不会有 filename这个参数,此时使用charles抓包是会发现如下。[/b] [img]http://files.jb51.net/file_images/article/201708/201782995004229.jpg?201772995013[/img] [b]上传文件并携带参数[/b]
var param: [String:String] = [:];
  param["postion"] = "portrait"
  let url = Bundle.main.url(forResource: "beauty", withExtension: "jpeg");
  // 2、多文件上传
  Alamofire.upload(multipartFormData: { (formdata) in
   formdata.append(url!, withName: "file2")

   //拼接参数
   for (key, value) in param {
    formdata.append(value.data(using: String.Encoding.utf8)!, withName: key)
   }

  }, to: UPLOAD_URL) { (encodingResult) in

   switch encodingResult{
   case .success(let uploadFile, _, _):
    //上传进度回调
    uploadFile.uploadProgress(closure: { (progress) in
     debugPrint("上传进度\(progress)")
    })
    //上传结果回调
    uploadFile.responseJSON(completionHandler: { (response) in
     LLog(response.result.value)
    })

    break
   case .failure( let error):
    LLog(error);
    break
   }



  }
[img]http://files.jb51.net/file_images/article/201708/201782995023947.jpg?201772995032[/img]   备注:在我们的实际开发中,后台有时候并没有配置专门的文件服务器,这个时候我们往往就需要在上传文件的时候,配置必要的参数,来表明我们上传文件资源的目的。 [b]最后[/b] Alamofire真的是一个很好用的网络请求库,同学们,赶紧开始使用吧!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部