0

I'm using API and getting json data with SwiftyJSON. I need an add token for the API. How can I do this with SwiftyJson?

My code :

let jsonData = (NSData(contentsOfURL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)! as NSData)

    var readableJSON = JSON(data: jsonData, options: .MutableContainers, error: nil)

    let name = readableJSON["standings"]

Normally I'm adding token with this code when I use Swift's JSON :

    let url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
    url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
    url.HTTPMethod = "GET"
jorjj
  • 910
  • 2
  • 15
  • 29

1 Answers1

0

Are you making a post/put with this data? Thats would make sense. I suppose you already have made the request to get the readable data "jsonData" contains that. Since you ndicate you dont have the json data already this would probably work.

var url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
    if error == nil {
        var readableJSON = JSON(data: data, options: .MutableContainers, error: nil)
        let name = readableJSON["standings"]
        url.HTTPBody = try! name.rawData()
        NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
           //do something with his response from getting the data
        })
    } else {
        print(error)
    }
})

This is kind of a hacky way of doing it but I think its what you are going for

Greg Price
  • 2,516
  • 1
  • 21
  • 31
  • No, I'll make get data. Is this works for GET? Sorry I'm not on the macbook right now. – jorjj Jun 23 '16 at 06:18
  • technically yes, although im not sure how ios handles this sort of thing: http://stackoverflow.com/questions/978061/http-get-with-request-body – Greg Price Jun 23 '16 at 16:00
  • Will `readbleJSON` get it with this way? url value is not implementing in `jsonData`. Is that a problem or url is the same and he will get the token because the same url implement? Btw API is working, but It's necessary for live apps. Also this code is working. – jorjj Jun 23 '16 at 16:39