我喜欢通过使用设备的IP地址来跟踪用户的“ 位置 ”。
我已经在寻找一些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()
Run Code Online (Sandbox Code Playgroud)
以上几行是我到目前为止所获得的全部内容。但是我真的希望有人可以帮助我解决这个问题。
您可以从尝试开始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()
}
Run Code Online (Sandbox Code Playgroud)
此函数返回字典或错误(在您解决TODO之后)。在completion被称为主线程假设你会使用结果来更新UI。如果没有,您可以删除DispatchQueue.main.async { }。
| 归档时间: |
|
| 查看次数: |
1474 次 |
| 最近记录: |