-
-
Save sandcastle/436ecb49c749942cb52adb2da169a2d4 to your computer and use it in GitHub Desktop.
using UnityEngine; | |
using System.Collections; | |
using Newtonsoft.Json; | |
/// <summary> | |
/// The Geo data for a user. | |
/// | |
/// http://ip-api.com/docs/api:json | |
/// | |
/// <code> | |
/// { | |
/// "status": "success", | |
/// "country": "COUNTRY", | |
/// "countryCode": "COUNTRY CODE", | |
/// "region": "REGION CODE", | |
/// "regionName": "REGION NAME", | |
/// "city": "CITY", | |
/// "zip": "ZIP CODE", | |
/// "lat": LATITUDE, | |
/// "lon": LONGITUDE, | |
/// "timezone": "TIME ZONE", | |
/// "isp": "ISP NAME", | |
/// "org": "ORGANIZATION NAME", | |
/// "as": "AS NUMBER / NAME", | |
/// "query": "IP ADDRESS USED FOR QUERY" | |
/// } | |
/// </code> | |
/// | |
/// </summary> | |
public class GeoData | |
{ | |
/// <summary> | |
/// The status that is returned if the response was successful. | |
/// </summary> | |
public const string SuccessResult = "success"; | |
[JsonProperty("status")] | |
public string Status { get; set; } | |
[JsonProperty("country")] | |
public string Country { get; set; } | |
[JsonProperty("query")] | |
public string IpAddress { get; set; } | |
} | |
public class GeoCountry : MonoBehaviour { | |
// Use this for initialization | |
void Start () { | |
HTTP.Request someRequest = new HTTP.Request( "get", "http://ip-api.com/json" ); | |
someRequest.Send( ( request ) => { | |
// Get Geo data | |
GeoData data = null; | |
try { | |
data = request.response.Get<GeoData>(); | |
} | |
catch (System.Exception ex) { | |
// TODO: Hook into an auto retry case | |
Debug.LogError("Could not get geo data: " + ex.ToString()); | |
return; | |
} | |
// Ensure successful | |
if (data.Status != GeoData.SuccessResult) { | |
// TODO: Hook into an auto retry case | |
Debug.LogError("Unsuccessful geo data request: " + request.response.Text); | |
return; | |
} | |
Debug.Log ("User's Country: \"" + data.Country + "\"; Query: \"" + data.IpAddress + "\""); | |
}); | |
} | |
// Update is called once per frame | |
void Update () { | |
} | |
} |
Http library is available since 4.6 .Net version. For older version you have to use old Unity way to request data: https://docs.unity3d.com/Manual/UnityWebRequest-RetrievingTextBinaryData.html
@Zaidiii / @ThunderboxEntertainment / @IridiumStudios / @regy42 - I have only just seen these comments..
I’m not actively developing in Unity any more, and I can't remember the library that was used for this sample.
I would suggest using a library like Best HTTP, this will make things work better cross-platform:
https://assetstore.unity.com/packages/tools/network/best-http-10872
I hear that net standard libraries are coming to Unity if that is the case the built-in HTTP ones might work, but don't take my word for it :)
How many request we can make with our game to http://ip-api.com/json ?
ThunderboxEntertainment: I'm having the same issue as Zaidiii. How did you solve it?