forked from easemob/easemob-demo-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppDelegate.swift
287 lines (237 loc) · 12.2 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//
// AppDelegate.swift
// EaseChatDemo
//
// Created by 朱继超 on 2024/3/5.
//
import UIKit
import EaseChatUIKit
import HyphenateChat
import UserNotifications
import SwiftFFDBHotFix
@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
@UserDefault("EaseChatDemoServerConfig", defaultValue: Dictionary<String,String>()) private var serverConfig
@UserDefault("EaseChatDemoPreferencesTheme", defaultValue: 0) var theme: UInt
@UserDefault("EaseMobChatMessageTranslation", defaultValue: true) var enableTranslation: Bool
@UserDefault("EaseMobChatMessageReaction", defaultValue: true) var messageReaction: Bool
@UserDefault("EaseMobChatCreateMessageThread", defaultValue: true) var messageThread: Bool
@UserDefault("EaseChatDemoPreferencesBlock", defaultValue: true) var block: Bool
@UserDefault("EaseChatDemoUserToken", defaultValue: "") private var token
@UserDefault("EaseChatDemoPreferencesLongPressStyle", defaultValue: 0) var longPressStyle: UInt8
@UserDefault("EaseChatDemoPreferencesAttachmentStyle", defaultValue: 0) var attachmentStyle: UInt8
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.setupEaseChatUIKit()
self.setupEaseChatUIKitConfig()
self.registerRemoteNotification()
return true
}
private func setupEaseChatUIKit() {
var appKey = AppKey
if let applicationKey = self.serverConfig["application"],let debugMode = self.serverConfig["debug_mode"],debugMode == "1" {
appKey = applicationKey
}
let options = ChatOptions(appkey: appKey)
options.includeSendMessageInMessageListener = true
options.isAutoLogin = true
options.enableConsoleLog = true
options.usingHttpsOnly = true
options.deleteMessagesOnLeaveGroup = false
options.enableDeliveryAck = true
options.enableRequireReadAck = true
//Simulator can't use APNS, so we need to judge whether it is a real machine.
#if DEBUG
options.apnsCertName = "EaseIM_APNS_Developer"
#else
options.apnsCertName = "EaseIM_APNS_Product"
#endif
if let debugMode = self.serverConfig["debug_mode"],debugMode == "1",let customServer = self.serverConfig["use_custom_server"], customServer == "1" {
options.setValue(false, forKey: "enableDnsConfig")
options.setValue(true, forKey: "usingHttpsOnly")
//Set the chat server and rest server address.Using private deploy.
if let chatServer = self.serverConfig["chat_server_ip"] {
options.setValue(chatServer, forKey: "chatServer")
}
if let chatPort = Int(self.serverConfig["chat_server_port"] ?? "6717") {
options.setValue(chatPort, forKey: "chatPort")
}
if let restAddress = self.serverConfig["rest_server_address"] {
options.setValue(restAddress, forKey: "restServer")
}
}
//Set up EaseChatUIKit
_ = ChatUIKitClient.shared.setup(option: options)
ChatUIKitClient.shared.registerUserStateListener(self)
_ = PresenceManager.shared
}
private func setupEaseChatUIKitConfig() {
//Set the theme of the chat demo UI.
if self.theme == 0 {
Appearance.avatarRadius = .extraSmall
Appearance.chat.inputBarCorner = .extraSmall
Appearance.alertStyle = .small
Appearance.chat.bubbleStyle = .withArrow
Appearance.chat.messageLongPressMenuStyle = .withArrow
Appearance.chat.messageAttachmentMenuStyle = .followInput
} else {
Appearance.avatarRadius = .large
Appearance.chat.inputBarCorner = .large
Appearance.alertStyle = .large
Appearance.chat.bubbleStyle = .withMultiCorner
Appearance.chat.messageLongPressMenuStyle = .actionSheet
Appearance.chat.messageAttachmentMenuStyle = .actionSheet
}
Appearance.hiddenPresence = false
Appearance.chat.enableTyping = true
Appearance.contact.enableBlock = self.block
self.longPressStyle = Appearance.chat.messageLongPressMenuStyle.rawValue
self.attachmentStyle = Appearance.chat.messageAttachmentMenuStyle.rawValue
//Enable message translation(开启翻译功能,前提是Console上已经开通)
Appearance.chat.enableTranslation = self.enableTranslation
if Appearance.chat.enableTranslation {
let preferredLanguage = NSLocale.preferredLanguages[0]
if preferredLanguage.starts(with: "zh-Hans") || preferredLanguage.starts(with: "zh-Hant") {
Appearance.chat.targetLanguage = .Chinese
} else {
Appearance.chat.targetLanguage = .English
}
}
//Whether show message topic or not.(是否显示根据消息创建话题的功能)
if self.messageThread {
Appearance.chat.contentStyle.append(.withMessageThread)
}
//Whether show message reaction or not.(是否显示消息表情回应功能)
if self.messageReaction {
Appearance.chat.contentStyle.append(.withMessageReaction)
}
//Notice: - Feature identify can't changed, it's used to identify feature action.
//Register custom components(注册Demo中继承EaseChatUIKit中类替换EaseChatUIKit中的父类)
ComponentsRegister.shared.ConversationsController = MineConversationsController.self
ComponentsRegister.shared.ContactsController = MineContactsViewController.self
ComponentsRegister.shared.MessageViewController = MineMessageListViewController.self
ComponentsRegister.shared.ContactInfoController = MineContactDetailViewController.self
ComponentsRegister.shared.GroupInfoController = MineGroupDetailViewController.self
ComponentsRegister.shared.MessageRenderEntity = MineMessageEntity.self
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
}
private func registerRemoteNotification() {
//Simulator can't use APNS, so we need to judge whether it is a real machine.
#if !targetEnvironment(simulator)
UIApplication.shared.applicationIconBadgeNumber = 0
EMLocalNotificationManager.shared().launch(with: self)
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
// Handle granted and error here
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
#endif
}
}
extension AppDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
ChatClient.shared().registerForRemoteNotifications(withDeviceToken: deviceToken) { error in
if error != nil {
consoleLogInfo("Register for remote notification error:\(error?.errorDescription ?? "")", type: .error)
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: any Error) {
DialogManager.shared.showAlert(title: "Register notification failed", content: error.localizedDescription, showCancel: true, showConfirm: true) { _ in
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
ChatClient.shared().application(application, didReceiveRemoteNotification: userInfo)
}
}
extension AppDelegate: EMLocalNotificationDelegate {
func emGetNotificationMessage(_ notification: UNNotification, state: EMNotificationState) {
if notification.request.trigger is UNPushNotificationTrigger {
//apns
consoleLogInfo("\(state == .willPresentNotification ? "Push Arrive":"Push Click") content:\(notification.request.content.title)", type: .debug)
} else {
//local notification
if let userInfo = notification.request.content.userInfo as? [String: Any] {
consoleLogInfo("\(state == .willPresentNotification ? "Local Arrive":"Local Click") content:\(notification.request.content.title)", type: .debug)
}
}
if state == .didReceiveNotificationResponse {
//click notification enter app
} else {
//notification will dispaly
}
}
}
//MARK: - UserStateChangedListener
extension AppDelegate: UserStateChangedListener {
private func logoutUser() {
ChatUIKitClient.shared.logout(unbindNotificationDeviceToken: true) { error in
if error != nil {
consoleLogInfo("Logout failed:\(error?.errorDescription ?? "")", type: .error)
}
}
}
func onUserTokenDidExpired() {
NotificationCenter.default.post(name: Notification.Name(rawValue: backLoginPage), object: nil)
}
func onUserLoginOtherDevice(device: String) {
self.logoutUser()
NotificationCenter.default.post(name: Notification.Name(rawValue: backLoginPage), object: nil)
}
func onUserTokenWillExpired() {
//Notice: - If you want to refresh token, you need to implement the logic in this method.
// EaseChatUIKitClient.shared.refreshToken(token: token)
}
func onSocketConnectionStateChanged(state: EaseChatUIKit.ConnectionState) {
//Socket state monitor network
}
func userAccountDidRemoved() {
self.logoutUser()
NotificationCenter.default.post(name: Notification.Name(rawValue: backLoginPage), object: nil)
}
func userDidForbidden() {
self.logoutUser()
NotificationCenter.default.post(name: Notification.Name(rawValue: backLoginPage), object: nil)
}
func userAccountDidForcedToLogout(error: EaseChatUIKit.ChatError?) {
self.logoutUser()
NotificationCenter.default.post(name: Notification.Name(rawValue: backLoginPage), object: nil)
}
func onUserAutoLoginCompletion(error: EaseChatUIKit.ChatError?) {
if error != nil {
NotificationCenter.default.post(name: Notification.Name(rawValue: backLoginPage), object: nil)
} else {
self.token = ChatClient.shared().accessUserToken ?? ""
ChatClient.shared().pushManager?.syncSilentModeConversations(fromServerCompletion: { error in
})
if let groups = ChatClient.shared().groupManager?.getJoinedGroups() {
var profiles = [EaseChatProfile]()
for group in groups {
let profile = EaseChatProfile()
profile.id = group.groupId
profile.nickname = group.groupName
profile.avatarURL = group.settings.ext
profiles.append(profile)
profile.insert()
}
ChatUIKitContext.shared?.updateCaches(type: .group, profiles: profiles)
}
if let users = ChatUIKitContext.shared?.userCache {
for user in users.values {
ChatUIKitContext.shared?.userCache?[user.id]?.remark = ChatClient.shared().contactManager?.getContact(user.id)?.remark ?? ""
}
}
NotificationCenter.default.post(name: Notification.Name(loginSuccessfulSwitchMainPage), object: nil)
}
}
}