Swift 3 alamofire swiftyjson subscript - ios

I don't know why my code doesn't work, my result is always nil.
I integrated alamofire and swiftyjson this is my code:
let urlString = "myurl"
let params: Parameters = [
"accessProvider": AccessProvider,
"inputToken": AccessToken
]
Alamofire.request(urlString, method: .post, parameters: params, encoding: URLEncoding.httpBody)
.responseJSON { response in
if let responseObject = response.result.value {
print("JSON: \(responseObject)")
let json = JSON(responseObject)
let path: [JSONSubscriptType] = ["user","id"]
let name = json[path].string
print("AAAAA")
print(name)
}
}
I can read the first part of user but the second one with id is always nil.
this is the response json:
{
"responseCode": 0,
"responseDescription": "OK",
"user": "{"id":"MAIL",
"nickname":"MYNAME",
"level":"U",
"status":"A",
"sex":null,
"ageGroup":null,
"address":null,
"latitude":null,
"longitude":null,
"creation_timestamp":"2017-05-10 18:40:21",
"notification":"1",
"last_login":"2017-05-11 18:32:07",
"mobilePreference":null,
"sport":null,
"spot":null,
"token":"LONGTOKENID"}"
}

Thank you vadian,
i solved the question with your indication,
if anyone have the same problem you can solve like this:
//Initialize the first json:
let json = JSON(responseObject)
//Extract the second Json to String
let path: [JSONSubscriptType] = ["user"]
let name = json[path].string
//Initialize the second json from string
if let dataFromString = name?.data(using: .utf8, allowLossyConversion: false)
let jsonuser = JSON(data: dataFromString)
//Access to the data
Thank you all,
Have nice day.

Related

how tobuild url request with get method using alamofire

I am not aware of building api with dynamic values.I have an api and from that, i want to get pluscode by sending url request with latitude, longitude and email to base url.My requirement is sending request in get method with lat,long and email values and getting pluscode from response.Can anyone help me to build this url.
lat = locValue.latitude
long = locValue.longitude
email = abcdefg#gmail.com
//base url
var pluscodeurl = "https://plus.codes/api?address="
let postParameters = ["address":lat+long ,"email":"mahithaa.angadi#gmail.com"] as [String : Any]
Alamofire.request(pluscodeurl, method: .get, encoding: URLEncoding.default, headers: nil).responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(_):
break
}
}
Here is the snippet you can write it
let lat = "19.0760"
let long = "72.8777"
let email = "abc#test.com"
let ApiURL = "https://plus.codes/api?address=\(lat),\(long)&email=\(email)"
Alamofire.request(ApiURL).responseJSON { response in
print("Result: \(response.result)")
if let json = response.result.value {
print("JSON: \(json)")
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
}
You can write your url in the below format:
let email = "abc#gmail.com"
let pluscodeurl = "https://plus.codes/api?address=\(lat),\(long)&email=\(email)"

Object reference not set to an instance of an object in iOS

When i am calling api with Alamofire from iOS getting error -
Object reference not set to an instance of an object
All other apis are working fine. Don't know it is from backend or not.
I debug it and check log with po command, but all parameters are going with request.
Can anyone suggest a solution ?
Any quick help will be appreciated.
Thanks
Code is given below:
let strToken: String = (USER_DEFAULT.value(forKey: "token") as? String)!
let strQuerystring = "token=" + strToken
let parameters: [String: String] = ["FirstName": txtFirstName.text!, "LastName":txtLastName.text!,"Gender":txtGender.text!,"DOB":strDate,"RelationId":strMemberID]
callPostApi(fileName: postAddMember + strQuerystring, parameters: parameters) { responseObject, errorResponse in
if(errorResponse == nil)
{
if let json = responseObject as? NSDictionary
{
let strStatus: Bool = json.value(forKey: "Status") as! Bool
let strMessage: String = json.value(forKey: "Message") as! String
if(strStatus == true)
{
forAlert(strMessage)
_ = self.navigationController?.popViewController(animated: true)
}
else
{
forAlert(strMessage)
}
}
else
{
forAlert("noResponseMessage".localized)
}
}
else
{
forAlert("noResponseMessage".localized)
}
SKActivityIndicator.dismiss()
}
}
The response object is not json, you will need to serialize it first before assigning the values to their respective variables.
something like this :
guard let dictionary = try? JSONSerialization.jsonObject(with:responseObject!,options: []) as! [String: AnyObject] else { return }
Hope that works.
You need to conform URLRequest with your parameters in body as Data
and create the request as following :
let auth = "Bearer"+token // or your Authorization type
let url = URL.init(string:urlString)
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(auth, forHTTPHeaderField: "Authorization")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters)
Alamofire.request(request)
.responseJSON { response in
// Handling your data
}
try this and hope that help you .
you can see :
How to post nested json by SwiftyJson and Alamofire?
see also : Using manager.request with POST
You don't need to serialize the parameters. From Alamofire Docs parameters must be of type Parameters
let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
In your case import Alamofire and then declare parameters like this and do not serialize it.:
let parameters: Parameters = [
"FirstName": txtFirstName.text!,
"LastName":txtLastName.text!,
"Gender":txtGender.text!,
"DOB":strDate,
"RelationId":strMemberID
]

Request to Alamofire

I need to send a request to the server like this
[{
"Case":"add",
"Table":"user",
"Field":["Email","Password"],
"Value":["a","a"],
"Duplicate":["Email"],
"SecureEncrpt":"Password",
"SecureDecrpt":"Password"
}]
and I'm using alamofire for the network process, and im using request structure like this
let loginparas = [
"Case": "add",
"Table":"user",
"Field":["Email","Password"],
"Value":[details,pass],
"Duplicate":["Email"],
"SecureEncrpt":"",
"SecureDecrpt":""
] as AnyObject
let parameters = loginparas as! Parameters
How can I get exactly like that format?
let loginparas = [
"Case": "add",
"Table":"user",
"Field":["Email","Password"],
"Value":[details,pass],
"Duplicate":["Email"],
"SecureEncrpt":"",
"SecureDecrpt":""
] as [String:Any]
Alamofire.request( url , method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers ).responseJSON { response in
if response.result.isSuccess {
guard let json = response.result.value as? NSArray else { return }
for j in json {
let jsonValur = j as? [String:Any]
let case = jsonValue["Case"] as? String
...
...
...
}
}
}

Postman Response OK, but on Alamofire return failure on Swift 3

I used GoogleMap Direction API to draw multiple location's route. I use postman to check response status, and I can check 200 OK. but problem is when I use Alamofire, response is Failure!
when I draw from origin to destination, response is ok.(always)
but if I add additional location, Alamofire return is failure.
Someone has same problem and to solve it?
below is my code. Thanx!
originAddress = locationInfoList[0]
destinationAddress = locationInfoList.last
var wayPointUrl:String = ""
var waypoint = locationInfoList.dropFirst()
waypoint = waypoint.dropLast()
for coordinate in waypoint {
print("~~~~")
let wayPoint = "|\(coordinate.latitude),\(coordinate.longitude)"
wayPointUrl.append(wayPoint)
print("~XXXXXXX~~~")
print(wayPointUrl)
print("XXXXXXX")
}
directionURL = "https://maps.googleapis.com/maps/api/directions/json?" +
"origin=\(originAddress.latitude),\(originAddress.longitude)&destination=\(destinationAddress.latitude),\(destinationAddress.longitude)&waypoints=optimize:true\(wayPointUrl)" +
"&key=apikey"
print("VVVVVVV")
print(directionURL)
print("VVVVVVVV")
}
Alamofire.request(directionURL, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
print(response)
if let JSON = response.result.value {
print(JSON)
let mapResponse: [String: AnyObject] = JSON as! [String : AnyObject]
let routesArray = (mapResponse["routes"] as? Array) ?? []
let routes = (routesArray.first as? Dictionary<String, AnyObject>) ?? [:]
let overviewPolyline = (routes["overview_polyline"] as? Dictionary<String,AnyObject>) ?? [:]
let polypoints = (overviewPolyline["points"] as? String) ?? ""
let line = polypoints
self.addPolyLine(encodedString: line)
}
}
}
It seems that you are sending the parameters in the URL and using JSON encoding. Change JSONEncoding.default to URLEncoding.defaultfor the encoding parameter of Alamofire request.
Also from the Google Map API Docs, It says as follows. So I believe, URL encoding will solve your issue.
Each waypoint can be either a place name, address, or comma-separated latitude/longitude coordinates. Strings should be URL-escaped, so waypoints such as "Berlin,Germany|Paris,France" should be converted to Berlin%2CGermany%7CParis%2CFrance.

How to successfully pass string array as parameter alamofire

I have an endpoint that accepts a string array as parameter but I can't get it working with alamofire.
I test my endpoint with postman and it works fine, even in the browser, but with alamofire it fails and just returns the whole thing (as if I didn't put any parameter).
func getQuotes(String url){
//THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX
let stringArray : [String] = ["4250_XSAU", "Test"]
let getQuoteParameters : Parameters = [
//"internal_symbols": stockInternalSymbols
"internal_symbols" : stringArray
]
print("attempting to get quotes on utility queue")
Alamofire.request(url, parameters: getQuoteParameters).responseJSON{ response in
print(response)
/* if (response.result.value != nil){
let jsonResponse = JSON(response.result.value!)
print(jsonResponse)
}
*/
}
}
Am I doing something wrong? When I go to url + "?internal_symbols=["4250_XSAU","Test"] on my browser, or postman, it works just fine.
I also tried setting my "getQuoteParamaters" variable as
let getQuoteParameters : Parameters = [
"internal_symbols" : ["4250_XSAU", "Test"]
]
but it doesn't work neither... it should be the same thing.
Just to clarify, this request ignores completely my parameters, when it should send the array to my backend.
You can simply pass your string array in converting it into a JSON format.Like in the sample code given below:
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = ["06786984572365", "06644857247565", "06649998782227"]
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
switch response.result {
case .failure(let error):
print(error)
if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
print(responseString)
}
case .success(let responseObject):
print(responseObject)
}
}
My solution in Swift 3:
let text: [String] = ["location.branches.longitude", "location.branches.latitude"]
let params: Parameters = [
"_source": text
]
Try by add encoding standard in your request, like JSONEncoding.default
func getQuotes(String url){
//THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX
let stringArray : [String] = ["4250_XSAU", "Test"]
let getQuoteParameters : Parameters = [
//"internal_symbols": stockInternalSymbols
"internal_symbols" : stringArray
]
print("attempting to get quotes on utility queue")
Alamofire.request(url, method: .post, parameters: getQuoteParameters, encoding: JSONEncoding.default).responseJSON{ response in
print(response)
/* if (response.result.value != nil){
let jsonResponse = JSON(response.result.value!)
print(jsonResponse)
}
*/
}
Thanks.

Resources