Geolocation by iPhone's IP address

流过昼夜 提交于 2020-05-10 18:50:38

问题


I like to track the users "location" by using the device's IP address.

I've already looked for some API services like:

  • freegeoip.net
  • api.petabyet.com
  • ip-api.com

But I have no idea how to use this services to get the location of the users device.

Actually I've already looked for some Swift code snippets to get achieve the wanted result (to get the Location) but I couldn't find any code matching to the current version of Swift.

let url = NSURL(string: "http://freegeoip.net")
    let task = URLSession.shared.dataTask(with: url! as URL) {(data, response, error) in
        let httpResponse = response as? HTTPURLResponse
        if (httpResponse != nil) {

        } else { }
    }; task.resume()

The few lines above are all that I got so far. But I really hope somebody could help me with this problem.


回答1:


You could start by trying http://ip-api.com/json, which returns a JSON as explained on their API page.

You can then convert this JSON string to a dictionary and access the data.

func getIpLocation(completion: @escaping(NSDictionary?, Error?) -> Void)
{
    let url     = URL(string: "http://ip-api.com/json")!
    var request = URLRequest(url: url)
    request.httpMethod = "GET"

    URLSession.shared.dataTask(with: request as URLRequest, completionHandler:
    { (data, response, error) in
        DispatchQueue.main.async
        {
            if let content = data
            {
                do
                {
                    if let object = try JSONSerialization.jsonObject(with: content, options: .allowFragments) as? NSDictionary
                    {
                        completion(object, error)
                    }
                    else
                    {
                        // TODO: Create custom error.
                        completion(nil, nil)
                    }
                }
                catch
                {
                    // TODO: Create custom error.
                    completion(nil, nil)
                }
            }
            else
            {
                completion(nil, error)
            }
        }
    }).resume()
}

This function returns the dictionary or an error (after you resolve the TODO's). The completion is called on the main thread assuming you'll use the result to update the UI. If not, you can remove the DispatchQueue.main.async { }.



来源:https://stackoverflow.com/questions/48530829/geolocation-by-iphones-ip-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!