AppDelegate.swift
15.7 KB
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//
// AppDelegate.swift
// ParentAssistant
//
// Created by 葛建军 on 2018/3/5.
// Copyright © 2018年 HANGZHOUTEAM. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var conn:Reachability!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setUpYXIM()
//1.设置网络状态监听
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.networkStatusChange), name: NSNotification.Name.reachabilityChanged, object: nil)
// 2、获得网络Reachability对象
// Reachability必须一直存在,所以需要设置为全局变量
conn = Reachability.forInternetConnection();
// 3、开启网络状态消息监听
conn.startNotifier()
AccountManager.shared.setTokenInfo(tokenInfo: AccountManager.shared.loadToken())
//第一次进来有网且在登录状态要刷新token
if conn.currentReachabilityStatus().rawValue != NetworkStatus.NotReachable.rawValue &&
AccountManager.shared.isOnline() {
AccountManager.shared.refreshUserInfo(AccountManager.shared.phone(), completionHandler: { (finish) in
if finish {
let ID = AccountManager.shared.rawUserInfo!.contentData()["userid"].stringValue
YXMessageManager.share.autoLogin(account: ID, token: ID.md5())
}else{
AccountManager.shared.logOut()
}
})
}
//定位
LocationManger.shared.locationSelf()
setShareSDKSetting()
let tabbarVC = Story.instantiateViewControllerWithIdentifier("TabBarController", storyName: "Main") as! TabBarController
self.window?.rootViewController = tabbarVC
self.window?.makeKeyAndVisible()
// 加载广告
requestAD(vc: tabbarVC)
return true
}
//设置云信的appkey
func setUpYXIM(){
var appkey = ""
var cername = ""
#if DEBUG
appkey = "330158c080acdf4dc1092d6a74576c2c"
cername = "parentdevelop"
#else
appkey = "a1ff0bc08fa0d6f95b480d131e55584b"
cername = "hxyproductpush"
#endif
// if Debug.isFormal{
// appkey = "a1ff0bc08fa0d6f95b480d131e55584b"
// cername = "hxyproductpush"
// }else{
// appkey = "330158c080acdf4dc1092d6a74576c2c"
// cername = "parentdevelop"
// }
let option = NIMSDKOption(appKey: appkey)
option.apnsCername = cername
NIMSDK.shared().register(with: option)
//添加代理
YXMessageManager.share.addYXDelegate()
}
// MARK: - 加载广告页
func requestAD(vc:TabBarController) -> Void {
var position:Int = 0
if Setting.getString("isFirst") == "\(AppDelegate.version())" {//是否是第一次下载
position = 1
let adView = ZLaunchAd.create()
//position 广告位置0-首次广告位1-开屏广告位2-资讯首页3-频道首页4-频道内容5-文章内容页 localAddress
HTTPServer.shared.getAds(["position":position as AnyObject], completionHandler: { (str, error) in
httpJsonResule(jsonString: str, error: error, successHandler: { (json) in
if json["status"] == 1 && error == nil{
if json.contentData().arrayValue.count>0 {
let imageResource = ZLaunchAdImageResourceConfigure()
imageResource.imageNameOrImageURL = HOSTImage+json.contentData().arrayValue[0]["fileSrc"].stringValue.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
imageResource.imageDuration = 5
imageResource.imageFrame = UIScreen.main.bounds
adView.setImageResource(imageResource, action: {
/// 广告点击
})
}else{
NSLog("************\(json.contentData())");
}
}
}, failHandler: { (error) in
})
})
}else{
let view = UIView(frame: CGRect(x: 0, y: 0, width: getScreenWidth(), height: getScreenHeight()))
view.backgroundColor = UIColor.white
vc.view.addSubview(view)
position = 0
let _ = Setting.save("\(AppDelegate.version())", forKey: "isFirst")
//position 广告位置0-首次广告位1-开屏广告位2-资讯首页3-频道首页4-频道内容5-文章内容页 localAddress
HTTPServer.shared.getAds(["position":position as AnyObject], completionHandler: { (str, error) in
view.removeFromSuperview()
httpJsonResule(jsonString: str, error: error, successHandler: { (json) in
if json["status"] == 1 && error == nil{
var images:[String] = []
if json.contentData().arrayValue.count>0 {
for item in json.contentData().arrayValue {
images.append(HOSTImage+item["fileSrc"].stringValue.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
}
LaunchIntroductionView.shared(withImages: images, buttonImage: "icon_getin", buttonFrame: CGRect(x: getScreenWidth()/2-551/4, y: getScreenHeight()-150, width: 551/2, height: 45))
}
}
}, failHandler: { (error) in
})
})
}
}
// MARK: - 设置网络
@objc func networkStatusChange() {
// 检测手机网络是否可用
let connection = Reachability.forInternetConnection()
if connection?.currentReachabilityStatus().rawValue != NetworkStatus.NotReachable.rawValue {
if AccountManager.shared.isOnline() {
AccountManager.shared.refreshUserInfo(AccountManager.shared.phone(), completionHandler: { (finish) in
if !finish {
//从没网变成有网要且在登录状态刷新token,以及如果在我的页面要告知我的页面刷新UI
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "checkNetworkStatusOutOnline"), object: nil)
}
})
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "checkNetworkStatus"), object: nil)
} else {
self.window?.makeToast("网络连接不可用")
}
}
// MARK: - 分享设置,统计设置
func setShareSDKSetting(){
// 配置友盟SDK产品并并统一初始化
// [UMConfigure setEncryptEnabled:YES]; // optional: 设置加密传输, 默认NO.
// [UMConfigure setLogEnabled:YES]; // 开发调试时可在console查看友盟日志显示,发布产品必须移除。
UMConfigure.initWithAppkey("5a9f50aaf43e4820c50000e3", channel: "App Store")
UMErrorCatch.initErrorCatch()
/* appkey: 开发者在友盟后台申请的应用获得(可在统计后台的 “统计分析->设置->应用信息” 页面查看)*/
// 统计组件配置
MobClick.setScenarioType(eScenarioType.E_UM_NORMAL)
// [MobClick setScenarioType:E_UM_GAME]; // optional: 游戏场景设置
// Push组件基本功能配置
// [UNUserNotificationCenter currentNotificationCenter].delegate = self;
// UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
//type是对推送的几个参数的选择,可以选择一个或者多个。默认是三个全部打开,即:声音,弹窗,角标等
// entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert;
// [UNUserNotificationCenter currentNotificationCenter].delegate = self;
// [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
// if (granted) {
// // 用户选择了接收Push消息
// }else{
// // 用户拒绝接收Push消息
// }
// }];
// 请参考「Share详细介绍-初始化第三方平台」
// 分享组件配置,因为share模块配置可选三方平台较多,代码基本跟原版一样,也可下载demo查看
// [self configUSharePlatforms]; // required: setting platforms on demand
// ...
// let socialManager = UMSocialManager.default()
// socialManager!.openLog(false)
// socialManager!.umSocialAppkey = "58a29d5aaed1797bc80006e2"
// //设置微信的appKey和appSecret
// socialManager!.setPlaform(UMSocialPlatformType.wechatSession, appKey: "wxc2ca78fbd4eff355", appSecret: "a2ed68d3ed35c00676fe171193a23acb", redirectURL: "http://mobile.umeng.com/social")
//
// //设置分享到QQ互联的appKey和appSecret
// socialManager!.setPlaform(UMSocialPlatformType.QQ, appKey: "1106048082", appSecret: "wy9p3flQnF9aZfjx", redirectURL: "http://mobile.umeng.com/social")
//
// //设置新浪的appKey和appSecret
// socialManager!.setPlaform(UMSocialPlatformType.sina, appKey: "3921700954", appSecret: "04b48b094faeb16683c32669824ebdad", redirectURL: "https://sns.whalecloud.com/sina2/callback")
//
// //设置短信
// socialManager!.setPlaform(UMSocialPlatformType.sms, appKey: "", appSecret: "", redirectURL: "")
}
func applicationWillResignActive(_ application: 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(_ application: 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(_ application: 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(_ application: 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(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
if #available(iOS 10.0, *) {
self.saveContext()
} else {
// Fallback on earlier versions
}
}
// MARK: - Core Data stack
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ParentAssistant")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
lazy var applicationDocumentsDirectory: URL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: "ParentAssistant", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("ParentAssistant.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
@available(iOS 10.0, *)
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}