Quellcode durchsuchen

网络工具类封装

半月迎风coder vor 5 Jahren
Ursprung
Commit
8941cfa6ba

+ 12 - 8
SolarStation.xcodeproj/project.pbxproj

@@ -7,6 +7,9 @@
 	objects = {
 
 /* Begin PBXBuildFile section */
+		83495F4824E910200094F0BB /* NetWorkConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83495F4724E910200094F0BB /* NetWorkConfig.swift */; };
+		83495F4A24E910640094F0BB /* NetWorkBaseApi.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83495F4924E910640094F0BB /* NetWorkBaseApi.swift */; };
+		83495F4C24E9113A0094F0BB /* NetWorkManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83495F4B24E9113A0094F0BB /* NetWorkManager.swift */; };
 		834BBA6D248504FE00A2FD16 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 834BBA6C248504FE00A2FD16 /* AppDelegate.swift */; };
 		834BBA6F248504FE00A2FD16 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 834BBA6E248504FE00A2FD16 /* SceneDelegate.swift */; };
 		834BBA71248504FE00A2FD16 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 834BBA70248504FE00A2FD16 /* ViewController.swift */; };
@@ -15,8 +18,6 @@
 		834BBA792485050300A2FD16 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 834BBA772485050300A2FD16 /* LaunchScreen.storyboard */; };
 		834BBA842485050300A2FD16 /* SolarStationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 834BBA832485050300A2FD16 /* SolarStationTests.swift */; };
 		834BBA8F2485050300A2FD16 /* SolarStationUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 834BBA8E2485050300A2FD16 /* SolarStationUITests.swift */; };
-		83F918DE24A33C7100252670 /* NetworkManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83F918DD24A33C7100252670 /* NetworkManager.swift */; };
-		83F918E024A3775000252670 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83F918DF24A3775000252670 /* Request.swift */; };
 		83F918F224A47EEF00252670 /* SSLoginVCtr.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83F918EF24A47EEF00252670 /* SSLoginVCtr.swift */; };
 		83F918F324A47EEF00252670 /* 1-登录_iphonex@3x.png in Resources */ = {isa = PBXBuildFile; fileRef = 83F918F024A47EEF00252670 /* 1-登录_iphonex@3x.png */; };
 		83F918F424A47EEF00252670 /* SSLoginVCtr.xib in Resources */ = {isa = PBXBuildFile; fileRef = 83F918F124A47EEF00252670 /* SSLoginVCtr.xib */; };
@@ -44,6 +45,9 @@
 
 /* Begin PBXFileReference section */
 		4E366BFCAA7F428E6F0624CA /* Pods_SolarStation.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SolarStation.framework; sourceTree = BUILT_PRODUCTS_DIR; };
+		83495F4724E910200094F0BB /* NetWorkConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetWorkConfig.swift; sourceTree = "<group>"; };
+		83495F4924E910640094F0BB /* NetWorkBaseApi.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetWorkBaseApi.swift; sourceTree = "<group>"; };
+		83495F4B24E9113A0094F0BB /* NetWorkManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetWorkManager.swift; sourceTree = "<group>"; };
 		834BBA69248504FE00A2FD16 /* SolarStation.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SolarStation.app; sourceTree = BUILT_PRODUCTS_DIR; };
 		834BBA6C248504FE00A2FD16 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
 		834BBA6E248504FE00A2FD16 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
@@ -58,8 +62,6 @@
 		834BBA8A2485050300A2FD16 /* SolarStationUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SolarStationUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
 		834BBA8E2485050300A2FD16 /* SolarStationUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SolarStationUITests.swift; sourceTree = "<group>"; };
 		834BBA902485050300A2FD16 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
-		83F918DD24A33C7100252670 /* NetworkManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkManager.swift; sourceTree = "<group>"; };
-		83F918DF24A3775000252670 /* Request.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = "<group>"; };
 		83F918EF24A47EEF00252670 /* SSLoginVCtr.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SSLoginVCtr.swift; sourceTree = "<group>"; };
 		83F918F024A47EEF00252670 /* 1-登录_iphonex@3x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "1-登录_iphonex@3x.png"; sourceTree = "<group>"; };
 		83F918F124A47EEF00252670 /* SSLoginVCtr.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = SSLoginVCtr.xib; sourceTree = "<group>"; };
@@ -180,8 +182,9 @@
 		834C8BE724960F3E0088B9DB /* Network */ = {
 			isa = PBXGroup;
 			children = (
-				83F918DD24A33C7100252670 /* NetworkManager.swift */,
-				83F918DF24A3775000252670 /* Request.swift */,
+				83495F4724E910200094F0BB /* NetWorkConfig.swift */,
+				83495F4924E910640094F0BB /* NetWorkBaseApi.swift */,
+				83495F4B24E9113A0094F0BB /* NetWorkManager.swift */,
 			);
 			name = Network;
 			sourceTree = "<group>";
@@ -422,13 +425,14 @@
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
-				83F918DE24A33C7100252670 /* NetworkManager.swift in Sources */,
 				834BBA71248504FE00A2FD16 /* ViewController.swift in Sources */,
 				83F918F824A480B800252670 /* SolarStationConstant.swift in Sources */,
 				83F918F224A47EEF00252670 /* SSLoginVCtr.swift in Sources */,
+				83495F4824E910200094F0BB /* NetWorkConfig.swift in Sources */,
 				83F918F724A480B800252670 /* AppShare.swift in Sources */,
-				83F918E024A3775000252670 /* Request.swift in Sources */,
+				83495F4C24E9113A0094F0BB /* NetWorkManager.swift in Sources */,
 				834BBA6D248504FE00A2FD16 /* AppDelegate.swift in Sources */,
+				83495F4A24E910640094F0BB /* NetWorkBaseApi.swift in Sources */,
 				834BBA6F248504FE00A2FD16 /* SceneDelegate.swift in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;

BIN
SolarStation.xcworkspace/xcuserdata/weclouds.xcuserdatad/UserInterfaceState.xcuserstate


+ 108 - 0
SolarStation/NetWorkBaseApi.swift

@@ -0,0 +1,108 @@
+//
+//  NetWorkBaseApi.swift
+//  SolarStation
+//
+//  Created by weclouds on 2020/8/16.
+//  Copyright © 2020 weclouds. All rights reserved.
+//
+/*
+ 创建继承自Target的类MyTestRequest,代码如下
+  //  MyTestRequest.swift
+ //  XCX_test
+ //
+ //  Created by 王成杰 on 2020/3/25.
+ //  Copyright © 2020 wangcj. All rights reserved.
+ //
+
+
+ import Foundation
+
+
+ class MyDataEngine: Target {
+
+     class func changePhoneNumberInfo(withControl: AnyObject, orderNum: String, mobileNum: String, complate: @escaping complateClosure ){
+     
+         callRequestWithControl(control: withControl as! NSObject, path: "/order/detail", params: ["order_number":orderNum ,"mobile":mobileNum], type: .GET, onComplete: complate)
+     }
+
+ }
+
+ 三、具体业务中的调用如下
+ private func getMyData(){
+     
+     MyDataEngine.changePhoneNumberInfo(withControl: self, orderNum: "111", mobileNum: "18543434354") { (data, error) -> (Void) in
+         print(data as Any)
+     }
+ }
+
+
+ */
+import Foundation
+import Moya
+
+enum RequestType {
+    case GET
+    case POST
+    case DELETE
+}
+
+private var tempPath: String?
+private var tempParam: [String:Any]?
+private var requestType: RequestType?
+
+class Target {
+
+    typealias complateClosure = (Dictionary<String, Any>?, Error?) -> (Void)
+
+    class func callRequestWithControl(control: NSObject, path: String, params: [String: Any] , type: RequestType, onComplete: @escaping complateClosure )  {
+        tempPath = path
+        tempParam = params
+        requestType = type
+        NetWorkManager.shared.request(target:Target()) { (data, error) -> (Void) in
+             onComplete(data,error)
+        }
+    }
+
+}
+
+extension Target: TargetType {
+
+    var baseURL: URL {
+        return URL.init(string: BaseUrl)!
+    }
+
+    var path: String {
+        return tempPath ?? ""
+    }
+
+    var method: Moya.Method {
+    
+        switch requestType {
+        case .GET:
+            return .get
+        case .POST:
+            return .post
+        case .DELETE:
+            return .delete
+        case .none:
+            return .get
+        }
+    }
+
+    var sampleData: Data {
+        return "".data(using: String.Encoding.utf8)!
+    }
+
+    var task: Task {
+        return   .requestParameters(parameters: tempParam ?? [:], encoding: URLEncoding.default)
+    }
+
+    var headers: [String : String]? {
+    
+        //公共参数
+        return ["api_version" : "1.0.0",]
+    }
+
+}
+
+

+ 30 - 0
SolarStation/NetWorkConfig.swift

@@ -0,0 +1,30 @@
+//
+//  NetWorkConfig.swift
+//  SolarStation
+//
+//  Created by weclouds on 2020/8/16.
+//  Copyright © 2020 weclouds. All rights reserved.
+//
+
+import Foundation
+import UIKit
+
+//baseUrl
+let BaseUrl = "https://baidu.com"
+
+//是否打印请求信息
+let NetWorkLog = true
+
+// 数据返回状态key
+let NetWorkResCodeKey = "code"
+
+// 数据成功的状态码code
+let NetWorkSuccessCode = 0
+
+// 数据消息提示key
+let NetWorkResMessageKey = "msg"
+
+
+class NetWorkConfig: NSObject {
+
+}

+ 163 - 0
SolarStation/NetWorkManager.swift

@@ -0,0 +1,163 @@
+//
+//  NetWorkManager.swift
+//  SolarStation
+//
+//  Created by weclouds on 2020/8/16.
+//  Copyright © 2020 weclouds. All rights reserved.
+//
+
+import Foundation
+import Moya
+import Alamofire
+
+//超时时间
+private var requestTimeOut: Double = 15
+struct NetWorkManager {
+     //MARK: - Closures
+        typealias complateClosure = (Dictionary<String, Any>?, Error?) -> (Void)
+
+
+        //MARK: - getters setters
+        private let endpointClosure = { (target: Target) -> Endpoint in
+            let url = target.baseURL.absoluteString + target.path
+            var endpoint = Endpoint(
+                url: url,
+                sampleResponseClosure: { .networkResponse(200, target.sampleData) },
+                method: target.method,
+                task: target.task,
+                httpHeaderFields: target.headers
+            )
+            return endpoint
+        }
+
+    private let requestClosure = { (endpoint: Endpoint, closure: MoyaProvider.RequestResultClosure) in
+        do {
+            var request = try endpoint.urlRequest()
+            request.timeoutInterval = requestTimeOut
+
+            if NetWorkLog {
+                           
+                if let requestData = request.httpBody {
+                    print("\(request.url!)"+"\n"+"\(request.httpMethod ?? "")"+"发送参数"+"\(String(data: request.httpBody!, encoding: String.Encoding.utf8) ?? "")")
+                }else{
+                    print("\(request.url!)"+"\(String(describing: request.httpMethod))")
+                }
+            }
+            closure(.success(request))
+            
+        } catch {
+            closure(.failure(MoyaError.underlying(error, nil)))
+        }
+    }
+
+   private let networkPlugin = NetworkActivityPlugin.init { (changeType, targetType) in
+       switch(changeType){
+       case .began:
+           print("开始请求")
+       case .ended:
+           print("请求结束")
+       }
+   }
+
+  //MARK:- life
+   static let shared = NetWorkManager()
+  private init() {}
+    
+    //MARK: - public methods
+
+    //取消所有请求
+    func cancelAllRequest() {
+
+        Alamofire.Session.default.session.getTasksWithCompletionHandler {
+            (sessionDataTask, uploadData, downloadData) in
+            sessionDataTask.forEach { $0.cancel() }
+            uploadData.forEach { $0.cancel() }
+            downloadData.forEach { $0.cancel() }
+        }
+    }
+
+    //取消指定URL的请求
+    func cancelRequest(url: String){
+        Alamofire.Session.default.session.getTasksWithCompletionHandler {
+            (sessionDataTask, uploadData, downloadData) in
+            sessionDataTask.forEach {
+                if ($0.originalRequest?.url?.absoluteString == url) {
+                    $0.cancel()
+                }
+            }
+        }
+    }
+
+    //网络状态判断
+    func currentNetReachability()  {
+        let manager = NetworkReachabilityManager()
+        manager?.startListening(onQueue: .main, onUpdatePerforming: { (status) in
+            var statusStr: String?
+                       switch status {
+                       case .unknown:
+                           statusStr = "未识别的网络"
+                           break
+                       case .notReachable:
+                           statusStr = "不可用的网络(未连接)"
+                           //toast
+                           return
+                       case .reachable:
+                        //蜂窝网络
+                           if (manager?.isReachableOnCellular)! {
+                               statusStr = "2G,3G,4G...的网络"
+                           } else if (manager?.isReachableOnEthernetOrWiFi)! {
+                               statusStr = "wifi的网络"
+                           }
+                               break
+                           }
+                           debugPrint(statusStr as Any)
+          })
+        }
+
+    //MARK: - request
+    func request(target: Target, completion: @escaping complateClosure) {
+        //判断网络状态
+        currentNetReachability()
+        
+        let provider = MoyaProvider(endpointClosure: endpointClosure, requestClosure: requestClosure, plugins: [networkPlugin], trackInflights: false)
+        
+        provider.request(target) { (result) in
+            
+            switch result {
+                
+            case let .success(response):
+                do {
+                    //转JSON
+                    let responseDict = try JSONSerialization.jsonObject(with: response.data)
+                    guard let dic = responseDict as? Dictionary<String, Any> else {
+                        debugPrint("不是json数据")
+                        return
+                    }
+
+                    if let code = dic[NetWorkResCodeKey] as? Int, code == NetWorkSuccessCode {
+                        completion(dic,nil )
+                        
+                    }else {
+                        let message = dic[NetWorkResMessageKey] as? String ?? "数据错误"
+                        debugPrint(message)
+                        //aleart
+                       
+                    }
+                } catch {
+                    
+                    debugPrint("数据转字典失败")
+                }
+            case let .failure(error):
+                
+                if let errorDescription = error.errorDescription {
+                    completion(nil, error)
+                    debugPrint("网络请求失败:\(errorDescription)")
+                }else {
+                    //网络连接失败
+                    debugPrint("网络连接失败")
+                }
+            }
+        }
+    }
+
+}

+ 0 - 75
SolarStation/NetworkManager.swift

@@ -1,75 +0,0 @@
-//
-//  NetworkManager.swift
-//  SolarStation
-//
-//  Created by weclouds on 2020/6/24.
-//  Copyright © 2020 weclouds. All rights reserved.
-//
-
-import Foundation
-import Moya
-
-
-
-private struct Target :TargetType {
-    
-    init(request:Request) {
-        self.request = request
-    }
-    var request :Request
-    var baseURL: URL{
-        return URL(string: request.baseURL)!
-    }
-    
-    var path: String{
-        return request.path
-    }
-    
-    var method: Moya.Method{
-        return request.method == .post ? .post : .get
-    }
-    
-    var sampleData: Data = "".data(using: .utf8)!
-    
-    var task: Task{
-        return .requestParameters(parameters: request.parameters, encoding: URLEncoding.default)
-    }
-    
-    var headers: [String : String]?{
-        return ["Content-Type":"application/x-www-form-urlencoded"]
-    }
-    
-
-}
-class NetworkManager {
-    static let shared = NetworkManager("")
-   
-    var baseURL = ""
-    
-    init(_ baseURL:String = "") {
-        self.baseURL = baseURL
-    }
-    
-    func post(path:String, params:[String:Any]? ,result:@escaping ((Result<Data,Error>)->())) {
-        let request = Request(method: .post, baseURL: baseURL, path: path, paramters: params)
-        let target = Target(request: request)
-        self.request(target: target, result: result)
-    }
-    
-    func get(path:String, params:[String:Any]? ,result:@escaping ((Result<Data,Error>)->())) {
-        let request = Request(method: .get, baseURL: baseURL, path: path, paramters: params)
-        let target = Target(request: request)
-        self.request(target: target, result: result)
-    }
-    
-   private func request(target: Target,result :@escaping ((Result<Data,Error>)->()))  {
-    MoyaProvider<Target>().request(target) { (res) in
-        switch res {
-          case .success(let a):
-            result(.success(a.data))
-          case .failure(let error):
-            result(.failure(error))
-        }
-    }
-    }
-}

+ 0 - 27
SolarStation/Request.swift

@@ -1,27 +0,0 @@
-//
-//  Request.swift
-//  SolarStation
-//
-//  Created by weclouds on 2020/6/24.
-//  Copyright © 2020 weclouds. All rights reserved.
-//
-
-import Foundation
-
-enum RequestMethod {
-    case post
-    case get
-}
-///请求对象
-struct Request {
-    var method:RequestMethod
-    var baseURL:String
-    var path :String
-    var parameters :[String:Any]
-    init(method:RequestMethod = .post, baseURL : String = "",path : String,paramters:[String:Any]?) {
-        self.method = method
-        self.baseURL = baseURL
-        self.path = path
-        self.parameters = paramters ?? [:]
-    }
-}