0

Hi my question is related to json object. i have this link "http://ip-api.com/json" and this link gives the details of your IP Address. i only need to print IP Address from this json file in swift 3. i am very new might be my question is basic but i need some help to sort out my project. so for i have done like below.

let requestURL: NSURL = NSURL(string: "http://ip-api.com/json")!

    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
    let session = URLSession.shared
    let task = session.dataTask(with: urlRequest as URLRequest) {
        (data, response, error) -> Void in

        let httpResponse = response as! HTTPURLResponse
        let statusCode = httpResponse.statusCode

        if (statusCode == 200) {
            print("Everyone is fine, file downloaded successfully.")

            do{

                let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]

                if let stations = json["city"] as? [[String: AnyObject]] {



                  for station in stations {

                      if let name = station["regionName"] as? String {

                        self.names.append(name)
                        print("this is query\(name)")

                      }
                      else{
                         print ("no ip address is found")
                    }

                  }

                }

            }
            catch {
                print("Error with Json: \(error)")
            }

        }
    }

    task.resume()

many thanks in advance.

1 Answers1

1

The IP address is the value for key query on the top level of the JSON

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:Any]
if let query = json["query"] as? String {
  print(query)
}

In Swift 3 the type of a JSON dictionary is [String:Any]

PS: You don't need a URL request for this task, pass the URL directly and use the native structs URL (and URLRequest)

let requestURL = URL(string: "http://ip-api.com/json")!
...
let task = session.dataTask(with: requestURL) {
vadian
  • 274,689
  • 30
  • 353
  • 361
  • i am using an api for this project and is not free. is there any other way you know to get the ip address from iOS Device. ??? thanks – Barry O'Reilly Nov 02 '16 at 11:07
  • For example [wtfismyip - IPv4](https://ipv4.wtfismyip.com/json) and [wtfismyip - IPv6](https://wtfismyip.com/json) – vadian Nov 02 '16 at 11:25