-
Notifications
You must be signed in to change notification settings - Fork 45
/
AppDelegate.swift
152 lines (134 loc) · 5.08 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
149
150
151
152
//
// AppDelegate.swift
// testapp
//
// Created by Christopher Batin on 27/02/2019.
// Copyright © 2019 Christopher Batin. All rights reserved.
//
import UIKit
import Ably
import UserNotifications
// 1
let authURL = "YOUR_NGROK_HTTPS/auth"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, ARTPushRegistererDelegate {
var window: UIWindow?
var realtime: ARTRealtime!
var channel: ARTRealtimeChannel!
var subscribed = false
//2
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
DispatchQueue.main.async() {
print("** didRegisterForRemoteNotificationsWithDeviceToken")
ARTPush.didRegisterForRemoteNotifications(withDeviceToken: deviceToken, realtime: self.getAblyRealtime())
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
DispatchQueue.main.async() {
print("** didFailToRegisterForRemoteNotificationsWithError")
ARTPush.didFailToRegisterForRemoteNotificationsWithError(error, realtime: self.getAblyRealtime())
}
}
//3
private func getAblyRealtime() -> ARTRealtime {
let options = ARTClientOptions()
options.authCallback = { params, callback in
self.getTokenRequest() { json, error in
do {
callback(try ARTTokenRequest.fromJson(json!), nil)
} catch let error as NSError {
callback(nil, error)
}
}
}
realtime = ARTRealtime(options: options)
realtime.connection.on { state in
if let state = state {
switch state.current {
case .connected:
print("connected")
case .failed:
print("failed")
default:
break
}
}
}
return realtime
}
// 4
func didActivateAblyPush(_ error: ARTErrorInfo?) {
if let error = error {
// Handle error
print("** push activation failed, err=\(String(describing: error))")
return
}
print("** push activated")
self.channel = self.realtime.channels.get("push")
self.channel.attach() { (err) in
print("** channel attached, err=\(String(describing: err))")
self.channel.push.subscribeDevice { (err) in
DispatchQueue.main.async {
print("** device ID \(self.realtime.device.id)")
}
print("** channel.push.subscribeDevice: err=\(String(describing: err))")
self.subscribed = true
}
}
}
// 5
func didDeactivateAblyPush(_ error: ARTErrorInfo?) {
if let error = error {
// Handle error
print("** push de-activation failed", error)
return
}
print("** push de-activated, re-activating")
self.realtime.push.activate()
}
// 6
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print("** received notification: \(userInfo)")
}
// 7
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
print("** hello")
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, err) in
DispatchQueue.main.async() {
UIApplication.shared.registerForRemoteNotifications()
print("** after registerForRemoteNotifications")
}
}
self.realtime = self.getAblyRealtime()
self.realtime.connection.on { (stateChange) in
print("** connection state change: \(String(describing: stateChange))")
}
self.realtime.connection.on(ARTRealtimeConnectionEvent.connected) { (stateChange) in
print("** connected, resetting Ably push")
self.realtime.push.deactivate()
}
return true
}
// 8
func getTokenRequest(completion: @escaping (NSDictionary?, Error?) -> ()) {
let requestURL = URL(string: authURL)!
let urlRequest = URLRequest(url: requestURL as URL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do{
let json = try JSONSerialization
.jsonObject(with: data!, options:.allowFragments) as! NSDictionary
completion(json, nil)
} catch {
print("There was an error while obtaining JSON")
}
}
}
task.resume()
}
}