swift shouldPerformSegueWithIdentifier get data async - ios

Im making a very basic app which has a search field to get data that is passed to a tableview.
What I want to do is run an Async task to get the data and if the data is succesfully fetched go to the next view, during the loading the screen must not freeze thats why the async part is needed.
When the user pressed the searchbutton I run the following code to get data in my
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
method.
var valid = true
let searchValue = searchField.text
let session = NSURLSession.sharedSession()
let url = NSURL(string: "https://someapi.com/search?query=" + searchValue!)
let task = session.dataTaskWithURL(url!, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let theData = data {
dispatch_async(dispatch_get_main_queue(), {
//for the example a print is enough, later this will be replaced with a json parser
print(NSString(data: theData, encoding: NSUTF8StringEncoding) as! String)
})
}
else
{
valid = false;
print("something went wrong");
}
})
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
task.resume()
return valid;
I removed some code that checks for connection/changes texts to show the app is loading data to make the code more readable.
This is the part where I have the problem, it comes after all the checks and im sure at this part I have connection etc.
What happens is it returns true (I can see this because the view is loaded), but also logs "Something went wrong" from the else statement.
I Understand this is because the return valid (at the last line) returns valid before valid is set to false.
How can I only return true (which changes the view) if the data is succesfully fetched and dont show the next view if something went wrong?

Because you want the data fetching to be async you cannot return a value, because returning a value is sync (the current thread has to wait until the function returns and then use the value). What you want instead is to use a callback. So when the data is fetched you can do an action. For this you could use closures so your method would be:
func shouldPerformSegue(identifier: String, sender: AnyObject?, completion:(success:Bool) -> ());
And just call completion(true) or completion(false) in your session.dataTaskWithURL block depending on if it was successful or not, and when you call your function you give a block for completion in which you can perform the segue or not based on the success parameter. This means you cannot override that method to do what you need, you must implement your own mechanism.

Related

How to move to the next view upon data reception?

I am struggling to trigger the logic responsible for changing the view at the right time. Let me explain.
I have a view model that contains a function called createNewUserVM(). This function triggers another function named requestNewUser() which sits in a struct called Webservices.
func createNewUserVM() -> String {
Webservices().requestNewUser(with: User(firstName: firstName, lastName: lastName, email: email, password: password)) { serverResponse in
guard let serverResponse = serverResponse else {
return "failure"
}
return serverResponse.response
}
}
Now that's what's happening in the Webservices' struct:
struct Webservices {
func requestNewUser(with user: User, completion: #escaping (Response?) -> String) -> String {
//code that creates the desired request based on the server's URL
//...
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
DispatchQueue.main.async {
serverResponse = completion(nil)
}
return
}
let decodedResponse = try? JSONDecoder().decode(Response.self, from: data)
DispatchQueue.main.async {
serverResponse = completion(decodedResponse)
}
}.resume()
return serverResponse //last line that gets executed before the if statement
}
}
So as you can see, the escaping closure (whose code is in the view model) returns serverResponse.response (which can be either "success" or "failure"), which is then stored in the variable named serverResponse. Then, requestNewUser() returns that value. Finally, the createNewUserVM() function returns the returned String, at which point this whole logic ends.
In order to move to the next view, the idea was to simply check the returned value like so:
serverResponse = self.signupViewModel.createNewUserVM()
if serverResponse == "success" {
//move to the next view
}
However, after having written a few print statements, I found out that the if statement gets triggered way too early, around the time the escaping closure returns the value, which happens before the view model returns it. I attempted to fix the problem by using some DispatchQueue logic but nothing worked. I also tried to implement a while loop like so:
while serverResponse.isEmpty {
//fetch the data
}
//at this point, serverResponse is not empty
//move to the next view
It was to account for the async nature of the code.
I also tried was to pass the EnvironmentObject that handles the logic behind what view's displayed directly to the view model, but still without success.
As matt has pointed out, you seem to have mixed up synchronous and asynchronous flows in your code. But I believe the main issue stems from the fact that you believe URLSession.shared.dataTask executes synchronously. It actually executes asynchronously. Because of this, iOS won't wait until your server response is received to execute the rest of your code.
To resolve this, you need to carefully read and convert the problematic sections into asynchronous code. Since the answer is not trivial in your case, I will try my best to help you convert your code to be properly asynchronous.
1. Lets start with the Webservices struct
When you call the dataTask method, what happens is iOS creates a URLSessionDataTask and returns it to you. You call resume() on it, and it starts executing on a different thread asynchronously.
Because it executes asynchronously, iOS doesn't wait for it to return to continue executing the rest of your code. As soon as the resume() method returns, the requestNewUser method also returns. By the time your App receives the JSON response the requestNewUser has returned long ago.
So what you need to do to pass your response back correctly, is to pass it through the "completion" function type in an asynchronous manner. We also don't need that function to return anything - it can process the response and carry on the rest of the work.
So this method signature:
func requestNewUser(with user: User, completion: #escaping (Response?) -> String) -> String {
becomes this:
func requestNewUser(with user: User, completion: #escaping (Response?) -> Void) {
And the changes to the requestNewUser looks like this:
func requestNewUser(with user: User, completion: #escaping (Response?) -> Void) {
//code that creates the desired request based on the server's URL
//...
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
DispatchQueue.main.async {
completion(nil)
}
return
}
let decodedResponse = try? JSONDecoder().decode(Response.self, from: data)
DispatchQueue.main.async {
completion(decodedResponse)
}
}.resume()
}
2. View Model Changes
The requestNewUser method now doesn't return anything. So we need to accommodate that change in our the rest of the code. Let's convert our createNewUserVM method from synchronous to asynchronous. We should also ask the calling code for a function that would receive the result from our Webservice class.
So your createNewUserVM changes from this:
func createNewUserVM() -> String {
Webservices().requestNewUser(with: User(firstName: firstName, lastName: lastName, email: email, password: password)) { serverResponse in
guard let serverResponse = serverResponse else {
return "failure"
}
return serverResponse.response
}
}
to this:
func createNewUserVM(_ callback: #escaping (_ response: String?) -> Void) {
Webservices().requestNewUser(with: User(firstName: firstName, lastName: lastName, email: email, password: password)) { serverResponse in
guard let serverResponse = serverResponse else {
callback("failure")
return
}
callback(serverResponse.response)
}
}
3. Moving to the next view
Now that createNewUserVM is also asynchronous, we also need to change how we call it from our controller.
So that code changes from this:
serverResponse = self.signupViewModel.createNewUserVM()
if serverResponse == "success" {
//move to the next view
}
To this:
self.signupViewModel.createNewUserVM{ [weak self] (serverResponse) in
guard let `self` = self else { return }
if serverResponse == "success" {
// move to the next view
// self.present something...
}
}
Conclusion
I hope the answer gives you an idea of why your code didn't work, and how you can convert any existing code of that sort to execute properly in an asynchronous fashion.
This can be achieve using DispatchGroup and BlockOperation together like below:
func functionWillEscapeAfter(time: DispatchTime, completion: #escaping (Bool) -> Void) {
DispatchQueue.main.asyncAfter(deadline: time) {
completion(false) // change the value to reflect changes.
}
}
func createNewUserAfterGettingResponse() {
let group = DispatchGroup()
let firstOperation = BlockOperation()
firstOperation.addExecutionBlock {
group.enter()
print("Wait until async block returns")
functionWillEscapeAfter(time: .now() + 5) { isSuccess in
print("Returned value after specified seconds...")
if isSuccess {
group.leave()
// and firstoperation will be complete
} else {
firstOperation.cancel() // means first operation is cancelled and we can check later if cancelled don't execute next operation
group.leave()
}
}
group.wait() //Waits until async closure returns something
} // first operation ends
let secondOperation = BlockOperation()
secondOperation.addExecutionBlock {
// Now before executing check if previous operation was cancelled we don't need to execute this operation.
if !firstOperation.isCancelled { // First operation was successful.
// move to next view
moveToNextView()
} else { // First operation was successful.
// do something else.
print("Don't move to next block")
}
}
// now second operation depends upon the first operation so add dependency
secondOperation.addDependency(firstOperation)
//run operation in queue
let operationQueue = OperationQueue()
operationQueue.addOperations([firstOperation, secondOperation], waitUntilFinished: false)
}
func moveToNextView() {
// move view
print("Move to next block")
}
createNewUserAfterGettingResponse() // Call this in playground to execute all above code.
Note: Read comments for understanding. I have run this in swift playground and working fine. copy past code in playground and have fun!!!

UI Update Delegate Method Not Called

Working on a practice project (solution found here: https://github.com/appbrewery/ByteCoin-iOS13-Completed) where you swipe with a picker view to see the value of 1 Bitcoin in the selected currency.
Right now, I'm successfully retrieving and parsing the data from coinapi.io, but my delegate method to update the text labels isn't activating and I can't figure out why, even comparing it to the solution code. I'm not getting any errors and it runs fine, but this update method just isn't calling. Why not?
ViewController.swift
// CoinManager Delegate Extension Functionality
extension ViewController: CoinManagerDelegate {
func didUpdateCoin(currency: String, value: String) {
// Test to see if it's being called
print("didUpdateCoin Called")
DispatchQueue.main.async {
// Change the information presented to the user
self.currencyLabel.text = currency
self.bitcoinLabel.text = String(value)
}
}
// If it fails, print the error that occurred
func didFailWithError(error: Error) {
print(error)
}
}
This is where I'm calling it.
CoinManager.swift
var delegate: CoinManagerDelegate?
func performRequest(with urlString: String, currency: String) {
// If the url is valid
if let url = URL(string: urlString) {
// Create the URLSession to request the data
let session = URLSession(configuration: .default)
// Create the task and session with the url
let task = session.dataTask(with: url) { (data, response, error) in
// If there's an error
if error != nil {
// Call the error-handling function
self.delegate?.didFailWithError(error: error!)
// Return without any request being performed
return
}
// If the data is retrieved successfully
if let safeData = data {
// Parse the data
if let value = self.parseJSON(safeData) {
print("Got to just before didUpdateCoin")
// The value is being passed correctly
print(value)
// Not calling, just skipping passed didUpdateCoin
self.delegate?.didUpdateCoin(currency: currency, value: value)
print("Passed didUpdateCoin")
}
}
}
// Continue running
task.resume()
}
}
Output
Got to just before didUpdateCoin
9768.79
Passed didUpdateCoin
The problem is - you have not connected your delegate with second view where you want to update content
For make it works follow next steps:
1) Create Protocol
2) Create delegate variable with your protocol type, you can make it optional
3) Chose where you want to call method from your delegate
4) In related VC assign it itself
5) Subscribe to protocol
6) Add protocol stubs
7) Configure your functionality
For better understanding: https://www.youtube.com/watch?v=DBWu6TnhLeY

Swift - TableView datasource from URLSession task

I have to populate a TableView with some data fetched with an URLSession task. The source is an XML file, so i parse it into the task. The result of parsing, is an array that i pass to another function that populate another array used by TableView Delegates.
My problem is that TableView Delegates are called before task ends, so tha table is empty when i start the app, unless a data reloading (so i know that parsing and task work fine).
Here is viewDidLoad function. listOfApps is my TableView
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
checkInstalledApps(apps: <ARRAY POPULATED>)
listOfApps.delegate = self
listOfApps.dataSource = self
}
}
fetchData is the function where i fetch the XML file and parse it
func fetchData() {
let myUrl = URL(string: "<POST REQUEST>");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = "firstName=James&lastName=Bond";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
self.parser = XMLParser(data: data!)
self.parser.delegate = self
}
task.resume()
}
while checkInstalledApps is the function where i compose the array used by TableView Delegates.
func checkInstalledApps(apps: NSMutableArray){
....
installedApps.add(...)
installedApps.add(...)
....
}
So, for example, to set the number of rows i count installedApps elements
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (installedApps.count == 0) {
noApp = true
return 1
}
return installedApps.count
}
that are 0. Obviously, if i reload data, it's all ok.
My problem is the async call: first of that i used an XML accessible via GET request, so i can use XMLParser(contentsOf: myUrl) and the time is not a problem. Maybe if the XML will grow up, also in this way i will have some trouble, but now i've to use a POST request
I've tried with DispatchGroup, with a
group.enter() before super.viewDidLoad
group.leave() after task.resume()
group.wait() after checkInstalledApps()
where group is let group = DispatchGroup(), but nothing.
So, how can i tell to the tableview delegate to wait the task response and the next function?
thanks in advance
I would forget about DispatchGroup, and change a way of thinking here (you don't want to freeze the UI until the response is here).
I believe you can leave the fetchData implementation as it is.
In XMLParserDelegate.parserDidEndDocument(_:) you will be notified that the XML has been parsed. In that method call checkInstalledApps to populate the model data. After that simply call listOfApps.reloadData() to tell the tableView to reload with the new data.
You want to call both checkInstalledApps and listOfApps.reloadData() on the main thread (using DispatchQueue.main.async {}).
Also keep listOfApps.delegate = self and listOfApps.dataSource = self in viewDidLoad as it is now.
The cleaner way is to use an empty state view / activityIndicator / loader / progress hud (whatever you want), informing the user that the app is fetching/loading datas,
After the fetch is done, just reload your tableview and remove the empty state view / loader
Your problem is caused by the fact that you currently have no way in knowing when the URLSession task ended. The reloadData() call occurs almost instantly after submitting the request, thus you see the empty table, and a later table reload is needed, though the new reload should be no sooner that the task ending.
Here's a simplified diagram of what happens:
Completion blocks provide here an easy-to-implement solution. Below you can find a very simplistic (and likely incomplete as I don't have all the details regarding the actual xml parsing) solution:
func fetchData(completion: #escaping () -> Void) {
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
self.parser = XMLParser(data: data!)
self.parser.delegate = self
completion()
}
override func viewDidLoad() {
super.viewDidLoad()
fetchData() { [weak self] in self?.tableView.reloadData() }
}
Basically the completion block will complete the xml data return chain.

Loading data from API pattern issue

I am building an app that populates data in a collectionView. The data come from API calls. When the screen first loads I get the products and store them locally in my ViewController.
My question is when should I get the products again and how to handle screen changing. My data will change when the app is running (sensitive attributes like prices) , but I don't find ideal solution to make the API call each time viewWillAppear is being called.
Can anybody please tell me what is the best pattern to handle this situation. My first though was to check if [CustomObject].isEmpty on viewWillAppear and then make the call. Including a timer that check again every 10-15 minutes for example.
Thank you for your input.
I'm not sure what the data looks like and how your API in detail works, but you certainly don't have to call viewWillAppear when your API updates the data.
There are two possible solutions to be notified when your data is updated.
You can either use a notification that lets you know whether the API is providing some data. After the Data has been provided your notification then calls to update the collection view. You can also include in the objects or structs that contain the data from your API the "didSet" call. Every time the object or struct is being updated the didSet routine is called to update your collection view.
To update your collection view you simply call the method reloadData() and the collection view will update itself and query the data source that now contains the newly received data from your API.
Hope this helps.
There is no set pattern but it is advisable not to send repeated network requests to increase energy efficiency (link). You can check the time interval in ViewWillApear and send the network requests after certain gap or can use timer to send requests at time intervals. First method would be better as it sends request only when user is on that screen. You can try following code snippet to get the idea
class ViewController: UIViewController {
let time = "startTime"
let collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
update()
}
private func update() {
if let startDateTime = NSUserDefaults.standardUserDefaults().objectForKey(time) as? NSDate {
let interval = NSDate().timeIntervalSinceDate(startDateTime)
let elapsedTime = Int(interval)
if elapsedTime >= 3600 {
makeNetworkRequest()
NSUserDefaults.standardUserDefaults().setObject(startDateTime, forKey: time)
}
} else {
makeNetworkRequest()
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: time)
}
}
func makeNetworkRequest() {
//Network Request to fetch data and update collectionView
let urlPath = "http://MyServer.com/api/data.json"
guard let endpoint = NSURL(string: urlPath) else {
print("Error creating endpoint")
return
}
let request = NSMutableURLRequest(URL:endpoint)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
guard let data = data else {
return
}
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] else {
print("Error in json parsing")
return
}
self.collectionView.reloadData()
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}

No array sent from parent app to Watch app

I am trying to receive an array of objects (that are retrieved from Parse within the app) from a parent application to be displayed in the watch application. I have been trying a few different things but with no success.
Here is my code in the extension:
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
var parkPassed = context as! String
openParentAppWithPark(parkPassed)
}
private func openParentAppWithPark(park: String) {
WKInterfaceController.openParentApplication(["request": park], reply: { (reply, error) -> Void in
println(reply)
})
}
And the code in the parent app:
func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {
println("Test")
if let userInfo = userInfo, request = userInfo["request"] as? NSArray {
if request == "Park 1" {
DataManager.sharedInstance.loadRides("Park 1")
} else if request == "Park 2" {
DataManager.sharedInstance.loadRides("Park 2")
} else if request == "Park 3" {
DataManager.sharedInstance.loadRides("Park 3")
} else {
DataManager.sharedInstance.loadRides("Park 4")
}
let rides = DataManager.sharedInstance.rideArray
println("Rides: \(rides)")
reply(["rideData": rides])
return
}
reply([:])
}
The println I have always returns nil the first time I try to load, and then [:] every other time. I assume this is because the request is timing out before the app has time to load the data from Parse? Also, the println that is supposed to print "Test" is never called.
In the extension, you're passing a String (park) to the parent application via the request key, but in the parent application, you're testing whether userInfo["request"] is an NSArray or not. You should be testing for a String, as in:
if let userInfo = userInfo, request = userInfo["request"] as? String {
First add a background task assertion to the openParentCall, you can find more context on that here: Background Task Watchkit
let backgroundTask = application.beginBackgroundTaskWithExpirationHandler { NSLog("TIME UP")}
///do code
reply(callback)
//
application.endBackgroundTask(backgroundId)
Now for the actual handleWatchKitExtensionRequest call I would change the first line to
if let request = userInfo["request"] as? String {
Now for the println("Test") not printing to console if you don't attach to process with the parentApplication then the println will not log out.
If the ride data is returning empty then I would inspect this function:
DataManager.sharedInstance.loadRides(ride: String)
make sure it is actually returning the correct data you need. Attach to process and place a breakpoint on each case and check that one of the cases is being called and also jump into the loadRides function to make sure it is coming back out from it. As a side note, the information you send back in the reply block has to be a property list or the reply block will always fail.

Resources