forked from Iterable/iterable-swift-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppDelegate.swift
148 lines (125 loc) · 6.98 KB
/
AppDelegate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
//
// Copyright © 2019 Iterable. All rights reserved.
//
import UIKit
import UserNotifications
@testable import IterableSDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
static var sharedInstance: AppDelegate {
UIApplication.shared.delegate as! AppDelegate
}
var window: UIWindow?
var mockInAppFetcher: MockInAppFetcher!
var mockNetworkSession: MockNetworkSession!
var networkTableViewController: NetworkTableViewController {
let tabBarController = window!.rootViewController! as! UITabBarController
let nav = tabBarController.viewControllers![tabBarController.viewControllers!.count - 1] as! UINavigationController
return nav.viewControllers[0] as! NetworkTableViewController
}
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
mockInAppFetcher = MockInAppFetcher()
mockNetworkSession = MockNetworkSession(statusCode: 200, urlPatternDataMapping: createUrlToDataMapper())
mockNetworkSession.requestCallback = { request in
self.logRequest(request: request)
}
let config = IterableConfig()
config.customActionDelegate = self
config.urlDelegate = self
let localStorage = MockLocalStorage()
localStorage.email = "user1@example.com"
IterableAPI.initializeForTesting(config: config,
networkSession: mockNetworkSession,
localStorage: localStorage,
inAppFetcher: mockInAppFetcher,
urlOpener: AppUrlOpener())
return true
}
func applicationWillResignActive(_: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func loadDataset(number: Int) {
let messages = loadMessages(from: "inbox-messages-\(number)", withExtension: "json")
mockInAppFetcher.mockMessagesAvailableFromServer(internalApi: IterableAPI.internalImplementation, messages: messages)
}
func addInboxMessage() {
ITBInfo()
mockInAppFetcher.mockMessagesAvailableFromServer(internalApi: IterableAPI.internalImplementation, messages: mockInAppFetcher.messages + [createNewMessage()])
}
func addMessageToServer() {
// mocks message added to server but not client since no sync has happened yet
mockInAppFetcher.add(message: createNewMessage())
}
private func createNewMessage() -> IterableInAppMessage {
let html = """
<body bgColor="#FFF">
<div style="width:100px;height:100px;position:absolute;margin:auto;top:0;bottom:0;left:0;right:0;"><a href="iterable://delete">Delete</a></div>
</body>
"""
let id = IterableUtil.generateUUID()
return IterableInAppMessage(messageId: "message-\(id)",
campaignId: TestHelper.generateIntGuid() as NSNumber,
trigger: IterableInAppTrigger.neverTrigger,
content: IterableHtmlInAppContent(edgeInsets: .zero, html: html),
saveToInbox: true,
inboxMetadata: IterableInboxMetadata(title: "title-\(id)", subtitle: "subTitle-\(id)"))
}
private func logRequest(request: URLRequest) {
let serializableRequest = request.createSerializableRequest()
networkTableViewController.requests.append(serializableRequest)
networkTableViewController.tableView.reloadData()
}
private func loadMessages(from file: String, withExtension extension: String) -> [IterableInAppMessage] {
let data = loadData(from: file, withExtension: `extension`)
let payload = try! JSONSerialization.jsonObject(with: data, options: []) as! [AnyHashable: Any]
return InAppTestHelper.inAppMessages(fromPayload: payload)
}
private func loadData(from file: String, withExtension extension: String) -> Data {
let path = Bundle(for: type(of: self)).path(forResource: file, ofType: `extension`)!
return FileManager.default.contents(atPath: path)!
}
private func createUrlToDataMapper() -> [String: Data?] {
var mapper = [String: Data?]()
mapper[#"mocha.png"#] = loadData(from: "mocha", withExtension: "png")
mapper[".*"] = nil
return mapper
}
}
extension AppDelegate: IterableCustomActionDelegate {
func handle(iterableCustomAction action: IterableAction, inContext _: IterableActionContext) -> Bool {
ITBInfo("handleCustomAction: \(action)")
NotificationCenter.default.post(name: .handleIterableCustomAction, object: nil, userInfo: ["name": action.type])
return true
}
}
extension AppDelegate: IterableURLDelegate {
func handle(iterableURL url: URL, inContext _: IterableActionContext) -> Bool {
ITBInfo("handleUrl: \(url)")
if url.absoluteString == "https://www.google.com" {
// I am not going to handle this, do default
return false
} else {
// I am handling this
NotificationCenter.default.post(name: .handleIterableUrl, object: nil, userInfo: ["url": url.absoluteString])
return true
}
}
}
extension Notification.Name {
static let handleIterableUrl = Notification.Name("handleIterableUrl")
static let handleIterableCustomAction = Notification.Name("handleIterableCustomAction")
}