如何向Almofire请求添加参数

时间:2015-10-09 12:22:11

标签: ios swift alamofire

免责声明:我是iOS编程新手,所以这个问题可能很简单。这不是一个棘手的问题!

我有一个使用Almofire发送HTTP请求的Swift项目。我想为每个请求的查询字符串添加一个参数。

所以,我想在每个请求中添加mykey=myval

  • EG:http://example.com/index -> http://example.com/index?mykey=myval
  • EG:http://example.com/index?key=val -> http://example.com/index?key=val&mykey=myval

我发现所有请求似乎都经过了

public func request(URLRequest: URLRequestConvertible) -> Request {
    return Manager.sharedInstance.request(URLRequest.URLRequest)
}

在名为Almofire.swift

的文件中

并通过

public func request(URLRequest: URLRequestConvertible) -> Request {
    var dataTask: NSURLSessionDataTask?
    dispatch_sync(queue) {
        dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
    }

    let request = Request(session: session, task: dataTask!)
    delegate[request.delegate.task] = request.delegate

    if startRequestsImmediately {
        request.resume()
    }

    return request
}

在一个名为Manager.swift的文件中,所以我假设我需要在这里添加一些代码。由于我缺乏斯威夫特知识,我花了几个小时进行实验,但没有快乐 - 只有例外。

有谁知道如何为所有请求添加参数?

3 个答案:

答案 0 :(得分:2)

您无需更改Alamofire代码中的任何内容。相反,您可以使用URLRequestConvertible协议将您的URL和参数封装在枚举中:

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
    }
}

然后您可以通过以下方式致电您的请求:

// 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
}

答案 1 :(得分:0)

简单请求 - >

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)
            }

    }
}

答案 2 :(得分:0)

我使用了路由请求, 您可以检查refreshToken方法

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
    }
}