IOS - Swift 4.0 - Basic access authentication with Alamofire -











up vote
2
down vote

favorite












I'm doing an app in Swift 4 i when I get to the point where I need to make a POST call, like "Basic access authentication" with a header and a body with parameters, it does not work for me.



Basically I want to simulate this call, to return a 200, but it's giving me back:




"responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.})) "




The API url is:



https://gist.github.com/juaniiton1/3a3e422ed99de22f3f3686bb3b7788d7



and the section is "Store a new trade in the authed user portfolio".



Here I pass the code that simulates the request "Store a new trade in the authoved user portfolio" with the help of Alamofire (4.7.3).



The steps I follow are the following:




  • What I do is, code the data of "username" and "password" that you
    give me in base64.


  • Then I format the date of type Stirng to type Date (type ISO).


  • After I created a dictionary for the data


  • And finally I created the request, putting together all of the above.


  • In addition in the Xcode I have the TransportSecurity to make the
    request "https"



Here I leave the code:



import Foundation
import UIKit
import Alamofire



class ViewController: UIViewController {



override func viewDidLoad() {
super.viewDidLoad()

//URL
let url = URL(string: "https://test.cryptojet.io/coins/portfolio")!

// credentials encoded in base64
let username = "richard@rich.com"
let password = "secret"
let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()
let headers = ["Authorization" : "Basic (base64LoginData)",
"Content-Type": "application/json"]

//Prepare date - Data UTC to ISO
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let dataSting = "2016-06-05T16:56:57.019+01:00"
let dateISO = dateFormatter.date(from: dataSting)

//Prepare paramsBody -> tot Data
let paramsBody: [String: Any] = ["coin_id": 2,
"amount": -2.2183,
"price_usd": 675.982,
"traded_at": dateISO!]

//Request
Alamofire.request(url, method: .post,parameters: paramsBody, encoding: URLEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
guard let json = response.result.value as? [String: Any],
let data = json["trade"] as? [String: Any] else {
return
}
print(data)
case .failure(let error):
print(error)
}
}

}


Could you tell me what I'm doing wrong with this POST authentication call with the server?










share|improve this question






















  • Are you trying to use digest protocol? if this is the issue you need to use alamo in a different way
    – ironRoei
    Nov 19 at 16:03

















up vote
2
down vote

favorite












I'm doing an app in Swift 4 i when I get to the point where I need to make a POST call, like "Basic access authentication" with a header and a body with parameters, it does not work for me.



Basically I want to simulate this call, to return a 200, but it's giving me back:




"responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.})) "




The API url is:



https://gist.github.com/juaniiton1/3a3e422ed99de22f3f3686bb3b7788d7



and the section is "Store a new trade in the authed user portfolio".



Here I pass the code that simulates the request "Store a new trade in the authoved user portfolio" with the help of Alamofire (4.7.3).



The steps I follow are the following:




  • What I do is, code the data of "username" and "password" that you
    give me in base64.


  • Then I format the date of type Stirng to type Date (type ISO).


  • After I created a dictionary for the data


  • And finally I created the request, putting together all of the above.


  • In addition in the Xcode I have the TransportSecurity to make the
    request "https"



Here I leave the code:



import Foundation
import UIKit
import Alamofire



class ViewController: UIViewController {



override func viewDidLoad() {
super.viewDidLoad()

//URL
let url = URL(string: "https://test.cryptojet.io/coins/portfolio")!

// credentials encoded in base64
let username = "richard@rich.com"
let password = "secret"
let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()
let headers = ["Authorization" : "Basic (base64LoginData)",
"Content-Type": "application/json"]

//Prepare date - Data UTC to ISO
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let dataSting = "2016-06-05T16:56:57.019+01:00"
let dateISO = dateFormatter.date(from: dataSting)

//Prepare paramsBody -> tot Data
let paramsBody: [String: Any] = ["coin_id": 2,
"amount": -2.2183,
"price_usd": 675.982,
"traded_at": dateISO!]

//Request
Alamofire.request(url, method: .post,parameters: paramsBody, encoding: URLEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
guard let json = response.result.value as? [String: Any],
let data = json["trade"] as? [String: Any] else {
return
}
print(data)
case .failure(let error):
print(error)
}
}

}


Could you tell me what I'm doing wrong with this POST authentication call with the server?










share|improve this question






















  • Are you trying to use digest protocol? if this is the issue you need to use alamo in a different way
    – ironRoei
    Nov 19 at 16:03















up vote
2
down vote

favorite









up vote
2
down vote

favorite











I'm doing an app in Swift 4 i when I get to the point where I need to make a POST call, like "Basic access authentication" with a header and a body with parameters, it does not work for me.



Basically I want to simulate this call, to return a 200, but it's giving me back:




"responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.})) "




The API url is:



https://gist.github.com/juaniiton1/3a3e422ed99de22f3f3686bb3b7788d7



and the section is "Store a new trade in the authed user portfolio".



Here I pass the code that simulates the request "Store a new trade in the authoved user portfolio" with the help of Alamofire (4.7.3).



The steps I follow are the following:




  • What I do is, code the data of "username" and "password" that you
    give me in base64.


  • Then I format the date of type Stirng to type Date (type ISO).


  • After I created a dictionary for the data


  • And finally I created the request, putting together all of the above.


  • In addition in the Xcode I have the TransportSecurity to make the
    request "https"



Here I leave the code:



import Foundation
import UIKit
import Alamofire



class ViewController: UIViewController {



override func viewDidLoad() {
super.viewDidLoad()

//URL
let url = URL(string: "https://test.cryptojet.io/coins/portfolio")!

// credentials encoded in base64
let username = "richard@rich.com"
let password = "secret"
let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()
let headers = ["Authorization" : "Basic (base64LoginData)",
"Content-Type": "application/json"]

//Prepare date - Data UTC to ISO
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let dataSting = "2016-06-05T16:56:57.019+01:00"
let dateISO = dateFormatter.date(from: dataSting)

//Prepare paramsBody -> tot Data
let paramsBody: [String: Any] = ["coin_id": 2,
"amount": -2.2183,
"price_usd": 675.982,
"traded_at": dateISO!]

//Request
Alamofire.request(url, method: .post,parameters: paramsBody, encoding: URLEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
guard let json = response.result.value as? [String: Any],
let data = json["trade"] as? [String: Any] else {
return
}
print(data)
case .failure(let error):
print(error)
}
}

}


Could you tell me what I'm doing wrong with this POST authentication call with the server?










share|improve this question













I'm doing an app in Swift 4 i when I get to the point where I need to make a POST call, like "Basic access authentication" with a header and a body with parameters, it does not work for me.



Basically I want to simulate this call, to return a 200, but it's giving me back:




"responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.})) "




The API url is:



https://gist.github.com/juaniiton1/3a3e422ed99de22f3f3686bb3b7788d7



and the section is "Store a new trade in the authed user portfolio".



Here I pass the code that simulates the request "Store a new trade in the authoved user portfolio" with the help of Alamofire (4.7.3).



The steps I follow are the following:




  • What I do is, code the data of "username" and "password" that you
    give me in base64.


  • Then I format the date of type Stirng to type Date (type ISO).


  • After I created a dictionary for the data


  • And finally I created the request, putting together all of the above.


  • In addition in the Xcode I have the TransportSecurity to make the
    request "https"



Here I leave the code:



import Foundation
import UIKit
import Alamofire



class ViewController: UIViewController {



override func viewDidLoad() {
super.viewDidLoad()

//URL
let url = URL(string: "https://test.cryptojet.io/coins/portfolio")!

// credentials encoded in base64
let username = "richard@rich.com"
let password = "secret"
let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()
let headers = ["Authorization" : "Basic (base64LoginData)",
"Content-Type": "application/json"]

//Prepare date - Data UTC to ISO
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let dataSting = "2016-06-05T16:56:57.019+01:00"
let dateISO = dateFormatter.date(from: dataSting)

//Prepare paramsBody -> tot Data
let paramsBody: [String: Any] = ["coin_id": 2,
"amount": -2.2183,
"price_usd": 675.982,
"traded_at": dateISO!]

//Request
Alamofire.request(url, method: .post,parameters: paramsBody, encoding: URLEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
guard let json = response.result.value as? [String: Any],
let data = json["trade"] as? [String: Any] else {
return
}
print(data)
case .failure(let error):
print(error)
}
}

}


Could you tell me what I'm doing wrong with this POST authentication call with the server?







ios swift post alamofire basic-authentication






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Aug 24 at 8:33









Jordi Gallen

255




255












  • Are you trying to use digest protocol? if this is the issue you need to use alamo in a different way
    – ironRoei
    Nov 19 at 16:03




















  • Are you trying to use digest protocol? if this is the issue you need to use alamo in a different way
    – ironRoei
    Nov 19 at 16:03


















Are you trying to use digest protocol? if this is the issue you need to use alamo in a different way
– ironRoei
Nov 19 at 16:03






Are you trying to use digest protocol? if this is the issue you need to use alamo in a different way
– ironRoei
Nov 19 at 16:03














2 Answers
2






active

oldest

votes

















up vote
0
down vote













I tried to make request to your url and seems response from your request is not JSON:



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="robots" content="noindex,nofollow" />
<style> body { background-color: #F9F9F9; color: #222; font: 14px/1.4 Helvetica, Arial, sans-serif; margin: 0; padding-bottom: 45px; }

a { cursor: pointer; text-decoration: none; }
a:hover { text-decoration: underline; }
...





share|improve this answer





















  • Yeah, it seems that the API does not work with POST type, with the GET type it does return JSON response.
    – Martin Prusa
    Aug 24 at 9:04










  • Yes, the API does work in POST. I know because the one who gave me the test says: "I see where the error is but you will understand that if I tell you the solution, the test would be grace since it is a problem of the code and not of the backend. .. "
    – Jordi Gallen
    Aug 24 at 9:37


















up vote
0
down vote













If you are trying digest you will need this method :



    credential = URLCredential(user: UserDefaults.standard.string(forKey: "userName") ?? "admin", password: UserDefaults.standard.string(forKey: "password") ?? "admin", persistence: .none)

let sessionMananager = Alamofire.SessionManager.default
_ = sessionMananager.request(url)
.authenticate(usingCredential: credential!)
.responseJSON { response in
}





share|improve this answer





















    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',
    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%2f52000469%2fios-swift-4-0-basic-access-authentication-with-alamofire%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    I tried to make request to your url and seems response from your request is not JSON:



    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <meta name="robots" content="noindex,nofollow" />
    <style> body { background-color: #F9F9F9; color: #222; font: 14px/1.4 Helvetica, Arial, sans-serif; margin: 0; padding-bottom: 45px; }

    a { cursor: pointer; text-decoration: none; }
    a:hover { text-decoration: underline; }
    ...





    share|improve this answer





















    • Yeah, it seems that the API does not work with POST type, with the GET type it does return JSON response.
      – Martin Prusa
      Aug 24 at 9:04










    • Yes, the API does work in POST. I know because the one who gave me the test says: "I see where the error is but you will understand that if I tell you the solution, the test would be grace since it is a problem of the code and not of the backend. .. "
      – Jordi Gallen
      Aug 24 at 9:37















    up vote
    0
    down vote













    I tried to make request to your url and seems response from your request is not JSON:



    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <meta name="robots" content="noindex,nofollow" />
    <style> body { background-color: #F9F9F9; color: #222; font: 14px/1.4 Helvetica, Arial, sans-serif; margin: 0; padding-bottom: 45px; }

    a { cursor: pointer; text-decoration: none; }
    a:hover { text-decoration: underline; }
    ...





    share|improve this answer





















    • Yeah, it seems that the API does not work with POST type, with the GET type it does return JSON response.
      – Martin Prusa
      Aug 24 at 9:04










    • Yes, the API does work in POST. I know because the one who gave me the test says: "I see where the error is but you will understand that if I tell you the solution, the test would be grace since it is a problem of the code and not of the backend. .. "
      – Jordi Gallen
      Aug 24 at 9:37













    up vote
    0
    down vote










    up vote
    0
    down vote









    I tried to make request to your url and seems response from your request is not JSON:



    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <meta name="robots" content="noindex,nofollow" />
    <style> body { background-color: #F9F9F9; color: #222; font: 14px/1.4 Helvetica, Arial, sans-serif; margin: 0; padding-bottom: 45px; }

    a { cursor: pointer; text-decoration: none; }
    a:hover { text-decoration: underline; }
    ...





    share|improve this answer












    I tried to make request to your url and seems response from your request is not JSON:



    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <meta name="robots" content="noindex,nofollow" />
    <style> body { background-color: #F9F9F9; color: #222; font: 14px/1.4 Helvetica, Arial, sans-serif; margin: 0; padding-bottom: 45px; }

    a { cursor: pointer; text-decoration: none; }
    a:hover { text-decoration: underline; }
    ...






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Aug 24 at 8:47









    Vitaliy Gozhenko

    6,19423053




    6,19423053












    • Yeah, it seems that the API does not work with POST type, with the GET type it does return JSON response.
      – Martin Prusa
      Aug 24 at 9:04










    • Yes, the API does work in POST. I know because the one who gave me the test says: "I see where the error is but you will understand that if I tell you the solution, the test would be grace since it is a problem of the code and not of the backend. .. "
      – Jordi Gallen
      Aug 24 at 9:37


















    • Yeah, it seems that the API does not work with POST type, with the GET type it does return JSON response.
      – Martin Prusa
      Aug 24 at 9:04










    • Yes, the API does work in POST. I know because the one who gave me the test says: "I see where the error is but you will understand that if I tell you the solution, the test would be grace since it is a problem of the code and not of the backend. .. "
      – Jordi Gallen
      Aug 24 at 9:37
















    Yeah, it seems that the API does not work with POST type, with the GET type it does return JSON response.
    – Martin Prusa
    Aug 24 at 9:04




    Yeah, it seems that the API does not work with POST type, with the GET type it does return JSON response.
    – Martin Prusa
    Aug 24 at 9:04












    Yes, the API does work in POST. I know because the one who gave me the test says: "I see where the error is but you will understand that if I tell you the solution, the test would be grace since it is a problem of the code and not of the backend. .. "
    – Jordi Gallen
    Aug 24 at 9:37




    Yes, the API does work in POST. I know because the one who gave me the test says: "I see where the error is but you will understand that if I tell you the solution, the test would be grace since it is a problem of the code and not of the backend. .. "
    – Jordi Gallen
    Aug 24 at 9:37












    up vote
    0
    down vote













    If you are trying digest you will need this method :



        credential = URLCredential(user: UserDefaults.standard.string(forKey: "userName") ?? "admin", password: UserDefaults.standard.string(forKey: "password") ?? "admin", persistence: .none)

    let sessionMananager = Alamofire.SessionManager.default
    _ = sessionMananager.request(url)
    .authenticate(usingCredential: credential!)
    .responseJSON { response in
    }





    share|improve this answer

























      up vote
      0
      down vote













      If you are trying digest you will need this method :



          credential = URLCredential(user: UserDefaults.standard.string(forKey: "userName") ?? "admin", password: UserDefaults.standard.string(forKey: "password") ?? "admin", persistence: .none)

      let sessionMananager = Alamofire.SessionManager.default
      _ = sessionMananager.request(url)
      .authenticate(usingCredential: credential!)
      .responseJSON { response in
      }





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        If you are trying digest you will need this method :



            credential = URLCredential(user: UserDefaults.standard.string(forKey: "userName") ?? "admin", password: UserDefaults.standard.string(forKey: "password") ?? "admin", persistence: .none)

        let sessionMananager = Alamofire.SessionManager.default
        _ = sessionMananager.request(url)
        .authenticate(usingCredential: credential!)
        .responseJSON { response in
        }





        share|improve this answer












        If you are trying digest you will need this method :



            credential = URLCredential(user: UserDefaults.standard.string(forKey: "userName") ?? "admin", password: UserDefaults.standard.string(forKey: "password") ?? "admin", persistence: .none)

        let sessionMananager = Alamofire.SessionManager.default
        _ = sessionMananager.request(url)
        .authenticate(usingCredential: credential!)
        .responseJSON { response in
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 at 16:15









        ironRoei

        17611




        17611






























            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.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • 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%2f52000469%2fios-swift-4-0-basic-access-authentication-with-alamofire%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

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Costa Masnaga