我喜欢通过使用设备的IP地址来跟踪用户的"location“。
我已经查找了一些API服务,如:
但是我不知道如何使用这个服务来获取用户设备的位置。
实际上,我已经寻找了一些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()以上几行是我目前为止所得到的全部。但我真的希望有人能帮我解决这个问题。
发布于 2018-01-30 21:35:04
您可以从尝试http://ip-api.com/json开始,它返回在他们的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‘s之后)。假设您将使用结果更新UI,则在主线程上调用completion。如果没有,可以删除DispatchQueue.main.async { }。
https://stackoverflow.com/questions/48530829
复制相似问题