Alamofire iOS13 - swift

I want to update my code in the past when I used swift 2 or 3. I am stuck where I want to use Alamofire but the way to use it changed and I don't know how to use it anymore. Can anybody update this part of the code and explain a little bit? Thank you.
This is the original code.
Alamofire.request(.POST, url)
.response{ (request, response, data, error) in
let xml = SWXMLHash.parse(data!)
let sunsetTime = xml["result"]["rise_and_set"]["sunset_hm"].element?.text
self.sunsetTimeLabel.text = sunsetTime
self.getDateFromString(sunsetTime,year: comp.year,month: comp.month,day: comp.day)
if (error != nil) {
print(error)
}
}
this is the code I was writing.
AF.request(url, method: .post).responseJSON { (responseData) in
let xml = SWXMLHash.parse(responseData as Data)
let sunsetTime = xml["result"]["rise_and_set"]["sunset_hm"].element?.text
self.sunsetTimeLabel.text = sunsetTime
There is an error saying "Cannot convert value of type 'AFDataResponse' (aka 'DataResponse') to type 'Data' in coercion"

Your first code snippet is Alamofire 3 syntax. I infer from the second code snippet that you are now using Alamofire 5.
There are a few issues:
You are calling responseJSON (which you’d only use if your response was JSON, not XML). Use response or, better, responseData.
The response object passed to this closure is not a Data, itself. In the case of responseData method, it is a AFDataResponse object, which has a data property (which is a Data?). You have to extract the Data object from this AFDataResponse, either by unwrapping the contents of the data property, or from the result (see next point).
You should probably check for success or failure and extract the Data from the response.result object.
So, pulling this together, you end up with something like:
AF.request(url, method: .post).responseData { response in
switch response.result {
case .failure(let error):
print(error)
case .success(let data):
let xml = SWXMLHash.parse(data)
...
}
}

Related

Swift program never enters CompletionHandler for a dataTask

I am in the process of implementing a REST API with Swift. Of course, part of this API is using HTTP requests to retrieve and send data.
Full disclosure, I am inexperienced with Swift and am using this as a learning project to get my feet wet, so to speak. But it's turned into much more of a difficult project than I anticipated.
In implementing the first get method, I have (finally) gotten rid of all the compilation errors. However, when I call the function which utilizes the URLRequest, URLSession, dataTask, etc, it is never entered.
Upon debugging the program, I can watch the program execution reach the CompletionHandler, and skip over it right to "task.resume()."
A similar construction works in a Swift Playground, but does not work in the actual project proper.
So far I have tried a few things, namely making the function access a class instance variable, in hopes that that would force it to execute. But it does not.
I think the issue may be dealing with synchronicity, and perhaps I need to use a Semaphore, but I want to make sure I'm not missing anything obvious first.
import Foundation
/**
A class to wrap all GET and POST requests, to avoid the necessity of repeatedly writing request code in each API method.
*/
class BasicRequest {
private var url: URL
private var header: [String: String]
private var responseType: String
private var jsonResponse: Any?
init(url: URL, header: [String: String], responseType: String) {
self.url = url
self.header = header
self.responseType = responseType
} //END INIT
public func requestJSON() -> Any {
// Create the URLRequest object, and fill the header with the header fields as provided.
var urlRequest = URLRequest(url: self.url)
for (value, key) in self.header {
urlRequest.addValue(value, forHTTPHeaderField: key)
}
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
print("Entered the completion handler")
if error != nil {
return
}
guard let httpResponse = response as? HTTPURLResponse, 200 == httpResponse.statusCode else {
print("HTTP Request unsuccessful")
return
}
guard let mime = response?.mimeType, mime == "application/json" else {
print("Not a JSON response")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print(json)
self.jsonResponse = json
} catch {
print("Could not transform to JSON")
return
}
}
task.resume()
return "Function has returned"
} //END REQUESTJSON
}
The expected result would be returning a JSON object, however that does not seem to be the case.
With respect to error messages, I get none. The only log I get in the debugger is the boilerplate "process exited with code 0."
To be truthful, I'm at a loss with what is causing this not to work.
It appears you're writing this in a command-line app. In that case the program is terminating before the URLRequest completes.
I think the issue may be dealing with synchronicity, and perhaps I need to use a Semaphore, but I want to make sure I'm not missing anything obvious first.
Exactly.
The typical tool in Swift is DispatchGroup, which is just a higher-level kind of semaphore. Call dispatchGroup.enter() before starting the request, and all dispatchGroup.leave() at the end of the completion handler. In your calling code, include dispatchGroup.wait() to wait for it. (If that's not clear, I can add code for it, but there are also a lot of SO answers you can find that will demonstrate it.)

How to get Image (not url or NSData )from server using Alamofire

I am trying to get image from server using Alamofire. It is working in postman ref:attachement
Below is my code for reference:
let headers = ["Authorization" : APITOKEN,"Content_Type" : CONTENT_TYPEVAL]
Alamofire.request(urlString!, method: .get, parameters: nil, encoding: URLEncoding.default, headers:headers ).responseJSON { (response) in
switch response.result {
case .success(let origObject):
debugPrint(origObject)
if let object = origObject as? Dictionary<String,AnyObject>
{
}
completion(.failure(Ya3ClientError.serverUnknownError))
case .failure(let e):
debugPrint("error:\(e.localizedDescription)")
}
Getting error "JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."
Any help how to solve this issue.
Instead of using .responseJson, you can try using .responseData to get a Data object and create the image using UIImage(data:)
Take a look at this
You can create a UIImage from a Data object, which you get from the response with Alamofire. However, without seeing your JSON response I cannot help with the exact code. If the response only contains the image as its data, then you can use
Alamofire.request(.GET, "https://myUrl/myPicture.png").response { (request, response, data, error) in
myImageView.image = UIImage(data: data)
}
You can also have a look at the Alamofire Image library.

Alamofire multiple requests iteration

I have four different requests in my application, three of them requires one call only and the last requires from 1 - 10.
All works fine until the last request when I´m iterating through my data and making the calls. This is my code in Class1:
var data = ...
var points = ...
// I create a new group
let getPointGroup = dispatch_group_create()
// I iterate through my data
for d in data{
// I enter the group
dispatch_group_enter(getPointGroup)
dataService.getPoints(d.point), success: { points -> Void in
points.append(points)
// I leave the group so that I go to the next iteration
dispatch_group_leave(getPointGroup)
}
}
Alamofire request looks like this in Class2:
let headers = [
"Authorization": "Bearer \(token)",
"Content-Type": "application/x-www-form-urlencoded"
]
Alamofire.request(.GET, url, headers:headers)
.responseJSON { response in
switch response.result {
case .Success:
let json = JSON(data: response.data!)
print(json)
success(json)
case .Failure(let error):
print(error)
}
}
But I never hit the GET request, if I remove the iteration completely and just call the Alamofire request once it works perfectly.
Any ideas of how to solve the Alamofire iteration request?
Edit
Not really a duplicate, I have the snippets below in the different classes and the example does not really solve my issue
If this is not running, you could be deadlocking if you use dispatch_group_wait on the main thread, thereby blocking that thread, and preventing Alamofire from running any of its completion handlers (which also require the main thread). This is solved (assuming you are, indeed, using dispatch_group_wait), by replacing that with dispatch_group_notify.
Thus:
let group = dispatch_group_create()
for d in data {
// I enter the group
dispatch_group_enter(group)
dataService.getPoints(d.point)) { additionalPoints, error in
defer { dispatch_group_leave(group) }
guard let let additionalPoints = additionalPoints else {
print(error)
return
}
points.append(additionalPoints)
}
}
dispatch_group_notify(group, dispatch_get_main_queue()) {
// go to the next iteration here
}
Where:
func getPoints(point: WhateverThisIs, completionHandler: (JSON?, NSError?) -> ()) {
let headers = [
"Authorization": "Bearer \(token)"
]
Alamofire.request(.GET, url, headers: headers)
.responseJSON { response in
switch response.result {
case .Success:
let json = JSON(data: response.data!)
completionHandler(json, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
}
Now, I don't know what your various parameter types were, so I was left to guess, so don't get lost in that. But the key is that (a) you should make sure that all paths within your Alamofire method will call the completion handler; and (b) the caller should use dispatch_group_notify rather than dispatch_group_wait, avoiding the blocking of any threads.
Note, in order to make the completion handler callable even if the network request failed, I had to make the parameter to that closure optional. And while I was there, I added an optional error parameter, too.
A few unrelated changes included in the above sample:
I'd suggest using a different variable name for the parameter of your closure. The points.append(points) in your original code snippet suggests some confusion between your points array and the points that is passed back in the closure.
You don't have to set the Content-Type header, as Alamofire does that for you.
I didn't change it above, but it is inefficient to use responseJSON (which uses NSJSONSerialization to parse the JSON) and then use SwiftyJSON to parse the raw data with NSJSONSerialization again. Personally, I don't bother with SwiftyJSON, but if you want to use it, I'd suggest use Alamofire's response method rather responseJSON. There's no point in parsing the JSON twice.

Alamofire HTTP sent twice SWIFT

every one,
I'm having an issue with Alamofire 3.0, when I post data, it seems the data is being sent twice.
I looked up on the web, found that a bug about special caratères was fixed, but I still get the error.
Anyone has an idea. I'm using a parameter in the header called X-Authorization.
Here is an extract of the code i'm using:
static func postData (url: String,token: String,params :Dictionary<String,AnyObject>){
print("POSTINGGGGGG")
Alamofire.request(.POST, url, parameters: params,headers: ["X-Authorization": token])
.responseJSON { response in
switch response.result {
case .Success(let data): break
//let resultJSON = JSON(data).dictionaryValue
// print(data)
case .Failure(let error):
print(error)
}
}
}
Thank you in advance,
Morgan

returning JSON as string in Swift using Swifty

I'm using Alamofire and Swifty and am able to make my API POST and get data back successfully. However, I'm unsure of how to get the data that I'm printing and be able to return it as a string.
In the below, the println's print fine. However, when I use the same json["ticket"] as the return, I get 'JSON' is not convertible to 'Void'
let encoding = Alamofire.ParameterEncoding.URL
// Fetch Request
Alamofire.request(.POST, "http://api.co/?v=1", parameters: bodyParameters, encoding: encoding)
.validate(statusCode: 200..<300)
.responseJSON{(request, response, data, error) in
if (error == nil)
{
var json = JSON(data!)
println(json["ticket"])
return json["TOKEN"]
}
else
{
println("HTTP HTTP Request failed: \(error)")
}
The problem is you are returning "Dictionary" from the closure, while Closure return type is Void. So, you need to get that in a completion handler.
For better idea, you can take a look at this solution. Hope it helps!