ava ava - 1 month ago 11
iOS Question

Alamofire HTTP Request

i want to send http post request with Alamofire. there is my code for send request in sampleViewController and get response from request. there is a problem i got response from server but when I want to print response in sample view controller my response always return nil. how can check response after get response from server?

public class PersistencyManager {

func SendPostHttpRequest(baseURL: String, parameter: [String:Any?], content: String) -> Any? {

let url = URL(string: Constant.baseURL)
var result : Any?

var urlRequest = URLRequest(url: url!)
urlRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.setURLEncodedFormData(parameters: parameter)

Alamofire.request(urlRequest).responseJSON { response in

switch response.result {

case .success :


if let JSON = response.result.value as? [String:Any] {
print("JSON: \(JSON)")

result = JSON
}



case .failure :

result = nil

}
}
default:
break
}

return result

}
}


class sampleViewController: UIViewController {

@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var centerVIew: UIView!
override func viewDidLoad() {
super.viewDidLoad()



}

@IBAction func SendRequest(_ sender: Any) {

let parameters = ["key":Constant.serverKey,"userid":"0" ,"action":"vitrin","step":"list","sort": nil,"filter":nil,"start":String("5"),"end":String("8")]

Constant.libraryAPI.parameters = parameters
Constant.libraryAPI.requestContent = "String"



let response = Constant.libraryAPI.GetAPIResponse(parameters: parameters, contentType: "String")
print(response) //this line call before get response from server
}
}

Answer Source

You need a closure but calling the closure in the callback of Alamofire when is success or failed, then you can check if error in your closure is nil, then all os ok and you can use the JSON

   func SendPostHttpRequest(baseURL: String, parameter: [String:Any?], content: String, closure:@escaping ((_ success:JSON?,_ error:NSError?) -> Void)) {

    let url = URL(string: Constant.baseURL)
    var result : Any?

    var urlRequest = URLRequest(url: url!)
    urlRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
    urlRequest.setURLEncodedFormData(parameters: parameter)

    Alamofire.request(urlRequest).responseJSON { response in

        switch response.result {

        case .success :

            if let JSON = response.result.value as? [String:Any] {
                print("JSON: \(JSON)")

                closure(JSON,nil)
            }else{
                closure(nil,NSError(domain: "Error in JSON parsing", code: 995, userInfo: nil))
            }

        case .failure :
            closure(nil,response.result.error)
        }

    }

}

Hope this helps