How to Upload Multipart Data Using Alamofire.upload with HTTPS Request?












0















I have made it work with HTTP request, however still cannot find a way to make HTTPS request using alamofire/upload/multipartFormData. Anyone could help?



func UploadUserPhoto (Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){
let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
certificates: ServerTrustPolicy.certificates(),
validateCertificateChain: true,
validateHost: true
)
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"***********": serverTrustPolicy,
]
let sessionManager = SessionManager(
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
let parameters = ["Authorization": Token ?? "Does not contain authorization information"]
sessionManager.upload(multipartFormData: { multipartFormData in
if let imageData = Photo.jpegData(compressionQuality: 1) {
multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.append((value.data(using: .utf8))!, withName: key)
}}, to: "https://***********/uploaduserphoto/(Username)", method: .post, headers: parameters,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response(completionHandler: { (response) in
if response.response?.statusCode == 200{
completion(true)
} else {
completion(false)
}
})
case .failure(let encodingError):
print("error:(encodingError)")
completion(false)
}
})
}


Update:
I finally found the code is good, the certificate was bad. After re-create a self-signed certificate, i worked. Thanks



Error Indicate That:



2018-11-20 12:49:45.130697+0800 TalentBaby1.0[1359:288066] Task <09FA46A5-9791-42DB-97AD-78A351050916>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://*******/uploaduserphoto/User, NSErrorFailingURLKey=https://*******/uploaduserphoto/User, _NSURLErrorRelatedURLSessionTaskErrorKey=("LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>"), _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>, NSLocalizedDescription=cancelled} [-999]









share|improve this question





























    0















    I have made it work with HTTP request, however still cannot find a way to make HTTPS request using alamofire/upload/multipartFormData. Anyone could help?



    func UploadUserPhoto (Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){
    let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
    certificates: ServerTrustPolicy.certificates(),
    validateCertificateChain: true,
    validateHost: true
    )
    let serverTrustPolicies: [String: ServerTrustPolicy] = [
    "***********": serverTrustPolicy,
    ]
    let sessionManager = SessionManager(
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )
    let parameters = ["Authorization": Token ?? "Does not contain authorization information"]
    sessionManager.upload(multipartFormData: { multipartFormData in
    if let imageData = Photo.jpegData(compressionQuality: 1) {
    multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
    }
    for (key, value) in parameters {
    multipartFormData.append((value.data(using: .utf8))!, withName: key)
    }}, to: "https://***********/uploaduserphoto/(Username)", method: .post, headers: parameters,
    encodingCompletion: { encodingResult in
    switch encodingResult {
    case .success(let upload, _, _):
    upload.response(completionHandler: { (response) in
    if response.response?.statusCode == 200{
    completion(true)
    } else {
    completion(false)
    }
    })
    case .failure(let encodingError):
    print("error:(encodingError)")
    completion(false)
    }
    })
    }


    Update:
    I finally found the code is good, the certificate was bad. After re-create a self-signed certificate, i worked. Thanks



    Error Indicate That:



    2018-11-20 12:49:45.130697+0800 TalentBaby1.0[1359:288066] Task <09FA46A5-9791-42DB-97AD-78A351050916>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://*******/uploaduserphoto/User, NSErrorFailingURLKey=https://*******/uploaduserphoto/User, _NSURLErrorRelatedURLSessionTaskErrorKey=("LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>"), _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>, NSLocalizedDescription=cancelled} [-999]









    share|improve this question



























      0












      0








      0








      I have made it work with HTTP request, however still cannot find a way to make HTTPS request using alamofire/upload/multipartFormData. Anyone could help?



      func UploadUserPhoto (Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){
      let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
      certificates: ServerTrustPolicy.certificates(),
      validateCertificateChain: true,
      validateHost: true
      )
      let serverTrustPolicies: [String: ServerTrustPolicy] = [
      "***********": serverTrustPolicy,
      ]
      let sessionManager = SessionManager(
      serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
      )
      let parameters = ["Authorization": Token ?? "Does not contain authorization information"]
      sessionManager.upload(multipartFormData: { multipartFormData in
      if let imageData = Photo.jpegData(compressionQuality: 1) {
      multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
      }
      for (key, value) in parameters {
      multipartFormData.append((value.data(using: .utf8))!, withName: key)
      }}, to: "https://***********/uploaduserphoto/(Username)", method: .post, headers: parameters,
      encodingCompletion: { encodingResult in
      switch encodingResult {
      case .success(let upload, _, _):
      upload.response(completionHandler: { (response) in
      if response.response?.statusCode == 200{
      completion(true)
      } else {
      completion(false)
      }
      })
      case .failure(let encodingError):
      print("error:(encodingError)")
      completion(false)
      }
      })
      }


      Update:
      I finally found the code is good, the certificate was bad. After re-create a self-signed certificate, i worked. Thanks



      Error Indicate That:



      2018-11-20 12:49:45.130697+0800 TalentBaby1.0[1359:288066] Task <09FA46A5-9791-42DB-97AD-78A351050916>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://*******/uploaduserphoto/User, NSErrorFailingURLKey=https://*******/uploaduserphoto/User, _NSURLErrorRelatedURLSessionTaskErrorKey=("LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>"), _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>, NSLocalizedDescription=cancelled} [-999]









      share|improve this question
















      I have made it work with HTTP request, however still cannot find a way to make HTTPS request using alamofire/upload/multipartFormData. Anyone could help?



      func UploadUserPhoto (Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){
      let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
      certificates: ServerTrustPolicy.certificates(),
      validateCertificateChain: true,
      validateHost: true
      )
      let serverTrustPolicies: [String: ServerTrustPolicy] = [
      "***********": serverTrustPolicy,
      ]
      let sessionManager = SessionManager(
      serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
      )
      let parameters = ["Authorization": Token ?? "Does not contain authorization information"]
      sessionManager.upload(multipartFormData: { multipartFormData in
      if let imageData = Photo.jpegData(compressionQuality: 1) {
      multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
      }
      for (key, value) in parameters {
      multipartFormData.append((value.data(using: .utf8))!, withName: key)
      }}, to: "https://***********/uploaduserphoto/(Username)", method: .post, headers: parameters,
      encodingCompletion: { encodingResult in
      switch encodingResult {
      case .success(let upload, _, _):
      upload.response(completionHandler: { (response) in
      if response.response?.statusCode == 200{
      completion(true)
      } else {
      completion(false)
      }
      })
      case .failure(let encodingError):
      print("error:(encodingError)")
      completion(false)
      }
      })
      }


      Update:
      I finally found the code is good, the certificate was bad. After re-create a self-signed certificate, i worked. Thanks



      Error Indicate That:



      2018-11-20 12:49:45.130697+0800 TalentBaby1.0[1359:288066] Task <09FA46A5-9791-42DB-97AD-78A351050916>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://*******/uploaduserphoto/User, NSErrorFailingURLKey=https://*******/uploaduserphoto/User, _NSURLErrorRelatedURLSessionTaskErrorKey=("LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>"), _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>, NSLocalizedDescription=cancelled} [-999]






      swift https alamofire multipartform-data






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 9:48







      Gang

















      asked Nov 20 '18 at 3:40









      GangGang

      12




      12
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Since you are already using Alamofire, try and use their upload instead of the SessionManager upload. Try this :



          func UploadUserPhoto(Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){

          let headers = ["Authorization": Token ?? "Does not contain authorization information"]

          Alamofire.upload(multipartFormData:{ multipartFormData in
          if let imageData = Photo.jpegData(compressionQuality: 1) {
          multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
          }
          },
          usingThreshold:UInt64.init(),
          to:"https://***********/uploaduserphoto/(Username)",
          method:.post,
          headers:headers,
          encodingCompletion: { encodingResult in
          switch encodingResult {
          case .success(let upload, _, _):
          upload.response(completionHandler: { (response) in
          if response.response?.statusCode == 200{
          completion(true)
          } else {
          completion(false)
          }
          })
          case .failure(let encodingError):
          print("error:(encodingError)")
          completion(false)
          }
          })
          }





          share|improve this answer
























          • Thanks The code is fine, but certificate errors

            – Gang
            Nov 21 '18 at 9:48











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53385885%2fhow-to-upload-multipart-data-using-alamofire-upload-with-https-request%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Since you are already using Alamofire, try and use their upload instead of the SessionManager upload. Try this :



          func UploadUserPhoto(Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){

          let headers = ["Authorization": Token ?? "Does not contain authorization information"]

          Alamofire.upload(multipartFormData:{ multipartFormData in
          if let imageData = Photo.jpegData(compressionQuality: 1) {
          multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
          }
          },
          usingThreshold:UInt64.init(),
          to:"https://***********/uploaduserphoto/(Username)",
          method:.post,
          headers:headers,
          encodingCompletion: { encodingResult in
          switch encodingResult {
          case .success(let upload, _, _):
          upload.response(completionHandler: { (response) in
          if response.response?.statusCode == 200{
          completion(true)
          } else {
          completion(false)
          }
          })
          case .failure(let encodingError):
          print("error:(encodingError)")
          completion(false)
          }
          })
          }





          share|improve this answer
























          • Thanks The code is fine, but certificate errors

            – Gang
            Nov 21 '18 at 9:48
















          0














          Since you are already using Alamofire, try and use their upload instead of the SessionManager upload. Try this :



          func UploadUserPhoto(Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){

          let headers = ["Authorization": Token ?? "Does not contain authorization information"]

          Alamofire.upload(multipartFormData:{ multipartFormData in
          if let imageData = Photo.jpegData(compressionQuality: 1) {
          multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
          }
          },
          usingThreshold:UInt64.init(),
          to:"https://***********/uploaduserphoto/(Username)",
          method:.post,
          headers:headers,
          encodingCompletion: { encodingResult in
          switch encodingResult {
          case .success(let upload, _, _):
          upload.response(completionHandler: { (response) in
          if response.response?.statusCode == 200{
          completion(true)
          } else {
          completion(false)
          }
          })
          case .failure(let encodingError):
          print("error:(encodingError)")
          completion(false)
          }
          })
          }





          share|improve this answer
























          • Thanks The code is fine, but certificate errors

            – Gang
            Nov 21 '18 at 9:48














          0












          0








          0







          Since you are already using Alamofire, try and use their upload instead of the SessionManager upload. Try this :



          func UploadUserPhoto(Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){

          let headers = ["Authorization": Token ?? "Does not contain authorization information"]

          Alamofire.upload(multipartFormData:{ multipartFormData in
          if let imageData = Photo.jpegData(compressionQuality: 1) {
          multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
          }
          },
          usingThreshold:UInt64.init(),
          to:"https://***********/uploaduserphoto/(Username)",
          method:.post,
          headers:headers,
          encodingCompletion: { encodingResult in
          switch encodingResult {
          case .success(let upload, _, _):
          upload.response(completionHandler: { (response) in
          if response.response?.statusCode == 200{
          completion(true)
          } else {
          completion(false)
          }
          })
          case .failure(let encodingError):
          print("error:(encodingError)")
          completion(false)
          }
          })
          }





          share|improve this answer













          Since you are already using Alamofire, try and use their upload instead of the SessionManager upload. Try this :



          func UploadUserPhoto(Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){

          let headers = ["Authorization": Token ?? "Does not contain authorization information"]

          Alamofire.upload(multipartFormData:{ multipartFormData in
          if let imageData = Photo.jpegData(compressionQuality: 1) {
          multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
          }
          },
          usingThreshold:UInt64.init(),
          to:"https://***********/uploaduserphoto/(Username)",
          method:.post,
          headers:headers,
          encodingCompletion: { encodingResult in
          switch encodingResult {
          case .success(let upload, _, _):
          upload.response(completionHandler: { (response) in
          if response.response?.statusCode == 200{
          completion(true)
          } else {
          completion(false)
          }
          })
          case .failure(let encodingError):
          print("error:(encodingError)")
          completion(false)
          }
          })
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 '18 at 15:07









          Arie PintoArie Pinto

          8451715




          8451715













          • Thanks The code is fine, but certificate errors

            – Gang
            Nov 21 '18 at 9:48



















          • Thanks The code is fine, but certificate errors

            – Gang
            Nov 21 '18 at 9:48

















          Thanks The code is fine, but certificate errors

          – Gang
          Nov 21 '18 at 9:48





          Thanks The code is fine, but certificate errors

          – Gang
          Nov 21 '18 at 9:48


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53385885%2fhow-to-upload-multipart-data-using-alamofire-upload-with-https-request%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to change which sound is reproduced for terminal bell?

          Can I use Tabulator js library in my java Spring + Thymeleaf project?

          Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents