Preprocessing in Swift application - ios

In my swift app, during the initialization and load process I need to check CoreData for the availability of some records and further more make some bluetooth connections before display to the user.
Is there a recommendation on how to do this? Should I write this code directly in the AppDelegate or should I write it in a different Swift class and then invoke from the AppDelegate?
I am new to Swift so your suggestions are appreciated.

You Can do all this stuff in your View Controller i.e. your rootViewController by showing loader on screen to user and Checking the records in core data if present ,then retrieve them.

Don't be Confuse , just create a function checkRecords in appDelegate and put your code inside it and Call this function.

Related

Keeping a WKWebView and it's UIViewController in the background running and accessible from multiple ViewControllers

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.

iMessage Extension and CoreData

I am trying to read CoreData out of an iMessage Extension (MSMessagesAppViewController) but as there is no AppDelegate there is also no managedContext.
Has anybody an idea if that is possible?
Is it possible to "instantiate the AppDelegate" of my App or something like that?
Update: How to access core data within an app and an extension: The solution for this is to use AppGroup container.
Using Core Data has nothing to do with whether there is an application delegate. They are two separate things. You can put them together but neither Core Data nor the application delegate requires that. It's not even very good design to do so. The app delegate's job is to respond to app life-cycle events like launching, going into the background, etc, and it's bad design to also mix in the separate job of managing the app's data.
If you create a new project in Xcode and check the "use Core Data" box, Xcode will include methods in the app delegate class to set up Core Data for the app. But that code can go in any class. There's nothing special about the app delegate that requires that code to be in that class. Just because Xcode puts that code in that class doesn't mean that it's necessary to do it that way. If you need to use Core Data in an app extension, that's what you'll do.
One common approach is to create a new class to manage Core Data. Put all your Core Data stack management code there, instead of in the app delegate. The app delegate might create an instance of this class in your app. In an app extension, the class can be instantiated wherever it's needed for the type of extension.

Sending a dictionary from iOS app to WatchKit - watchOS2

My goal is to send a dictionary to the watchKit from iOS app prior to the watchKit's app launch. I'm using interactive messaging (sendMessage) to quickly transfer the dictionary.
The issue is - dictionary is created inside the MainViewController. If i declare the WCSession and activate it inside the MainViewController i can transfer the data to the watchKit on the simulator without any problem. But when i test the process on a real device - the iOS app never gets called.
Waking the app in the background is done by declaring and activating the WCSession inside the AppDelegate, but there's another blocker - i cannot create the dictionary - because multiple variables for its creation are declared inside the MainViewController.
I tried a third approach - wrapping the WCSession inside a singleton (suggested by Natasha the robot). The only drawback of this framework is that the Interactive messaging never works and wasn't ever tested by Natasha herself.
So i'm confused - what do i do to send the dictionary to the watchKit?
Thanks for any insights
You need to figure out a way to get the dictionary created outside of MainViewController. Perhaps you can write a class method in the controller that creates and returns the dictionary so that it can be used from both AppDelegate and MainViewController.
You should use a data store to hold your dictionary, then have it create its data based on the variables passed to it by the main view controller.
Once that occurs, you can use the WCSession manager to transfer the data store's dictionary.
I know Natasha covers these aspects in her tutorial. If you have a specific question as to how to do that, you'd really need to post code showing what you tried, along with a description of what's not working.
If the watch asks for data, but it has not been created yet, you need to return a "No data yet" reply so the watch can display a message telling the user to open the app and set the view controller's variables used for creating the data.
It really is better to separate and encapsulate responsibilities into these different components. The view controller shouldn't need to contain any code related to creating or transferring the dictionary.
Having said all that...
I cannot create the dictionary - because multiple variables for its creation are declared inside the MainViewController
This really sounds like an XY problem. You've been focused on the problem of "sending" this dictionary of large arrays that you have to create, when there's likely an easier way to accomplish what you're actually trying to do with this large dictionary in the first place.
For one, I'd wonder why you're sending that huge computed data set to the watch for it to do something with, instead of also handling that computation on the phone side, then sending a very small set of "results".
Perhaps you should describe the real Y problem you want to solve on the watch, instead of asking us for an X solution which may end up being unnecessary.

Changing Core Data when app starts

I am developing an iOS app which downloads xml data that are valid for 4 hours. I want to check validity and, if needed, update this data when my app starts.
I am using this xml parser to load data http://www.theappguruz.com/blog/xml-parsing-using-nsxmlparse-swift
Right now I am calling beginParse() and parsing data in AppDelegate.swift in function didiFinishLaunchingWithOptions. Is this the correct place to perform this background task?
In tutorial which I posted the guy does it in view controller but I want to use this parser to update coredata and I need it to run in background after app launches.
Thanks in advance
The professional way to do this would be have a function (or even a full class), to manage this download/parse data and asynchronously save in your core data, after that, you can inform the view that you have new content to load (or if there was an error or something).
About where to call the function, it depends...
If you should only show to the user the most updated information (like locking the screen whit a "loading..." or something like it), put the call in the first view controller, just because would be simpler to just call an completion handler to unlock and load the data.
But, if you can load the "old" information, just to be faster and refresh when the new content is available, i think that you can call in the appDelegate with no problem.

Send Progress from NSURLSession to ViewController [swift - iOS]

I'm developing an app which handles some downloads in the background. I move the file to the documents directory and save it under the original name (using downloadTask.originalRequest?.URL!.pathExtension). So far so good.
Using
URLSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)
I can print out the progress in the console while downloading. But this doesn't help me if I'm using the App on the phone. What I'm expecting to do is to call a function to update a progress bar from here within my View that was initialising the download. But I have no idea how to call it.
Does anybody know how I can find out from which UIViewController (actually most of the time it will be a TableCellViewController) I started the download and how to send the progress to a function of that ViewController?
I 'd like to tell you a good tutorial about this question. NSURLSession Tutorial
Delegates are often used in the following situations
When a class needs to communicate some information to another class
When a class wants to allow another class to customize it
The classes don't need to know anything about each other beforehand except that the delegate class conforms to the required protocol.
I the following article you can see how to create a delegate in objective-C and Swift 2.0.
How do I create delegates in Objective-C?

Resources