123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193 |
- //
- // SWNetRequest.swift
- // LiteraryHeaven
- //
- // Created by SanW on 2017/8/2.
- // Copyright © 2017年 ONON. All rights reserved.
- //
- import Alamofire
- import UIKit
- // 默认超时时间
- public let timeoutInterval: TimeInterval = 30
- // MARK: - 错误
- /// 错误
- public struct PQError: Error {
- public var msg: String? // 提示信息
- public var code: Int // 错误吗
- public init(msg: String?, code: Int = 0) {
- self.msg = msg
- self.code = code
- }
- public var localizedDescription: String {
- return msg ?? ""
- }
- }
- // MARK: - 网络请求
- /// 网络请求
- public class SWNetRequest: NSObject {
- // static let share = SWNetRequest()
- /// 回调方法
- public typealias completeHander = (_ jsonObject: Any?, _ error: PQError?, _ duration: TimeInterval?) -> Void
- static let sessionManager: Session? = {
- let configuration = URLSessionConfiguration.default
- configuration.timeoutIntervalForRequest = timeoutInterval
- return Session(configuration: configuration, delegate: SessionDelegate(), serverTrustManager: nil)
- }()
- static let reTrySessionManager: Session? = {
- let configuration = URLSessionConfiguration.default
- configuration.timeoutIntervalForRequest = 5
- return Session(configuration: configuration, delegate: SessionDelegate(), serverTrustManager: nil)
- }()
- /// get请求
- public class func getRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
- requestData(method: .get, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
- response(responseObject, error, timeline)
- }
- }
- /// post请求
- public class func postRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
- requestData(method: .post, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
- response(responseObject, error, timeline)
- }
- }
- // put请求
- public class func putRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
- requestData(method: .put, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
- response(responseObject, error, timeline)
- }
- }
- /// delete请求
- public class func deleteRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
- requestData(method: .delete, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
- response(responseObject, error, timeline)
- }
- }
- /// head请求
- public class func headRequestData(url: String, parames: [String: Any]?, encoding: ParameterEncoding = URLEncoding.default, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
- requestData(method: .head, encoding: encoding, url: url, parames: parames, timeoutInterval: timeoutInterval) { responseObject, error, timeline in
- response(responseObject, error, timeline)
- }
- }
- /// 网络请求
- fileprivate class func requestData(method: HTTPMethod, encoding: ParameterEncoding, url: String, parames: [String: Any]?, timeoutInterval: TimeInterval = timeoutInterval, response: @escaping completeHander) {
- if !bf_validURL(url: url) {
- response(nil, PQError(msg: "非法地址", code: 0), nil)
- return
- }
- debugPrint("网络请求-发起:url = \(url),parames = \(parames ?? [:])")
- AF.request(url, method: method, parameters: parames, encoding: encoding, headers: nil, requestModifier: { request in
- request.timeoutInterval = timeoutInterval
- }).validate().responseJSON { jsonResponse in
- switch jsonResponse.result {
- case .success:
- let jsonData: Any = try! JSONSerialization.jsonObject(with: jsonResponse.data!, options: JSONSerialization.ReadingOptions.mutableContainers)
- debugPrint("网络请求-成功:url = \(jsonResponse.request?.url?.absoluteString ?? ""),jsonData = \(jsonData)")
- response(jsonData, nil, jsonResponse.metrics?.taskInterval.duration)
- case .failure:
- let code: Int? = jsonResponse.response?.statusCode
- response(nil, PQError(msg: (code == -1009 || code == -1001) ? "网络不可用" : jsonResponse.error?.localizedDescription, code: code ?? 10001), jsonResponse.metrics?.taskInterval.duration)
- debugPrint("网络请求-失败:url = \(jsonResponse.request?.url?.absoluteString ?? ""),error = \(String(describing: jsonResponse.error))")
- }
- }
- }
- /// 取消网络请求
- /// - Parameter url: 某一个地址,空则取消所有
- /// - Returns: <#description#>
- public class func cancelTask(url: String?) {
- sessionManager?.session.getAllTasks(completionHandler: { tasks in
- tasks.forEach { task in
- if task.currentRequest?.url?.absoluteString == url {
- task.cancel()
- }
- }
- })
- }
- public class func bf_validURL(url: String?) -> Bool {
- if url == nil || (url?.count ?? 0) <= 4 || (!(url?.hasPrefix("http") ?? false) && !(url?.hasPrefix("https") ?? false)) {
- return false
- }
- return true
- }
- /// 获取网络状态
- /// - Returns: <#description#>
- public class func networkStatusDescription() -> String {
- let status = NetworkReachabilityManager(host: "www.baidu.com")?.status
- var statusStr: String!
- switch status {
- case .unknown:
- statusStr = "NETWORK_UNKNOWN"
- case .notReachable:
- statusStr = "NETWORK_NO"
- case .reachable(.cellular):
- statusStr = "4G/5G"
- case .reachable(.ethernetOrWiFi):
- statusStr = "Wi-Fi"
- default:
- statusStr = "NETWORK_UNKNOWN"
- }
- return statusStr
- }
- /// 判断是否有网
- /// - Returns: <#description#>
- public class func isNetReachabled() -> Bool {
- return NetworkReachabilityManager(host: "www.baidu.com")?.status == .reachable(.cellular) || NetworkReachabilityManager(host: "www.baidu.com")?.status == .reachable(.ethernetOrWiFi)
- }
- /// 获取ip地址
- /// - Returns: <#description#>
- public class func ipAddressDescription() -> String {
- var addresses = [String]()
- var ifaddr: UnsafeMutablePointer<ifaddrs>?
- if getifaddrs(&ifaddr) == 0 {
- var ptr = ifaddr
- while ptr != nil {
- let flags = Int32(ptr!.pointee.ifa_flags)
- var addr = ptr!.pointee.ifa_addr.pointee
- if (flags & (IFF_UP | IFF_RUNNING | IFF_LOOPBACK)) == (IFF_UP | IFF_RUNNING) {
- if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
- var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
- if getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0 {
- if let address = String(validatingUTF8: hostname) {
- addresses.append(address)
- }
- }
- }
- }
- ptr = ptr!.pointee.ifa_next
- }
- freeifaddrs(ifaddr)
- }
- return addresses.first ?? "0.0.0.0"
- }
- // 将原始的url编码为合法的url
- public class func bf_urlEncoded(url: String) -> String {
- let encodeUrlString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
- return encodeUrlString ?? ""
- }
- // 将编码后的url转换回原始的url
- public class func bf_urlDecoded(url: String) -> String {
- return url.removingPercentEncoding ?? ""
- }
- }
|