How to solve the Alamofire to display the data - ios

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)
}
}
}

Related

How to grab the Optional response in swift?

I want to grab the ImagePath from the response.
Response look like this
The response for print(response.result.value)
I am using Alamofire POST request to get the data from Api. Here is my code:
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if response.result.error != nil {
}
let Response = response.result.value
print("Response JSON:- \(String(describing: Response))")
let mydata = (String(describing : Response))
let jSon = JSON(mydata)
print("New :- \(String(describing: jSon["data"]["ImagePath"].stringValue))")
print("New :- \(jSon["data"]["ImagePath"])")
print(jSon["data"]["ImagePath"])
print(jSon["status"].stringValue)
if let data = response.result.value {
let json = JSON(data)
//print(json)
}
}
Try optional handling this way
if let Response = response.result.value as? [String : Any],
myData = Response["data"] as? [String : Any],
imgPath = myData["ImagePath"] {
print("ImagePath --> ", imgPath)
}

How to get key Value from post webservice API and fetch that to tableview

I got data from API in this format but the problem is that I want to get all questions and answers from the API but whenever I try to get the value by using the key value it returns nil value and application crashes
this is my api data looks like after getting into a dictionary
here's my code for getting data from API
Alamofire.request(url, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: header ).responseJSON {
response in
switch response.result {
case .success:
print(response)
if let result = response.result.value {
print(result)
let responseDict = result as! [String : Any]
print(responseDict)
let data = responseDict["Result"] as! [Any]
print(data)
}
break
case .failure(let error):
print(error)
}
}
You can try
if let res = responseDict["Result"] as? [[String:Any]] {
for item in res {
if let ques = item["Question"] as? String {
print(ques)
}
if let op = item["Options"] as? [[String:Any]] {
print(op)
}
}
}

Alamofire receive and parse an array of strings swift

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)
}
}
}
})

Alamofire AFError when work with Flickr API

I am using Alamofire to get JSON data from flickr API.
Here if the function, which prepares an array of URLs from the response:
func urlTolinkslist (tag: String) {
print (viewSearchBar.text)
let url = "https://api.flickr.com/services/feeds/photos_public.gne?tags=\(tag.replacingOccurrences(of: " ", with: "%20"))&format=json&nojsoncallback=1"
Alamofire.request(url).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
let items = json["items"]
self.linksList = []
for i in 0..<items.count {
let item = items[i]
let media = item["media"]
var link = String(describing: media["m"])
self.linksList.append(link)
}
print("count: \(self.linksList.count)")
self.viewCollectionView.reloadData()
case .failure(let error):
print(error)
}
}
}
"tag" in the API URL is the parameter I get from a search bar. In most of the cases it works fine, but in some cases I get:
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence around character 1029." UserInfo={NSDebugDescription=Invalid escape sequence around character 1029.}))
I think there may be some extra characters, but I don't know how to fix it.
Let Alamofire encode for you the parameters:
func urlTolinkslist (tag: String) {
let url = "https://api.flickr.com/services/feeds/photos_public.gne"
var dict = [String:AnyObject]()
dict["tags"] = tag
dict["format"] = "json"
dict["nojsoncallback"] = 1
Alamofire.request(.GET, url, parameters: dict, encoding: .URLEncodedInURL, headers: nil).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
let items = json["items"]
self.linksList = []
for i in 0..<items.count {
let item = items[i]
let media = item["media"]
var link = String(describing: media["m"])
self.linksList.append(link)
}
print("count: \(self.linksList.count)")
self.viewCollectionView.reloadData()
case .failure(let error):
print(error)
}
}
}

Alamofire4 trouble with JSONResponseSerializer & HTTPURLResponse Swift 3.0

Since I updated Alamofire I get the errors: Type Request has no member JSONResponseSerializer and cannot call value of non-function type HTTPURLResponse
I have already switched Response to DataResponse but I still get the error.
Code:
extension Alamofire.Request {
func responseUserEventsArray(_ completionHandler: #escaping (DataResponse<UserEventsWrapper>) -> Void) -> Self {
let responseSerializer = DataResponseSerializer<UserEventsWrapper> { request, response, data, error in
guard error == nil else
{
return .failure(error!)
}
guard let responseData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .allowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)
switch result {
case .Success(let value):
let json = JSON(value)
let wrapper = UserEventsWrapper()
wrapper.next = json["eventhistory"]["next_page_url"].stringValue
wrapper.previous = json["eventhistory"]["prev_page_url"].stringValue
wrapper.count = json["eventhistory"]["total"].intValue
var allUserEvents:Array = Array<UserEvents>()
print(json)
let results = json["eventhistory"]["data"]
print(results)
for jsonAds in results
{
print(jsonAds.1)
let adsData = UserEvents(json: jsonAds.1, id: Int(jsonAds.0))
allUserEvents.append(adsData)
}
wrapper.usereventsitems = allUserEvents
return .success(wrapper)
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
}
}
EDITED
Change
Request.JSONResponseSerializer to DataRequest.jsonResponseSerializer
extension Alamofire.Request to extension Alamofire.DataRequest – Mat0
.success and .failure - FranMowinckel

Resources