Swift Completion Handler Tutorial

  Рет қаралды 19,549

Code Pro

Code Pro

Күн бұрын

My full length Udemy course: Saving Data in Your iOS App Using Core Data: bit.ly/30dcIjA
Check out my new full length iOS course:
Saving Data using Core Data: skl.sh/2O23FMN
In this tutorial we will learn the basics of closures and how we can use a closure as a completion handler for asynchronous tasks such as waiting for a networking response. We will also learn how to make completion handlers optional and give the completion handler a typealias.
If you are new to iOS development and would like to learn from a more in depth course make sure to check out my iOS Development Fundamentals Course below which contains 20 video tutorials and over 3 hours of video tutorial content where we build an app from scratch.
--
50% off iOS Development Fundamentals Course on Udemy:
Udemy: bit.ly/2JfXdyn
or use CODEPRO999 for 50% off the course price.
Skillshare: skl.sh/2GgUwOL
--
Useful Learning Resources
iOS Programming Guide: amzn.to/2H3gqCq
Beginner's Guide to iOS Development: amzn.to/2snniaw
--
Check out some of the apps I've built:
itunes.apple.c...
itunes.apple.c...
itunes.apple.c...
itunes.apple.c...
--
Follow Code Pro on:
Twitter: / codepro7
Patreon: / codepro
Facebook: / thecodepro
If you found this tutorial helpful please like the video, share the video, and subscribe to CodePro. You can follow CodePro on Twitter, Facebook, for the latest channel news and updates.

Пікірлер: 49
@CodePro
@CodePro 6 жыл бұрын
This tutorial goes out to one of my subscribers who had asked about this topic. We can't always expect certain tasks to fire and finish right away. Completion handlers are a great way to let asynchronous tasks run and complete and then notify us when those tasks are finished. Let me know what tutorial you guys would like to see in the future.
@teaberry73
@teaberry73 4 жыл бұрын
OK! i just want to say that your videos have been saving my life over last couple weeks. Amazing detail in your tutorials. I'll be signing up for your courses. thank you so much for all you do!
@shully0809
@shully0809 3 жыл бұрын
I love you!!! It really helped me... It works greatly on healthkit data retriving
@wei-xuanwang5698
@wei-xuanwang5698 6 жыл бұрын
Thanks for this great tutorial! It solved my problem which suffer me for couple of days!
@CodePro
@CodePro 6 жыл бұрын
Yeah the syntax for closures and completion handlers can be a little confusing. Glad this cleared things up. 😃
@stevengao8345
@stevengao8345 6 жыл бұрын
thanks for this great tutorial, this is what I called down-to-earth illustrated class. a hard topic explained so well that everyone will be able to digest .
@CodePro
@CodePro 6 жыл бұрын
Thanks!
@magedmohmed4403
@magedmohmed4403 2 жыл бұрын
Great . Thank You for a fantastic explanation . Keep going for us
@skandaiyer12
@skandaiyer12 5 жыл бұрын
Excellent video. Saved my day! Thank you
@myrondulay8628
@myrondulay8628 3 жыл бұрын
Thank you for this! Big help!
@santoshlohar152
@santoshlohar152 4 жыл бұрын
Thank you
@cometmace
@cometmace 5 жыл бұрын
I've been struggling for weeks trying to implement a REST API that returns structs that were parsed from JSON results. In less that 20 minutes, you've made it perfectly clear how to do that. You've cleared up @escapting, self., and syntax. Thanks
@CodePro
@CodePro 5 жыл бұрын
Thanks, glad this helped you out, yeah closure syntax can get a little strange but glad I was able to clear up any uncertainties.
@jeet0218
@jeet0218 5 жыл бұрын
Hi, could you please add on video for nested api call, where each api call is depends on previous api and end api will return result and update UI
@karwandekamlesh
@karwandekamlesh 5 жыл бұрын
Hi, thanks a ton for this tutorial, it has helped me save hours in understanding the concepts. I am new to iOS and had a hell lot of time understanding the JSON parsing without using the new codable (server response are unstable). can you please post a simple tutorial help us all understand it.
@CodePro
@CodePro 5 жыл бұрын
Glad this helped, I currently have a lesson on how to use Codable for handling JSON responses however there are third party frameworks that still do this (ObjectMapper) for example and I can add lessons on how to handle this without using Codable in future lessons.
@sheetalshinde17
@sheetalshinde17 5 жыл бұрын
Thanks
@tusharsingh2439
@tusharsingh2439 6 жыл бұрын
Thanks for the tutorial !
@CodePro
@CodePro 6 жыл бұрын
Glad it helped 😀
@teaberry73
@teaberry73 4 жыл бұрын
Whats the difference between weak/strong vs unowned self? i've used unowned self and it worked, but not sure of any side effects.
@iosselfhelp6123
@iosselfhelp6123 4 жыл бұрын
What is the shortcut you used at 5:38 to auto complete the closure???
@Alex-vi6fr
@Alex-vi6fr 6 жыл бұрын
a very useful tutorial
@saadaltwaim9672
@saadaltwaim9672 4 жыл бұрын
Hi can write any name in the completion handler like ( jsonPayLoad)
@___Sahil.
@___Sahil. 6 жыл бұрын
This is a greatly informative video. I was struggling with separating my networking code out of my view controller and calling network requests from another class instead, but I was having difficulty updating the UI back on the view controller as my networking class doesn't have access to my view controllers UI. So this is exactly the solution I was searching for! thanks :) PS: your "loved" comments look like kiss emojis lmao
@CodePro
@CodePro 6 жыл бұрын
Awesome glad it helped. Yeah completion handers are just another way to callback when an async task finishes. You could achieve the same thing with the delegate pattern as well. Yeah lol, the loved comment does look like a kiss haha.
@___Sahil.
@___Sahil. 6 жыл бұрын
Code Pro which would you say of the two is the better option to pass data between classes?
@davidilenwabor8582
@davidilenwabor8582 5 жыл бұрын
Which do you think is better for knowing when a task is complete, completion handlers or delegation?
@CodePro
@CodePro 5 жыл бұрын
It depends on the situation and use case and how you build your APIs. I lean a little bit more towards delegation as the "outer layer" API that other consumers can listen in for when things finish, start, or progress is underway. However internally I may be using completion handlers to execute async work and inform the delegates when async work completes. This has benefits in unit testing. Since delegates are blue printed by the protocol, you can create mock delegates that conform to the same protocol and begin easily mocking your APIs, etc. TLDR: Both are good, depends on the use case and architecture.
@jasondhindsa6774
@jasondhindsa6774 5 жыл бұрын
I still don’t understand how you wait for one closure/completion handler to end (ie. downloading json data), before you execute the next step to parse it. Can you clarify? (Ie how do you know when the first completion handler finished?)
@CodePro
@CodePro 5 жыл бұрын
You can chain callbacks so when one closure finishes, i.e. downloading data you'll receive a response in the closure when that work is done. Then you can parse the response in the same function or another function and if that "outer" function has a completion handler as a parameter, you can call that completion handler when the parsing is finished, hence chaining the download + parsing together.
@jasondhindsa6774
@jasondhindsa6774 5 жыл бұрын
@@CodePro Yes, I understand WHAT you are trying to do. I just didn't see how it actually did that.
@cometmace
@cometmace 5 жыл бұрын
@@jasondhindsa6774 I agree that it's difficult to see the flow by looking at the code. I think this is a Swift shortcoming of the completion handlers in-line rather than as separate, discrete, functions that are called by name.
@atlas_research
@atlas_research 6 жыл бұрын
any source code?
@clipartinc
@clipartinc 6 жыл бұрын
Hi, I am using the json data to reload a collectionView within the do block... do { let decoder = JSONDecoder() self.courses = try decoder.decode([Course].self, from: data) //print(courses) //print("refreshing images") completionHandler() self.collectionView?.reloadData() } What is the proper syntax for the completionHandler for that? [String: Any] is throwing errors. (completionHandler:@escaping ([String: Any]?, Error?)->Void) Thanks!
@CodePro
@CodePro 6 жыл бұрын
From what you posted, if you wanted to call that completion handler like that you'd need to do completionHandler(nil, nil) in the success case. However it may make more sense to update the signature to (completionHandler: @escaping([Course]?, Error?)-> Void) if you want to pass back the collection of courses or simply make it take no parameters such as (completionHandler:@escaping ()->Void) It all depends on what you want to do and how you want to use it.
@clipartinc
@clipartinc 6 жыл бұрын
Thank you for your help! I'm trying to reload the collectionView on a pull down refresh. Here is most of the code... @objc private func refreshImageData() { // Fetch Weather Data print("refreshing image list") reloadCollection() refresher.endRefreshing() } func reloadCollection() { fetchJSON { json, error in } } fileprivate func fetchJSON(completionHandler:@escaping ([Course]?, Error?)->Void) { let urlString = "www.xxxx" guard let url = URL(string: urlString) else { return } URLSession.shared.dataTask(with: url ) { (data, _, err) in DispatchQueue.main.async { if let err = err { print("failed to get data:", err) return } guard let data = data else { return } do { let decoder = JSONDecoder() self.courses = try decoder.decode([Course].self, from: data) //print(courses) //print("refreshing images") completionHandler(nil, nil) self.collectionView?.reloadData() } catch let jsonErr { print("error:", jsonErr) } } }.resume() // Do any additional setup after loading the view, typically from a nib. } The pull down works, but not sure it's refreshing the fetchJSON call once the pull down is used. Based on what you see, what do you think? The JSON loads properly on initial load, but I would like to allow the user to refresh the JSON on a pull down refresh.
@clipartinc
@clipartinc 6 жыл бұрын
It seems to be working :) I did remove the completionHandler(nil, nil) from the fetchJSON, but it does work. Thanks for your help!
@clipartinc
@clipartinc 6 жыл бұрын
Hi, I thought it was working, but it's not. Any assistance would be appreciated.
@CodePro
@CodePro 6 жыл бұрын
Yeah I can take a look, send me a GitHub gist on the Facebook page or you can email me directly and I can look there too.
@RakeshKusuma1987
@RakeshKusuma1987 5 жыл бұрын
Thanks for the tutorial man. I have one small query. When you change the completion handler to optional, why we are supposed to remove @escaping. Does removing @escaping key would till do the functionality as expected of @escaping?
@firaseljerdy1244
@firaseljerdy1244 3 жыл бұрын
so overwhelming
@user-id1gc8uu6l
@user-id1gc8uu6l 5 жыл бұрын
new to swift, awesome tutorial makes a ton of sense. Dumb question though - does this all seem unreasonably complicated to anyone else? In python I literally can do: from selenium import webdriver browser = webdriver.Chrome() browser.get("kzbin.infovideos") and i've got the payload and I'm happy. Can anyone explain intuitively why we have to go through all of this in swift? Thanks!
@stevengao8345
@stevengao8345 6 жыл бұрын
just watched this 2 more times, try to write a completion handler for urlsession to download video url from firebase, then save video mp4 file on iPhone local file system, after successfully saved then start play, what I just described is even possible for completion handler or there is another way to approach it? thanks
@CodePro
@CodePro 6 жыл бұрын
Yeah that approach could work but it largely matters how you structure your code. Your process would consist of multiple steps such as download, once finished, save the data to the filesystem, once finished, read back and play etc. You'd probably need chain multiple callbacks. You could even use operations inside of an operation queue and have them fire one at a time. It's a little bit more work but it would achieve the same result.
@stevengao8345
@stevengao8345 6 жыл бұрын
thanks for your time, because of my level, not fully understand what you are saying but I will search your keywords in google. thanks again for your hint and explanation.
@CodePro
@CodePro 6 жыл бұрын
It just boils down to app architecture and how the code is structured for each task / event that needs to happen in the download process. Meaning, one function might download a video and save it to the file system which has an async callback. Once that's done, another function waiting on that callback may verify that the video is downloaded and everything is in the proper format etc, once that's verified it calls its completion handler which may call up to another function that begins to load / play the video etc. Depending on how the code is written, that could be 3 functions each of which provides a completion handler and calls back one by one as things finish, i.e. 'chaining' completion handlers.
@stevengao8345
@stevengao8345 6 жыл бұрын
chaining completion functions, sounds very cool to me, I will give it a try. thanks for you time and full explanation.
Completion Handlers
17:06
Stewart Lynch
Рет қаралды 12 М.
How To Survive the iOS Interview
11:26
Code Pro
Рет қаралды 20 М.
LIFEHACK😳 Rate our backpacks 1-10 😜🔥🎒
00:13
Diana Belitskay
Рет қаралды 3,9 МЛН
Крутой фокус + секрет! #shorts
00:10
Роман Magic
Рет қаралды 17 МЛН
iOS Swift Tutorial: Programmatic and Storyboard Segues
16:47
Code Pro
Рет қаралды 46 М.
Weak and Unowned Self Closure Memory Leak Fixes
12:21
Lets Build That App
Рет қаралды 56 М.
Swift Closures: @escaping Explained
4:45
Sean Allen
Рет қаралды 45 М.
Use Closures Not Delegates | Swift 5, Xcode 10
14:52
Kilo Loco
Рет қаралды 24 М.
iOS Unit Test Mocking Tutorial
24:50
Code Pro
Рет қаралды 27 М.
How to use escaping closures in Swift | Continued Learning #20
21:56
Swiftful Thinking
Рет қаралды 19 М.
Custom View Controller Transitions
35:21
Code Pro
Рет қаралды 26 М.
iOS Alamofire Tutorial
19:46
Code Pro
Рет қаралды 47 М.
LIFEHACK😳 Rate our backpacks 1-10 😜🔥🎒
00:13
Diana Belitskay
Рет қаралды 3,9 МЛН