I'm working on a chat app and the issue I'm having is with pagination. I'm able to load the first batch of documents and when I scroll to the top to load the next batch, it loads but instead of keeping the first batch of documents, it removes them. I'm not sure what I'm missing or doing wrong. Any help is greatly appreciated. Here is my code:
VC
var messages = [Message]()
var lastDocument: DocumentSnapshot? = nil
var fetchMoreDocs = false
func fetchChatMessages() {
fetchMoreDocs = true
var query: Query!
if messages.isEmpty {
query = MESSAGES_COLLECTION.document(currentUID!).collection(user.memberId).order(by: TIMESTAMP).limit(to: 5)
} else {
query = MESSAGES_COLLECTION.document(currentUID!).collection(user.memberId).order(by: TIMESTAMP).start(afterDocument: self.lastDocument!).limit(to: 5)
}
query.addSnapshotListener { (snapshot, error) in
if let error = error {
print("Error..\(error.localizedDescription)")
} else if snapshot!.isEmpty {
self.fetchMoreDocs = false
return
} else {
self.messages = Message.parseData(snapshot: snapshot)
DispatchQueue.main.async {
self.chatRoomTV.reloadData()
self.scrollToBottom()
self.fetchMoreDocs = false
}
}
self.lastDocument = snapshot!.documents.last
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let position = scrollView.contentOffset.y
let maxOffset = scrollView.contentSize.height - scrollView.frame.size.height
if maxOffset - position <= -50 {
fetchChatMessages()
}}
func scrollToBottom() {
if messages.count > 0 {
let index = IndexPath(row: messages.count - 1, section: 0)
chatRoomTV.scrollToRow(at: index, at: UITableView.ScrollPosition.bottom, animated: false)
}}
Related
I have to cache images one by one passing them into an array.
When I configure Controller, I got array of images from API. Images I got using Animation, every 0.1 sec I got new Image. But when I got all of them, I need to use cached images instead of load them again
Some variables for help
private var imagesCount = 0
private var nextImage = 0
private var imagesArray: [String] = []
private var isAnimating = true {
didSet {
if isAnimating {
animateImage()
}
}
}
Here I configure VC, and do imagesArray = images, then I will use only my array of urls
func configureView(images: ApiImages) {
guard let images = images.images else { return }
imagesArray = images
imagesCount = images.count
imageView.setImage(imageUrl: images[nextImage])
nextImage += 1
animateImage()
}
When I start my animation. Every 0.1 I get new one image, but after the end of cycle I want to use cached images
func animateImage() {
UIView.transition(with: self.imageView, duration: 0.1, options: .transitionCrossDissolve) { [weak self] in
guard let self = self else { return }
self.imageView.setImage(imageUrl: self.imagesArray[self.nextImage])
} completion: { [weak self] _ in
guard let self = self else { return }
if self.nextImage == self.imagesCount - 1{
//here is end of cycle
self.nextImage = 0
} else {
self.nextImage += 1
}
if self.isAnimating {
self.animateImage()
}
}
}
I use kingfisher, so what options I have to put here??
extension UIImageView {
func setImage(imageUrl: String, completion: (() -> ())? = nil) {
self.kf.setImage(with: URL(string: imageUrl), options: [.transition(.fade(0.5)), .alsoPrefetchToMemory]) { result in
completion?()
}
}
}
Thank you!
I don't quite understand what I am doing wrong since I am very new to MVVM. It worked in MVC architecture. I've setup my VM and am able to get the first set of results and even then that's not working properly. I get 4 results instead of 10 which is what LOADLIMIT is set as. I was able to get it to work in an MVC architecture without any issues. The VM function which triggers the query is called multiple (3) times instead of just once i.e. even prior to scrolling.
Here is my VM:
enum FetchRestaurant {
case success
case error
case location
case end
}
class ListViewModel {
let restaurant: [Restaurant]?
let db = Firestore.firestore()
var restaurantArray = [Restaurant]()
var lastDocument: DocumentSnapshot?
var currentLocation: CLLocation?
typealias fetchRestaurantCallback = (_ restaurants: [Restaurant]?, _ message: String?, _ status: FetchRestaurant) -> Void
var restaurantFetched: fetchRestaurantCallback?
var fetchRestaurant: FetchRestaurant?
init(restaurant: [Restaurant]) {
self.restaurant = restaurant
}
func fetchRestaurantCallback (callback: #escaping fetchRestaurantCallback) {
self.restaurantFetched = callback
}
func fetchRestaurants(address: String) {
print("address received: \(address)")
getLocation(from: address) { location in
if let location = location {
self.currentLocation = location
self.queryGenerator(at: location)
} else {
self.restaurantFetched?(nil, nil, .location)
}
}
}
func queryGenerator(at location: CLLocation) {
var query: Query!
if restaurantArray.isEmpty {
query = db.collection("Restaurant_Data").whereField("distributionType", isLessThanOrEqualTo: 2).limit(to: Constants.Mealplan.LOADLIMIT)
} else {
print("last document:\(String(describing: lastDocument?.documentID))")
query = db.collection("Restaurant_Data").whereField("distributionType", isLessThanOrEqualTo: 2).start(afterDocument: lastDocument!).limit(to: Constants.Mealplan.LOADLIMIT)
}
batchFetch(query: query)
}
func batchFetch(query: Query) {
query.getDocuments { (querySnapshot, error) in
if let error = error {
self.restaurantFetched?(nil, error.localizedDescription, .error)
} else if querySnapshot!.isEmpty {
self.restaurantFetched?(nil, nil, .end)
} else if !querySnapshot!.isEmpty {
let queriedRestaurants = querySnapshot?.documents.compactMap { querySnapshot -> Restaurant? in
return try? querySnapshot.data(as: Restaurant.self)
}
guard let restaurants = queriedRestaurants,
let currentLocation = self.currentLocation else {
self.restaurantFetched?(nil, nil, .end)
return }
self.restaurantArray.append(contentsOf: self.applicableRestaurants(allQueriedRestaurants: restaurants, location: currentLocation))
DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
self.restaurantFetched?(self.restaurantArray, nil, .success)
})
self.lastDocument = querySnapshot!.documents.last
}
}
}
func getLocation(from address: String, completionHandler: #escaping (_ location: CLLocation?) -> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,
let location = placemarks.first?.location else {
completionHandler(nil)
return
}
completionHandler(location)
}
}
}
And in the VC viewDidLoad:
var fetchMore = false
var reachedEnd = false
let leadingScreensForBatching: CGFloat = 5.0
var searchController = UISearchController(searchResultsController: nil)
var currentAddress : String?
var listViewModel = ListViewModel(restaurant: [Restaurant]())
override func viewDidLoad() {
super.viewDidLoad()
listViewModel.fetchRestaurantCallback { (restaurants, error, result) in
switch result {
case .success :
self.loadingShimmer.stopShimmering()
self.loadingShimmer.removeFromSuperview()
guard let fetchedRestaurants = restaurants else { return }
self.restaurantArray.append(contentsOf: fetchedRestaurants)
self.tableView.reloadData()
self.fetchMore = false
case .location :
self.showAlert(alertTitle: "No businesses nearby", message: "Try going back and changing the address")
case .error :
guard let error = error else { return }
self.showAlert(alertTitle: "Error", message: error)
case .end :
self.fetchMore = false
self.reachedEnd = true
}
}
if let currentAddress = currentAddress {
listViewModel.fetchRestaurants(address: currentAddress)
}
}
I would really appreciate links or resources for implementing MVVM in Swift for a Firestore back-end. I'm coming up short on searches here and on Google. Even tried medium.
EDIT
class ListViewController: UITableViewController {
lazy var loadingShimmer: UIImageView = {
let image = UIImage(named: "shimmer_background")
let imageview = UIImageView(image: image)
imageview.contentMode = .top
imageview.translatesAutoresizingMaskIntoConstraints = false
return imageview
}()
var restaurantArray = [Restaurant]()
var planDictionary = [String: Any]()
var fetchMore = false
var reachedEnd = false
let leadingScreensForBatching: CGFloat = 5.0
var searchController = UISearchController(searchResultsController: nil)
var currentAddress : String?
var listViewModel = ListViewModel(restaurant: [Restaurant]())
override func viewDidLoad() {
super.viewDidLoad()
setupTable()
}
override func viewWillAppear(_ animated: Bool) {
clearsSelectionOnViewWillAppear = false
}
func setupTable() {
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Restaurant", style: .plain, target: nil, action: nil)
tableView.register(RestaurantCell.self, forCellReuseIdentifier: "Cell")
tableView.delegate = self
tableView.dataSource = self
let navigationBarHeight: CGFloat = self.navigationController!.navigationBar.frame.height
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: -navigationBarHeight, right: 0)
tableView.separatorStyle = .none
tableView.showsVerticalScrollIndicator = false
tableView.addSubview(loadingShimmer)
loadingShimmer.topAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.topAnchor).isActive = true
loadingShimmer.leadingAnchor.constraint(equalTo: tableView.leadingAnchor).isActive = true
loadingShimmer.trailingAnchor.constraint(equalTo: tableView.trailingAnchor).isActive = true
loadingShimmer.startShimmering()
initialSetup()
}
func initialSetup() {
let addressOne = planDictionary["addressOne"] as! String + ", "
let city = planDictionary["city"] as! String + ", "
let postalCode = planDictionary["postalCode"] as! String
currentAddress = addressOne + city + postalCode
setupSearch()
listViewModel.fetchRestaurantCallback { (restaurants, error, result) in
switch result {
case .success :
self.loadingShimmer.stopShimmering()
self.loadingShimmer.removeFromSuperview()
guard let fetchedRestaurants = restaurants else { return }
self.restaurantArray.append(contentsOf: fetchedRestaurants)
self.tableView.reloadData()
self.fetchMore = false
case .location :
self.showAlert(alertTitle: "No businesses nearby", message: "Try going back and changing the address")
case .error :
guard let error = error else { return }
self.showAlert(alertTitle: "Error", message: error)
case .end :
self.fetchMore = false
self.reachedEnd = true
}
}
if let currentAddress = currentAddress {
listViewModel.fetchRestaurants(address: currentAddress)
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let off = scrollView.contentOffset.y
let off1 = scrollView.contentSize.height
if off > off1 - scrollView.frame.height * leadingScreensForBatching {
print("\(fetchMore), \(reachedEnd)")
if !fetchMore && !reachedEnd {
if let address = self.currentAddress {
print("address sent: \(address)")
listViewModel.fetchRestaurants(address: address)
}
}
}
}
}
That you're only getting back 4 results instead of 10 is not due to a faulty query or get-document request—those are coded properly. You're either losing documents when you parse them (some are failing Restaurant initialization), Constants.Mealplan.LOADLIMIT is wrong, or there aren't more than 4 documents in the collection itself that satisfy the query.
That the query is executed 3 times instead of once is also not due to anything in this code—viewDidLoad is only called once and geocodeAddressString only returns once. You're making a fetch request elsewhere that we can't see.
In the batchFetch method, you have a guard that returns out of the function without ever calling its completion handler. This will leave the UI in a state of limbo. I'd recommend always calling the completion handler no matter why the function returns.
You never manage the document cursor. If the get-document return has less documents than the load limit, then nil the last-document cursor. This way, when you attempt to get the next page of documents, guard against a nil cursor and see if there is even more to fetch.
There's no need to pass in an empty array and have your function fill it; simply construct and return an array of results within ListViewModel itself.
We can't see how you trigger pagination. Is it through a scroll delegate when the user reaches the bottom or through a button tap, for example? If it's through a scroll delegate, then I'd disable that for now and see how many returns you get—I suspect one, instead of 3.
What is the particular reason you've ditched MVC for MVVM here? With MVC, you can get pagination up with just a few lines of code. I think MVVM is overkill for iOS applications and would advise against using it unless you have a compelling reason.
I am paginating data from Firestore and I am able to get that to work.
Here is the paginating query:
if restaurantArray.isEmpty {
query = db.collection("Restaurant_Data").limit(to: 4)
} else {
query = db.collection("Restaurant_Data").start(afterDocument: lastDocument!).limit(to: 4)
}
query.getDocuments { (querySnapshot, err) in
if let err = err {
print("\(err.localizedDescription)")
} else if querySnapshot!.isEmpty {
self.fetchMore = false
return
} else {
if (querySnapshot!.isEmpty == false) {
let allQueriedRestaurants = querySnapshot!.documents.compactMap { (document) -> Restaurant in (Restaurant(dictionary: document.data(), id: document.documentID)!)}
guard let location = self.currentLocation else { return }
self.restaurantArray.append(contentsOf: self.applicableRestaurants(allQueriedRestaurants: allQueriedRestaurants, location: location))
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
self.tableView.reloadData()
self.fetchMore = false
})
self.lastDocument = querySnapshot!.documents.last
}
}
}
The pagination is triggered when the user drags the table view up:
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let off = scrollView.contentOffset.y
let off1 = scrollView.contentSize.height
if off > off1 - scrollView.frame.height * leadingScreensForBatching{
if !fetchMore { // excluded reachedEnd Bool
if let location = self.currentLocation {
queryGenerator(searched: searchController.isActive, queryString: searchController.searchBar.text!.lowercased(), location: location)
}
}
}
}
I also added an activity indicator to the bottom and that works as expected. Here is the code for that:
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastSectionIndex = tableView.numberOfSections - 1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1
if indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex {
// print("this is the last cell")
let spinner = UIActivityIndicatorView(style: .medium)
spinner.startAnimating()
spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44))
tableView.tableFooterView = spinner
tableView.tableFooterView?.isHidden = false
}
}
However, once the bottom of the table view is reached and there is no more data available, the indicator is still showing and I dont know how to get it to not show.
I tried using a variable to check if the Firestory query is done but my implementation is probably wrong so I cannot get it to work.
If you know the moment when there is no more data available, you set the tableView footer view to nil or hidden = true, see below
tableView.tableFooterView?.isHidden = true
or
tableView.tableFooterView = nil
before you call self.tableView.reloadData()
If you do not know it, see code below
query.getDocuments { (querySnapshot, err) in
if let err = err {
print("\(err.localizedDescription)")
} else if querySnapshot!.isEmpty {
// Here you know when there is no more data
self.fetchMore = false
self.tableView.tableFooterView = nil // or self.tableView.tableFooterView?.isHidden = true
self.tableView.reloadData()
return
} else {
if (querySnapshot!.isEmpty == false) {
let allQueriedRestaurants = querySnapshot!.documents.compactMap { (document) -> Restaurant in (Restaurant(dictionary: document.data(), id: document.documentID)!)}
guard let location = self.currentLocation else { return }
self.restaurantArray.append(contentsOf: self.applicableRestaurants(allQueriedRestaurants: allQueriedRestaurants, location: location))
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
self.tableView.reloadData()
self.fetchMore = false
})
self.lastDocument = querySnapshot!.documents.last
}
}
}
I'm trying to paginate data (infinitely scroll my tableview) using firestore. I've integrated the code google gives for pagination as best I can, but I'm still having problems getting the data to load in correctly.
The initial set of data loads into the tableview as wanted. Then, when the user hits the bottom of the screen, the next "x" amount of items are load in. But when the user hits the bottom of the screen the second time, the same "x" items are simply appended to the table view. The same items keep getting added indefinitely.
So its the initial 3 "ride" objects, followed by the next 4 "ride" objects repeating forever.
123 4567 4567 4567 4567...
How do I get the data to load in correctly?
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
if offsetY > contentHeight - scrollView.frame.height {
// Bottom of the screen is reached
if !fetchingMore {
beginBatchFetch()
}
}
}
func beginBatchFetch() {
// Array containing "Ride" objcets is "rides"
fetchingMore = true
// Database reference to "rides" collection
let ridesRef = db.collection("rides")
let first = ridesRef.limit(to: 3)
first.addSnapshotListener { (snapshot, err) in
if let snapshot = snapshot {
// Snapshot isn't nil
if self.rides.isEmpty {
// rides array is empty (initial data needs to be loaded in).
let initialRides = snapshot.documents.compactMap({Ride(dictionary: $0.data())})
self.rides.append(contentsOf: initialRides)
self.fetchingMore = false
DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: {
self.tableView.reloadData()
})
print("first rides loaded in")
}
} else {
// Error
print("Error retreiving rides: \(err.debugDescription)")
return
}
// reference to lastSnapshot
guard let lastSnapshot = snapshot!.documents.last else{
// The collection is empty
return
}
let next = ridesRef.limit(to: 4).start(afterDocument: lastSnapshot)
next.addSnapshotListener({ (snapshot, err) in
if let snapshot = snapshot {
if !self.rides.isEmpty {
let newRides = snapshot.documents.compactMap({Ride(dictionary: $0.data())})
self.rides.append(contentsOf: newRides)
self.fetchingMore = false
DispatchQueue.main.asyncAfter(deadline: .now() + 7, execute: {
self.tableView.reloadData()
})
print("new items")
return
}
} else {
print("Error retreiving rides: \(err.debugDescription)")
return
}
})
}
}
So here's the solution I've come up with! It is very likely that this solution makes multiple calls to firestore, creating a large bill for any real project, but it works as a proof of concept I guess you could say.
If you have any recommendations or edits, please feel free to share!
var rides = [Ride]()
var lastDocumentSnapshot: DocumentSnapshot!
var fetchingMore = false
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
//print("offsetY: \(offsetY) | contHeight-scrollViewHeight: \(contentHeight-scrollView.frame.height)")
if offsetY > contentHeight - scrollView.frame.height - 50 {
// Bottom of the screen is reached
if !fetchingMore {
paginateData()
}
}
}
// Paginates data
func paginateData() {
fetchingMore = true
var query: Query!
if rides.isEmpty {
query = db.collection("rides").order(by: "price").limit(to: 6)
print("First 6 rides loaded")
} else {
query = db.collection("rides").order(by: "price").start(afterDocument: lastDocumentSnapshot).limit(to: 4)
print("Next 4 rides loaded")
}
query.getDocuments { (snapshot, err) in
if let err = err {
print("\(err.localizedDescription)")
} else if snapshot!.isEmpty {
self.fetchingMore = false
return
} else {
let newRides = snapshot!.documents.compactMap({Ride(dictionary: $0.data())})
self.rides.append(contentsOf: newRides)
//
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
self.tableView.reloadData()
self.fetchingMore = false
})
self.lastDocumentSnapshot = snapshot!.documents.last
}
}
}
A little late in the game, but I would like to share how I do it, using the query.start(afterDocument:) method.
class PostsController: UITableViewController {
let db = Firestore.firestore()
var query: Query!
var documents = [QueryDocumentSnapshot]()
var postArray = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
query = db.collection("myCollection")
.order(by: "post", descending: false)
.limit(to: 15)
getData()
}
func getData() {
query.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
querySnapshot!.documents.forEach({ (document) in
let data = document.data() as [String: AnyObject]
//Setup your data model
let postItem = Post(post: post, id: id)
self.postArray += [postItem]
self.documents += [document]
})
self.tableView.reloadData()
}
}
}
func paginate() {
//This line is the main pagination code.
//Firestore allows you to fetch document from the last queryDocument
query = query.start(afterDocument: documents.last!)
getData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postArray.count
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// Trigger pagination when scrolled to last cell
// Feel free to adjust when you want pagination to be triggered
if (indexPath.row == postArray.count - 1) {
paginate()
}
}
}
Result like so:
Here is a reference.
My solution was similar to #yambo, however, I tried to avoid making extra calls to the database. After the first call to the database, I get back 10 objects and when it is time to load the new page I kept a reference of how many objects and I checked if the count + 9 is in the range of my new count.
#objc func LoadMore() {
let oldCount = self.uploads.count
guard shouldLoadMore else { return }
self.db.getNextPage { (result) in
switch result {
case .failure(let err):
print(err)
case .success(let newPosts):
self.uploads.insert(contentsOf: newPosts, at: self.uploads.count)
if oldCount...oldCount+9 ~= self.uploads.count {
self.shouldLoadMore = false
}
DispatchQueue.main.async {
self.uploadsView.collectionView.reloadData()
}
}
}
}
Simple, Fast and easy way is...
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, FeedCellDelegate {
private var quotes = [Quote]() {
didSet{ tbl_Feed.reloadData() }
}
var quote: Quote?
var fetchCount = 10
#IBOutlet weak var tbl_Feed: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
fetchPost()
}
// MARK: - API
func fetchPost() {
reference(.Quotes).limit(to: getResultCount).getDocuments { (snapshot, error) in
guard let documents = snapshot?.documents else { return }
documents.forEach { (doc) in
let quotes = documents.map {(Quote(dictionary: $0.data()))}
self.quotes = quotes
}
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let currentOffset = scrollView.contentOffset.y
let maxxOffset = scrollView.contentSize.height - scrollView.frame.size.height
if maxxOffset - currentOffset <= 300 { // Your cell size 300 is example
fetchCount += 5
fetchPost()
print("DEBUG: Fetching new Data")
}
}
}
I am new to Swift and Realm, sorry. I am trying to build a Scrollable Tab Pages, wherein all data comes from Realm.
First Launch, after I successfully login: The data is not loaded automatically.
Second Launch, I am getting this error.
'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: <NSIndexPath: 0x6000002264a0> {length = 2, path = 0 - 0}'
I tested my code using static String Arrays, it works well. Actually, this coded was also taken from somewhere...
This is my ViewController:
class ViewController: UIViewController{
let tabs = try! Realm().objects(Tabs)
//after successful login. begin collecting Tab Items
override func viewDidLoad() {
WebController().getTabs()
buildTabItems()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.layoutIfNeeded()
buildSamplePages()
let firstPageIndex = 2
focusView.layer.cornerRadius = (scrollingTabBar.height - scrollingTabBar.focusVerticalMargin * 2.0) / 2.0
scrollView.contentSize = CGSize(width: view.width * CGFloat(tabItems.count), height: scrollView.contentSize.height)
scrollingTabBar.width = view.width
scrollingTabBar.pageWidth = scrollView.width
scrollingTabBar.reloadTabs(tabItems, indexOf: firstPageIndex)
scrollView.setContentOffset(CGPoint(x: scrollView.width * CGFloat(firstPageIndex), y: scrollView.contentOffset.y), animated: false)
}
//collect Tab Items from Realm
func buildTabItems() {
let array = Array(tabs).description
var strings = [String]()
for tabData in tabs{
strings.append(tabData.title)
}
for str in strings {
let tabItem = USGScrollingTabItem()
tabItems.append(tabItem)
}
}
//display Pages
func buildTabPages() {
for (pageNum, _) in tabItems.enumerated() {
let label = UILabel(frame: CGRect.zero)
label.text = "i am a test\(pageNum)"
scrollView.addSubview(label)
}
}
}
extension ViewController: USGScrollingTabBarDelegate {
func tabBar(_ tabBar: USGScrollingTabBar, didSelectTabAt index: Int) {
scrollView.setContentOffset(CGPoint(x: scrollView.width * CGFloat(index), y: scrollView.contentOffset.y), animated: true)
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollingTabBar.enabled = !scrollView.isTracking;
if (scrollView.isTracking || scrollView.isDecelerating) {
scrollingTabBar.scrollToOffset(scrollView.contentOffset.x)
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollingTabBar.stopScrollDeceleration()
scrollingTabBar.enabled = false
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
scrollingTabBar.enabled = true
}
}
This is my WebService Code
class WebController{
let a = UserDefaults.standard.string(forKey: "a")
let b = UserDefaults.standard.string(forKey: "b")
let c = UserDefaults.standard.integer(forKey: "c")
let d = UserDefaults.standard.string(forKey: "d")
func getTabs() {
let reqParams: Parameters = ["a": a ,"b": b]
let header = ["c":"c, "d":"d"]
let url = APIConstant.URLS().TabsURL
guard let realm = try? Realm() else {
return
}
Alamofire.request(url, method: HTTPMethod.post, parameters:reqParams, headers:header).responseJSON { response in
guard response.result.isSuccess, let value = response.result.value else {
return
}
let json = JSON(value)
let tabs = json["result"]
realm.beginWrite()
for (_, subJson) : (String, JSON) in tabs {
let tabs: Tabs = Mapper<Tabs>().map(JSONObject: subJson.dictionaryObject!)!
realm.add(tabs, update: true)
}
do {
try realm.commitWrite()
} catch {
}
}
}
}
Anyone can give me an idea, how to load a Realm Data automatically after I login (or launch) the page?