Making multiple requests with Alamofire depending on array of chunks - swift

I'm struggling with making badge requests with Alamofire and I need help.
I have some ids and with them I need to struct parameters (Dictionary String) and send a GET request with Alamofire. Everything is fine, but I need to cover the case when ids are above 200, because when they are more than 200, API returns 414 code status (too long URL). So when ids are more than 200 they are separated in chunks. With each chunk I'm making a new request to API. The problem is that I return only the first 200 ids when I call my method. Here is an example:
func request (_ idsDict: [String: [String]], _ idSchema: String, _ completion: #escaping Result<SomeModel, Error>) -> Void {
let chunks = transformEntitiesIdsToChunks(idsDict)
let decoder = JSONDecoder()
chunks.forEach {chunk in
let parameters = constructQueryParams(idsDict, chunk, idSchema, apiKey, clientId)
AF.request(baseURL, parameters: parameters).response { response in
switch response.result {
case .success(let data):
// some error handling for decoding and no data
completion(.success(data.data))
case .failure(let error):
return completion(.failure(error.localizedDescription))
}
}
}
}
// Method wraps AF request in a continuation block and makes sure that the closure from request method returned data or throwed error.
// That way fetching from API becomes async/await and can be used in do/try/catch block.
func getIdsEntities (_ idsDict: [String: [String]], _ idSchema: String) async throws -> [SomeModel] {
return try await withUnsafeThrowingContinuation { continuation in
request(idsDict, idSchema) { result in
switch result {
case .success(let data):
continuation.resume(returning: data)
return
case .failure(let error):
continuation.resume(throwing: error)
return
}
}
}
}
I have tried with recursive functions and with DispatchGroup but none of them worked. Any help will be appriciated. Thank you in advance.

Thanks to Larme's comment I was able to find my mistake. When making request to API I was passing the decoded response to the completion closure. To fix this I had to declare an array of model let responses:[SomeModel] = [] and append the decoded result to it. I used let group = DispatchGroup() so I can wait the requests to execute and have my final array of results and then I used group.notify(queue: .main, execute: {completion(.success(responses))}) to return to the main queue and have my array of completed fetched data. This is now how my code looks like:
private func request (_ idsDict: [String: [String]], _ idSchema: String, _ completion: #escaping APIListResponseClosure<SomeModel>) -> Void {
var responses: [SomeModel] = []
let group = DispatchGroup()
let chunks = transformEntitiesIdsToChunks(idsDict)
let decoder = JSONDecoder()
chunks.forEach {chunk in
group.enter()
let parameters = constructQueryParams(idsDict, chunk, idSchema, apiKey, clientId)
AF.request(baseURL, parameters: parameters).response { response in
switch response.result {
case .success(let data):
// some error handling for decoding and no data
responses.append(data.data)
group.leave()
case .failure(let error):
return completion(.failure(.APIError(error.localizedDescription)))
}
}
}
group.notify(queue: .main, execute: {
print("Ids are fetched")
completion(.success(responses))
})
}
Thanks again to Larme and I hope I helped someone else with this case.

Related

cast server response in AFError

What I'm trying to achieve is that I have a NetworkManager that handles the request's to the server, and handle the error through AFError.
However sometimes when the server response is 4xx, there is a custom message with that response which I want to show that to the user But don't know how to implement it.
This is my NetworkManager
static let shared:NetworkManager = {
return NetworkManager()
}()
typealias completionHandler = ((Result<Data, AFError>) ->Void)
func handleAFrequest(request: DataRequest,completion: #escaping completionHandler) {
request.validate(statusCode: 200..<300)
request.responseJSON { (response) in
switch response.result {
case .success(_):
if let data = response.data {
completion(.success(data))
}
case .failure(let error):
print(error.localizedDescription)
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url) - \(error.localizedDescription)")
completion(.failure(.invalidURL(url: URL)))
case .responseValidationFailed(let reason):
print("Response validation failed: \(error.localizedDescription); Reason:\(reason)")
completion(.failure(.responseValidationFailed(reason: reason)))
I want to be able to cast server response in addition to the error, and show Message of the response to the user.
Server Response example when StatusCode is 4xx:
{
"data":
"code":401;
"Message":"Phone Invalid"
}
I have parsed api errors in many of my projects. I believe there is a better alternative to handle the showing or errors if any, to the user. Please see my code, in it, if there is a error I show it in a toast. Showing in a toast is the not focal point but you can see how I handle the error case in my code and it has never failed. Please change the params accordingly to your api call
func postMethod(mylist: [String:Any]) {
print(K.APIUrl)
print(K.port)
AF.request("\(K.urlFromUrlField!):\(K.configPort)/snhttp-01?", method: .put, parameters: mylist)
.authenticate(username: username, password: password)
.response { response in
switch response.result {
case .success:
print("\nValidation Successful from put method")
print(response.result)
print(response.value as Any)
//get xml code and error msg if any
if let response = response.data{
let xml = XML.parse(response)
print(xml)
print("\nThis is the data sent to the server: \(mylist["data"] ?? "No data in data key of the parameter")" )
let code = xml.Response.Code.text ?? "No code value in response"
let responseMessage = xml.Response.Message.text ?? "No message returned from server"
print("\nCode value from server: \(code)")
print("\nResponse message from server: \(responseMessage)")
}
else{
print("\nSuccess block: Request Successfully sent, BUT there was nothing from the server to unwrap! / nothing sent back from the server\nThis is the data sent to the server: \(mylist["data"] ?? "No data in data key of the parameter")")
}
case let .failure(error):
if let response = response.data {
let xml = XML.parse(response)
let code = xml.Response.Code.text ?? "\nNo code value in response"
let responseMessage = xml.Response.Message.text ?? "No message returned from server"
print("\nCode value from server: \(code)")
print("\nResponse message from server: \(responseMessage)")
print(error)
}
else {
print("\nFailure Block: A connection to the server could not be established")
}
}}
}
This code parses the xml from the api. However you can discard that and just focus on how I handle the response and consequently the error.
This is the solution that works for me.
All you need to do is create a custom error type:
struct APIError: Error, Decodable {
let status: Int?
let message: String?
let key: String?
}
Then call Alamofire, which will return an AFDataResponse which you can parse:
func performRequest<T: Decodable>(route: APIRouter, completion: #escaping (APIResponse<T>) -> Void) {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
AF.request(route)
.validate()
.responseDecodable(decoder: decoder, emptyResponseCodes: [200, 201]) { (response: AFDataResponse<T>) in
self.parseResponse(response: response, completion: completion)
}
}
Parsing is done like this:
private func parseResponse<T: Decodable>(response: AFDataResponse<T>, completion: #escaping (APIResponse<T>) -> Void) {
switch response.result {
case .success(let data):
completion(APIResponse<T>.success(data))
case .failure(let error):
if let data = response.data,
// THIS IS WHERE YOU CAST AFError TO YOUR CUSTOM APIError
let apiError = try? JSONDecoder().decode(APIError.self, from: data) {
completion(APIResponse.failure(apiError))
} else {
completion(APIResponse.failure(error))
}
}
}
Hope this helps!

How to make a method execute methods synchronously

I tried using DispatchQueue and DispatchGroup but its still asynchronous, I also tried both dispatchQueue.Async and dispathQueue.sync and neither have worked.
myFunc is a function called in the init() which itself calls 2 functions, getArrOneData() annd getArrTwoData([ArrOneType]).
The first function downloads ArrOneType data from firestore and returns an array which is initialised to a field.
The second function uses the downloaded data/field from the first function to initialise a field in ArrTwoType while simultaneously downloading other relevent ArrTwoType data from firestore to return as an array.
So the Problem is its still asynchronous. How do I use DispatchQueue and DispatchGroup correctly in this scenario?
thanks
note: get arrTwoData is mainly psuedocode
func myFunc(){
let group = DispatchGroup()
let dispatchQueue = DispatchQueue.global(qos: .default)
group.enter()
dispatchQueue.sync {
self.arrOne = self.getArrOneData()//getArrOneData gets data from firestore
group.leave()
}
dispatchQueue.sync {
group.enter()
self.arrTwo = self.getArrTwoData(inputArr: self.arrOne)//getArrTwoData gets data from firestore
group.leave()
}
}
//ArrOneType is an array field in ArrTwoType
func getArrTwoData(inputArr: [ArrOneType]) -> [ArrTwoType]{
var result = [ArrTwoType]()
//retrieving data from firestore, code excluded...
for document in querySnapshot!.documents {
let data = document.data()
name = data["Name"] as? String ?? "Name Unknown"
//returns an array which is a subset of inputArr filtered by name, however
//I dont think the inputArr is populated at this point when I run the program
var field2:[ArrOneType] = someFunc(name, inputArr)
var x = ArrTwoType(name: name, field2: field2)
result.append(x)
}
}
}
return result
}
If you have two requests, one which uses the response from one to prepare the next, the idea is to use #escaping completion handler closures for all asynchronous methods, e.g.
func getArrayOneData(completion: #escaping (Result<[ArrayOneType], Error>) -> Void) {
someAsynchronousMethod {
let values: [ArrayOneType] = ...
completion(.success(values))
}
}
func getArrayTwoData(for typeOneValues: [ArrayOneType], completion: #escaping (Result<[ArrayTwoType], Error>) -> Void) {
someAsynchronousMethod(for: typeOneValues) {
let values: [ArrayTwoType] = ...
completion(.success(values))
}
}
Then you can do things like:
func getEverything(completion: #escaping (Result<[ArrayTwoType], Error>) -> Void) {
getArrayOneData { result in
switch result {
case .failure(let error):
print(error)
case .success(let typeOneValues):
getArrayTwoData(for: typeOneValues) { result in
switch result {
case .failure(let error):
print(error)
case .success(let typeTwoValues):
completion(.success(typeTwoValues))
}
}
}
}
}
Note, no dispatch groups needed. Having added completion handlers to the asynchronous methods, we can just call the second method from the completion handler of the first.

How to handle priorities in a Swifty JSON Alamofire request?

How can I use the dispatchQueue or something like "await" in Javascript to return a value in self.arrayData (because the end of my loop is ran before the previous content). I am used to R and Python where the code runs line by line, What is the best behavior to adopt in Swift ?
Here is the function :
func fetch2(){
var i:Int = 0
repeat {
AF.request(itemLookUp[i]).validate().responseJSON { response in
switch response.result {
case .failure(let error):
print("\(error) in fetch2")
case .success(let value):
let json = JSON(value)
//Extract the Matiere for ML Extraction
self.matiereInput = json["ResultSet"]["0"]["Result"]["0"]["SpAdditional"].string ?? "none"
let energyCheck:Bool = self.matiereInput.contains("エネルギー") //energy-kcal
if energyCheck==true && self.arrayData[0]==0.0{
//regular expression
var patEnergy = #"(エネルギー)(([^\d]+)(\d+)(\.)(\d+)|([^\d]+)(\d+))"# //avoid the repetition of the pattern within the same matiereinput
let patEnergy2 = self.matches(for: patEnergy, in: self.matiereInput)
patEnergy = patEnergy2.joined(separator:"")
let valueEnergy = self.matches(for: self.regex2, in: patEnergy)
self.arrayData[0] = Double(valueEnergy.joined(separator: "")) ?? 0.0
}
}
}
i = i+1
print(self.arrayData[0])
} while i <= (self.returned-1)
}
Thank you in advance !
The standard pattern is notify with a DispatchGroup, and then use a completion handler to asynchronously notify the caller of the result:
func fetchAll(completion: #escaping (Result<[Double], Error>) -> Void) {
let group = DispatchGroup()
var results: [Double] = []
var errors: [Error] = []
for item in lookupItems {
group.enter() // enter before request
AF.request(item).validate().responseJSON { response in
defer { group.leave() } // leave when this closure is done
switch response.result {
case .failure(let error):
errors.append(error)
case .success(let value):
let result = ...
results.append(result)
}
}
}
group.notify(queue: .main) {
if let error = errors.first { // I don’t know what you want to do if there were multiple errors, so for now I’ll just grab the first one
completion(.failure(error))
} else {
completion(.success(results))
}
}
}
And then you’d use it like so:
fetchAll { result in
switch result {
case .failure(let error):
print(error)
case .success(let values):
print(values)
}
}
Now, I wasn’t able to reverse engineer what you were trying to do (you appear to be updating self.arrayData[0] in every iteration!), so I just returned an array of Double. But you can obviously change the type of results and the parameter of the completion closure to match whatever is relevant in your case.
But don’t get lost in the details of the above example, but rather just focus on a few key observations:
Supply completion handler closure to call when all the requests are done.
Use DispatchGroup to keep track of when all the requests are done.
Supply a notify closure to your DispatchGroup which will be called when all the group.enter() calls are offset by their respective group.leave() calls.
A more subtle observation is that you should refrain from updating properties from within the responseJSON block. Within your asynchronous code, you really want to limit your interaction to local variables if at all possible. Pass the result back in the completion closure (and the caller can update the model and the UI as it sees fit).

Thread 1 : signal SIGABRT alamofire

I'm very new to Swift 3, and i have to do a GET request on my API. I'm using Alamofire, which uses Asynchronous functions.
I do exactly the same on my Android App, and the GET returns JSON data
This is my code in swift :
func getValueJSON() -> JSON {
var res = JSON({})
let myGroup = DispatchGroup()
myGroup.enter()
Alamofire.request(url_).responseJSON { response in
res = response.result.value as! JSON
print("first result", res)
myGroup.leave()
}
myGroup.notify(queue: .main) {
print("Finished all requests.", res)
}
print("second result", res)
return res
}
But i have a problem with the line "res = response.result.value" wich gives me the error : Thread 1 : signal SIGABRT
I really don't understand where the problem comes from, it was pretty hard to do a "synchronous" function, maybe i'm doing it wrong.
My objective is to store the result of the request in a variable that i return. Anyone can help ?
I'd recommend you to use Alamofire together with SwiftyJSON because that way you'll be able to parse JSON easier a lot.
Here's a classical example:
Alamofire.request("http://example.net", method: .get).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
case .failure(let error):
print(error)
}
}
If you need to pass parameters, or headers, just add it in the request method.
let headers: HTTPHeaders = [
"Content-Type:": "application/json"
]
let parameters: [String: Any] = [
"key": "value"
]
So your request will be something like this (this is POST request):
Alamofire.request("http://example.net", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
print(value)
case .failure(let error):
print(error)
}
}
I haven't tested it, but it should work. Also, you need to set allow arbitary load to yes (App Transport Security Settings in info.plist) if you want to allow requests over HTTP protocol.
This is NOT recommended, but it's fine for development.

Best way to handle errors from async closures in Swift 2?

I'm using a lot of async network request (btw any network request in iOS need to by async) and I'm finding way to better handle errors from Apple's dataTaskWithRequest which not supports throws.
I have code like that:
func sendRequest(someData: MyCustomClass?, completion: (response: NSData?) -> ()) {
let request = NSURLRequest(URL: NSURL(string: "http://google.com")!)
if someData == nil {
// throw my custom error
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
// here I want to handle Apple's error
}
task.resume()
}
I need to parse my possible custom errors and handle possible connection errors from dataTaskWithRequest. Swift 2 introduced throws, but you can't throw from Apple's closure because they have no throw support and running async.
I see only way to add to my completion block NSError returning, but as I know using NSError is old-style Objective-C way. ErrorType can be used only with throws (afaik).
What's the best and most modern method to handle error when using Apple network closures? There is no way no use throws in any async network functions as I understand?
there are many ways you can solve this, but i would recommend using a completion block which expects a Result Enum. this would probably be the most 'Swift' way.
the result enum has exactly two states, success and error, which a big advantage to the usual two optional return values (data and error) which lead to 4 possible states.
enum Result<T> {
case Success(T)
case Error(String, Int)
}
Using the result enum in a completion block finishes the puzzle.
let InvalidURLCode = 999
let NoDataCode = 998
func getFrom(urlString: String, completion:Result<NSData> -> Void) {
// make sure the URL is valid, if not return custom error
guard let url = NSURL(string: urlString) else { return completion(.Error("Invalid URL", InvalidURLCode)) }
let request = NSURLRequest(URL: url)
NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
// if error returned, extract message and code then pass as Result enum
guard error == nil else { return completion(.Error(error!.localizedDescription, error!.code)) }
// if no data is returned, return custom error
guard let data = data else { return completion(.Error("No data returned", NoDataCode)) }
// return success
completion(.Success(data))
}.resume()
}
because the return value is a enum, you should switch off of it.
getFrom("http://www.google.com") { result in
switch result {
case .Success(let data):
// handle successful data response here
let responseString = String(data:data, encoding: NSASCIIStringEncoding)
print("got data: \(responseString)");
case .Error(let msg, let code):
// handle error here
print("Error [\(code)]: \(msg)")
}
}
another solution would be to pass two completion blocks, one for success and one for error. something along the lines of:
func getFrom(urlString: String, successHandler:NSData -> Void, errorHandler:(String, Int) -> Void)
It's very similar to Casey's answer,
but with Swift 5, now we have Result (generic enumeration) implementation in standard library,
//Don't add this code to your project, this has already been implemented
//in standard library.
public enum Result<Success, Failure: Error> {
case success(Success), failure(Failure)
}
It's very easy to use,
URLSession.shared.dataTask(with: url) { (result: Result<(response: URLResponse, data: Data), Error>) in
switch result {
case let .success(success):
handleResponse(success.response, data: success.data)
case let .error(error):
handleError(error)
}
}
https://developer.apple.com/documentation/swift/result
https://github.com/apple/swift-evolution/blob/master/proposals/0235-add-result.md
There's an elegant approach utilising a JavaScript-like Promise library or a Scala-like "Future and Promise" library.
Using Scala-style futures and promises, it may look as follows:
Your original function
func sendRequest(someData: MyCustomClass?, completion: (response: NSData?) -> ())
may be implemented as shown below. It also shows, how to create a promise, return early with a failed future and how to fulfill/reject a promise:
func sendRequest(someData: MyCustomClass) -> Future<NSData> {
guard let url = ... else {
return Future.failure(MySessionError.InvalidURL) // bail out early with a completed future
}
let request = ... // setup request
let promise = Promise<NSData>()
NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard let error = error else {
promise.reject(error) // Client error
}
// The following assertions should be true, unless error != nil
assert(data != nil)
assert(response != nil)
// We expect HTTP protocol:
guard let response = response! as NSHTTPURLResponse else {
promise.reject(MySessionError.ProtocolError) // signal that we expected HTTP.
}
// Check status code:
guard myValidStatusCodeArray.contains(response.statusCode) else {
let message: String? = ... // convert the response data to a string, if any and if possible
promise.reject(MySessionError.InvalidStatusCode(statusCode: response.statusCode, message: message ?? ""))
}
// Check MIME type if given:
if let mimeType = response.MIMEType {
guard myValidMIMETypesArray.contains(mimeType) else {
promise.reject(MySessionError.MIMETypeNotAccepted(mimeType: mimeType))
}
} else {
// If we require a MIMEType - reject the promise.
}
// transform data to some other object if desired, can be done in a later, too.
promise.fulfill(data!)
}.resume()
return promise.future!
}
You might expect a JSON as response - if the request succeeds.
Now, you could use it as follows:
sendRequest(myObject).map { data in
return try NSJSONSerialization.dataWithJSONObject(data, options: [])
}
.map { object in
// the object returned from the step above, unless it failed.
// Now, "process" the object:
...
// You may throw an error if something goes wrong:
if failed {
throw MyError.Failed
}
}
.onFailure { error in
// We reach here IFF an error occurred in any of the
// previous tasks.
// error is of type ErrorType.
print("Error: \(error)")
}