Browse Source

网络监听

南鑫林 6 years ago
parent
commit
5868a55a8a

+ 1 - 0
RainbowPlanet/Podfile

@@ -8,6 +8,7 @@ target 'RainbowPlanet' do
   # 网络请求
   pod 'Alamofire'
   pod 'Moya/RxSwift'
+  pod 'ReachabilitySwift'
   # Rx
   pod 'RxSwift'
   pod 'RxCocoa'

+ 5 - 1
RainbowPlanet/Podfile.lock

@@ -24,6 +24,7 @@ PODS:
     - RxSwift (~> 4.0)
   - ObjectMapper (3.4.2)
   - PPBadgeViewSwift (3.1.0)
+  - ReachabilitySwift (4.3.1)
   - Realm (3.15.0):
     - Realm/Headers (= 3.15.0)
   - Realm/Headers (3.15.0)
@@ -76,6 +77,7 @@ DEPENDENCIES:
   - Moya/RxSwift
   - ObjectMapper
   - PPBadgeViewSwift
+  - ReachabilitySwift
   - RealmSwift
   - RxCocoa
   - RxSwift
@@ -111,6 +113,7 @@ SPEC REPOS:
     - Moya
     - ObjectMapper
     - PPBadgeViewSwift
+    - ReachabilitySwift
     - Realm
     - RealmSwift
     - Result
@@ -144,6 +147,7 @@ SPEC CHECKSUMS:
   Moya: f4a4b80ff2f8a4ffc208dfb31cd91636622fee6e
   ObjectMapper: 0d4402610f4e468903ae64629eec4784531e5c51
   PPBadgeViewSwift: 18a219a9897f418342c22dd1a54f7b18ac56546b
+  ReachabilitySwift: 4032e2f59586e11e3b0ebe15b167abdd587a388b
   Realm: 9b834e1be6062f544805252c812348872dc5d4ed
   RealmSwift: 8a41886f8ab6efef9eb8df97de2f2bb911561a79
   Result: bd966fac789cc6c1563440b348ab2598cc24d5c7
@@ -159,6 +163,6 @@ SPEC CHECKSUMS:
   UMCSecurityPlugins: 0831a08f3988f3cea9f1d3a7626cd9bee4fef150
   UMCShare: 552b29753f1b4da87b51d96545ed19e6263df397
 
-PODFILE CHECKSUM: 49bfe27defc187ee34a3de662667b0ab9a9418c5
+PODFILE CHECKSUM: 49d6a5e69ac37ef68bd4fbcf86378c5b48afee7e
 
 COCOAPODS: 1.6.2

+ 14 - 0
RainbowPlanet/RainbowPlanet.xcodeproj/project.pbxproj

@@ -157,6 +157,7 @@
 		A738D202225AD6AD00EEE860 /* Extension+UICollectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A738D201225AD6AD00EEE860 /* Extension+UICollectionView.swift */; };
 		A738D205225AF90D00EEE860 /* WeChatpayOrderModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A738D204225AF90D00EEE860 /* WeChatpayOrderModel.swift */; };
 		A738D66F225D9BD900EEE860 /* UMLoginModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A738D66E225D9BD900EEE860 /* UMLoginModel.swift */; };
+		A73911AD229CD62F0033177E /* ReachabilitySwiftManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A73911AC229CD62F0033177E /* ReachabilitySwiftManager.swift */; };
 		A73D7C682268A032002A4CE3 /* SwiftyStarRatingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A73D7C672268A032002A4CE3 /* SwiftyStarRatingView.swift */; };
 		A75414FD224B5F28002480B5 /* MobileLoginViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A75414FB224B5F28002480B5 /* MobileLoginViewController.swift */; };
 		A7541502224C5ECB002480B5 /* BaiduMapManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7541501224C5ECA002480B5 /* BaiduMapManager.swift */; };
@@ -545,6 +546,7 @@
 		A738D201225AD6AD00EEE860 /* Extension+UICollectionView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Extension+UICollectionView.swift"; sourceTree = "<group>"; };
 		A738D204225AF90D00EEE860 /* WeChatpayOrderModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WeChatpayOrderModel.swift; sourceTree = "<group>"; };
 		A738D66E225D9BD900EEE860 /* UMLoginModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UMLoginModel.swift; sourceTree = "<group>"; };
+		A73911AC229CD62F0033177E /* ReachabilitySwiftManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReachabilitySwiftManager.swift; sourceTree = "<group>"; };
 		A73D7C672268A032002A4CE3 /* SwiftyStarRatingView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftyStarRatingView.swift; sourceTree = "<group>"; };
 		A75414FB224B5F28002480B5 /* MobileLoginViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileLoginViewController.swift; sourceTree = "<group>"; };
 		A7541501224C5ECA002480B5 /* BaiduMapManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaiduMapManager.swift; sourceTree = "<group>"; };
@@ -1488,6 +1490,7 @@
 		A72A725422321B9400B21995 /* Manager */ = {
 			isa = PBXGroup;
 			children = (
+				A73911AB229CD6080033177E /* ReachabilitySwiftManager */,
 				A7778CA52243A03400C7C47A /* IQKeyboardManagerSwiftManager */,
 				A72A730522321F1D00B21995 /* PayManager */,
 				A72A726122321DBD00B21995 /* MapManager */,
@@ -1711,6 +1714,14 @@
 			path = Model;
 			sourceTree = "<group>";
 		};
+		A73911AB229CD6080033177E /* ReachabilitySwiftManager */ = {
+			isa = PBXGroup;
+			children = (
+				A73911AC229CD62F0033177E /* ReachabilitySwiftManager.swift */,
+			);
+			path = ReachabilitySwiftManager;
+			sourceTree = "<group>";
+		};
 		A73D7C662268A032002A4CE3 /* SwiftyStarRatingView */ = {
 			isa = PBXGroup;
 			children = (
@@ -3258,6 +3269,7 @@
 				"${BUILT_PRODUCTS_DIR}/Moya/Moya.framework",
 				"${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework",
 				"${BUILT_PRODUCTS_DIR}/PPBadgeViewSwift/PPBadgeViewSwift.framework",
+				"${BUILT_PRODUCTS_DIR}/ReachabilitySwift/Reachability.framework",
 				"${BUILT_PRODUCTS_DIR}/Realm/Realm.framework",
 				"${BUILT_PRODUCTS_DIR}/RealmSwift/RealmSwift.framework",
 				"${BUILT_PRODUCTS_DIR}/Result/Result.framework",
@@ -3286,6 +3298,7 @@
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Moya.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ObjectMapper.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PPBadgeViewSwift.framework",
+				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Reachability.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Realm.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RealmSwift.framework",
 				"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Result.framework",
@@ -3349,6 +3362,7 @@
 				A71AA51C227219EF008FF1A5 /* EditExpressAddressView.swift in Sources */,
 				BDAA40FB228E9CC300CF841D /* OrderApplyRefundNoteInfoCell.swift in Sources */,
 				A7CC751122715AE3003C4F38 /* MessageDetailesTimeView.swift in Sources */,
+				A73911AD229CD62F0033177E /* ReachabilitySwiftManager.swift in Sources */,
 				A7BB684F2268DCEC00AB07A2 /* SelfRecommendationViewController.swift in Sources */,
 				A7B4E7352281907A0012914A /* CMSModel.swift in Sources */,
 				A72A72BE22321DE000B21995 /* Extension+RxTimer.swift in Sources */,

+ 2 - 1
RainbowPlanet/RainbowPlanet/AppDelegate/AppDelegate+Window.swift

@@ -23,6 +23,8 @@ extension AppDelegate {
             /// 设置全局的navigation
             self?.setNavBarAppearence()
         }
+        // 获取默认配置
+        SwiftMoyaNetWorkServiceConfig.shared().configPickupNodeIndexApi { _ in }
         if (UserModel.shared().getModel()?.token) != nil && (DeliveryMethodTypeModel.shared().getModel()?.deliveryMethodType) != nil {
             /// 设置Tabbar
             /// 刷新token
@@ -39,7 +41,6 @@ extension AppDelegate {
 
         /// 引导页
         setGuidePageView()
-        
     }
     
     /// 设置Tabbar

+ 123 - 0
RainbowPlanet/RainbowPlanet/Manager/ReachabilitySwiftManager/ReachabilitySwiftManager.swift

@@ -0,0 +1,123 @@
+//
+//  ReachabilitySwiftManager.swift
+//  RainbowPlanet
+//
+//  Created by 南鑫林 on 2019/5/28.
+//  Copyright © 2019 RainbowPlanet. All rights reserved.
+//
+
+import UIKit
+import Reachability
+
+class ReachabilitySwiftManager: NSObject {
+    static let shared : ReachabilitySwiftManager = ReachabilitySwiftManager()
+    
+    public lazy var reachability: Reachability = {
+        let reachability = Reachability()!
+        return reachability
+    }()
+    
+    /// 初始化网络监听
+    public func initStartReachability() {
+        whenReachable()
+        whenUnreachable()
+        startNotifier()
+    }
+    
+    
+    /// 初始化网络监听需要他停止监听
+    public func initStartStopReachability() {
+        whenReachableStopNotifier()
+        whenUnreachableStopNotifier()
+        startNotifier()
+    }
+    
+    /// 监听到连接
+    private func whenReachable() {
+        reachability.whenReachable = { reachability in
+            if reachability.connection == .wifi {
+                NXLLog("Reachable via WiFi")
+            } else if reachability.connection == .cellular {
+                NXLLog("Reachable via Cellular")
+            }
+        }
+    }
+    
+    /// 监听到没有连接
+    private func whenUnreachable() {
+        reachability.whenUnreachable = { [weak self] _ in
+            self?.alert()
+            NXLLog("Not reachable")
+        }
+    }
+    
+    /// 监听到连接需要停止监听
+    private func whenReachableStopNotifier() {
+        reachability.whenReachable = { [weak self] reachability in
+            if reachability.connection == .wifi {
+                NXLLog("Reachable via WiFi")
+               
+            } else if reachability.connection == .cellular {
+                NXLLog("Reachable via Cellular")
+            }
+            self?.stopNotifier()
+        }
+    }
+    /// 监听到没有连接需要停止监听
+    private func whenUnreachableStopNotifier() {
+        reachability.whenUnreachable = { _ in
+            AlertSheetView.alert(title: "网络连接失败", detailTitle: "检测到网络权限可能未开启,您可以在\"设置\"中检查蜂窝移动网络", cancelTitle: "取消", sureTitle: "设置", cancelBlock: {[weak self] (popupView, index, str) in
+                self?.stopNotifier()
+                }, confirmBlock: { (popupView, index, str) in
+                    DispatchQueue.main.async(execute: {  [weak self] () -> Void in
+                        let url = URL(string: UIApplication.openSettingsURLString)
+                        if let url = url, UIApplication.shared.canOpenURL(url) {            if #available(iOS 10.0, *) {
+                            UIApplication.shared.open(url, options: [:],completionHandler: {
+                                [weak self] (success) in
+                                self?.stopNotifier()
+                            })
+                        }else {
+                            UIApplication.shared.openURL(url)
+                            self?.stopNotifier()
+                            }
+                            
+                        }
+                        
+                    })
+            })
+            NXLLog("Not reachable")
+        }
+    }
+    
+    /// 开始监听
+    private func startNotifier() {
+        do {
+            try reachability.startNotifier()
+        } catch {
+            startNotifier()
+            NXLLog("Unable to start notifier")
+        }
+    }
+    
+    
+    /// 停止监听
+    private func stopNotifier() {
+        reachability.stopNotifier()
+    }
+    
+    /// 弹框跳转设置页面
+    public func alert(){
+        AlertSheetView.alert(title: "网络连接失败", detailTitle: "检测到网络权限可能未开启\n您可以在\"设置>无线数据>WLAN或WLAN与蜂窝移动网\"开启一下吧", cancelTitle: "取消", sureTitle: "设置", cancelBlock:nil, confirmBlock: { (popupView, index, str) in
+                DispatchQueue.main.async(execute: {() -> Void in
+                    let url = URL(string: UIApplication.openSettingsURLString)
+                    if let url = url, UIApplication.shared.canOpenURL(url) {            if #available(iOS 10.0, *) {
+                        UIApplication.shared.open(url, options: [:],completionHandler: {(success) in})
+                        }else {
+                            UIApplication.shared.openURL(url)
+                        }
+                    }
+                })
+        })
+    }
+
+}

+ 6 - 1
RainbowPlanet/RainbowPlanet/Manager/UMManager/UMManager.swift

@@ -313,7 +313,12 @@ extension UMManager {
     ///
     /// - Parameter platformType: 平台
     func loginGetUserInfo(platformType: UMSocialPlatformType,callBack: @escaping (UMLoginModel) -> (Void)) {
-
+        
+        if ReachabilitySwiftManager.shared.reachability.connection == .none {
+             ReachabilitySwiftManager.shared.alert()
+            return
+        }
+        
         let isInstall = UMSocialManager.default()?.isInstall(platformType)
         if isInstall!  { //验证
             UMSocialManager.default().getUserInfo(with: platformType, currentViewController: nil) { result, error in

+ 0 - 2
RainbowPlanet/RainbowPlanet/Service/SwiftMoyaService/SwiftMoyaServiceApi/SwiftMoyaServiceConfig/SwiftMoyaNetWorkServiceConfig.swift

@@ -22,8 +22,6 @@ class SwiftMoyaNetWorkServiceConfig: NSObject {
     /// 数据回调
     typealias apiCallBack = (Any) -> (Void)
     
-
-    
     /// 前端config配置
     ///
     /// - Parameter completion: 回调

+ 2 - 2
RainbowPlanet/RainbowPlanet/Service/SwiftMoyaService/SwiftMoyaServiceManger/SwiftMoyaNetWorkManager/ApiMacro.swift

@@ -8,8 +8,8 @@
 
 import Foundation
 
-let kDevelopSever = false
-let kTestSever = true
+let kDevelopSever = true
+let kTestSever = false
 let kProductSever = false
 
 

+ 15 - 10
RainbowPlanet/RainbowPlanet/Service/SwiftMoyaService/SwiftMoyaServiceManger/SwiftMoyaNetWorkManager/SwiftMoyaNetWorkManager.swift

@@ -33,9 +33,7 @@ private let myEndpointClosure = { (target: MultiTarget) -> Endpoint in
         method: target.method,
         task: task,
         httpHeaderFields: target.headers
-    )
-    requestTimeOut = 10//每次请求都会调用endpointClosure 到这里设置超时时长 也可单独每个接口设置
-    
+    )    
     return endpoint
 }
 
@@ -85,6 +83,10 @@ private let provider = MoyaProvider<MultiTarget>(endpointClosure: myEndpointClos
 private var isNetworkConnect: Bool {
     get{
         let network = NetworkReachabilityManager()
+        if !(network?.isReachable ?? true) {
+            SwiftProgressHUD.shared().showError("网络链接失败,请检查网络")
+            ReachabilitySwiftManager.shared.alert()
+        }
         return network?.isReachable ?? true //无返回就默认网络已连接
     }
 }
@@ -129,9 +131,12 @@ public class SwiftMoyaNetWorkManager: NSObject {
     func request<T: BaseMappable>(_ type: T.Type ,target: MultiTarget,isCustomAlert:Bool = false,completion: @escaping successCallTBack) -> Void {
         //判断是否链接网络
         if !isNetworkConnect{
-             SwiftProgressHUD.shared().showError("网络链接失败,请检查网络")
+            if let falseCallback = self.falseCallback  {
+                falseCallback()
+            }
             return
         }
+        
 
         provider.rx
             .request(target)
@@ -167,7 +172,6 @@ public class SwiftMoyaNetWorkManager: NSObject {
     func requestArray<T: BaseMappable>(_ type: T.Type ,target: MultiTarget,isCustomAlert:Bool = false,completion: @escaping successCallArrayTback) -> Void {
         //判断是否链接网络
         if !isNetworkConnect{
-            SwiftProgressHUD.shared().showError("网络链接失败,请检查网络")
             if let falseCallback = self.falseCallback  {
                 falseCallback()
             }
@@ -254,7 +258,6 @@ public class SwiftMoyaNetWorkManager: NSObject {
     func request(target: MultiTarget,isCustomAlert:Bool = false,completion: @escaping successCallback) -> Void {
         //判断是否链接网络
         if !isNetworkConnect{
-            SwiftProgressHUD.shared().showText("网络链接失败,请检查网络")
             if let falseCallback = self.falseCallback  {
                 falseCallback()
             }
@@ -286,8 +289,9 @@ public class SwiftMoyaNetWorkManager: NSObject {
     func requestValue(target: MultiTarget,completion: @escaping successCallback) -> Void {
         //判断是否链接网络
         if !isNetworkConnect{
-            SwiftProgressHUD.shared().showText("网络链接失败,请检查网络")
-            
+            if let falseCallback = self.falseCallback  {
+                falseCallback()
+            }
             return
         }
         
@@ -316,8 +320,9 @@ public class SwiftMoyaNetWorkManager: NSObject {
     func requestArray(target: MultiTarget,completion: @escaping successCallArrayback) -> Void {
         //判断是否链接网络
         if !isNetworkConnect{
-            SwiftProgressHUD.shared().showText("网络链接失败,请检查网络")
-            
+            if let falseCallback = self.falseCallback  {
+                falseCallback()
+            }
             return
         }