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.
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.
- Collect analytics data from your app(s).
- The top 200 Segment companies collect data from 5+ source types (web, mobile, server, CRM, etc.).
- 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.
- 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.
-
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.
-
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.
-
Send data from anywhere. Send Segment data from any device, and we'll transform and send it on to any tool.
-
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:
How do you get this in your own Swift app? Follow the steps below.
To install Segment in your own app, follow the 3 steps below:
-
The recommended way to install Analytics for iOS is via Cocoapods. Add the
Analytics
dependency to yourPodfile
to access the SDK:pod 'Analytics', :git => 'https://github.com/segmentio/analytics-ios.git', :branch => 'master'
If you are using Carthage, use this line in your
Cartfile
:github "segmentio/analytics-ios" "master"
-
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 config = SEGAnalyticsConfiguration(writeKey: "YOUR_WRITE_KEY") SEGAnalytics.setup(with: config) return true }
-
Sign up with Segment and locate your Segment project's Write Key. Replace
YOUR_WRITE_KEY
in the snippet above with your Segment project's write key.Tip! You can find your write key in your Segment project setup guide or settings.
Now SEGAnalytics.shared()
is loaded and available to use throughout your app!
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
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.
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.
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
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")
}
}
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
])
}
}
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.
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")
}
Once you've mastered the basics, here are some advanced use cases you can apply with Segment.
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)")
}
}
}
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.
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.
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.
- Swift 4.2+
- Xcode 10.1+
analytics-ios
3.6.10
To run the demo app, follow the instructions below:
-
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 }
-
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. -
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 thehome
screen. - Screen event:
About
- When someone views theabout
screen. - Track event:
Learn About Segment Clicked
- When someone clicks the "Learn About Segment" link.
- Screen event:
Congrats! You're seeing live data from your demo Swift app in Segment! π
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!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!
use_frameworks!
pod 'AnalyticsSwift', '~> 0.2.0'
- Download the latest binary of the library.
- Drag the
AnalyticsSwift.framework
file into your project. - Under 'Build Phases', click the 'New Copy Files Phase' button.
- 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.
-
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)
- Create an instance of a message (either
identify
,group
,track
,screen
,alias
). Note that eitheruserId
oranonymousId
is always required.
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()
You can see basic examples of the library in action here.
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.