iosswift4rx-swiftreactiverxalamofire

RxAlmofire pass parameters to requestJSON [:]


Following is method provided by RxAlamofire for making requestJSON request there is no method to pass parameters [String : String]

RxAlamofire.requestJSON(.get, url)
        .subscribe(onNext: { [weak self] (r, json) in
            if let jsonResult = JSON(json) as? JSON {
                if let foodMenuResult = MenuResult(jsonResult) as? MenuResult {
                    self?.delegate?.showMenu(menuResult: foodMenuResult)
                }
            }

            }, onError: {  [weak self] (error) in
                self?.delegate?.onError()
            },onCompleted: {})
        .disposed(by: disposeBag)

How to pass parameters to RxAlamofire requestJSON method


Solution

  • You need to construct the URL from URLComponents.

    var components = URLComponents(string: "https://www.example.com/path")!
    components.queryItems = [
        .init(name: "param1", value: "value1"),
        .init(name: "param2", value: "value2"),
    ]
    
    let url = components.url!
    

    The url above will be

    https://www.example.com/path?param1=value1&param2=value2
    

    The use of ! should not be problematic above as the data you are passing should be valid. Please refer to the documentation of these methods though to assess the requirement for proper nil handling.