Alamofire receive and parse an array of strings swift - ios

I getting the result as an array of strings like this
["India","America","Australia","China","Russia"]
And I'm using Alamofire to get the response using code. There's no error, but I got the result as null. Please help in parsing this.
sessionManager?.request(strURL, method: method, parameters: params, encoding: encoding , headers: headers).responseJSON { (response) in
switch response.result {
case .success:
let resJson = JSON(response.result.value!)
success(resJson)
break
case .failure(let error):
failure(error as NSError)
break
}
}

Try this:
if let responseData = response.result.value{
let responsevalue = responseData as? [String]
}

For anyone looking for another derived answer, just put this chunk of code after Alamofire.request(...):
.responseJSON(completionHandler: { (response) in
switch response.result{
case .success(let value):
// Here is your array of String
let arrayOfStrings = value as? [String]
case .failure(let error):
// Some code when error happens...
print(error.localizedDescription)
}
})

This solution using SwiftyJSON:
.responseJSON(completionHandler: { (response) in
switch response.result{
case .failure(let error):
print(error.localizedDescription)
case .success(let res):
let json = JSON(res)
let res = json["result"]
var models = [String]()
if let models1 = company["models"].array {
for model in models1 {
guard let mod = model.string else { return }
models.append(mod)
}
}
}
})

Related

"'isSuccess' is inaccessible due to 'internal' protection level", AlamoFire not working like before

Im using alamoFire on swift but i came across this problem: "isSuccess' is inaccessible due to 'internal' protection level".
I have tried this and i have also tried this,
here is my code:
AF.request(jsonURL, method: .get, parameters: parameters).responseJSON { (response) in
if response.result.isSuccess { //problem is here
print("Got the info")
print(response)
let flowerJSON : JSON = JSON(response.result.value!)
let list = flowerJSON["..."]["..."]["..."].stringValue
print(list)
}
}
result is now of the built-in Result enum type, which means you can do pattern matching on it. Your code can be rewritten as:
AF.request("", method: .get, parameters: [:]).responseJSON { (response) in
if case .success(let value) = response.result {
print("Got the info")
print(response)
let flowerJSON : JSON = JSON(value)
...
}
}
Use a switch statement if you want the error case as well:
switch response.result {
case .success(let value):
// ...
case .failure(let error):
// ...
}

Polyline in google map for IOS swift

I have been working in google poly line functionality. I have initialised the URL and I have used alamofire request. Everything with the URL is working fine but I could not draw the line and it was stating like invalid URL.
I have attached the code which I have tried.
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(pickupcordinates)&destination=\(dropCoordinates)&mode=driving&key=AIzaSyDJUX9uBiZivQGlAu1KTUC1kcmaiAnI270"
Alamofire.request(urlString,method: .get, parameters: nil,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
invalidURL(url: "https://maps.googleapis.com/maps/api/directions/json?origin=13.03589205752495,80.25411217280107&destination=13.0277895999, 80.22673778239999&mode=driving&key=AIzaSyDJUX9uBiZivQGlAu1KTUC1kcmaiAnI270")
The above is my console response error
I want to draw a poly line from my source to destination.
I am using this way give it a try. May help you.
func drawPath(source: CLLocationCoordinate2D, destination: CLLocationCoordinate2D){
let orgin = "\(source.latitude),\(source.longitude)"
let destin = "\(destination.latitude),\(destination.longitude)"
let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(orgin)&destination=\(destin)&mode=driving"
Alamofire.request(url).responseJSON { response in
switch response.result {
case .success:
let json = JSON(data: response.data!)
let routes = json["routes"].arrayValue
print(response)
break
case .failure(let error):
print(error)
}
}
}

How to solve the Alamofire to display the data

I have the URL to display the data and it is working in the urlsession. But I need Alamofire so I have done it in the Alamofire. But in that it is showing as:
Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(404)
How to fix the problem?
This is the code in the Alamofire:
Alamofire.request("http://www.example.com").validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON{ response in
let status = response.response?.statusCode
print("STATUS \(status)")
print(response)
switch response.result {
case .success(let data):
print("success",data)
let result = response.result
print(result)
if let wholedata = result.value as? [String:Any]{
print(wholedata)
if let data = wholedata["data"] as? Array<[String:Any]>{
print(data)
print(response)
for question in data {
let typebutton = question["button_type"] as? String
print(typebutton)
self.type = typebutton
let options = question["options"] as! [String]
// self.dataListArray1 = [options]
self.tableArray.append(options)
// self.savedataforoptions(completion: <#T##(NH_OptionslistDataSourceModel?) -> ()#>)
self.no = options.count
}
print(self.tableArray)
let newDataSource:QuestionDataSourceModel = QuestionDataSourceModel(array: data)
completion(newDataSource)
}
}
case .failure(let encodingError ):
print(encodingError)
// if response.response?.statusCode == 404{
print(encodingError.localizedDescription)
completion(nil)
}
}
}

Error Handling with Alamofire in Swift 2

Hi I am practising some code, my code is fine with case .Success(let value): and it is displaying alert but will case .Failure(let error): display alert with The 4xx class of status code?
Alamofire.request(.GET, URL).responseJSON { (response) -> Void in
if let value = response.result.value {
let json = JSON(value)
switch response.result {
case .Success(let value):
let name = json["name"].string
if let nothing = name {
self.alertMessage(message: "Name not Found")
} else {
self.alertMessage(message: "Name Found")
}
case .Failure(let error):
self.alertMessage(message: "Error 4xx / 5xx")
}
You can use validate to check status codes:
Alamofire.request(.GET, URL)
.validate() // or, if you just want to check status codes, validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .Success(let value):
let json = JSON(value)
if let name = json["name"].string {
self.alertMessage(message: "Name Found: \(name)")
} else {
self.alertMessage(message: "Name not Found")
}
case .Failure(let error):
self.alertMessage(message: "Error 4xx / 5xx: \(error)")
}
}
Or, in Swift 3:
Alamofire.request(url)
.validate() // or, if you just want to check status codes, validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
if let name = json["name"].string {
self.alertMessage(message: "Name Found: \(name)")
} else {
self.alertMessage(message: "Name not Found")
}
case .failure(let error):
self.alertMessage(message: "Error 4xx / 5xx: \(error)")
}
}
Also note that you should probably move the examination of response.result.value to inside the Success section (or just grab the value passed there). Also, the determination of whether name is found was backwards.

How to make a good pattern to control multiple requests dependency by using Alamofire? Such as request2 need request1's response

I use Alamofire to send multiple requests at the same time. But the request A need request B's response named token. I will give a example :
var token = "111111111111"
let URLString1 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString1, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http1: \(JSON)")
token = "22222222222"
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
//I want to wait for request1's response and get the new token value.
let URLString2 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString2, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http2: \(JSON)")
print("token: \(token)")
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
I don't want to put request2 in request1's success.
So now my solution is: I give a variable named tokenChange.I have a array to store all the request that need the token. When the token is changed , I send them one by one from the array. But this solution is not elegant.
So is there a good pattern to control this ?
I find this method dispatch_semaphore_signal.It can solve my problem. So any other way ?
var token = "111111"
let group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in
let semaphore = dispatch_semaphore_create(0)
//token is 111111
let URLString = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http1: \(JSON)--class:")
token = "222222"
print("\n")
dispatch_semaphore_signal(semaphore)
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
//token is 222222
let URLString2 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString2, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http2: \(JSON)--class:")
print("\n")
print ("token is:\(token)")
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
//token is 2222222
let URLString3 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString3, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
// token = (JSON["args"]!!["value"]) as! String
print("http3: \(JSON)--class:")
print("\n")
print ("token is:\(token)")
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
}
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in
NSLog("finish");
}
you need to execute the second url string inside the first request because the response will came in background thread so your code will be like this:
var token = "111111111111"
let URLString1 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString1, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http1: \(JSON)")
token = "22222222222"
case .Failure(let error):
print("Request failed with error: \(error)")
}
let URLString2 = "http://httpbin.org/get?token=\(token)"
Alamofire.request(.GET, URLString2, parameters: nil, encoding:.JSON).responseJSON { response in
switch response.result {
case .Success(let JSON):
print("http2: \(JSON)")
print("token: \(token)")
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
}

Resources