do network call from current ViewController or parent ViewController? - ios

I'm writing an app that contains network call in every other screen. The result of calls would be the dataSource for a specific screen.
The question is, should I do network call in the parent viewController and inject the data before pushing current viewController or push currentViewController and do network call on viewDidLoad()/viewWillAppear()?
Both the methods makes sense to me.

Where you make the request to network should actually make no difference. You are requesting some data which you will have to wait for and present it. Your question is where should you wait for the data to be received.
As #Scriptable already mentioned you can do either of the two. And which to use depends on what kind of user experience you wish to have. This varies from situation to situation but in general when we create a resource we usually wait for it on current screen and when we are reading resources we wait for it on the next screen:
For instance if you are creating a new user (sign up) after you will enter a new username and password an indicator will appear and once the request is complete you will either navigate to next screen "enter your personal data" or you will receive a message like "User already exists".
When you then for instance press "My friends" you will be navigated to the list first where you will see activity indicator. Then the list appears or usually some screen like "We could not load your data, try again."
There are still other things to consider because for the 2nd situation you can add more features like data caching. A lot of messaging applications will for instance have your chats saved locally and once you press on some chat thread you will be navigated directly to seeing whatever is cached and you may see after a bit new messages are loaded and shown.
So using all of this if we get back to where you should "call" the request it seem you best do it before you show the new controller or at the same time. At the same time I mean call it the load on previous view controller but load the new view controller before you receive the new data.
How to do this best is having a data model. Consider something like this:
class UsersModel {
private(set) var users: [User]?
}
For users all we need is a list of them so all I did was wrapped an array. So in your case we should have an option to load these users:
extension UsersModel {
func fetchUsers() {
User.fetchAll { users, error in
self.users = users
self.error = error // A new property needed
}
}
}
Now a method is added that loads users and assigns them to internal property. And this is enough for what we need in the first view controller:
func goToUsers() {
let controller = UserListViewController()
let model = UserModel()
controller.model = model
model.fetchUsers()
navigationController.push(controller...
}
Now at this point all we need is to establish the communication inside the second view controller. Obviously we need to refresh on viewDidLoad or even on view will appear. But we would also want some delegate (or other type of connections) so our view controller is notified of changes made:
func viewDidLoad() {
super.viewDidLoad()
self.refreshList()
self.model.delegate = self
}
And in refresh we should now have all the data needed:
func refreshList() {
guard let model = model else {
// TODO: no model? This looks like a developer bug
return
}
if let users = model.users {
self.users = users
tableView?.reloadData()
if users.count.isEmpty {
if let error = model.error {
// TODO: show error screen
} else {
// TODO: show no data screen
}
}
} else {
// TODO: show loading indicator screen
}
}
Now all that needs to be done here is complete the model with delegate:
extension UsersModel {
func fetchUsers() {
User.fetchAll { users, error in
self.users = users
self.error = error // A new property needed
self.delegate?.usersModel(self, didUpdateUsers: self.users)
}
}
}
And the view controller simply implements:
func usersModel(_ sender: UserModel, didUpdateUsers users: [User]?) {
refreshList()
}
Now I hope you can imagine the beauty of such a system that your model could for instance first asynchronously load users from some local cache or database and call the delegate and then call the request to server and call the delegate again while your view controller would show appropriate data for any situation.

Related

Retreiving data with Core Data

I'm working on a project where I should save data locally with Core Data.
Here is my workflow :
To start, I ask the user to fill a form, let's say his firstname and lastname.
He clicks on the submit button, then data is saved on the device using Core Data
User is redirected to the "last filled form" view controller.
I have a bar button item that when clicked can show the latest filled form.
I should test if the array of filled forms is empty, then the button should be disabled.
Otherwise, the button should be enabled ...
I tried this piece of code, where I fetch data from the database and affected to an array but the button seams not working at all and it never gets disabled ...
class ViewController: UIViewController {
var userIdentity: UserIDentity = UserIDentity(context: PersistanceService.context)
var identityArray = [UserIDentity]()
override func viewDidLoad() {
super.viewDidLoad()
self.fetchIdentityHistoryArray()
}
func fetchIdentityHistoryArray(){
let fetchRequest: NSFetchRequest<UserIDentity> = UserIDentity.fetchRequest()
do {
let identityArray = try PersistanceService.context.fetch(fetchRequest)
if identityArray.isEmpty {
self.identityHistoryButton.isEnabled = false
}
else {
self.identityHistoryButton.isEnabled = true
}
}
catch {
print("Error fetching sworn statement history !")
}
}
}
So I have 2 questions :
What's wrong with my code ?
How can I manage that when the user clicks on the "back button" for the first form filled ever, the "history button" can refresh itself and turn from disabled to enabled button ?
Any help is much appreciated. Thank you
You are initialising a core data object directly in your code
var userIdentity: UserIDentity = UserIDentity(context: PersistanceService.context)
This new object will exist in Core Data and will be included everytime you execute the fetch request. You must understand that Core Data is not a database layer it is an object mapping layer so even if you haven't called save() yet the object exists in the Core Data context.
Either change the declaration to
var userIdentity: UserIDentity?
or remove it completely if it isn't used.

How to read in data just the once when using a tabcontroller

I feel like I'm missing something and this should not be too hard.
I'm reading in some data in the initial scene in my app.
I've got a singleton and I make the call in viewDidLoad to singleton.getData().
This initial scene is part of a tab controller. And while I thought viewDidLoad would only get called once for each scene I'm pretty sure it's being called a few times during the lifecycle of my app.
So just wondering if there is a way to ensure a function call to retrieve some data only happens once.
viewDidLoad will be called when selected tab is changed, you can change the place you call getData.
If you want to call getData in viewDidLoad and be sure it won't be called multiple times you can create a flag and check, if it is previously called or not.
class Singleton {
static let sharedInstance = Singleton()
private static var getDataCalled = false
func getData() {
if Singleton.getDataCalled {
return
}
Singleton.getDataCalled = true
// request data
print("data requested")
}
}
Singleton.sharedInstance.getData()
Singleton.sharedInstance.getData()
Calling getData multiple times print data requested only once.

How to communicate between Service and Viewcontroller?

I'm pretty new to iOS and swift development. A lot of swift + firebase tutorials out there, the firebase stuff (such as authentication, fetching and saving data) is done in the ViewController. As far as I got on learning swift, this leads directly to the problem of "Massive View Controllers". In some tutorials they use classes like "DataService.swift" and access them as a singleton:
class DataService {
static let dataService: DataService = DataService()
func createUser(FIRUser: user) {}
...
}
BUT these classes have no communication with the view controller when they're done with e.g. creating the user. Let me be more specific. I guess it should like this:
User taps login button.
Then, ViewController calls dataService.createUser(user) which handles the login stuff and saves the user data to firebase.
If it's finished it should communicate to the view controller, that it's finished.
ViewController checks the result of the createUser() and navigates the user to another view.
How can i do this? At the moment i'm using the delegation pattern. Is this a good way to handle this stuff?
You can do it this way:
// User.swift
struct User {
// Declare necessary properties.
// Such as firstName, lastName, email, etc.
}
// AuthenticationService.swift
protocol AuthenticationService {
func createUser(user: User, completion: (Error?, User?) -> Void)
}
// AuthServiceProvider.swift
class AuthServiceProvider: AuthenticationService {
func createUser(user: User, completion: (Error?, User?) -> Void) {
// Do the necessary work here.
// Convert user to an instance of 'FIRUser' if necessary.
// Use the completion block when you are done.
}
}
// RegisterViewController.swift
class RegisterViewController: UIViewController {
var service = AuthServiceProvider()
#IBAction func didTapRegisterButton(sender: UIButton) {
var user = User()
// Fill the necessary properties to be included.
// Then call the 'createUser' function.
service.createUser(user: user) { (error, user) -> Void in
// This is where you are redirected upon completion.
// Handle always the error if there is.
// If there is none, navigate to your next scene/view.
}
}
}
By the way, as much as possible, just avoid implementing a Singleton Class. This kind of implementation might give you a hard time on doing some unit tests.
Regarding with your concern on "Massive View Controller", you can consider on modularizing your project. But right now, I would suggest that it is better to experience this "MVC" problem than avoiding it.

Won't update UILabel from Parse data in swift

I am trying to update my UILabel to a String from my Parse database.
My problem is the label will not update my firstnameLabel when I first sign in. But it WILL update, when i sign in (nothing happens), push the stop button in Xcode and then launch it again (still logged in) and then it updates the label.
How can I do this faster??
Here is my code:
var currentUser = PFUser.currentUser()
if currentUser != nil {
var query = PFQuery(className:"_User")
query.getObjectInBackgroundWithId(currentUser.objectId) {
(bruger: PFObject!, error: NSError!) -> Void in
if error == nil && bruger != nil {
var firstName: String = bruger["firstname"] as String
self.usernameLabel.text = firstName
} else {
println("Error")
}
}
} else {
self.performSegueWithIdentifier("goto_login", sender: self)
}
Hope you can help me!
Rather than trying to load the user object again by the id, try just doing a fetch instead.
[currentUser fetchIfNeededInBackgroundWithBlock: ... ];
By trying to load the object, you might be getting a cached version.
I read somewhere that it could be because of the fact that the could was put inside the ViewDidLoad. I tried to put it outside of that and it worked!
It sounds like you put it in the ViewDidLoad method. You should put it in the ViewWillAppear method instead. Here's an example.
1) ViewDidLoad - Whenever I'm adding controls to a view that should appear together with the view, right away, I put it in the ViewDidLoad method. Basically this method is called whenever the view was loaded into memory. So for example, if my view is a form with 3 labels, I would add the labels here; the view will never exist without those forms.
2) ViewWillAppear: I use ViewWillAppear usually just to update the data on the form. So, for the example above, I would use this to actually load the data from my domain into the form. Creation of UIViews is fairly expensive, and you should avoid as much as possible doing that on the ViewWillAppear method, becuase when this gets called, it means that the iPhone is already ready to show the UIView to the user, and anything heavy you do here will impact performance in a very visible manner (like animations being delayed, etc).
3) ViewDidAppear: Finally, I use the ViewDidAppear to start off new threads to things that would take a long time to execute, like for example doing a webservice call to get extra data for the form above.The good thing is that because the view already exists and is being displayed to the user, you can show a nice "Waiting" message to the user while you get the data.

ios swift parse: methods with async results

When I go to a viewController I call within my viewDidAppear Method a function:
override func viewDidAppear(animated: Bool) {
getLessons()
}
This methods loads from parse.com a list of data I want to use in a pickerView.
The function itself:
func getLessons(){
var query = PFQuery(className:"Lesson")
query.orderByAscending("name")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
var name = object["name"] as String
self.languagePickerKeys.append(object.objectId)
self.languagePickerValues.append(name)
self.selectedLanguage.text = self.languagePickerValues.first // set the first lessons name into the text field
self.selectedLessonObjectId = self.languagePickerKeys.first // set the first objectId for the lesson
self.languagePicker?.reloadAllComponents()
}
} else {
// Log details of the failure
println("\(error.userInfo)")
}
}
println("getLessons done")
}
The thing is, that the textfield is empty, as the getLesson() gets the data async and the data is not available to the textfield.
I also tried to put the getLesson into the viewDidAppear method, but this doesn't help me, the textfield is empty anyway.
What can I do, to have the data from the getLessons() method ready and loaded its first value into my textfield when the view is shown to the user?
You certainly have to get the data from asyncTask before setting it to pickerView.
Here's the ViewController lifecycle after instantiation:
Preparation if being segued to.
Outlet setting
Appearing and Disappearing.
So, you have two options:
Load the data in previous ViewController and then perform the segue. You need to follow these steps for it.
a. Create a segue from previous ViewController to your ViewController.
b. Call the function when you want to go next ViewController which fetches the data, and the end (after getting the data) call performSegueWithIdentifier which will lead to your ViewController.
c. Set the data in prepareForSegue
let navigationController = segue.destinationViewController as UINavigationController
navigationController.data = yourData //you got from async call
Now when you reach your ViewController, you are sure that your data is present, and you can set it to your pickerView.
If you want to do it in the same ViewController: here's is the lifeCycle of ViewController:so you need to call your function in viewDidLoad, and always set your pickerView after completion of the async network call.
Make sure that you initiate all changes to the UI from the main thread e.g. like so:
dispatch_async(dispatch_get_main_queue(), {
selectedLanguage.text = languagePickerValues.first
self.languagePicker?.reloadAllComponents()
})
The problem is that findObjectsInBackgroundWithBlock is an asynchronous method, so even if you fire it in the ViewDidLoad you will never know when you will receive the response data and you can't be sure that the data will be ready by the time you view appear.
I think you have just 2 possibility:
The first one is to load the data in the previous view controller and then just pass the data that got ready to you view controller.
The second is to use a synchronous method (the findobject method maybe?) and put the call in a method that is fired BEFORE the view appear (like the viewWillAppear: method). But your view will stuck for a moment (I think) while the data is retreiving... However this second solution probably resolve your problem but using synchronous method to retrieve data from a slower data source is usually bad design solution.
D.

Resources