TwilioDevEd / twiliochat-swift

Swift implementation of Twilio Chat
https://www.twilio.com/docs/tutorials/walkthrough/ip-chat/ios/swift
MIT License
46 stars 18 forks source link

Getting a nil value while fetching Twilio access token #17

Closed itsaark closed 7 years ago

itsaark commented 7 years ago

I'm trying to setup Twilio Programmable Chat in my iOS app and when I try to fetch access token it's returning a Nil. I'm using the same function calls which are provided in the swift sample app.

This is the function which is trying to fetch access token which is present in a dictionary

func fetchToken(params:[String:String], completion:@escaping (NSDictionary, NSError?) -> Void) {

if let filePath = Bundle.main.path(forResource: "Keys", ofType:"plist"),
    let dictionary = NSDictionary(contentsOfFile:filePath) as? [String: AnyObject],
    let tokenRequestUrl = dictionary["TokenRequestUrl"] as? String {
    print(tokenRequestUrl)
    var request = URLRequest(url: URL(string: tokenRequestUrl)!)
    request.httpMethod = "POST"
    let postString = self.postDataFrom(params: params)
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            completion(NSDictionary(), NSError(domain: "TWILIO", code: 1000, userInfo: [NSLocalizedDescriptionKey: "Incorrect return code for token request."]))
            return
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
            print("json = \(json)")
            completion(json as NSDictionary, error as NSError?)
        } catch let error as NSError {
            completion(NSDictionary(), error)
        }
    }
    task.resume()
}
else {
    let userInfo = [NSLocalizedDescriptionKey : "TokenRequestUrl Key is missing"]
    let error = NSError(domain: "app", code: 404, userInfo: userInfo)

    completion(NSDictionary(), error)
}
}

The print json command is not getting executed, but when I tried printing Data before try it returns 2730 bytes. Hence a null is getting passed as dictionary and I'm eventually getting nil when I try to fetch access token