Use conditional compilation

Use conditional compilation to leverage platform specific API


You can leverage all of the iOS functionality and soon all of the Android SDK in your cross platform application. Depending on your mobile os, you use conditional compilation statements to execute code for the specific platform. In below examples, we execute iOS specific functionality. We will extend this chapter with examples of invoking the Android API shortly.

We use Apple Swift compiler conditional compilation statements. A good documentation can be found here Apple Swift Conditional Compilation Blocks

Checking for the platform

We introduced Android as an additional platform. Here a code snippet to execute code on iOS or Android

#if os(iOS)
	canOpenUrl = UIApplication.shared.canOpenURL(url)

#if os(Android)
	// Execute some Android code

#if swift(>=3.0)
	// Execute some Swift 3.0 code

canOpenURL example

In this example, we add conditional code. If we are on iOS, we use canOpenUrl function to check the validity of the URL. The app is simple. Whenever we press the check button, it gets the text value and checks its URL using the platform specific canOpenUrl. Depending on the result, we show a red or green indicator.

We use the foundations URL class. SCADE provides both Swift 3 and the foundation cross platform for Android and Apple. This includes the URL class.

The code for the app looks like this and is hopefully self explanatory.

import ScadeKit

#if os(iOS)
import UIKit

class MainPageAdapter: SCDLatticePageAdapter {

	dynamic var validUrl : Bool = false 
	dynamic var invalidUrl : Bool = true 
	// page adapter initialization
	override func load(_ path: String) {		
		let button =!.getWidgetByName("btnCheck") as! SCDWidgetsClickable
		button.onClick.append(SCDWidgetsEventHandler{ _ in self.check() } )

	func check() {
		if let tbUrl =!.getWidgetByName("tbUrl") as? SCDWidgetsTextbox {
			// Lets use the Foundation URL class
			if let url = URL(string: tbUrl.text) {
				let result = checkUrl(url: url) 
				print("Result is \(result)")
				self.validUrl = result
				self.invalidUrl = !result
	func checkUrl(url:URL) -> Bool {
		var canOpenUrl = false

		// Lets make a conditional check and use canOpenUrl on iOS
		#if os(iOS)
			canOpenUrl = UIApplication.shared.canOpenURL(url)
		// used canOpenUrl to check URL syntax on iOS		
		return canOpenUrl