Swift compatibility

If you're using Swift, there are a few actions you need to take in order to ensure your app works with Localytics

Installation

After you follow our standard installation instructions, you'll need generate a bridging header to call the Localytics SDK from Swift code. By default, Xcode will offer to create a bridging header when you import Objective-C files. If you choose to create the header manually, it should look something like:

//
//  Localytics_Bridge.h
//

#import "Localytics.h"

After generating or manually creating the header, check the following:

For more detail read Apple's documentation on using Swift and Objective-C in the Same Project.

Integration

The Localytics SDK supports both automatic and manual integration. See below for Swift examples of each.

//
//  AppDelegate.swift
//

import UIKit

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        Localytics.autoIntegrate("App Key", launchOptions: launchOptions)
        return true
    }
}
Note: When using automatic integration, Swift exhibits a bug when accessing your app delegate that can crash your application. The following is a workaround for calling methods on your app delegate.
if let appDelegate = UIApplication.sharedApplication().delegate {
    let originalClass:AnyClass = object_setClass(appDelegate, AppDelegate.self)
    let myAppDelegate = appDelegate as AppDelegate
    myAppDelegate.doSomething()     
    object_setClass(appDelegate, originalClass)
}

The call to object_setClass manipulates the Objective-C type of the AppDelegate object. It replaces direct manipulation of the object's isa pointer. This kind of manipulation should be avoided whenever possible.

//
//  AppDelegate.swift
//

import UIKit

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        Localytics.integrate("App Key")
        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        Localytics.closeSession()
        Localytics.upload()
    }

    func applicationDidEnterBackground(application: UIApplication) {
        Localytics.closeSession()
        Localytics.upload()
    }

    func applicationWillEnterForeground(application: UIApplication) {
        Localytics.openSession()
        Localytics.upload()
    }

    func applicationDidBecomeActive(application: UIApplication) {
        Localytics.openSession()
        Localytics.upload()
    }

    func applicationWillTerminate(application: UIApplication) {
        Localytics.closeSession()
        Localytics.upload()
    }
}