2017-07-27 226 views
0

使用Alamofires ServerTrustPolicy.disableEvaluation這是我的會話管理器類如何迅速3

import UIKit 
import Alamofire 
import ObjectMapper 
import AlamofireObjectMapper 
import Reqres 


class Manager: SessionManager { 
    static let sharedInstance: Manager = Manager() 
    static let manager: Manager = { 
     let configuration = Reqres.defaultSessionConfiguration() 
     let manager = Manager(configuration: configuration) 

     return manager 
    }() 

    func getRequest(url:URL,param:Parameters,withSuccess success:@escaping (_ response: Dictionary<String, Any>) ->()){ 
     guard Utils.isInternetAvailable() else{ 
      Utils.showAlert(message: "Internet connection lost", action: { 

      }) 
      return 
     } 
     Utils.addHUD() 
     Alamofire.request(url, method: .get, parameters: param, encoding: URLEncoding.default).responseJSON { (response: 
      DataResponse<Any>) in 
      guard response.result.isSuccess else{ 
       Utils.hideHUD() 
       Utils.showAlert(message: (response.result.error?.localizedDescription)!, action: { 

       }) 
       return 
      } 
      Utils.hideHUD() 
      print(response.request!) // original URL request 
      print(response.response!) // HTTP URL response 
      print(response.data!)  // server data 
      print(response.result) // result of response serialization 
      success(response.result.value! as! Dictionary<String, Any>) 
     } 
    } 
} 

我必須做出請求到服務器的URL是沒有有效的SSL certificates.I HTTPS請求已經應用服務器策略這樣做,但仍然得到錯誤: 「此服務器的證書無效」

,我已經嘗試其他替代

class Manager: SessionManager { 
    static let manager: Manager = { 
     let configuration = Reqres.defaultSessionConfiguration() 
     let serverTrustPolicies: [String: ServerTrustPolicy] = ["192.168.1.28:8443": .DisableEvaluation] 
     let manager = Manager(configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)) 

     return manager 
    }() 
+0

你爲什麼要創建一個CustomServerTrustPolicyManager。您可以直接執行ServerTrustPolicyManager(策略:serverTrustPolicies)。任何特定的原因來創建一個自定義的? –

+0

我已經嘗試過,但沒有工作 –

+0

您是否還在plist中設置了App Transport安全設置? –

回答

1

試試這個,這似乎是爲我工作 -

extension SessionManager { 
static func getManager() -> SessionManager{ 

    let serverTrustPolicies: [String: ServerTrustPolicy] = [ 
     "192.168.1.28:8443": .disableEvaluation 
    ] 

    let configuration = Reqres.defaultSessionConfiguration() 
    configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders 

    return Alamofire.SessionManager(
     configuration: configuration, 
     serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) 
    ) 
} 

} 

,並使用此SessionManager執行以下操作 -

var manager: SessionManager? 
manager = SessionManager.getManager() 
manager?.request// Here is your request call. 
+0

在這種情況下,我的get請求方法請參閱我編輯的整個單例類我的問題顯示整個類 –

+0

我剛剛創建了SessionManager類的擴展。因此,您可以使用此默認會話managet而不是使用默認會話managet。剩下的代碼將保持不變,因此您目前正在執行此操作。我假設你的經理Singleton是你的網絡層抽象權的自定義類嗎?那你爲什麼從SessionManager中擴展它呢?理想情況下不應該。 –

+0

您的請求方法也可以保持原樣。你所要做的就是不用調用Alamofire.Request,而是調用我給經理的代碼?.request –

0

在如果任何一個需要在這裏是我的網絡類情況..

import UIKit 
import Alamofire 
import Reqres 

class Manager{ 
    static let sharedInstance: Manager = Manager() 
    static let manager:SessionManager = { 
     let configuration = Reqres.defaultSessionConfiguration() 
     let manager = SessionManager() 
     return manager 
    }() 

    // Call this function before each get/post request only if you have unsigned certificate for https request 
    func setByPass() { 
     let delegate: SessionDelegate = Manager.manager.delegate 
     delegate.sessionDidReceiveChallenge = { session, challenge in 
      var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling 
      var credential: URLCredential? 
      if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { 
       disposition = URLSession.AuthChallengeDisposition.useCredential 
       credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) 
      } else { 
       if challenge.previousFailureCount > 0 { 
        disposition = .cancelAuthenticationChallenge 
       } else { 
        credential = Manager.manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) 
        if credential != nil { 
         disposition = .useCredential 
        } 
       } 
      } 
      return (disposition, credential) 
     } 
    } 

    func getRequest(url:URL,param:Parameters,withSuccess success:@escaping (_ response: Dictionary<String, Any>) ->()){ 
     guard Utils.isInternetAvailable() else{ 
      Utils.showAlert(message: "Internet connection lost", action: { 

      }) 
      return 
     } 
     self.setByPass() 
     Utils.addHUD() 
     Manager.manager.request(url, method: .get, parameters: param, encoding: URLEncoding.default).responseJSON { (response: 
      DataResponse<Any>) in 
      guard response.result.isSuccess else{ 
       Utils.hideHUD() 
       Utils.showAlert(message: (response.result.error?.localizedDescription)!, action: { 

       }) 
       return 
      } 
      Utils.hideHUD() 
      print(response.request!) // original URL request 
      print(response.response!) // HTTP URL response 
      print(response.data!)  // server data 
      print(response.result) // result of response serialization 
      success(response.result.value! as! Dictionary<String, Any>) 
     } 
    } 

    func getRequestWithoutParam(url:URL,withSuccess success:@escaping (_ response: Dictionary<String, Any>) ->()){ 
     guard Utils.isInternetAvailable() else{ 
      Utils.showAlert(message: "Internet connection lost", action: { 

      }) 
      return 
     } 
    self.setByPass() 
    Utils.addHUD() 
    let headers = ["Content-Type":"Application/json"] 
    Manager.manager.request(url, encoding:JSONEncoding.default, headers: headers).responseJSON { (response: 
    DataResponse<Any>) in 
    guard response.result.isSuccess else{ 
     Utils.hideHUD() 
    Utils.showAlert(message: (response.result.error?.localizedDescription)!, action: { 

    }) 
    return 
    } 
     Utils.hideHUD() 
    print(response.request!) // original URL request 
    print(response.response!) // HTTP URL response 
    print(response.data!)  // server data 
    print(response.result) // result of response serialization 
    success(response.result.value! as! Dictionary<String, Any>) 
    } 
    } 



    func postRequest(url:URL,param:Parameters,withSuccess success:@escaping (_ response: Dictionary<String, Any>) ->()){ 
     guard Utils.isInternetAvailable() else{ 
      Utils.showAlert(message: "Internet connection lost", action: { 

      }) 
      return 
     } 
     self.setByPass() 
     Utils.addHUD() 
     let headers = ["Content-Type":"Application/json"] 
     Manager.manager.request(url, method: .post, parameters: param, encoding:JSONEncoding.default, headers: headers).responseJSON { (response: 
      DataResponse<Any>) in 
      guard response.result.isSuccess else{ 
       Utils.hideHUD() 
      Utils.showAlert(message: (response.result.error?.localizedDescription)!, action: { 

      }) 
      return 
     } 
      Utils.hideHUD() 
      print(response.request!) // original URL request 
      print(response.response!) // HTTP URL response 
      print(response.data!)  // server data 
      print(response.result) // result of response serialization 
      success(response.result.value! as! Dictionary<String, Any>) 
     } 
    } 

    func putRequest(url:URL,param:Parameters,withSuccess success:@escaping (_ response: Dictionary<String, Any>) ->()){ 
     guard Utils.isInternetAvailable() else{ 
      Utils.showAlert(message: "Internet connection lost", action: { 

      }) 
      return 
     } 
     self.setByPass() 
     Utils.addHUD() 
     let headers = ["Content-Type":"Application/json"] 
     Manager.manager.request(url, method: .put, parameters: param, encoding:JSONEncoding.default, headers: headers).responseJSON { (response: 
      DataResponse<Any>) in 
      guard response.result.isSuccess else{ 
       Utils.hideHUD() 
       Utils.showAlert(message: (response.result.error?.localizedDescription)!, action: { 

       }) 
       return 
      } 
      Utils.hideHUD() 
      print(response.request!) // original URL request 
      print(response.response!) // HTTP URL response 
      print(response.data!)  // server data 
      print(response.result) // result of response serialization 
      success(response.result.value! as! Dictionary<String, Any>) 
     } 
    } 
}