-1

I was trying to use flask as a backend for my iOs application. Currently it seems to be working, and the backend is hosted on heroku. The flask backend looks a little like this:

@app.route('/get_token', methods=['POST'])
def create_token():
    token = make_token()
    return token

I can run this function and confirm that it runs using a snippet like this with swift (using alamofire):

let url = "https://my-backend.herokuapp.com/get_token"
Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default)

And that runs fine. But now I want to do something (specifically save the token from flask) with the return value from flask. But I am confused as to how to do this. Any suggestions?

Brian L
  • 549
  • 7
  • 21

1 Answers1

1

I would return a JSON response from Flask, and then you can easily parse that JSON object however you choose in your iOS app. Flask has a built in method, jsonify, which makes it easy to create a JSON responses.

You response would look like return jsonify(token=token)

Parse JSON with Alamofire:

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
            .responseJSON { response in
                print(response)
            //to get status code
            if let status = response.response?.statusCode {
                switch(status){
                    case 201:
                        print("example success")
                    default:
                        print("error with response status: \(status)")
                }
            }
            //to get JSON return value
            if let result = response.result.value {
                let JSON = result as! NSDictionary
                print(JSON)
            }

        }

Source: https://stackoverflow.com/a/33022923/6685140

Sam Hollenbach
  • 652
  • 4
  • 19
  • Yes, I understand you can return a JSON object. But I do not know how to access the result. My confusion is with getting the token in the iOs app. Can you add a snippet that shows how to access the result of the alamofire request in swift? – Brian L Jan 06 '19 at 00:12
  • Edited with more info – Sam Hollenbach Jan 06 '19 at 01:09