Hi everyone

Hi everyone
Does anyone know how to get the country code for where a device is currently residing in firemonkey?

I can get the language code (eg. "En") but need the country too?

Comments

  1. We've used this API for getting the IP. It's pretty good for our needs - not perfect but works for the most part.
    https://www.ipify.org/

    ReplyDelete
  2. Thanks for the advice. With a lot of digging through the sources, I found a more stable solution using the native APIs which I thought would be useful to share for anyone else who has the same requirement.

    Note - this code is for sample purposes so not the cleanest! :)

    {$IFDEF IOS}
    uses iOSAPI.Foundation, MacAPI.ObjectiveC;
    {$ENDIF}
    {$IFDEF ANDROID}
    uses AndroidAPI.JNI.JavaTypes, AndroidApi.Helpers;
    {$ENDIF}

    function GetDeviceCountry: String;
    {$IFDEF ANDROID}
    var
    Locale: JLocale;
    {$ENDIF}
    {$IFDEF IOS}
    const
    FoundationFwk: string = '/System/Library/Frameworks/Foundation.framework/Foundation';
    var
    CurrentLocale: NSLocale;
    CountryISO: NSString;
    {$ENDIF}
    begin
    Result:='Unknown';
    {$IFDEF ANDROID}
    Locale := TJLocale.JavaClass.getDefault;
    Result := JStringToString(Locale.getISO3Country);
    {$ENDIF}
    {$IFDEF IOS}
    CurrentLocale := TNSLocale.Wrap(TNSLocale.OCClass.currentLocale);
    CountryISO := TNSString.Wrap(CurrentLocale.objectForKey((CocoaNSStringConst(FoundationFwk, 'NSLocaleCountryCode') as ILocalObject).GetObjectID));
    Result := UTF8ToString(CountryISO.UTF8String);
    {$ENDIF}
    if Length(Result) > 2 then
    Delete(Result, 3, MaxInt);
    end;

    ReplyDelete

Post a Comment