如何使用Alamofire上传带有身份验证的MultipartFormData

编程入门 行业动态 更新时间:2024-10-26 06:33:16
本文介绍了如何使用Alamofire上传带有身份验证的MultipartFormData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使用Alamofire上传 MultipartFormData 并进行身份验证?我不明白的部分是放在哪里 .authenticate(用户名:用户名,密码:密码)。?我通常使用 MultipartFormData 上传图片:

How to upload MultipartFormData with authentication using Alamofire? The part that I don't understand is where to put .authenticate(user: username, password: password).? This is how I usually upload pictures using MultipartFormData:

Alamofire.upload( .POST, "myExampleUrl/photo/upload", headers: headers, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: "default".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"_formname") multipartFormData.appendBodyPart(fileURL: fileUrl, name: "photo") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseString { response in debugPrint(response) } case .Failure(let encodingError): print(encodingError) } } )

我认为可以添加身份验证过程进入标题?

I think it's possible to add authentication process into headers?

推荐答案

没有太多时间来探索 rilbits的API 。当我访问Safari中的地址时,我收到以下错误:

Haven't had much time to explore the API for rilbits. When I visited the address in Safari, I got the following error:

Please add 'Authorization' or 'X-Access-Token' header to your request

这表明有两种选择:

  • 首先登录并获取访问令牌,然后您可以使用上传请求
  • 发送基本授权标题以及上传请求。
  • Login first and get back an access token, which you can then use the for the upload request
  • Send a basic Authorization header along with the upload request.
  • 以下是发送授权标题(第二个选项):

    Here's how you can send the Authorization header (second option):

    let username = "username" let password = "password" let credentialData = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)! let base64Credentials = credentialData.base64EncodedStringWithOptions([]) let headers = ["Authorization": base64Credentials] Alamofire.upload( .POST, "rilbits/supersafe/photo/upload", headers: headers, multipartFormData: { multipartFormData in let data = "default".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! multipartFormData.appendBodyPart(data: data, name: "_formname") multipartFormData.appendBodyPart(fileURL: fileURL, name: "photo") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseString { response in debugPrint(response) } case .Failure(let encodingError): print(encodingError) } } )

    完整披露:

    • 授权代码取自Alamofire的 readme
    • 我没有测试上面的代码

    更多推荐

    如何使用Alamofire上传带有身份验证的MultipartFormData

    本文发布于:2023-11-26 03:34:47,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1632472.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:如何使用   身份验证   上传   MultipartFormData   Alamofire

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!