Giter Site home page Giter Site logo

sakari-ai / analytics-swift Goto Github PK

View Code? Open in Web Editor NEW

This project forked from segment-boneyard/analytics-swift

0.0 1.0 0.0 358 KB

The hassle-free way to add analytics to your Swift app.

Home Page: https://segment.com/

License: MIT License

Ruby 2.35% Swift 95.14% Objective-C 2.02% Makefile 0.49%

analytics-swift's Introduction

analytics-swift Carthage compatible

analytics-swift is an Swift client for Segment.

Our analytics-ios library is more full featured than it's Swift counterpart. You can use analytics-ios from a Swift project.

The analytics-ios library supports the following features that are NOT offered in the Swift library:

  • Queing events offline. Without this, the swift library will drop events once the user closes the app or when the user is offline.
  • Client side integrations. Without this, some integrations (such as Flurry, Localytics and others) cannot be used with the Swift library.

NOTE: Official support from Segment for this plugin is deprecated. We recommend using our analytics-ios library.

๐Ÿƒ๐Ÿ’จ Quickstart for analytics-ios

You can't fix what you can't measure

Analytics helps you measure your users, product, and business. It unlocks insights into your app's funnel, core business metrics, and whether you have product-market fit.

How to get started

  1. Collect analytics data from your app(s).
    • The top 200 Segment companies collect data from 5+ source types (web, mobile, server, CRM, etc.).
  2. Send the data to analytics tools (for example, Google Analytics, Amplitude, Mixpanel).
    • Over 250+ Segment companies send data to eight categories of destinations such as analytics tools, warehouses, email marketing and remarketing systems, session recording, and more.
  3. Explore your data by creating metrics (for example, new signups, retention cohorts, and revenue generation).
    • The best Segment companies use retention cohorts to measure product market fit. Netflix has 70% paid retention after 12 months, 30% after 7 years.

Segment collects analytics data and allows you to send it to more than 250 apps (such as Google Analytics, Mixpanel, Optimizely, Facebook Ads, Slack, Sentry) just by flipping a switch. You only need one Segment code snippet, and you can turn integrations on and off at will, with no additional code. Sign up with Segment today.

Why?

  1. Power all your analytics apps with the same data. Instead of writing code to integrate all of your tools individually, send data to Segment, once.

  2. Install tracking for the last time. We're the last integration you'll ever need to write. You only need to instrument Segment once. Reduce all of your tracking code and advertising tags into a single set of API calls.

  3. Send data from anywhere. Send Segment data from any device, and we'll transform and send it on to any tool.

  4. Query your data in SQL. Slice, dice, and analyze your data in detail with Segment SQL. We'll transform and load your customer behavioral data directly from your apps into Amazon Redshift, Google BigQuery, or Postgres. Save weeks of engineering time by not having to invent your own data warehouse and ETL pipeline.

    For example, you can capture data on any app:

    analytics.track('Order Completed', { price: 99.84 })

    Then, query the resulting data in SQL:

    select * from app.order_completed
    order by price desc

In this tutorial you'll add your write key to the Swift demo app to start sending data from the app to Segment, and from there to any of our destinations, using our analytics-ios library. Once your app is set up, you'll be able to turn on new destinations with the click of a button! Ready to try it for yourself? Scroll down to the demo section and run the app!

Start sending data from your iOS source by interacting with the demo app:


And view events occur live in your Segment Debugger:

๐Ÿ”Œ Installing on Your App

How do you get this in your own Swift app? Follow the steps below.

๐Ÿ“ฆ Step 1: Install the SDK

To install Segment in your own app, follow the 3 steps below:

  1. The recommended way to install Analytics for iOS is via Cocoapods. Add the Analytics dependency to your Podfile to access the SDK:

    pod 'Analytics', :git => 'https://github.com/sakari-ai/analytics-ios.git', :branch => 'sakari-development'

    If you are using Carthage, use this line in your Cartfile:

    github "sakari-ai/analytics-ios" "sakari-development"
  2. In AppDelegate, import the library:

    import Analytics

    Then, modify your application method with the following snippet below:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let sakariKit = Analytics.create(writeKey: "key", accountID: "accountID")
        sakariKit.enqueue(messageBuilder: TrackMessageBuilder(event: "bye, world" + String(index)).userId("prateek"))
        return true
    }

Logging

To see a trace of your data going through the SDK, you can enable debug logging with debug property. Set the debug property to true on the config object in your AppDelegate:

config.debug = true

Middleware

A middleware is a simple function that is invoked by the Segment SDK and can be used to monitor, modify or reject events.

See the middlewares section in our official documentation.

In the next sections you'll build out your implementation to track screen loads, to identify individual users of your app, and track the actions they take.

๐Ÿ“ฑ Step 2: Track Screen Views

The snippet from Step 1 loads analytics-ios into your app and is ready to track screen loads. The screen method lets you record screen views on your website, along with optional information about the screen being viewed. You can read more about how this works in the screen reference.

Automatic Screen Calls

Our SDK can automatically instrument screen calls. It can detect when ViewControllers are loaded and uses the label of the view controller (or the class name if a label is not available) as the screen name. If present, it removes the string "ViewController" from the name.

Set the recordScreenViews property to true on the config object in your AppDelegate:

config.recordScreenViews = true

Manual Screen Calls

If your screens are separated into their own UIViewController classes, you can use the inherited viewDidAppear method to invoke screen calls. The example below shows one way you could do this.

import UIKit
import Analytics

class ViewController: UIViewController {
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        SEGAnalytics.shared().screen("Home")
    }
}

๐Ÿ” Step 3: Identify Users

The identify method is how you tell Segment who the current user is. It includes a unique User ID and any optional traits you can pass on about them. You can read more about this in the identify reference.

Note: You don't need to call identify for anonymous visitors to your site. Segment automatically assigns them an anonymousId, so just calling screen and track still works just fine without identify.

Here's what a basic call to identify might look like:

SEGAnalytics.shared().identify("f4ca124298", properties: [
    "name": "Michael Bolton",
    "email": "[email protected]"
])

This call identifies Michael by his unique User ID and labels him with name and email traits.

In Swift, if you have a form where users sign up or log in, you can use an action method and bind a UIButton handler to call identify, as in the example below:

import UIKit
import Analytics

class SignUpViewController: UIViewController {

    @IBOutlet fileprivate var usernameField: UITextField!
    @IBOutlet fileprivate var emailField: UITextField!
    @IBOutlet fileprivate var passwordField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        usernameField.text = ""
        emailField.text = ""
        passwordField.text = ""
    }

    @IBAction func signUp(_ sender: UIButton) {
        // Handle sign up validation logic...
      
        // Add your own unique ID here or we will automatically assign an anonymousID
        SEGAnalytics.shared().identify(traits: [
            "name": usernameField.text,
            "email": emailField.text
        ])
    }
}

โฐ Step 4: Track Actions

The track method is how you tell Segment about which actions your users are performing on your site. Every action triggers what we call an "event", which can also have associated properties. It is important to figure out exactly what events you want to track instead of tracking anything and everything. A good way to do this is to build a tracking plan. You can read more about track in the track reference.

Here's what a call to track might look like when a user bookmarks an article:

SEGAnalytics.shared().track("Article Bookmarked", properties: [
    "title": "Snow Fall",
    "subtitle": "The Avalanche at Tunnel Creek",
    "author": "John Branch"
])

The snippet tells us that the user just triggered the Article Bookmarked event, and the article they bookmarked was the Snow Fall article authored by John Branch. Properties can be anything you want to associate to an event when it is tracked.

Track Calls with Event Handlers

In Swift, you can use an action method to call the track events. In the example below, we bind a UIButton handler to make a track call to log a User Signup.

@IBAction func handleSignupEvent(_ sender: UIButton) {
    SEGAnalytics.shared().track("User Signup")
}

๐ŸŽ“ Advanced

Once you've mastered the basics, here are some advanced use cases you can apply with Segment.

Eureka Form

If you're using the Eureka library to build your forms, you can use the onChange callback to send track calls for when a user interacts with part of the form.

import Eureka
import Analytics

class MyFormViewController: FormViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        form +++ Section("Section1")
            <<< TextRow(){ row in
                row.title = "Text Row"
                row.placeholder = "Enter text here"
            }.onChange { row in
                SEGAnalytics.shared().track("Updated Text Row With \(row.value)")
            }

            <<< PhoneRow(){
                $0.title = "Phone Row"
                $0.placeholder = "And numbers here"
            }.onChange {
                SEGAnalytics.shared().track("Updated Phone Row With \($0.value)")
            }

        +++ Section("Section2")
            <<< DateRow(){
                $0.title = "Date Row"
                $0.value = Date(timeIntervalSinceReferenceDate: 0)
            }.onChange {
                SEGAnalytics.shared().track("Updated Date Row With \($0.value)")
            }
    }
}

โŒ› Batching

You may see a delay in some of your events because of the behavior of our SDK. Our SDK queues API calls so that we:

  • Reduce Network Usage โ€” Each batch is gzip compressed, decreasing the amount of bytes on the wire by 10x-20x.
  • Save Battery โ€” Because of data batching and compression, Segment's SDKs reduce energy overhead by 2-3x which means longer battery life for your app's users.

It is not recommended, but you can immediately send your queued events by calling flush after your original call:

SEGAnalytics.shared().screen("About")
SEGAnalytics.shared().flush()

Or, set your batch size to 1 by modifying the flushAt property on the config object in your AppDelegate:

config.flushAt = 1;

You can read more about the lifecycle of a mobile API call by reading our blog post.

๐Ÿค” What's next?

Once you've added a few track calls, you're done! You've successfully installed analytics-ios tracking with your Swift app. Now you're ready to see your data in the Segment dashboard, and turn on any destination tools. ๐ŸŽ‰

You may wondering what you can be doing with all the raw data you are sending to Segment from your Swift app. With our warehouses product, your analysts and data engineers can shift focus from data normalization and pipeline maintenance to providing insights for business teams. Having the ability to query data directly in SQL and layer on visualization tools can take your product to the next level.

๐Ÿ’พ Warehouses

A warehouse is a special subset of destinations where we load data in bulk at a regular intervals, inserting and updating events and objects while automatically adjusting their schema to fit the data you've sent to Segment. We do the heavy lifting of capturing, schematizing, and loading your user data into your data warehouse of choice.

Examples of data warehouses include Amazon Redshift, Google BigQuery, MySQL, and Postgres.

๐Ÿ“บ Demo

Requirements:

  • Swift 4.2+
  • Xcode 10.1+
  • analytics-ios 3.6.10

To run the demo app, follow the instructions below:

  1. Sign up with Segment and edit the snippet in AppDelegate to replace YOUR_WRITE_KEY with your Segment Write Key.

    Tip! You can find your key in your project setup guide or settings in the Segment.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let config = SEGAnalyticsConfiguration(writeKey: "YOUR_WRITE_KEY")
        SEGAnalytics.setup(with: config)
        return true
    }
  2. From the command line, use pod install to install the dependencies:

    pod install

    Then, open the project in Xcode and press โŒ˜R to run the app.

  3. Go to the Segment site, and in the Debugger look at the live events being triggered in your app. You should see the following:

    • Screen event: Home - When someone views the home screen.
    • Screen event: About - When someone views the about screen.
    • Track event: Learn About Segment Clicked - When someone clicks the "Learn About Segment" link.

Congrats! You're seeing live data from your demo Swift app in Segment! ๐ŸŽ‰

๐Ÿš€ Startup Program

If you are part of a new startup (<$5M raised, <2 years since founding), we just launched a new startup program for you. You can get a Segment Team plan (up to $25,000 value in Segment credits) for free up to 2 years โ€” apply here!

๐Ÿ“ Docs & Feedback

Check out our full analytics-ios reference to see what else is possible, or read about the Tracking API methods to get a sense for the bigger picture. If you have any questions, or see anywhere we can improve our documentation, let us know!

Installing the Library

CocoaPods

use_frameworks!

pod 'AnalyticsSwift', '~> 0.2.0'

Manual

  1. Download the latest binary of the library.
  2. Drag the AnalyticsSwift.framework file into your project.
  3. Under 'Build Phases', click the 'New Copy Files Phase' button.
  4. In the 'Copy Files' target, select 'Frameworks' as the destination and drag the Analytics.framework file from the binary we added to the project in step 2.

Usage

  • Add the AnalyticsSwift library to your project.

  • Add the correct imports import AnalyticsSwift

  • Create an instance of the analytics client with your project write key:

var analytics = Analytics.create(YOUR_SEGMENT_WRITE_KEY_HERE)

var message = TrackMessageBuilder(event: "Button A").userId("prateek")

  • Enqueue the message.

analytics.enqueue(message)

  • Wait for the message to be uploaded or trigger a flush manually.

analytics.flush()

Examples

You can see basic examples of the library in action here.

License

WWWWWW||WWWWWW
 W W W||W W W
      ||
    ( OO )__________
     /  |           \
    /o o|    MIT     \
    \___/||_||__||_|| *
         || ||  || ||
        _||_|| _||_||
       (__|__|(__|__|


(The MIT License)

Copyright (c) 2013 Segment Inc. <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

analytics-swift's People

Contributors

f2prateek avatar tonyxiao avatar weburnit avatar williamgrosset avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.