• Stars
    star
    607
  • Rank 73,845 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

☂️ Analytics abstraction layer for Swift

☂️ Umbrella

Swift CocoaPods CI Codecov

Analytics abstraction layer for Swift. Inspired by Moya.

Table of Contents

Why?

There are many tools for mobile app analytics such as Firebase, Google Analytics, Fabric Answers, Flurry, Mixpanel, etc. You might use one or more of those in your application. But most of those SDKs have some problems: if you use multiple analytics tools, your code will be messed up. And the SDKs take event name as a string and parameters as a dictionary which is not guaranteed by Swift compiler. It means that if you change the event definition, you should find all related code by your hand. It has an opportunity that cause a human error. Umbrella uses Swift enums and the associated values to solve these problems.

Features

  • 💪 Taking advantages of Swift compiler by using an enum and associated values.
  • 🎯 Logging events to multiple analytics providers at once.
  • 🎨 Creating custom analytics providers.

At a Glance

Before 🤢

FIRAnalytics.logEvent(withName: kFIREventEcommercePurchase, parameters: [
  kFIRParameterCurrency: "USD" as NSObject,
  kFIRParameterValue: 9.99 as NSNumber,
  kFIRParameterTransactionID: "20170709123456" as NSObject,
])
Flurry.logEvent("purchase", withParameters: [
  "Currency": "USD",
  "Price": 9.99,
  "Transaction ID": "20170709123456"
])
MyCustomAnalytics.logEvent("purchase", withParameters: [
  "currency": "USD",
  "price": 9.99,
  "transaction_id": "20170709123456"
])

After 😊

let analytics = Analytics<MyAppEvent>()
analytics.register(provider: FirebaseProvider())
analytics.register(provider: FlurryProvider())
analytics.register(provider: MyCustomProvider())
analytics.log(.purchase(currency: "USD", price: 9.99, transactionID: "20170709123456"))

Getting Started

Defining Events

First of all, you should define all of your events in a single enum. Let's assume that we have three events that have associated parameters.

enum MyAppEvent {
  case signup(username: String)
  case viewContent(productID: Int)
  case purchase(productID: Int, price: Float)
}

Then make the enum to conform the protocol EventType. It requires two functions: name(for:) and parameters(for:).

extension MyAppEvent: EventType {
  /// An event name to be logged
  func name(for provider: ProviderType) -> String? {
    switch self {
    case .signup: return "signup"
    case .viewContent: return "view_content"
    case .purchase: return "purchase"
    }
  }

  /// Parameters to be logged
  func parameters(for provider: ProviderType) -> [String: Any]? {
    switch self {
    case let .signup(username):
      return ["username": username]
    case let .viewContent(productID):
      return ["product_id": productID]
    case let .purchase(productID, price):
      return ["product_id": productID, "price": price]
    }
  }
}

You can even provide different event names and parameters by providers.

Using Analytics

You can define an Analytics instance anywhere but it's recommended to define at a global scope.

let analytics = Analytics<MyAppEvent>()

Then you should register providers. A prodiver is a wrapper for an actual analytics service such as Firebase and Fabric Answers. It's recommended to register providers in application(_:didFinishLaunchingWithOptions:).

analytics.register(provider: AnswersProvider())
analytics.register(provider: FirebaseProvider())
analytics.register(provider: FlurryProvider())
analytics.register(provider: MyAwesomeProvider())

If you finished those steps, you can now log the events 🎉

analytics.log(.signup(username: "devxoul"))

Built-in Providers

There are several built-in providers.

If there's no provider you're looking for, you can create an issue or create custom providers. It's also welcomed to create a pull request for missing services 🎉

Creating Custom Providers

If there's no built-in provider for the serivce you're using, you can also create your own. It's easy to create a provider: just create a class and conform to the protocol ProviderType.

final class MyAwesomeProvider: ProviderType {
  func log(_ eventName: String, parameters: [String: Any]?) {
    AwesomeAnalytics.logEvent(withName: eventName, parameters: parameters)
  }
}

Installation

Umbrella currently support CocoaPods only.

pod 'Umbrella'
pod 'Umbrella/Firebase' # using with built-in FirebaseProvider
pod 'Umbrella/...'

Contributing

Any discussions and pull requests are welcomed 💖

Generating Xcode Workspace

$ make project

This will automatically generate Umbrella.xcworkspace and perform pod install.

Creating New Provider

For example, imagine that we are going to create a new provider for an analytics service 'Raincoat'.

  1. Add a library and a target definition in Package.swift.

      let package = Package(
        name: "Umbrella",
        products: [
          .library(name: "Umbrella", targets: ["Umbrella"]),
          .library(name: "UmbrellaFirebase", targets: ["UmbrellaFirebase"]),
          .library(name: "UmbrellaMixpanel", targets: ["UmbrellaMixpanel"]),
    +     .library(name: "UmbrellaRaincoat", targets: ["UmbrellaRaincoat"]),
        ],
        targets: [
          .target(name: "Umbrella"),
          .target(name: "UmbrellaFirebase", dependencies: ["Umbrella"]),
          .target(name: "UmbrellaMixpanel", dependencies: ["Umbrella"]),
    +     .target(name: "UmbrellaRaincoat", dependencies: ["Umbrella"]),
          .testTarget(name: "UmbrellaTests", dependencies: ["Umbrella"]),
          .testTarget(name: "UmbrellaFirebaseTests", dependencies: ["UmbrellaFirebase"]),
          .testTarget(name: "UmbrellaMixpanelTests", dependencies: ["UmbrellaMixpanel"]),
    +     .testTarget(name: "UmbrellaRaincoat", dependencies: ["UmbrellaRaincoat"]),
        ]
      )
  2. Add a source file and a test file.

      ...
      ├── Sources
      │   ├── UmbrellaFirebase
      │   │   └── FirebaseProvider.swift
      │   ├── UmbrellaMixpanel
      │   │   └── MixpanelProvider.swift
    + │   ├── UmbrellaRaincoat
    + │   │   └── RaincoatProvider.swift
      |   ...
      ├── Tests
      │   ├── UmbrellaFirebaseTests
      │   │   └── FirebaseProviderTests.swift
      │   ├── UmbrellaMixpanelTests
      │   │   └── MixpanelProviderTests.swift
    + │   ├── UmbrellaRaincoatTests
    + │   │   └── RaincoatProviderTests.swift
      ... ...
  3. Add a CocoaPods dependency in Podfile.

     target 'UmbrellaFirebaseTests' do
       platform :ios, '8.0'
       pod 'Firebase/Analytics'
     end
    
     target 'UmbrellaMixpanelTests' do
       platform :ios, '8.0'
       pod 'Mixpanel'
     end
    
    + target 'UmbrellaRaincoatTests' do
    +   platform :ios, '8.0'
    +   pod 'Raincoat'
    + end
  4. Add a CocoaPods subspec in Umbrella.podspec.

      s.subspec "Firebase" do |ss|
        ss.source_files = "Sources/UmbrellaFirebase/*.swift"
        ss.dependency "Umbrella/Core"
      end
    
      s.subspec "Mixpanel" do |ss|
        ss.source_files = "Sources/UmbrellaMixpanel/*.swift"
        ss.dependency "Umbrella/Core"
      end
    
    + s.subspec "Raincoat" do |ss|
    +   ss.source_files = "Sources/UmbrellaRaincoat/*.swift"
    +   ss.dependency "Umbrella/Core"
    + end
  5. Create a Xcode workspace and run tests. Don't forget to check the code coverage to ensure that tests can cover the new provider.

    $ make project

License

Umbrella is under MIT license. See the LICENSE file for more info.

More Repositories

1

Then

✨ Super sweet syntactic sugar for Swift initializers
Swift
4,045
star
2

URLNavigator

⛵️ Elegant URL Routing for Swift
Swift
3,219
star
3

Toaster

🍞 Toast for Swift
Swift
1,668
star
4

UITextView-Placeholder

A missing placeholder for UITextView
Objective-C
1,458
star
5

RxTodo

iOS Todo Application using RxSwift and ReactorKit
Swift
1,291
star
6

SwiftyImage

🎨 Generate image resources in Swift
Swift
1,075
star
7

SwiftUITodo

An example to-do list app using SwiftUI which is introduced in WWDC19
Swift
715
star
8

Drrrible

Dribbble for iOS using ReactorKit
Swift
514
star
9

Pure

Pure DI in Swift
Swift
366
star
10

CocoaSeeds

Git Submodule Alternative for Cocoa.
Ruby
341
star
11

RxViewController

RxSwift wrapper for UIViewController and NSViewController
Swift
331
star
12

SwipeBack

Enable iOS 7+ swipe-to-back when custom back button is set.
Objective-C
321
star
13

UICollectionViewFlexLayout

A drop-in replacement for UICollectionViewFlowLayout
Swift
296
star
14

MoyaSugar

🍯 Syntactic sugar for Moya
Swift
191
star
15

Carte

🍴 Open source license notice view generator for Swift
Ruby
189
star
16

graygram-ios

[40시간만에 Swift로 iOS 앱 만들기] 흑백 사진 전용 소셜 미디어 앱
Swift
180
star
17

ReusableKit

Generic reusables for UICollectionView and UITableView
Swift
158
star
18

UINavigationItem-Margin

Margins for UINavigationItem
Objective-C
158
star
19

allkdic

올ㅋ사전 - 맥에서 단축키를 누르면 영어사전이 뙇!!!!
Swift
128
star
20

SwiftyColor

🎨 The most sexy way to use colors in Swift.
Swift
120
star
21

RxCodable

RxSwift wrapper for Codable
Swift
113
star
22

RxExpect

RxSwift testing framework
Swift
105
star
23

korail

🚆 An unofficial Korail API for Python.
Python
90
star
24

Stubber

A minimal method stub for Swift
Swift
86
star
25

Cleverbot

iOS Messaging Application using Cleverbot and ReactorKit
Swift
78
star
26

Blockchain

A blockchain simulator written in Swift
Swift
65
star
27

LetsGitHubSearch

Let'Swift 18 Workshop - Let's TDD
Swift
63
star
28

CancelBag

A DisposeBag for Combine
Swift
53
star
29

TouchAreaInsets

Expand UIView touch area just like a charm
Objective-C
50
star
30

UIViewController-NavigationBar

[Deprecated] UIViewController with its own navigation bar. It provides an availability for the smooth push/pop animations between view controllers which have different navigation bar styles.
Swift
50
star
31

ios-with-swift-in-40-hours

40시간만에 Swift로 iOS 앱 하나를 만들어봅시다.
49
star
32

SectionReactor

A ReactorKit extension for managing table view and collection view sections with RxDataSources
Swift
45
star
33

Fallback

💊 Syntactic sugar for Swift do-try-catch
Swift
42
star
34

SafeCollection

Safe Collection for Swift
Swift
42
star
35

AsyncBlockOperation

NSOperation subclass for async block.
Objective-C
41
star
36

CGFloatLiteral

CGFloat(10) becomes 10.f
Swift
35
star
37

Endpoint

🚀 Elegant API Abstraction for Swift
Swift
35
star
38

RxJSON

RxSwift wrapper for JSON
Swift
33
star
39

ASCollectionFlexLayout

A custom collection layout that allows to use Texture layout specs in ASCollectionNode.
Swift
27
star
40

next-route-map

🚏 Routes for Next.js
TypeScript
26
star
41

Date.swift

📅 A Swift Date Library
Swift
26
star
42

ImageEffects

Bring UIImageEffects (WWDC 2013) to UIImage category with handy interface.
Objective-C
25
star
43

Todobox

[40시간만에 Swift로 iOS 앱 만들기] 할 일 목록 관리 애플리케이션
Swift
24
star
44

RxReusable

Reusable cells and views for RxSwift
Swift
23
star
45

AlertReactor

A ReactorKit extension for UIAlertController
Swift
23
star
46

UIButton-BackgroundContentMode

A missing background content mode for UIButton.
Objective-C
22
star
47

sketch-export-sizes-generator

💎 A simple plugin for Sketch that generates export sizes of layers.
20
star
48

RxDelegateCells

[Don't use this] UITableView Cell Height and UICollectionView Cell Size for RxSwift
Swift
19
star
49

Immutable

Missing non-mutating functions in Swift
Swift
18
star
50

PureSwinject

Auto register Pure factories to Swinject
Swift
18
star
51

graygram-web

Python
16
star
52

daumpostcode

다음 우편번호 서비스를 별도의 패키지 설치 없이도 네이티브 앱에서 쉽게 사용할 수 있습니다.
HTML
16
star
53

Swiftproj

A command-line tool for managing Xcode project with Swift Package Manager.
Ruby
15
star
54

Meal

[40시간만에 Swift로 iOS 앱 만들기] 전국 초/중/고등학교 급식 조회 애플리케이션
Swift
15
star
55

SwinjectSafeAuto

SwinjectSafeAuto allows to auto-register services to the container and verify the required services are properly registered.
Swift
14
star
56

FastLogin

2018 FAST CAMPUS DEV SEMINAR 실습 앱
Swift
14
star
57

NSOperationQueue-CompletionBlock

Completion block for NSOperationQueue.
Objective-C
13
star
58

graphql-codegen-typescript-fixtures

A plugin for graphql-code-generator that generates TypeScript fixtures for testing.
TypeScript
12
star
59

Kodium

Better Korean typo for medium.com
JavaScript
11
star
60

Estimator

Planning Poker application that communicates over BLE (Bluetoothe Low Energy)
Swift
10
star
61

Slots

Dynamic contents management for Swift.
Swift
9
star
62

MapViewVisibleAnnotations

Displays which annotations are currently visible in the specific area.
Swift
9
star
63

jira-velocity-chart-completion-rate

Displays completion rate in JIRA velocity chart.
JavaScript
9
star
64

github-monospace-editor

GitHub Monospace Editor Userscript
JavaScript
9
star
65

flask-restdoc

Flask-Restdoc is a simple tool that generates RESTful API documentation automatically from python files.
Python
9
star
66

notion-badge

Embed App Store badge in Notion
HTML
9
star
67

SwinjectFactory

Experimental Swinject extension for factory injection.
Swift
8
star
68

if_

Swift if-else statement as an expression (Experimental)
Swift
8
star
69

flask-errorhandler

Error handlers for Flask blueprints.
Python
7
star
70

shlee322-fb-troll

상혁이의 페북 글마다 일하라는 댓글을 달아보아요 ^오^
Python
7
star
71

adorable

M꙼̈ă̎k̊̈ě̈ t̐̈ȇ̈x̆̈t꙼̈ å̈ď̈ō̈r̐̈ȃ̈b̆̈l꙼̈ĕ̎
HTML
7
star
72

ModelKit

[deprecated] Experimental Model framework for Swift
Swift
7
star
73

resume

My résumé
Makefile
6
star
74

Playground

A playground for an ideal project
HCL
6
star
75

Bagel

GIF converter for Mac
Swift
5
star
76

RxGitHubSearch

An example GitHub search app for my lecture
Swift
5
star
77

xcode-project-template

Swift
5
star
78

staccato

Staccato 모임 소개 페이지
Python
5
star
79

fbmarkdown

Chrome extension that enable markdown on facebook.
JavaScript
5
star
80

JLModel

JLModel allows you to manage models in very simple way.
Objective-C
5
star
81

blog

언젠간 쓰겠지?
CSS
4
star
82

TypedKey

Statically-typed key for Swift.
Swift
4
star
83

devxoul.github.io

HTML
4
star
84

Hippo-iOS

Objective-C
4
star
85

naver-cafe-chat-notification

네이버 카페 새 채팅 개수를 브라우저 타이틀로 알려주는 스크립트.
JavaScript
4
star
86

fabric-verbose

Python
4
star
87

TistoryMarkdown

A Markdown plugin for Tistory.
4
star
88

4SharedDownloader

You can download files from 4shared.com without delay.
ActionScript
4
star
89

help-me-rx-tableview-cell-height

Help me!
Swift
3
star
90

macsafe

Keep your MacBook from thieves.
Python
3
star
91

NAR

Nginx Auto Reloader
JavaScript
2
star
92

Editag

The easiest way to edit id3 tag.
ActionScript
2
star
93

ImageCrawler

JavaScript
2
star
94

ovenbreak

Utils for ovenapp.io
Makefile
2
star
95

JLChromeTabController

A chrome-like tab bar for iOS.
Objective-C
2
star
96

Evermind

Evermind is a handy tool that makes it easy to mindmap your idea from your work, study, and everyday life.
ActionScript
2
star
97

JLUtils

Objective-C
1
star
98

FastcampusFrame

Swift
1
star
99

Sonaki

Objective-C
1
star
100

Calendar

Infinite-scrolling calendar example
Objective-C
1
star