我喜欢追踪用户”location" 通过使用设备的 IP 地址。
我已经寻找过一些 API 服务,例如:
- 自由地理网
- api.petabyet.com
- ip-api.com
但我不知道如何使用此服务来获取用户设备的位置。
实际上我已经寻找了一些 Swift 代码片段来实现想要的结果(获取位置)但我找不到任何与当前版本的 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()
上面的几行是我到目前为止所得到的全部内容。但我真的希望有人能帮助我解决这个问题。
你可以从尝试开始http://ip-api.com/json
,它返回一个 JSON,如所解释的在他们的 API 页面上 http://ip-api.com/docs/api:json.
然后,您可以将此 JSON 字符串转换为字典并访问数据。
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 之后)。这completion
在主线程上调用,假设您将使用结果来更新 UI。如果没有,您可以删除DispatchQueue.main.async { }
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)