2

I have been searching for 2 days now (I linked the threads I used below) and so far nothing has worked. My code is as below for Serializing the data that the api sends back and trying to save it in User Defaults using Swift 4.

do{
                let token = try JSONSerialization.jsonObject(with: data!, options: [])
                print(token)
                UserDefaults.standard.set(token, forKey: "savedToken")


            }catch{
                if httpResponse.statusCode == 401{
                      Helper.showAlert(viewController: self, title: "Oops", message: "Username or Password Incorrect")
                }
                print(error)
            }
        } else if let error = error {
            Helper.showAlert(viewController: self, title: "Well Damn", message: "Ay chief we have no idea what just happened but it didn't work")
            print(error)
        }

When I try to retrieve the data that I thought was stored in the key "savedToken",

let tokenData = UserDefaults.standard.object(forKey: "savedToken")

I have it print tokenData into the console and it says nil. I tried the method in this thread and it still says that it is nil. I did have to remove the "if" command from the answer so I can use the value. This is the code I'm using that requires the saved token;

        let tokenData = UserDefaults.standard.object(forKey: "savedToken")
    let areaHeaders = [
        "Authorization": "token \(tokenData)", // <-- this is where I need the token.
        "Content-Type": "application/x-www-form-urlencoded",
        "anonym": "true",
        "cache-control": "no-cache",
        "Postman-Token": "0017837d-5229-46a3-98ff-58fe3aa09df9"
    ]

    let areaData = NSMutableData(data: "undefined=undefined".data(using: String.Encoding.utf8)!)

    let areaRequest = NSMutableURLRequest(url: NSURL(string: "http://localhost:8000/areas/sample/")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
    areaRequest.httpMethod = "GET"
    areaRequest.allHTTPHeaderFields = areaHeaders
    areaRequest.httpBody = areaData as Data

    let areaSession = URLSession.shared
    let areaDataTask = areaSession.dataTask(with: areaRequest as URLRequest, completionHandler: { (data, response, error) -> Void in
        if let data = data {
            do{
                let postData = try JSONSerialization.jsonObject(with: data, options: [])
                print(postData)

            }catch{
                print(error)
            }

        } else {
            let httpResponse = response as? HTTPURLResponse
            print(httpResponse)

        }
    })
    areaDataTask.resume()

I am completely lost at this point. I've also tired this method too. All I'm trying to do is save the returned data that looks like this;printed json data in consol to a Users Defaults or something where I can easily retrieve it.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253

1 Answers1

2

I figured out how to do this and I thought I'd share how I pulled it off. I first started out by creating a struct for the token as such;

struct token: Decodable {
    let token: String!
}

I then Decoded and saved the token by doing this;

let JSONFromServer = try JSONSerialization.jsonObject(with: data, options: [])
let decoder = JSONDecoder()
                let tokenArray = try decoder.decode(token.self, from: data)
                print(tokenArray.token)
                UserDefaults.standard.set(tokenArray.token, forKey: "savedToken")

I then am able to pull the retrieve the token by using

let savedToken = UserDefaults.standard.object(forKey: "savedToken") 

And in order to use that object and remove the "optional" part that is contained in the let by doing this;

"Authorization": "token \(self.tokenData ?? "nope")",

The ?? removes the optional part of the data and just leaves the token itself.