Egle Matutyte Egle Matutyte - 4 years ago 147
Swift Question

Alamofire and SwiftyJSon get value outside request function

Hey I am new here and I am trying to get value from request outside the request function in VC, but I cant do that I get errors I tried few ways, but I keep getting different errors, now I get Type Any has no subscript members, could you help me how to get string from request and find an array and take a value from it.

I need to get value from Json strin in VC so I am trying this way:

let retur = Json()
retur.login(userName: userName.text!, password: password.text!) { (JSON) in

let json = JSON
let name = json["ubus_rpc_session"].stringValue


My request:

private func makeWebServiceCall (urlAddress: String, requestMethod: HTTPMethod, params:[String:Any], completion: @escaping (_ JSON : Any) -> ()) {

Alamofire.request(urlAddress, method: requestMethod, parameters: params, encoding: JSONEncoding.default).responseString { response in

switch response.result {
case .success:
if let jsonData = response.result.value {


case .failure( _):
if let data = {
let json = String(data: data, encoding: String.Encoding.utf8)
completion("Failure Response: \(json)")


Function which call request method:

public func login(userName: String, password: String, loginCompletion: @escaping (Any) -> ()) {
let loginrequest = JsonRequests.loginRequest(userName: userName, password: password)
makeWebServiceCall(urlAddress: URL, requestMethod: .post, params: loginrequest, completion: { (JSON : Any) in

enter image description here
enter image description here

Answer Source

You can't subscript with Any and after you converting JSON to [String:Any] if you are trying .stringValue with subscripting Dictionary then Dictionary doesn't have any property stringValue you are mixing two things here SwiftyJSON and Swift native type. I will access your JSON response this way.

First get clear about how you get value of ubus_rpc_session from your JSON response. You can't directly get value of ubus_rpc_session from your JSON response because it is inside the 2nd object in your result array,so to get the ubus_rpc_session try like this way.

retur.login(userName: userName.text!, password: password.text!) { (json) in
     if let dic = json as? [String:Any], let result = dic["result"] as? [Any], 
        let subDic = result.last as? [String:Any],
        let session = subDic["ubus_rpc_session"] as? String {


If you want to work with SwiftyJSON then you can get value of ubus_rpc_session this way.

retur.login(userName: userName.text!, password: password.text!) { (json) in

     let jsonDic = JSON(json) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download