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
print(JSON)
let json = JSON
let name = json["ubus_rpc_session"].stringValue
print(name)
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 {
completion(jsonData)
}
case .failure( _):
if let data = response.data {
let json = String(data: data, encoding: String.Encoding.utf8)
completion("Failure Response: \(json)")
}
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
loginCompletion(JSON)
})
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
print(json)
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 {
print(session)
}
}
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
print(json)
let jsonDic = JSON(json)
print(jsonDic["result"][1]["ubus_rpc_session"].stringValue)
}