ios App improve network performance by requesting data up front - ios

I have an application that I'm writing that pulls data from a few network sources:
1) list of blog posts (UITableViewController)
2) list of videos (UIViewController with an embedded UIScrollView)
3) list of images (UIViewController with an embedded UIScrollView)
Right now, there is a home screen with a menu and when you push one of the buttons, a destinationViewController (described above) is what loads the data on demand. I've noticed this is quite slow, especially when on a cellular data connection as opposed to wifi.
I was thinking about creating a class that requests all the data up front and kick it off every time the app is reentered. Does anyone have suggestions that could help me answer the following?
1) are there any classes, frameworks, or existing i code i can use to kick off these requests in a single place?
2) how do my destination view controllers (mentioned above) get the data?
3) how do my destination view controllers get informed that the data is ready if they happen to be invoked before the data is available?
4) is there a better strategy i should employ?
I appreciate the help.
Thanks,
jas

Off the top of my head, I would make the request class you mentioned and start all the request methods in applicationDidFinishLaunching in AppDelegate. I would also probably make custom NSObjects for each type of object you would be fetching and in each of your request class methods, convert the fetched data into said object, then cache each object to disk as they are downloaded. Then in your viewcontrollers, fetch the cached objects as needed.
When you are cacheing, make sure you cache each object with a key that will 100% be unique, because you are going to want to run a check on the current local cache before you start a new download. I would probably string together the file type and file name, and set that string as the key for the cached object.
To run the check on current cache in your request class methods, something that says "if current cache contains object for key:
uniqueKey... do nothing. If else, start the download and cache the object when finished."
Also run a check in your view controllers, because you're also going to want to handle the case where your view controller is requesting a cached object, but it hasn't downloaded yet. So something along the lines of "if current cache has object for key:key, great! use it. If else, start the download... cache it... then give me a call back here so i can use it while I display a loading message to the end user."
Im sure there are other scenarios that you are going to have to deal with, but that's the theoretical direction I would head in.
EDIT:
check out this, it will probably help you a lot. I think it also uses Ego Cache (if you dont want to write your own cache methods): https://github.com/Infusion-apps/Download-Manager
EDIT 2:
I also agree with #RyanDignards point #4. If possible, avoid fetching data you don't need. However, only you really know your UI/UX and app functionality, and my suggestion is assuming there is a good chance your end user is going to be using your app for the sole purpose of consuming the content you provide. So they are most likely going to be wanting to read the blog posts, watch the videos etc... The call is up to you, if you think there is more of a chance that the user will be viewing all the content than not, I would go the preload route, because nothing pisses off a user like having to wait.

1) RestKit is generally regarded as one of the the standard web interaction frameworks http://restkit.org
2) RestKit provides methods such as -[getObjectsAtPath: parameters: success: failure:] or post, which will provide the response in success. Additionally, it can convert the response directly into the respective objects for you with mapping.
3) Generally I would post a notification which is unique to that request, and any controller interested would get notified, with the response located on notification.object within the listener. Additionally most network requests provide for a callback handler where you could update the UI directly.
4) I would advise against preemptive loading since you're using resources for something that you may not actually use. My advice would be to breakdown your calls to the smallest possible level, then as the notifications are posted, that data would be inserted into the UI.

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.

swift iOS what ways can I cache network calls

The first thing a user has to do when he/she is launching my app is to select a category and a sub-category from two table views. (relational)
I populate the table views by calling my remote API/Server and the output the data.
But is there a way to cache the data so that I don't have to make a API network call every time?
You can serialize the data returned from the API calls and manually save them on the disk Explanation here
Also you can use core data this is a bit more troubling in the beginning but after the initial setup it is pretty easy to use.

Best way to handle a JSON call and use it's information in all views

I have a API serving a JSON with all the information needed to put into my app, and it will serve with texts and all the news needed for all the views in the app.
This information and JSON will never be big enough that i need to make multiple calls or even paginate, but the information might be changed in the future since it's an app for an event, and some minimum stuff will be added to the information like, sponsors logo, and some stuff like that.
I was wondering, what is the best way to handle this? Make an API call on the appdelegate or something, save it local and make one API call per day to "update" this local file?
Also, technically speaking, how do i handle the information for all the views?
Keep reading this local file everytime a view is loaded?
implement a singleton class that holds your data inside proper data structure(s). you need to download the JSON in the root view controller and display an activity indicator to the user. in every view controller you can access the singleton class object asking for the data relative to you controller.
I wouldn't put it in the app delegate -- the app delegate should remain small and only deal with APP specific issues and to do
generally you want to keep the Separation of Concerns (dijkstra ;))
I would have a singleton MyDataManager that exposes dataWithCompletion: and in that method, decide if you return the cached data (saved locally) or make an HTTP Request to update it)
For starters you can make a shared instance (singleton) to handle your API calls with AFNetworking or what ever you prefer.
Doing this only once a day is not a bright idea if the response is very small, eg. 5000 characters is only 5kb. You can download and save the images once. So I would prefer calling your API every time the app launches in didFinishLaunchingWithOptions.
To handle the views from your response, you need to make sure your JSON response structure (keys) are always the same.
Example: self.eventTitle = [response objectForKey:#"event-title"]; where "event-title" should never change, your app will crash or give a (null) value.
You can create a singleton object with the json serialize method. The you can instantiate your method to serialialize a JSON that is inside your singleton object wherever you want.
You can follow this guide: http://www.galloway.me.uk/tutorials/singleton-classes/

How to ensure data consistency and truly take advantage of Core Data?

I've worked on several iOS apps, some of them utilize Core Data, and some of them don't. While I consider myself having a basic to somewhat good understanding of Core Data, there's always something that makes me doubt the usefulness of it. I've done a lot of reading on the subject, and the general consensus seems to be the advantages of using it outweighs the disadvantages. I recently submitted an app without using Core Data, and always planned on going back to update the project to utilize it when I have the time for some optimization work. Now's the time, but I wonder if it makes sense for the app I'm working on, and maybe I am not using it correctly all along. Please advise and point out what I am missing.
The project I am working on is a social networking app, which also has a front-end site. We have standard features like a newsfeed, event listing, the ability to follow/unfollow someone, and a map with POIs at user's location. Currently, we're using pagination whenever needed when requesting data from server.
My understanding of why Core Data is great:
Easier to manage data with complicated relationship
Easier to access data without having to pass them around
Easier to manipulate, fetch, and sort your data
Better memory utilization
Improve perceived performance by preloading data stored locally until latest data's received
The problem I am having is, since I am using pagination when requesting for data instead of requesting for all at once. The data stored locally is only a subset of the current state in the database. Let's use newsfeed as an example. If I do the following, it will cause some problems:
User manually refresh the newsfeed -> Controller notifies model that it needs the latest 20 items -> Model requests for the latest 20 items in the newsfeed and save them as NSManagedObject -> Model notifies controller that data is ready -> Fetch the latest 20 items to show in UITableView
If user A refreshes the newsfeed, background the app, and then user B deletes his post in the newsfeed (let's say it was 10th item) before user A foregrounds the app again to refresh the newsfeed. In user A's newsfeed, B's post will still be up there because according to the createdAt attribute, it's indeed one of the latest 20 items.
To fix this problem, I can think of a few solutions:
Add a flag to the item to indicate it's removed
Always discard local data when new data arrives
Disable pagination
Instead of using the workflow described above, always present the requested data only instead of fetching the latest
Solution 1 means custom code is required to deal with different clients since browser doesn't need deleted items but iOS client does. However, even though it can work, it can potentially mess up the pagination mechanism and can cause weird behaviours in the client. For example, if a large amount of items gets removed, the latest 20 items will contain only a few items that will actually show up in the newsfeed on the client when user refreshes it. As user follows more people, more stories will be inserted in his newsfeed as well. This solution won't work very well in this situation.
Solution 2 totally defeats the purpose of using Core Data in the first place unless I am missing something.
Solution 3 means the client always needs to request for all data. This is nearly impossible to do because as you get more data, the time to retrieve and process them will make the app slow and unresponsive. It also doesn't make sense from technical and UX point of view.
Solution 4 also kinda defeats the purpose of using Core Data because it's the same workflow when we only store data in memory. You can still fetch and find objects but they might be invalid on the server already at the time of access.
Am I missing something? How is Core Data supposed to be used in this scenario? How do you ensure data consistency when the client doesn't have all the data? Thanks you in advance.

Hold a data object temporarily in MVC controller,MVC,MVC Controller temp storage

I have a object that i want to store for a moment. The object is in a controller for now, the controller will generate a view. A AJAX request is made from the view to next controller. For that moment i need the object previously stored. Previously, i used session and it worked well. But not sure it is the right thing to do. Is session the answer for this or is there anything else?
I have used cache also.but as per the cache concept.It will access for all the users.So one user data will be override to another.So the cached object data will be change for the same user.I need to handle the data storage for an particular user(Independent).
How is it possible? anyother approach is there please share me.
In Controller I have used Httpcontext.cache["key"]=dataset;
but some one suggested like this.but its not displaying
Explain:
In Controller: httpcontext.current.cache is not coming.
HttpContext.Currenthandler and HttpContext.Currentnotification properties only coming.So How can we handle the temp data storage in MVC.
Please help me.
You could use TempData if you want to store data for the next request only. If data should be accessible between multiple requests, then use Session. Here is short explanation of each one with examples.
As Alex said you could use TempData but if you want to use the data in multiple request, you could use TempData.Keep("YourKey") after reading the value to retain the data for the next request too. For your Information TempData internally uses Session to store your data (temporarily)
I would recommend URL parameters for a HTTP Get, or hidden form fields for a HTTP Post, if this is short lived. This is highly about avoiding the session.
But if it should really persist, then a database might be a reasonable location. Imagine a shopping cart that you don't want to dump just because a session timed out; because you'd like to remind the user next time about items they still haven't purchased.
Why not use the session? I don't generally recommend using the session, as you could find yourself with a global variable that two different browser windows are manipulating. Imagine a glass. One window is trying to fill it with Ice Tea. Another window is trying to fill it with Lemonade. But what do you have? Is it Lemonade? Is it Ice Tea? Or is it an Arnold-Palmer? If you try to put too much stuff on the session, and overly expect it to just be there, you might create an application that is non-deterministic if heaven forbid a user opens a second window or tab, and switches back and forth between the windows.
I'm more ok with Temp Data, if you truly have no other options. But this is not for persisting data for more than a second. Temp data will disappear after the first request reads it, as in, it's meant for a very temporary usage.
I personally only use TempData if I have to do a redirect where I can't otherwise keep it with me, or if I need to have that data for say generating a PDF or image that is going to be called via a HTTP Get by a viewer on the actual page, and then only if the model data is too large for the GET url ( many browsers only support just over 2000 characters, which long description or many fields could fill up.)
But again, pushing items around in hidden form variables, or in url parameters can be safe, because you have no multiple window use conflicts (each carries around its own data for peace of mind.)

Resources