通过iPhone的IP地址进行地理位置定位 [英] Geolocation by iPhone's IP address

查看:288
本文介绍了通过iPhone的IP地址进行地理位置定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用设备的IP地址来跟踪用户的"位置".

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

我已经在寻找一些API服务,例如:

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.

实际上,我已经在寻找一些Swift代码段来获得想要的结果(获取位置),但是我找不到与当前版本的Swift匹配的代码. /p>

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.

推荐答案

您可以先尝试http://ip-api.com/json,它会返回

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

然后您可以将此JSON字符串转换为字典并访问数据.

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()
}

此函数返回字典或错误(在您解决TODO之后).假设您将使用结果更新UI,则在主线程上调用completion.如果没有,则可以删除DispatchQueue.main.async { }.

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 { }.

这篇关于通过iPhone的IP地址进行地理位置定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆