Search code examples
swiftalamofire

Failing to make request to server using alamofire and DisabledTrustEvaluator


I am trying to get some data off a server that created I using asp.net core, however; when trying to get the data in my Swift iOS code it keeps on failing without any error showing. I have done all the TSL checks in my info.plist.

model.swift

    import Foundation

struct User: Decodable {
    let name:String
    let userEmail: String
    let firebaseId: String
    let userMode: Int
    let profileImg: String
    let loginType: Int?
}

userController.swift

    import UIKit
import ProgressHUD

class LoginViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        removeNavBar()

        
//        UserApiService.shared.makeGetAPICall(user:{users, error in
//         //   ProgressHUD.dismiss()
//            guard let users = users else {return}
//            print(users)
//            guard let errors = error else {return}
//            print(errors)
//        })
    }
    
    @IBAction func googleLogin(_ sender: Any) {
        ProgressHUD.animationType = .circleSpinFade
        ProgressHUD.show()
        UserApiService.init().makeGetAPICall(user: {users, error in
               ProgressHUD.dismiss()
               guard let users = users else {return}
               print(users)
               guard let errors = error else {return}
               print(errors)
           })
    
    }
    private func removeNavBar(){
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

apiService.swift

 import Foundation
import Alamofire

class UserApiService{
    
    static let shared =  UserApiService.init()
    
    let session: Session = {
        let manager = ServerTrustManager(allHostsMustBeEvaluated: false,evaluators: ["localhost:5001": DisabledTrustEvaluator()])
        let configuration = URLSessionConfiguration.af.default

        return Session(configuration: configuration, serverTrustManager: manager)
    }()

    //MARK:- GET
    func makeGetAPICall(user completionHandler: @escaping ([User]?,Error?) -> Void) {
        var urlComponent = URLComponents()
        urlComponent.scheme = "https"
        urlComponent.host = "localhost"
        urlComponent.port = 5001
        urlComponent.path = "/api/user"
        print(urlComponent.url!)
        guard let url = urlComponent.url else {
            return
        }
        
        session.request(url, method: .get).validate().responseDecodable(of: [User].self) {(response) in
            switch response.result{
            case .success:
                guard let users = response.value else {
                    return
                }
                print(users)
                completionHandler(users, nil)
                
            case .failure(let error):
                completionHandler(nil, error)
            }
        }
    }
}

info.plist

    <key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSIncludesSubdomains</key>
                <true/>
            </dict>
        </dict>
    </dict>
    <key>NSAllowsArbitraryLoadsForMedia</key>
    <true/>
    <key>NSAllowsLocalNetworking</key>
    <true/>
    <key>NSAllowsArbitraryLoadsInWebContent</key>
    <true/>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

I debugged it with breakpoints, and I am getting <unavailable; try printing with "VO" or "PO">. I'm having trouble understanding what that means and how I should resolve this.

Also, I have changed my info.plist and it looks like this, however; I am still getting the same issue

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoadsForMedia</key>
        <true/>
        <key>NSAllowsLocalNetworking</key>
        <true/>
        <key>NSAllowsArbitraryLoadsInWebContent</key>
        <true/>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

Solution

  • So I managed to fix my issue, Hooray!!!

    What I did was, I changed evaluators: ["localhost:5001": DisabledTrustEvaluator() to evaluators: ["localhost": DisabledTrustEvaluator()

    Also, when calling my method, I was referencing normally from a class but then after, I had to call it as a singleton, and then, HEY PRESTO, IT WORKED!

     @IBAction func googleLogin(_ sender: Any) {
        ProgressHUD.animationType = .circleSpinFade
        ProgressHUD.show()
        UserApiService.shared.makeGetAPICall(user: {users, error in
               ProgressHUD.dismiss()
               guard let users = users else {return}
               print(users)
               guard let errors = error else {return}
               print(errors)
           })
    
    }
    

    This link helped me figure out part of the reason for my issues https://github.com/Alamofire/Alamofire/issues/3336