國行iPhone在iOS10后應工信部要求新增加網(wǎng)絡請求權限,這是國行手機獨有的權限,用戶在第一次安裝APP時會提示用戶是否允許APP使用網(wǎng)絡權限;
如果APP在授權期間請求網(wǎng)絡的話會請求失敗,不幸的是Apple并未提供具體的API供開發(fā)者處理授權期間的網(wǎng)路請求;
這就導致用戶在第一次安裝后授權結束后可能會出現(xiàn)很多依賴于didFinishLaunchingWithOptions的操作初始化失敗,比如首頁網(wǎng)絡請求、SDK初始化失敗等;
本文提供一種我覺得合適的處理方式:網(wǎng)絡狀態(tài)變更通知
大體思路是通過Reachability來監(jiān)聽APP的網(wǎng)絡狀態(tài),在網(wǎng)絡可用時及時reconnect
框架:Reachability
//網(wǎng)絡狀態(tài)監(jiān)控
func setUpNetworkNoti() {
/// 2、實時監(jiān)聽網(wǎng)絡鏈接狀態(tài)
hostReachability?.whenReachable = { reachability in
NotificationCenter.default.post(name: NSNotification.Name.connected, object: nil)
if reachability.connection == .wifi {
/// TODO……
guard let lastStatus = UserDefaults.standard.value(forKey: kNetworkStatus) else {
return
}
if !(lastStatus as! Bool) {
UserDefaults.standard.set(true, forKey: kNetworkStatus)
NotificationCenter.default.post(name: NSNotification.Name.connected, object: nil)
}
} else if reachability.connection == .cellular {
/// TODO……
guard let lastStatus = UserDefaults.standard.value(forKey: kNetworkStatus) else {
return
}
if !(lastStatus as! Bool) {
UserDefaults.standard.set(true, forKey: kNetworkStatus)
NotificationCenter.default.post(name: NSNotification.Name.connected, object: nil)
}
} else {
UserDefaults.standard.set(false, forKey: kNetworkStatus)
NotificationCenter.default.post(name: NSNotification.Name.unreachable, object: nil)
/// TODO……
}
}
hostReachability?.whenUnreachable = { _ in
UserDefaults.standard.set(false, forKey: kNetworkStatus)
NotificationCenter.default.post(name: NSNotification.Name.unreachable, object: nil)
/// TODO……
}
do {
try hostReachability?.startNotifier()
} catch {
/// print("Unable to start notifier")
}
}
當網(wǎng)絡通暢時會執(zhí)行hostReachability?.whenReachable閉包,可以在didFinishLaunchingWithOptions中將需要初始化的操作或者網(wǎng)絡請求放在whenReachable閉包中;
切記:whenReachable閉包在網(wǎng)絡通暢時didFinishLaunchingWithOptions執(zhí)行時并不會執(zhí)行,只有在網(wǎng)絡變化時才會執(zhí)行,所以,需要在閉包外部同樣執(zhí)行初始化操作或者網(wǎng)絡請求