The Podcast at Delphi.org

Beyond the being the longest running podcast about Object Pascal and Delphi programming languages, tools, news, and community, this is also Jim McKeeth's blog on other things related to programming and technology.

15 2013

Sending a URL to Another App on Android and iOS with Delphi XE5

by Jim McKeeth

Here is the source code for my Open and View URL library from my CodeRage 8 session “Beyond the App”. Here is a download of the example app. I’ll see about posting it to a SVN repository too so it can grow and evolve. Thanks to Al Mannarino for his code that started this!

Note the code is using TidURL.URLEncode on all URLs. I found it is only required on the maps for iOS (iOS doesn’t like spaces) but may be causing trouble with the geo:// on Android.

Some example protocols

Example URLs

[delphi]unit OpenViewUrl;

interface

// URLEncode is performed on the URL // so you need to format it protocol://path function OpenURL(const URL: string; const DisplayError: Boolean = False): Boolean;

implementation

uses IdURI, SysUtils, Classes, FMX.Dialogs, {$IFDEF ANDROID} Androidapi.Helpers, FMX.Helpers.Android, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net, Androidapi.JNI.JavaTypes; {$ELSE} {$IFDEF IOS} Macapi.Helpers, iOSapi.Foundation, FMX.Helpers.iOS; {$ENDIF IOS} {$ENDIF ANDROID}

function OpenURL(const URL: string; const DisplayError: Boolean = False): Boolean; {$IFDEF ANDROID} var Intent: JIntent; begin // There may be an issue with the geo: prefix and URLEncode. // will need to research Intent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_VIEW, TJnet_Uri.JavaClass.parse(StringToJString(TIdURI.URLEncode(URL)))); try SharedActivity.startActivity(Intent); exit(true); except on e: Exception do begin if DisplayError then ShowMessage(‘Error: ‘ + e.Message); exit(false); end; end; end; {$ELSE} {$IFDEF IOS} var NSU: NSUrl; begin // iOS doesn’t like spaces, so URL encode is important. NSU := StrToNSUrl(TIdURI.URLEncode(URL)); if SharedApplication.canOpenURL(NSU) then exit(SharedApplication.openUrl(NSU)) else begin if DisplayError then ShowMessage(‘Error: Opening "’ + URL + ‘" not supported.’); exit(false); end; end; {$ELSE} begin raise Exception.Create(‘Not supported!’); end; {$ENDIF IOS} {$ENDIF ANDROID}

end.[/delphi]

tags: Conferences - iOS - Mobile