Search code examples
xcodeswifthttpwebrequestalamofire

swift web request not submitting (using alamofire)


I'm speculating that my request is incomplete...I can't figure out what piece I'm missing. When I run this, nothing submits, it just hangs forever...please help!

import Foundation
import Alamofire
import SwiftyJSON

class getToken: UIViewController {


let headers = [
"Content-Type": "application/json",
"Accept": "application/json"]

func fetchToken(contentID: String, completion: ([String]) -> Void) {
Alamofire.request(
    .GET,
    "https://secure3.saashr.com:443/ta/rest/v1/login?company=slszdr&username=abc&password=123",
    headers: headers).validate().responseJSON { response in
        switch response.result {
        case .Success(let data):
            let json = JSON(data)
            let name = json["name"].stringValue
            print(name)
        case .Failure(let error):
            print("request failed with error: \(error)")
        }
}}}

and this is the call from my view controller:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    getToken()
}}

Solution

  • In your View controller class, I see this code:

    override func viewDidLoad() {
    super.viewDidLoad()
    getToken()
    }
    

    This seems wrong. Because you are creating an instance of getToken "class", And you never really called you method fetchtoken() I think you must change this to something like:

    override func viewDidLoad() {
        super.viewDidLoad()
        let instanceOfGetTokenClass = getToken()
        instanceOfGetTokenClass.fetchToken(// send parameters here)
    }
    

    Maybe you got confused with class name "getToken" and method name "fetchToken" :)