How to add parameter to Almofire request

后端 未结 3 848
别那么骄傲
别那么骄傲 2021-01-01 07:17

Disclaimer: I\'m new to iOS programming, so this question is probably as simple as it looks. It\'s not a trick question!

I\'ve a Swift project that uses Almofire to

相关标签:
3条回答
  • 2021-01-01 07:56

    Simple request ->

    func someFunction()
    {
        Alamofire.request(.GET, "apiName", parameters:["Key":"Value"])
            .response { request, response, data, error in
                if error == nil {
                    print(request)
                    print(response)
                }
                else {
                    //Display Error Message
                    print(error)
                }
    
        }
    }
    
    0 讨论(0)
  • 2021-01-01 07:59

    You don't need to change anything in Alamofire's code. Instead you can use the URLRequestConvertible protocol to encapsulate your URLs and parameter in an enum:

    enum Router: URLRequestConvertible {
        static let baseURLString = "https://example.com" // define your base URL here
        static var defaultParams = ["myKey": "myValue"] // set the default params here
    
        // define a case for every request you need
        case Index
        case Endpoint1(param: String)
        case Endpoint2(param1: String, param2: String)
    
        var URLRequest: NSMutableURLRequest {
            let result: (path: String, parameters: [String: AnyObject]) = {
                // set the path and params for each request
                switch self {
                case .Index:
                    return ("/index", Router.defaultParams)
                case .Endpoint1(let param):
                    var params = Router.defaultParams
                    params.updateValue(param, forKey: "key")
                    return ("/endpoint", params)
                case .Endpoint2(let param1, let param2):
                    var params = Router.defaultParams
                    params.updateValue(param1, forKey: "key1")
                    params.updateValue(param2, forKey: "key2")
                    return ("/endpoint2", params)
                }
            }()
    
            // create the URL and the request
            let URL = NSURL(string: Router.baseURLString)!
            let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(result.path))
            let encoding = Alamofire.ParameterEncoding.URL
    
            return encoding.encode(URLRequest, parameters: result.parameters).0
        }
    }
    

    Then you can call your requests in the following matter:

    // sends a request to 'https://example.com/index?myKey=myValue'
    Alamofire.request(Router.Index).response { (request, urlResponse, data, error) -> Void in
        // handle response
    }
    
    // sends a request to 'https://example.com/endpoint?key=value&myKey=myValue'
    Alamofire.request(Router.Endpoint1(param: "value")).response { (request, urlResponse, data, error) -> Void in
        // handle response
    }
    
    // sends a request to 'https://example.com/endpoint2?key1=value1&key2=value2&myKey=myValue'
    Alamofire.request(Router.Endpoint2(param1: "value1", param2: "value2")).response { (request, urlResponse, data, error) -> Void in
        // handle response
    }
    
    0 讨论(0)
  • 2021-01-01 08:08

    I used the Routing Request, You can check the refreshToken method

    enum UserRouter: URLRequestConvertible {
    
        case loginUser(parameters: Parameters)
        case logoutUser(query: String)
        case refreshToken(parameters: Parameters)
    
        static let baseURLString = Constants.baseURL
    
        var method: HTTPMethod {
            switch self {
            case .loginUser:
                return .post
    
            case .logoutUser:
                return .post
    
            case .refreshToken:
                return .get
            }
        }
    
        var path: String {
            switch self {
            case .logoutUser:
                return "logout"
    
            case .loginUser:
                return "login"
    
            case .refreshToken:
                return "token/refresh"
    
            }
        }
    
        // MARK: URLRequestConvertible
        func asURLRequest() throws -> URLRequest {
            let url = try UserRouter.baseURLString.asURL()
    
            var urlRequest = URLRequest(url: url.appendingPathComponent(path))
            urlRequest.httpMethod = method.rawValue
    
            switch self {
            case .refreshToken(let parameters):
                urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
            case .loginUser(let parameters):
                urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
    
            default:
                break
            }
    
            return urlRequest
        }
    }
    
    0 讨论(0)
提交回复
热议问题