When app starts I need to do some network requests. For example, App fetches my servers public key to operate a secure restful connection. If it can get the key, It does other network operations. My problem is that these operations are nested so one is finished, other one start but If there is a problem with one of them I need to display a message. I have AppDelegate class and SplashViewController in which I can do these operations. I'm not sure what will be the best approach in terms of speed when doing that;
1-) Start operations in AppDelegate and with notification, notify splashviewcontroller and display message If there is an error.
2-)Start operations in SplashViewController class.
3-)Wait all network operations to be finished before opening SplashViewController (I'm not sure If I can display error message in AppDelegate class)
Example code I run at AppDelegate;
APIClient.checkCMS { (result) in
switch result{
case .error(let error):
print(error)
//Notify SplashViewController?
case .success(let returnedObject):
print(returnedObject)
print("Devam")
}
}
The fact that you are even thinking about using notifications here to communicate between view controllers is probably a code smell. I think the AppDelegate approach is definitely wrong.
I'm making some assumptions about your app that may be incorrect, namely that you are using a storyboard/xibs and that your SplashVC is going to be instantiated and presented when the app runs, regardless of the state of the network call (i.e. the app isn't just going to hang until the outcome of the network call is known).
In this scenario, if you make the call from the AppDelegate you will use NSNotificationCenter to update the SplashVC. This seems like a bad idea, just because it introduces unnecessary complication to the design. You might just conceivably do everything from the AppDelegate if you are loading the VCs manually in code, but even then you probably don't really want the app to show nothing until the network call completes.
The way I would handle this is as follows:
(If you haven't already done it) encapsulate all of your network requests into a service object of some kind. Then you can use Dependency Injection with a singleton scope (perhaps using Swinject or another similar library). This would allow you to make network requests from anywhere in the app they are required.
Have a default VC (maybe SplashVC, or some other root VC) that loads first and dependency injects the network service from 1
Make the calls in the viewDidLoad of the SplashVC. Handle errors appropriately, (by showing an alert, or by presenting a custom modal VC, or whatever you like. This avoids having the app just show a black screen if the request is slow).
Usually, developers create a fake splash screen. It looks like splash, so user can't notice any difference. On controllers initializer(or in viewDidLoad) you can download all needed data and when everything is done go to next controller. Even more, you can choose where to go next(for example if the user was logged in before, he should be redirected to the main page).
Related
Background: In order to make web requests to an API endpoint, I need to scrape a website and retrieve a token every 25-30 seconds. I'm doing this with a WKWebView and injecting some custom JavaScript using WKUserScript to retrieve AJAX response headers containing the token. Please focus on the question specifically and not on this background information - I'm attempting this entirely for my own educational purposes.
Goal
I will have different 'model' classes, or even just other UIViewControllers, that may need to call the shared UIViewController to retrieve this token to make an authenticated request.
Maybe I might abstract this into one "Sdk" class. Regardless, this 'model' SDK class could be instantiated and used by any other ViewController.
More info
I would like to be able to call the UIViewController of the WKWebView and retrieve some data. Unless I re-create it every 25 seconds, I need to run it in the background or share it. I would like to be able to run a UIViewController 'in the background' and receive some information from it once WKWebView has done it's thing.
I know there are multiple ways of communicating with another ViewController including delegation and segueing. However, I'm not sure that these help me keep the view containing the WKWebView existing in the background so I can call it's ViewController and have it re-perform the scrape. Delegation may work for normal code, but what about one that must have the view existing? Would I have to re-create this WKWebView dynamically each time a different model, or view controller, were to try and get this token?
One post suggests utilising ContainerViewControllers. From this, I gather that in the 'master' ViewController (the one containing the other ones), I could place the hidden WKWebView to do it's thing and communicate to the child view controllers that way via delegation.
Another post suggests using AppDelegate and making it a shared service. I'm completely against using a Singleton as it is widely considered an anti-pattern. There must be another way, even if a little more complex, that helps me do what I want without resorting to this 'cheat'.
This post talks about communicating between multiple ViewControllers, but I can't figure out how this would be useful when something needs to stay running and executing things.
How about any other ways to do this? Run something in a background thread with a strong pointer so it doesn't get discarded? I'm using Xcode 9.2, Swift 4, and iOS 11. As I'm very new to iOS programming, any small code examples on this would be appreciated.
Unfortunately, WKWebView must be in the view hierarchy to use it. You must have added it as a sub view of an on-screen view controller.
This was fine for me. I added this off-screen so it was not visible. Hidden attribute might have worked as well. Either way you must call addSubview with it to make it work.
There are some other questions and answers here which verify this.
Here is a way if you don't wish to use a singleton.
1- In the DidFinishlaunchingWithOptions, Make a timer that runs in the background and call a method inside the app delegate Called FetchNewToken.
2- In FetchNewToken, make the call needed and retrieve the new token (you can use alamofire or any 3rd library to make the call easier for you).
Up on successfully retrieving the token, save it in NSUserDefaults under the name upToDateToken
You can access this token anywhere from the application using NSUserDefaults and it will always be up to date.
Learning iOS Swift programming and like to know how to implement user login process ?
The backend-iOS mechanism is this :
User login with email and Password,
The Server returns user token and user id
In subsequent requests, user token and user id is sent to fetch data/work with the App.
I have doubt in iOS implementation.
Will be storing User token and User id in Core Data. Will there be
any slowness if I get the user token on every screen from Core
Data?
If the login token expires or is invalid on any screen, how to fall back to login page? Should I check the JSON output and have code "present login VC" on every screen? Any streamlined way to have abstract the code to a swift or cocoa touch file?
Actually, there are many approaches. It's all depends on you, how you will manage it. I can point you two examples, how I manage it by myself.
Using NSOperation.
There was an awesome session on WWDC 2015, about advanced NSOperations. Here it is.
Basically, you create a subclass of NSOperaton and make other operations depend on it. In your case, you will have operation of user login, and all other operations will depend on user login (of course only ones, who needs it). If it succeed, then operation will execute. In user login operation, you will check, if user already logged in, and you have a token, if not, present logging screen.
There is also awesome library called Operations, based on that WWDC talk. Here it is.
Using PromiseKit.
Here is another one, using PromiseKit. It is not really much difference from operations, but, in my opinion, a little simpler. You create Promise that ensures that you did login. It is very simple to make a chain of promises, so you promise a user login and chain anything else from it. If login succeed, chain of promises continues executing.
It's all based on another awesome library, PromiseKit. Here it is
It is very powerful and very simple to use, once you understand the thing. It is very well documented, and has a bunch of tutorials here.
There are many other approaches, so you can choose any of it, and combine one with other however you like.
Asking on your first question, you make it asynchronous, so it is not so much matter about slowness of CoreData as you make a web request.
1 - well, yes, a bit. But I doubt you will notice any lag or anything: CoreData is really fast and it won't take any significant amount of time to fetch just one object. Alternatively, your CoreData object that holds this data (let's call it User) can be a property of your subclass of UIApplicationDelegate (let's call it MyAppDelegate). You will fetch this User in
- application:didFinishLaunchingWithOptions:, and update it on login/logout/expire/etc. In such way you can access it from everywhere, and you don't need to fetch it from CoreData anytime you need it.
Also, instead of CoreData you can use iOS Keychain. (Here is tutorial that might help with this).
2 - again, you can use MyAppDelegate. For example you can add method to it, that will save current navigation state, and change root controller of UIWindow to your LoginViewController. Or it will present LoginViewController on top of current controller. After successful login you will return navigation stack to previous state.
Also you can move this code to some kind of NavigationController - class that will handle this situation. It will have something like
func checkToken(Dictionary response, UIViewController currentController) -> Bool. If token is valid, it just returns true, and if not, it returns false and handles navigation to LoginViewController, and after login - back to currentController. This NavigationController can be property of MyAppDelegate, it can be singleton, created every time you need it, or you can pass it along to every UIViewController that you show.
Ok so i have been trying to figure out how to do this for a while but i did not seem to find way to do it. Also i would like the proper way to do this.
A server that i have is sending notifications every 30 seconds to my device. Lets say i am in ViewController B, but the data that is received by the notification is ment to be displayed/used in ViewController A.
Lets say i received two notifications while i was in ViewController B. Then i navigate to ViewController A. How would i get it to display the most recent data that was received by the notification?
You should receive the notification in a (global) 3rd object that will store them, then when the VC A is displayed you'll easily retrive them from that object...
Follow the "shared instance" path used by many iOS classes (even if someone don't like it 'cause they read singletons are evil, I think this's the perfect case to use it).
You can solve it this way:
Create at startup your singleton class that will receive the notifications and keep them in a queue.
Add to the singleton methods to read/consume the notification queue.
From any class you need the data (i.e. your view controller) get the infos you need via the methods above.
This solution keep data manager (notification handling) and presentation (the view controller) separated, I don't see any real cons...
Again, I know singletons have a bad reputation (and often people abuse of this pattern) but you know Apple's NSNotificationCenter have a +defaultCenter class method that return the shared instance (another word for singleton) so I'm quite sure this's the case to use it.
here http://www.daveoncode.com/2011/12/19/fundamental-ios-design-patterns-sharedinstance-singleton-objective-c/ you can find a good example how to implement the +sharedInstance (or +defaultCenter or whatever you want to call it) method.
Hope this help.
I would like to use AFNetworking to perform periodical JSON requests to my server (updating the user's profile and checking for changes).
What if the background job is running but the user pushed the "Back" button or anything that makes the ViewController to be destroyed? How can I manage this? I mean, in that case I would like to ignore the result and perform it again when the user returns to the View
Thank you
PS: I don't want a full working code. I just would like to know how can I know, from a background download job (ran using AFNetworking) if the ViewController has been destroyed or not.
In order to stop the running network request, you can send cancel to the network operation in method viewWillDisappear: of the View Controller.
Likewise, in order to "automatically" start the network request when the view becomes visible, use method viewWillAppear:.
Check out this question:
Best architecture for an iOS application that makes many network requests?
A simple way is to create a singleton instance of a custom Network Manager class which will handle all the request and network background jobs. You can access it from anywhere (e.g. view controllers) and it keeps its instance for the whole runtime of the app.
About singleton: http://en.wikipedia.org/wiki/Singleton_pattern
If you just need to achieve your task . mean, trying to get the changes if & only if the particular ViewController appears.
Use the methods
-(void) viewDidappear{
// Initialise Your task here
}
-(void) viewWillDisappear{
// Destoy(Cancel ) the task
}
One solution would be to implement the downloading in a way that uses NSNotification mechanism :
Set up the ViewController as a listener.
Set up the bg download to fire up a notification when the download process has been finished.
If the VC is still around when the notification fires, great - it
will handle notification and do whatever you need. If it is not around... nothing happens.
The high level design of my app consists of the App Delegate being the owner of the model which is created in didFinishLaunchingWithOption and then the app delegate passes a reference to the model to any controller class that needs to use it.
On app launch my app needs to call home to a server and download some content. This must be something common done by many apps, my question is what is the standard way of doing so, in particular which object and at at what point should be responsible for instructing the model to connect to the server? Lets assume there is a function on the model called CallHome() implemented asynchronously using NSURLConnection which can notify interested classes when complete.
Where should I perform this:
1) Could it be done in didFinishLaunchingWithOptions?
2) If didFinishLaunchingWithOptions should execute and return before the model executes CallHome() then which class should call CallHome()? Can the AppDelegate do this? If so where?
3) Could the model invoke CallHome() itself, if so when?
4) Or is this actually the job of a controller? If so should it be the root controller?
5) However what if the root controller doesn't need a reference to the model otherwise? So does that imply it should be another controller?
What is the recommended approach for the high level design for this functional requirement?
Many thanks.
you should make any server requests not before first view controller's viewDidAppear you can trigger your web service request in viewDidAppear of first view controller.
the reason behind the scene is if you web service call is synchronous, it will block the main thread (your application ideally, should not block application's main thread) and hence on device your application will crash unexpectedly during launch and hence will be rejected by apple on submitting it for AppStore.