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 Answer 1

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) {
Sign up to request clarification or add additional context in comments.

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.