I am trying to create a service object in my Swift application to handle requests a bit easier. I've got most of it wired up, however I might be misunderstanding completion handlers.
I have this function that simply posts to a local API endpoint I have running.
func createList(name: String, completion: #escaping (Response) -> Void) {
let parameters = ["name": name, "user_id": session.auth.currentUser!.uid]
AF.request("\(url)/wishlist", method: .post, parameters: parameters, encoding: URLEncoding.default).responseDecodable(of: Response.self) { response in
switch response.result {
case .failure(let err):
print(err)
case .success(let res):
completion(res)
}
}
}
All that needs to happen is I need to pass that name to the function which I do here
barback.createList(name: name) -> after a button is tapped
However, I am now getting this error.
Missing argument for parameter 'completion' in call
My goal here is to just return the Response object so I can access attributes on that to do certain things in the UI. I was not able to return res here because, from my understanding, this is an async request and it's actually returning from that competition handler? (could be butchering that). The way I saw others doing this was by adding a competition handler to the params and adding an escape to that.
My end goal here is to do something like...
if barback.createList(name: name).status = 200
(trigger some UI component)
else
(display error toast)
end
Is my function flawed in it's design? I've tried changing my competition handler to be
completion: (#escaping (Response) -> Void) = nil
but run into some other errors there. Any guidance here?
Completion handlers are similar to function return values, but not the same. For example, compare the following functions:
/// 1. With return value
func createList(name: String) -> Response { }
/// 2. With completion handler
func createList(name: String, completion: #escaping (Response) -> Void) { }
In the first function, you'd get the return value instantly.
let response = barback.createList(name: name)
if response.status = 200 {
/// trigger some UI component
}
However, if you try the same for the second function, you'll get the Missing argument for parameter 'completion' in call error. That's because, well, you defined a completion: argument label. However, you didn't supply it, as matt commented.
Think of completion handlers as "passing in" a chunk of code into the function, as a parameter. You need to supply that chunk of code. And from within that chunk of code, you can access your Response.
/// pass in chunk of code here
barback.createList(name: name, completion: { response in
/// access `response` from within block of code
if response.status = 200 {
/// trigger some UI component
}
})
Note how you just say barback.createList, not let result = barback.createList. That's because in the second function, with the completion handler, doesn't have a return value (-> Response).
Swift also has a nice feature called trailing closure syntax, which lets you omit the argument label completion:.
barback.createList(name: name) { response in
/// access `response` from within block of code
if response.status = 200 {
/// trigger some UI component
}
}
You can also refer to response, the closure's first argument, by using $0 (which was what I did in my comment). But whether you use $0 or supply a custom name like response is up to you, sometimes $0 is just easier to type out.
barback.createList(name: name) {
/// access $0 (`response`) from within block of code
if $0.status = 200 {
/// trigger some UI component
}
}
Calling createList would look something more like this:
barback.createList(name: name) { response in
if response.status == 200 {
// OK
} else {
// Error
}
}
This fixes the issue because you are now running this completion closure - { response in ... } - where response is the value you pass in. In this case, you pass in res. See this post about using completion handlers.
If you did want an optional completion handler so you don't always need to include it, you could change the definition to the following (adding = { _ in }, meaning it defaults to an empty closure):
func createList(name: String, completion: #escaping (Response) -> Void = { _ in })
Another way is actually making the closure optional:
func createList(name: String, completion: ((Response) -> Void)? = nil)
And then inside the method you need ? when you call completion, since it's optional:
completion?(res)
Use the completion handler as mentioned in the comments and answers.
In addition you should include a completion when it fails, otherwise you
will never get out of that function.
I would restructure your code to cater for any errors that might happens, like this:
func createList(name: String, completion: #escaping (Response?, Error?) -> Void) {
let parameters = ["name": name, "user_id": session.auth.currentUser!.uid]
AF.request("\(url)/wishlist", method: .post, parameters: parameters, encoding: URLEncoding.default).responseDecodable(of: Response.self) { response in
switch response.result {
case .failure(let err):
print(err)
completion(nil, err)
case .success(let res):
completion(res, nil)
}
}
}
call it like this:
barback.createList(name: name) { (response, error) in
if error != nil {
} else {
}
}
If you do not put a completion(...) in your "case .failure" it will never get out of there.
Related
I am struggling to trigger the logic responsible for changing the view at the right time. Let me explain.
I have a view model that contains a function called createNewUserVM(). This function triggers another function named requestNewUser() which sits in a struct called Webservices.
func createNewUserVM() -> String {
Webservices().requestNewUser(with: User(firstName: firstName, lastName: lastName, email: email, password: password)) { serverResponse in
guard let serverResponse = serverResponse else {
return "failure"
}
return serverResponse.response
}
}
Now that's what's happening in the Webservices' struct:
struct Webservices {
func requestNewUser(with user: User, completion: #escaping (Response?) -> String) -> String {
//code that creates the desired request based on the server's URL
//...
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
DispatchQueue.main.async {
serverResponse = completion(nil)
}
return
}
let decodedResponse = try? JSONDecoder().decode(Response.self, from: data)
DispatchQueue.main.async {
serverResponse = completion(decodedResponse)
}
}.resume()
return serverResponse //last line that gets executed before the if statement
}
}
So as you can see, the escaping closure (whose code is in the view model) returns serverResponse.response (which can be either "success" or "failure"), which is then stored in the variable named serverResponse. Then, requestNewUser() returns that value. Finally, the createNewUserVM() function returns the returned String, at which point this whole logic ends.
In order to move to the next view, the idea was to simply check the returned value like so:
serverResponse = self.signupViewModel.createNewUserVM()
if serverResponse == "success" {
//move to the next view
}
However, after having written a few print statements, I found out that the if statement gets triggered way too early, around the time the escaping closure returns the value, which happens before the view model returns it. I attempted to fix the problem by using some DispatchQueue logic but nothing worked. I also tried to implement a while loop like so:
while serverResponse.isEmpty {
//fetch the data
}
//at this point, serverResponse is not empty
//move to the next view
It was to account for the async nature of the code.
I also tried was to pass the EnvironmentObject that handles the logic behind what view's displayed directly to the view model, but still without success.
As matt has pointed out, you seem to have mixed up synchronous and asynchronous flows in your code. But I believe the main issue stems from the fact that you believe URLSession.shared.dataTask executes synchronously. It actually executes asynchronously. Because of this, iOS won't wait until your server response is received to execute the rest of your code.
To resolve this, you need to carefully read and convert the problematic sections into asynchronous code. Since the answer is not trivial in your case, I will try my best to help you convert your code to be properly asynchronous.
1. Lets start with the Webservices struct
When you call the dataTask method, what happens is iOS creates a URLSessionDataTask and returns it to you. You call resume() on it, and it starts executing on a different thread asynchronously.
Because it executes asynchronously, iOS doesn't wait for it to return to continue executing the rest of your code. As soon as the resume() method returns, the requestNewUser method also returns. By the time your App receives the JSON response the requestNewUser has returned long ago.
So what you need to do to pass your response back correctly, is to pass it through the "completion" function type in an asynchronous manner. We also don't need that function to return anything - it can process the response and carry on the rest of the work.
So this method signature:
func requestNewUser(with user: User, completion: #escaping (Response?) -> String) -> String {
becomes this:
func requestNewUser(with user: User, completion: #escaping (Response?) -> Void) {
And the changes to the requestNewUser looks like this:
func requestNewUser(with user: User, completion: #escaping (Response?) -> Void) {
//code that creates the desired request based on the server's URL
//...
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
DispatchQueue.main.async {
completion(nil)
}
return
}
let decodedResponse = try? JSONDecoder().decode(Response.self, from: data)
DispatchQueue.main.async {
completion(decodedResponse)
}
}.resume()
}
2. View Model Changes
The requestNewUser method now doesn't return anything. So we need to accommodate that change in our the rest of the code. Let's convert our createNewUserVM method from synchronous to asynchronous. We should also ask the calling code for a function that would receive the result from our Webservice class.
So your createNewUserVM changes from this:
func createNewUserVM() -> String {
Webservices().requestNewUser(with: User(firstName: firstName, lastName: lastName, email: email, password: password)) { serverResponse in
guard let serverResponse = serverResponse else {
return "failure"
}
return serverResponse.response
}
}
to this:
func createNewUserVM(_ callback: #escaping (_ response: String?) -> Void) {
Webservices().requestNewUser(with: User(firstName: firstName, lastName: lastName, email: email, password: password)) { serverResponse in
guard let serverResponse = serverResponse else {
callback("failure")
return
}
callback(serverResponse.response)
}
}
3. Moving to the next view
Now that createNewUserVM is also asynchronous, we also need to change how we call it from our controller.
So that code changes from this:
serverResponse = self.signupViewModel.createNewUserVM()
if serverResponse == "success" {
//move to the next view
}
To this:
self.signupViewModel.createNewUserVM{ [weak self] (serverResponse) in
guard let `self` = self else { return }
if serverResponse == "success" {
// move to the next view
// self.present something...
}
}
Conclusion
I hope the answer gives you an idea of why your code didn't work, and how you can convert any existing code of that sort to execute properly in an asynchronous fashion.
This can be achieve using DispatchGroup and BlockOperation together like below:
func functionWillEscapeAfter(time: DispatchTime, completion: #escaping (Bool) -> Void) {
DispatchQueue.main.asyncAfter(deadline: time) {
completion(false) // change the value to reflect changes.
}
}
func createNewUserAfterGettingResponse() {
let group = DispatchGroup()
let firstOperation = BlockOperation()
firstOperation.addExecutionBlock {
group.enter()
print("Wait until async block returns")
functionWillEscapeAfter(time: .now() + 5) { isSuccess in
print("Returned value after specified seconds...")
if isSuccess {
group.leave()
// and firstoperation will be complete
} else {
firstOperation.cancel() // means first operation is cancelled and we can check later if cancelled don't execute next operation
group.leave()
}
}
group.wait() //Waits until async closure returns something
} // first operation ends
let secondOperation = BlockOperation()
secondOperation.addExecutionBlock {
// Now before executing check if previous operation was cancelled we don't need to execute this operation.
if !firstOperation.isCancelled { // First operation was successful.
// move to next view
moveToNextView()
} else { // First operation was successful.
// do something else.
print("Don't move to next block")
}
}
// now second operation depends upon the first operation so add dependency
secondOperation.addDependency(firstOperation)
//run operation in queue
let operationQueue = OperationQueue()
operationQueue.addOperations([firstOperation, secondOperation], waitUntilFinished: false)
}
func moveToNextView() {
// move view
print("Move to next block")
}
createNewUserAfterGettingResponse() // Call this in playground to execute all above code.
Note: Read comments for understanding. I have run this in swift playground and working fine. copy past code in playground and have fun!!!
I've run into a problem.
I've made a service for API calls that returns a User object, and the API call works fine and it returns the User object.
However, I need to use completion and #escaping, and I'm not sure how to do it properly, since I'm new to Swift and iOS development.
The Code is below.
func login(with credentials: LoginCredentials) {
let params = credentials
AF.request(Service.baseURL.appending("/user/login"), method: .post, parameters: params, encoder: JSONParameterEncoder.default).responseJSON { response in
switch response.result {
case .success:
print("Success")
case.failure:
print("Fail")
}
}
Also, how do I call a function when there is completion?
It’s not clear what kind of argument (if it takes one) the completion for your method shall take, thus I’m gonna give you a couple of hints.
Perhaps you want to also have the completion for your method execute on a queue specified as parameter in the call.
Therefore you might structure your method’s signature in this way:
func login(with credentials: LoginCredentials, queue: DispatchQueue = .main, _ completion: #esacping (Bool) -> Void)
Here I’ve used the type Bool as argument for the completion to be executed, and defaulted the queue argument to be .main, assuming that you’re just interested in deliver as result argument in the completion a value of true in case you’ve gotten a .success response, false otherwise; I’m also assuming that this method will mainly be called with the completion being executed on the main thread for updating a state, hence the default value for the queue argument.
Therefore your method body could become like this:
func login(with credentials: LoginCredentials, queue: DispatchQueue = .main, _ completion: #escaping (Bool) -> Void) {
let params = credentials
AF.request(
Service.baseURL.appending("/user/login"),
method: .post,
parameters: params,
encoder: JSONParameterEncoder.default
).responseJSON { response in
switch response.result {
case .success:
queue.async { completion(true) }
case.failure:
queue.async { completion(false) }
}
}
Now of course if you need to deliver something different (as in the token for the login session and an error in case of failure) then you’d better adopt a Result<T,Error> Swift enum as argument to pass to the completion.
Without you giving more details in these regards, I can only give a generic suggestion for this matter, cause I cannot go into the specifics.
EDIT
As a bonus I'm also adding how you could structure this method with the new Swift concurrency model:
// Assuming you are returning either a value of type User or
// throwing an error in case the login failed (as per your comments):
func login(with credentials: LoginCredentials) async throws -> User {
withCheckedThrowingContinuation { continuation in
AF.request(
Service.baseURL.appending("/user/login"),
method: .post,
parameters: credentials,
encoder: JSONParameterEncoder.default
).responseJSON { response in
switch response.result {
case .success:
let loggedUser = User(/* your logic to create the user to return*/)
continuation.resume(returning: loggedUser)
case.failure:
continuation.resume(throwing: User.Error.loginError)
}
}
}
// Here's possible way to implement the error on your User type
extension User {
enum Error: Swift.Error {
case loginError
// add more cases for other errors related to this type
}
}
I am trying to create a simple app that fetches a new video from Vimeo everyday. I can access Vimeo and the videos no problem, but the built in "request" function defaults to returning void and I would like to use the video info (URIs, names, .count, etc.) outside of the request function.
The request function returns something called a "RequestToken" which contains a path and a URLSessionDataTask. I thought maybe that was the key but, probably since I'm new to programming, I have been unable to effectively use this info. I've also read a lot of the Vimeo class files associated with VimeoClient and Request and so forth and it seems like it creates a dictionary object when a request has completed but I have no idea how to access that. I feel like this is just some knowledge about functions/closures/returns that I lack and can't quite find the internet search terms to answer.
let videoRequest = Request<[VIMVideo]>(path: "/user/videos")
vimeoClient.request(videoRequest) { result in
switch result {
case .success(let response):
let video: [VIMVideo] = response.model
print("retrieved videos: \(video.count)")
case .failure(let error):
print ("error retrieving video: \(error)")
Here is the full method call under VimeoClient class.
public func request<ModelType>(_ request: Request<ModelType>, completionQueue: DispatchQueue = DispatchQueue.main, completion: #escaping ResultCompletion<Response<ModelType>>.T) -> RequestToken
{
if request.useCache
{
self.responseCache.response(forRequest: request) { result in
switch result
{
case .success(let responseDictionary):
if let responseDictionary = responseDictionary
{
self.handleTaskSuccess(forRequest: request, task: nil, responseObject: responseDictionary, isCachedResponse: true, completionQueue: completionQueue, completion: completion)
}
else
{
let error = NSError(domain: type(of: self).ErrorDomain, code: LocalErrorCode.cachedResponseNotFound.rawValue, userInfo: [NSLocalizedDescriptionKey: "Cached response not found"])
self.handleError(error, request: request)
completionQueue.async {
completion(.failure(error: error))
}
}
case .failure(let error):
self.handleError(error, request: request)
completionQueue.async {
completion(.failure(error: error))
}
}
}
return RequestToken(path: request.path, task: nil)
}
else
{
let success: (URLSessionDataTask, Any?) -> Void = { (task, responseObject) in
DispatchQueue.global(qos: .userInitiated).async {
self.handleTaskSuccess(forRequest: request, task: task, responseObject: responseObject, completionQueue: completionQueue, completion: completion)
}
}
let failure: (URLSessionDataTask?, Error) -> Void = { (task, error) in
DispatchQueue.global(qos: .userInitiated).async {
self.handleTaskFailure(forRequest: request, task: task, error: error as NSError, completionQueue: completionQueue, completion: completion)
}
}
let path = request.path
let parameters = request.parameters
let task: URLSessionDataTask?
switch request.method
{
case .GET:
task = self.sessionManager?.get(path, parameters: parameters, progress: nil, success: success, failure: failure)
case .POST:
task = self.sessionManager?.post(path, parameters: parameters, progress: nil, success: success, failure: failure)
case .PUT:
task = self.sessionManager?.put(path, parameters: parameters, success: success, failure: failure)
case .PATCH:
task = self.sessionManager?.patch(path, parameters: parameters, success: success, failure: failure)
case .DELETE:
task = self.sessionManager?.delete(path, parameters: parameters, success: success, failure: failure)
}
guard let requestTask = task else
{
let description = "Session manager did not return a task"
assertionFailure(description)
let error = NSError(domain: type(of: self).ErrorDomain, code: LocalErrorCode.requestMalformed.rawValue, userInfo: [NSLocalizedDescriptionKey: description])
self.handleTaskFailure(forRequest: request, task: task, error: error, completionQueue: completionQueue, completion: completion)
return RequestToken(path: request.path, task: nil)
}
return RequestToken(path: request.path, task: requestTask)
}
}`
In the Print statement I get the correct count for the videos on the page so I know that it is working properly inside the function. The request doesn't explicitly say that it returns void but if I try to return a [VIMVideo] object the debug tells me that the expected return is Void and then will not build.
All the information I need I can get, but only inside the function. I would like to be able to use it outside the function but the only way I know how is returning the object which it isn't allowing me to do.
Thanks for your help.
After reading the provided documentation on async, it looks like the callback is the way forward here. However, when looking back at the class method in question it already has a completion handler built in. In the examples given to me by the helpful people here the completion handler would use a simple variable that could be referenced in the callback. The, seemingly, built-in VimeoNetworking Pod completion handler has a complex-looking reference to a response class (which may be part of the responseDictionary?) any ideas on how I can reference that completion handler in a callback? Or is that not the purpose and I should attempt to craft my own completion handler on top of the provided one?
Thanks much!
I am using Firebase FirAuth API and before the API return result, Disposables.create() has been returned and it's no longer clickable (I know this might due to no observer.onCompleted after the API was called. Is there a way to wait for it/ listen to the result?
public func login(_ email: String, _ password: String) -> Observable<APIResponseResult> {
let observable = Observable<APIResponseResult>.create { observer -> Disposable in
let completion : (FIRUser?, Error?) -> Void = { (user, error) in
if let error = error {
UserSession.default.clearSession()
observer.onError(APIResponseResult.Failure(error))
observer.on(.completed)
return
}
UserSession.default.user.value = user!
observer.onNext(APIResponseResult.Success)
observer.on(.completed)
return
}
DispatchQueue.main.async {
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: completion)
}
return Disposables.create()
}
return observable
}
You are correct in your assumption that an onError / onCompletion event terminate the Observable Sequence. Meaning, the sequence won't emit any more events, in any case.
As a sidenote to that, You don't need to do .on(.completed) after .onError() , since onError already terminates the sequence.
the part where you write return Disposables.create() returns a Disposable object, so that observable can later be added to a DisposeBag that would handle deallocating the observable when the DisposeBag is deallocated, so it should return immediately, but it will not terminate your request.
To understand better what's happening, I would suggest adding .debug() statements around the part that uses your Observable, which will allow you to understand exactly which events are happening and will help you understand exactly what's wrong :)
I had the same issue some time ago, I wanted to display an Alert in onError if there was some error, but without disposing of the observable.
I solved it by catching the error and returning an enum with the cases .success(MyType) and .error(Error)
An example:
// ApiResponseResult.swift
enum ApiResponseResult {
case error(Error)
case success(FIRUser)
}
// ViewModel
func login(...) -> Observable<ApiResponseResult> {
let observable = Observable.create { ... }
return observable.catchError { error in
return Observable<ApiResponseResult>.just(.error(error))
}
}
// ViewController
viewModel
.login
.subscribe(onNext: { result in
switch result {
case .error(let error):
// Alert or whatever
break
case .success(let user):
// Hurray
break
}
})
.addDisposableTo(disposeBag)
Let us say that I have a method:
func getData(id:Int, completion: (object: object, error: Error?) -> ()){
// some code
let error = ErrorParser.parseData(data!)
if error?.statusCode <= 200 {
// do sth
}
else {
completion(object: object, error: error)
}
}
}
My question is, what happens when I call this method from another class and the completion block is never called (the calling class never gets the block returned)? Is this safe?
It depends on the part you've skipped in // some code.
Let's imagine you are using some 3rd party lib that is performing async request:
func getData(id:Int, completion: (object: object, error: Error?) -> ()){
MyLibrary.doRequest(id: id) { data in
let error = ErrorParser.parseData(data!)
if error?.statusCode <= 200 {
// do sth
}
else {
completion(object: object, error: error)
}
}
}
Here you are passing a new closure (let's name it B) as a parameter to MyLibrary.doRequest method. And your completion parameter is captured by the B closure, and won't be released until this closure is released.
Then MyLibrary stores a strong reference to B closure somewhere and most likely it will release B closure after the request is completed (or failed) and the B closure is executed.
Alternatively you can have some synchronous code here:
func getData(id:Int, completion: (object: object, error: Error?) -> ()){
let data = OtherLib.loadDataFromDisk(id)
let error = ErrorParser.parseData(data!)
if error?.statusCode <= 200 {
// do sth
}
else {
completion(object: object, error: error)
}
}
In this case, your completion block will be released after function returns.