JSON data shown on viewDidAppear and not viewDidLoad - ios

I have this that download the JSON and I have appended them into an array
func downloadDetails(completed: #escaping DownloadComplete){
Alamofire.request(API_URL).responseJSON { (response) in
let result = response.result
let json = JSON(result.value!).array
let jsonCount = json?.count
let count = jsonCount!
for i in 0..<(count){
let image = json![i]["urls"]["raw"].stringValue
self.imagesArray.append(image)
}
self.tableView.reloadData()
print(self.imagesArray)
completed()
}
}
I know that viewDidLoad loads first and viewDidAppear load later. I am trying to retrieve the array that contain all the informations but it's not showing on viewDidLoad as the array is empty but its showing on viewDidAppear with an array of ten and I dont know how to get that from viewDidAppear.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var imageList: Image!
var imagesArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad " ,imagesArray)
setupDelegate()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
downloadDetails {
DispatchQueue.main.async {
}
print("viewDidAppear ", self.imagesArray)
}
}
The output is as follow
viewDidLoad []
viewDidAppear ["https://images.unsplash.com/photo-1464550883968-cec281c19761", "https://images.unsplash.com/photo-1464550838636-1a3496df938b", "https://images.unsplash.com/photo-1464550580740-b3f73fd373cb", "https://images.unsplash.com/photo-1464547323744-4edd0cd0c746", "https://images.unsplash.com/photo-1464545022782-925ec69295ef", "https://images.unsplash.com/photo-1464537356976-89e35dfa63ee", "https://images.unsplash.com/photo-1464536564416-b73260a9532b", "https://images.unsplash.com/photo-1464536194743-0c49f0766ef6", "https://images.unsplash.com/photo-1464519586905-a8c004d307cc", "https://images.unsplash.com/photo-1464519046765-f6d70b82a0df"]
What is the right way to access the array with information in it?

that's because the request is asynchronous it's not getting executed as serial lines of code , there should be a delay according to network status , besides you don't even call downloadDetails inside viewDidLoad
//
you also need to reload table here
downloadDetails { // Alamofire callback by default runs in main queue
self.tableView.reloadData()
}

Just call your method on
viewDidLoad()
And maybe you should learn more about iOS lifecycle, so you can spot the difference between viewDidLoad and viewDidAppear 😉

Related

Networking in Swift Using WikipediaKit / Delegate Design Pattern

I'm trying to request basic info from Wikipedia - user selects tableView row and is taken to a new view that displays info associated with the row (album descriptions). Flow is:
tableView Cell passes user choice to network struct, performs segue to new view
network struct uses choice to query Wikipedia API
received info is passed via delegate method to new view
info is displayed in new view to user
Two issues I'm having:
Networking seems to not be carried out until after the new view is triggered and updated. Initially I didn't use delegate, and just had networking method return its result. But either way, I need networking to get its result back before we get to and update the new view. I've added Dispatch.main.async to the new view for the UI. I thought I may need a completion handler, but I don't fully understand this
Delegate protocol was introduced to fix problem 1, but it still doesn't work. For some reason nothing of the delegate method in the new view is triggering.
Here's the initial tableView trigger:
extension TopTenViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
albumManager.getAlbumInfo(albumTitle: topTenList[indexPath.row][1])
performSegue(withIdentifier: "topTenAlbumInfoSeg", sender: self)
}
Here is the delegate and all the networking:
protocol AlbumManagerDelegate {
func didUpdateAlbumInfo(albumInfo: String)
}
struct AlbumManager {
var newResult: String = ""
var delegate: AlbumManagerDelegate?
func getAlbumInfo(albumTitle: String) {
let wikipedia = Wikipedia.shared
let language = WikipediaLanguage("en")
let _ = wikipedia.requestArticle(language: language, title: albumTitle, imageWidth: 5) { result in
switch result {
case .success(let article):
print(article.displayTitle)
self.delegate?.didUpdateAlbumInfo(albumInfo: article.displayTitle)
print("delegate should be updated")
case .failure(let error):
print(error)
}
}
}
}
Here is the target view:
class AlbumInfoViewController: UIViewController, AlbumManagerDelegate {
#IBOutlet weak var albumDescriptionLabel: UILabel!
#IBOutlet weak var myWebView: WKWebView!
var albumDescription: String = ""
var albumManager = AlbumManager()
override func viewDidLoad() {
super.viewDidLoad()
albumManager.delegate = self
print(albumDescriptionLabel.text)
}
func didUpdateAlbumInfo(albumInfo: String) {
DispatchQueue.main.async {
print("This worked: \(albumInfo)")
self.albumDescriptionLabel.text = "Hi this is: \(albumInfo)"
}
}
}
Currently nothing in didUpdateAlbumInfo in the new view is being triggered. albumDescriptionLabel is not being updated. Could the issue be that the segue is performed too soon? Thanks in advance!

Am I implementing the tableviewdatasource correctly to get downloaded data to show?

I am developing a small app to connect to my site, download data via a PHP web service, and display it in a table view. To get started I was following a tutorial over on Medium by Jose Ortiz Costa (Article on Medium).
I tweaked his project and got it running to verify the Web service was working and able to get the data. Once I got that working, I started a new project and tried to pull in some of the code that I needed to do the networking and tried to get it to display in a tableview in the same scene instead of a popup scene like Jose's project.
This is where I am running into some issues, as I'm still rather new to the swift programming language (started a Udemy course and have been picking things up from that) getting it to display in the table view. I can see that the request is still being sent/received, but I cannot get it to appear in the table view (either using my custom XIB or a programmatically created cell). I thought I understood how the code was broken down, and even tried to convert it from a UITableViewController to a UITableviewDataSource via an extension of the Viewcontroller.
At this point, I'm pretty stumped and will continue to inspect the code and tweak what I think might be the root cause. Any pointers on how to fix would be really appreciated!
Main Storyboard Screenshot
Struct for decoding my data / Lead class:
import Foundation
struct Lead: Decodable {
var id: Int
var name: String
var program: String
var stage: String
var lastAction: String
}
class LeadModel {
weak var delegate: Downloadable?
let networkModel = Network()
func downloadLeads(parameters: [String: Any], url: String) {
let request = networkModel.request(parameters: parameters, url: url)
networkModel.response(request: request) { (data) in
let model = try! JSONDecoder().decode([Lead]?.self, from: data) as [Lead]?
self.delegate?.didReceiveData(data: model! as [Lead])
}
}
}
ViewController:
import UIKit
class LeadViewController: UIViewController {
// Buttons
#IBOutlet weak var newButton: UIButton!
#IBOutlet weak var firstContactButton: UIButton!
#IBOutlet weak var secondContactButton: UIButton!
#IBOutlet weak var leadTable: UITableView!
let model = LeadModel()
var models: [Lead]?
override func viewDidLoad() {
super.viewDidLoad()
//Make Buttons rounded
newButton.layer.cornerRadius = 10.0
firstContactButton.layer.cornerRadius = 10.0
secondContactButton.layer.cornerRadius = 10.0
//Delegate
model.delegate = self
}
//Send request to web service based off Buttons Name
#IBAction func findLeads(_ sender: UIButton) {
let new = sender.titleLabel?.text
let param = ["stage": new!]
print ("findLead hit")
model.downloadLeads(parameters: param, url: URLServices.leads)
}
}
extension LeadViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
print ("number of sections hit")
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
guard let _ = self.models else {
return 0
}
print ("tableView 1 hit")
return self.models!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Create an object from LeadCell
let cell = tableView.dequeueReusableCell(withIdentifier: "leadID", for: indexPath) as! LeadCell
// Lead selection
cell.leadName.text = self.models![indexPath.row].name
cell.actionName.text = self.models![indexPath.row].lastAction
cell.stageName.text = self.models![indexPath.row].stage
cell.progName.text = self.models![indexPath.row].program
print ("tableView 2 hit")
// Return the configured cell
return cell
}
}
extension LeadViewController: Downloadable {
func didReceiveData(data: Any) {
//Assign the data and refresh the table's data
DispatchQueue.main.async {
self.models = data as? [Lead]
self.leadTable.reloadData()
print ("LeadViewController Downloadable Hit")
}
}
}
EDIT
So with a little searching around (okay...A LOT of searching around), I finally found a piece that said I had to set the class as the datasource.
leadTable.dataSource = self
So that ended up working (well after I added a prototype cell with the identifier used in my code). I have a custom XIB that isn't working right now and that's my next tackle point.
You load the data, but don't use it. First, add the following statement to the end of the viewDidLoad method
model.delegate = self
Then add the following LeadViewController extension
extension LeadViewController: Downloadable {
func dicReceiveData(data: [Lead]) {
DispatchQueue.main.async {
self.models = data
self.tableView.reloadData()
}
}
}
And a couple of suggestions:
It is not a good practice to use the button title as a network request parameter:
let new = sender.titleLabel?.text
let param = ["stage": new!]
It is better to separate UI and logic. You can use the tag attribute for buttons (you can configure it in the storyboard or programmatically) to check what button is tapped.
You also have several unnecessary type casts in the LeadModel class. You can change
let model = try! JSONDecoder().decode([Lead]?.self, from: data) as [Lead]?
self.delegate?.didReceiveData(data: model! as [Lead])
to
do {
let model = try JSONDecoder().decode([Lead].self, from: data)
self.delegate?.didReceiveData(data: model)
}
catch {}

viewDidLoad, is it called only once?

I am a beginner in iOS development, and I am following one tutorial using firebase database to make a simple chat app. Actually I am confused with the use of viewDidLoad method.
Here is the screenshot of the app: https://ibb.co/gqD4Tw
I don't understand why retrieveMessage() method is put on viewDidLoad when I want to send data (chat message) to firebase database, I used sendButtonPressed() method (which is an IBAction) and when I want to retrieve data from the database, I use retrieveMessage().
The retrieveMessage() method is called on viewDidLoad, as far as I know the viewDidLoad method is called only once after the view is loaded into memory. We usually use it for initial setup.
So, if viewDidLoad is called only once in initial setup, why the retrieveMessage() method can retrieve all the message that I have sent to my own database over and over again, after I send message data to the database ?
I don't understand why retrieveMessage() method is put on viewDidLoad below is the simplified code:
class ChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var messageArray = [Message]()
#IBOutlet var messageTextfield: UITextField!
#IBOutlet var messageTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//Set as the delegate and datasource :
messageTableView.delegate = self
messageTableView.dataSource = self
//the delegate of the text field:
messageTextfield.delegate = self
retrieveMessage()
///////////////////////////////////////////
//MARK: - Send & Recieve from Firebase
#IBAction func sendPressed(_ sender: AnyObject) {
// Send the message to Firebase and save it in our database
let messageDB = FIRDatabase.database().reference().child("message")
let messageDictionary = ["MessageBody":messageTextfield.text!, "Sender": FIRAuth.auth()?.currentUser?.email]
messageDB.childByAutoId().setValue(messageDictionary) {
(error,ref) in
if error != nil {
print(error!)
} else {
self.messageTextfield.isEnabled = true
self.sendButton.isEnabled = true
self.messageTextfield.text = ""
}
}
}
//Create the retrieveMessages method :
func retrieveMessage () {
let messageDB = FIRDatabase.database().reference().child("message")
messageDB.observe(.childAdded, with: { (snapshot) in
let snapshotValue = snapshot.value as! [String:String]
let text = snapshotValue["MessageBody"]!
let sender = snapshotValue["Sender"]!
let message = Message()
message.messsageBody = text
message.sender = sender
self.messageArray.append(message)
self.messageTableView.reloadData()
})
}
}
viewDidLoad method is called only once in ViewController lifecycle.
The reason retrieveMessage() is called in viewDidLoad because it's adding observer to start listening for received and sent message. Once you receive or send message then this block(observer) is called and
then adding that text in array self.messageArray.append(message) and updating tableview.
viewDidLoad gets called only once but the firebase functions starts a listener, working in background and syncronizeing data.
Its called in viewDidLoad because it tells -> When this view loads, start listening for messages.
ViewDidLoad() is only called upon initializing the ViewController.
If you want to have a function called every time the user looks at the VC again (e.g. after a segue back from another VC) you can just use ViewDidAppear().
It is also called when ViewDidLoad() is called.

New added data in firebase database duplicate it self before pull to refresh using Swift3

Why when I'am adding new data to firebase database appears duplicated in my app , but when I pull down to make refresh its back again not duplicated , I put a Screenshot of how data appears in my project simulator .This is how data appears in my project
This is my Code.
import UIKit
import FirebaseDatabase
import SDWebImage
import FirebaseAuth
class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var Ref:FIRDatabaseReference?
var Handle:FIRDatabaseHandle?
var myarray = [Posts]()
var refresh = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
refresh.addTarget(self, action: #selector(ViewController.loadData), for: .valueChanged)
tableView.addSubview(refresh)
}
override func viewDidAppear(_ animated: Bool) {
loadData()
}
func loadData(){
self.myarray.removeAll()
Ref=FIRDatabase.database().reference()
Handle = Ref?.child("Posts").queryOrdered(byChild: "Des").queryEqual(toValue: "11").observe(.childAdded ,with: { (snapshot) in
if let post = snapshot.value as? [String : AnyObject]{
let img = Posts()
img.setValuesForKeys(post)
self.myarray.append(img)
print("##############################\(img)")
self.tableView.reloadData()
}
})
self.refresh.endRefreshing()
}
It appears self.refresh.endRefreshing() is being called outside the Firebase closure.
This is bad as that code will run before Firebase returns the data and reloads the tableView data.
Remember that Firebase is asynchronous and it takes time for the internet to get the data from the Firebase server to your app, so in-line code will usually execute before the code in the closure.
Also, the Handle is unneeded in this case unless you are using it elsewhere.
Ref?.child("Posts").queryOrdered(byChild: "Des").queryEqual(toValue: "11")
.observe(.childAdded ,with: { (snapshot) in
if let post = snapshot.value as? [String : AnyObject]{
let img = Posts()
img.setValuesForKeys(post)
self.myarray.append(img)
print("##############################\(img)")
self.tableView.reloadData()
}
self.refresh.endRefreshing()
})
Also, you may consider just removing the refreshing entirely as when you add an observer to a Firebase node (.childAdded) any time a child it added, your tableview will automatically refresh due to the code executed in the closure.

Firebase removeAllObservers() keeps making calls when switching views -Swift2 iOS

I read other stack overflow q&a's about this problem but it seems to be a tabBarController issue which I haven't found anything on.
I have a tabBarController with 3 tabs. tab1 is where I successfully send the info to Firebase. In tab2 I have tableView which successfully reads the data from tab1.
In tab2 my listener is in viewWillAppear. I remove the listener in viewDidDisappear (I also tried viewWillDisappear) and somewhere in here is where the problem is occurring.
override func viewDidDisappear(animated: Bool) {
self.sneakersRef!.removeAllObservers()
//When I tried using a handle in viewWillAppear and then using the handle to remove the observer it didn't work here either
//sneakersRef!.removeObserverWithHandle(self.handle)
}
Once I switch from tab2 to any other tab, the second I go back to tab2 the table data doubles, then if I switch tabs again and come back it triples etc. I tried setting the listener inside viewDidLoad which prevents the table data from duplicating when I switch tabs but when I send new info from tab1 the information never gets updated in tab2.
According to the Firebase docs and pretty much everything else I read on stackoverflow/google the listener should be set in viewWillAppear and removed in viewDidDisappear.
Any ideas on how to prevent my data from duplicating whenever I switch between back forth between tabs?
tab1
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class TabOneController: UIViewController{
var ref:FIRDatabaseReference!
#IBOutlet weak var sneakerNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.ref = FIRDatabase.database().reference()
}
#IBAction func sendButton(sender: UIButton) {
let dict = ["sneakerName":self.sneakerNameTextField.text!]
let usersRef = self.ref.child("users")
let sneakersRef = usersRef.child("sneakers").childByAutoID()
sneakersRef?.updateChildValues(dict, withCompletionBlock: {(error, user) in
if error != nil{
print("\n\(error?.localizedDescription)")
}
})
}
}
tab2
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class TabTwoController: UITableViewController{
#IBOutlet weak var tableView: UITableView!
var handle: Uint!//If you read the comments I tried using this but nahhh didn't help
var ref: FIRDatabaseReference!
var sneakersRef: FIRDatabaseReference?
var sneakerArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.ref = FIRDatabase.database().reference()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let usersRef = self.ref.child("users")
//Listener
self.sneakersRef = usersRef.child("sneakers")
//I tried using the handle
//---self.handle = self.sneakersRef!.observeEventType(.ChildAdded...
self.sneakersRef!.observeEventType(.ChildAdded, withBlock: {(snapshot) in
if let dict = snapshot.value as? [String:AnyObject]{
let sneakerName = dict["sneakerName"] as? String
self.sneakerArray.append(sneakerName)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}), withCancelBlock: nil)
}
//I also tried viewWillDisappear
override func viewDidDisappear(animated: Bool) {
self.sneakersRef!.removeAllObservers()
//When I tried using the handle to remove the observer it didn't work either
//---sneakersRef!.removeObserverWithHandle(self.handle)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sneakerArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("sneakerCell", forIndexPath: indexPath)
cell.textLabel?.text = sneakerArray[indexPath.row]
return cell
}
}
tab3 does nothing. I just use it as an alternate tab to switch back and forth with
The removeAllObservers method is working correctly. The problem you're currently experiencing is caused by a minor missing detail: you never clear the contents of sneakerArray.
Note: there's no need for dispatch_async inside the event callback. The Firebase SDK calls this function on the main queue.
The official accepted Answer was posted by #vzsg. I'm just detailing it for the next person who runs into this issue. Up vote his answer.
What basically happens is when you use .childAdded, Firebase loops around and grabs each child from the node (in my case the node is "sneakersRef"). Firebase grabs the data, adds it to the array (in my case self.sneakerArray), then goes goes back to get the next set of data, adds it to the array etc. By clearing the array on the start of the next loop, the array will be empty once FB is done. If you switch scenes, you'll always have an empty array and the only data the ui will display is FB looping the node all over again.
Also I got rid of the dispatch_async call because he said FB calls the function in the main queue. I only used self.tableView.reloadData()
On a side note you should subscribe to firebase-community.slack.com. That's the official Firebase slack channel and that's where I posted this question and vzsg answered it.
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//CLEAR THE ARRAY DATA HERE before you make your Firebase query
self.sneakerArray.removeAll()
let usersRef = self.ref.child("users")
//Listener
self.sneakersRef = usersRef.child("sneakers")
//I tried using the handle
//---self.handle = self.sneakersRef!.observeEventType(.ChildAdded...
self.sneakersRef!.observeEventType(.ChildAdded, withBlock: {(snapshot) in
if let dict = snapshot.value as? [String:AnyObject]{
let sneakerName = dict["sneakerName"] as? String
self.sneakerArray.append(sneakerName)
//I didn't have to use the dispatch_async here
self.tableView.reloadData()
}
}), withCancelBlock: nil)
}
Thank for asking this question.
I have also faced same issue in past. I have solved this issue as follow.
1) Define array which contain list of observer.
var aryObserver = Array<Firebase>()
2) Add observer as follow.
self.sneakersRef = usersRef.child("sneakers")
aryObserver.append( self.sneakersRef)
3) Remove observer as follow.
for fireBaseRef in self.aryObserver{
fireBaseRef.removeAllObservers()
}
self.aryObserver.removeAll() //Remove all object from array.

Resources