“I’m using segment control and I have two segments, one segment(Recipes) and second segment(Restaurant) click i should click first segment and data show first-array and second segment click second segment and data show secondary”
var dataArray = [FollowedData]()
var restdataArray = [RestaurantFollowed]()
#IBAction func btnActionSegmnet(_ sender: UISegmentedControl) {
switch (segmentSelect.selectedSegmentIndex) {
case 0:
dataArray.removeAll()
ShowPostRecipesData()
tableView.reloadData()
break
case 1:
restdataArray.removeAll()
ShowPostRestaurantsData()
tableView.reloadData()
break
default:
break
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (segmentSelect.selectedSegmentIndex) {
case 0:
return dataArray.count
case 1:
return restdataArray.count
default:
return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 430
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FollowedCell")as! FollowedCell
switch (segmentSelect.selectedSegmentIndex)
case 0:
cell.tittleLbl.text = dataArray[indexPath.row].postDetailsData.title
cell.descriptionLbl.text = dataArray[indexPath.row].postDetailsData.descriptions
let date = getDateFromTime(timeStanp: dataArray[indexPath.row].mbersdata.created)
cell.showDateLbl.text = date + "/ " + dataArray[indexPath.row].postDetailsData.viewscount + "views "
let urlString = "https://myfoodtalk.com:3001/storage/posts/\(dataArray[indexPath.row].postDetailsData.image1)"
let escapedString1 = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString1!)
if let imgurls = URL(string: escapedString1!) {
print(imgurls)
cell.recipesImage.sd_setImage(with:imgurls, placeholderImage: UIImage(named:"placeholder"))
}
let urlStrings = "https://myfoodtalk.com:3001/storage/members/\(dataArray[indexPath.row].mbersdata.photo)"
let escapedStrings = urlStrings.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedStrings!)
if let imgurl = URL(string: escapedStrings!) {
print(imgurl)
cell.userImage.sd_setImage(with:imgurl, placeholderImage: UIImage(named:"placeholder"))
}
break
case 1:
cell.tittleLbl.text = restdataArray[indexPath.row].restaurantDetailsData.title
cell.descriptionLbl.text = restdataArray[indexPath.row].restaurantDetailsData.descriptions
let dates = getDateFromTime(timeStanp: restdataArray[indexPath.row].created)
cell.showDateLbl.text = dates + "/ " + restdataArray[indexPath.row].restaurantDetailsData.viewscount + "views "
let urls = "https://myfoodtalk.com:3001/storage/members/\(restdataArray[indexPath.row].mbersdata.photo)"
let escapedString2 = urls.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString2!)
if let imgurls = URL(string: escapedString2!) {
print(imgurls)
cell.userImage.sd_setImage(with:imgurls, placeholderImage: UIImage(named:"placeholder"))
}
let url = "https://myfoodtalk.com:3001/storage/restaurants/\(restdataArray[indexPath.row].restaurantDetailsData.image1)"
let escapedStrings3 = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedStrings3!)
if let imgurl = URL(string: escapedStrings3!) {
print(imgurl)
cell.recipesImage.sd_setImage(with:imgurl, placeholderImage: UIImage(named:"placeholder"))
}
break
default:
break
}
return cell
}
func ShowPostRecipesData(){
let accessToken = UserDefaults.standard.value(forKey: "access_token")as! String
let userid = UserDefaults.standard.value(forKey: "userId")as! String
var mainString = ""
var url = ""
mainString = """
{"where":{"m_id":"\(userid)"},"include":[{"relation":"posts"},{"relation":"members"}]}
"""
url = "follow-posts?filter=\(mainString)&access_token=\(accessToken)"
let escapedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)
FTHelper.requestGETURLArray(escapedString!, isShowHud: true, headers: nil, success:
{ (response) in
let dataArray = response
if dataArray.isEmpty{
_ = presentAlertWithOptions("", message: "You have no recipes data ", controller: self, buttons: ["OK"], tapBlock:
{
(UIAlertAction, position) in
if position == 0{
}
})
}else{
let followObj = FollowedData()
self.dataArray = followObj.getfollowData(dataArray: dataArray)
self.tableView.reloadData()
}
})
{ (error) in
print(error)
}
}
func ShowPostRestaurantsData(){
let accessToken = UserDefaults.standard.value(forKey: "access_token")as! String
let mid = UserDefaults.standard.value(forKey: "userId")as! String
var mainString = ""
var url = ""
mainString = """
{"where":{"m_id": "\(mid)"},"include":[{"relation":"restaurants"},{"relation":"members"}]}
"""
url = "follow-restaurants?filter=\(mainString)&access_token=\(accessToken)"
let escapedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)
FTHelper.requestGETURLArray(escapedString!, isShowHud: true, headers: nil, success:
{ (response) in
let dataArray = response
if dataArray.isEmpty{
_ = presentAlertWithOptions("", message: "You have no recipes data ", controller: self, buttons: ["OK"], tapBlock:
{
(UIAlertAction, position) in
if position == 0{
}
})
}else{
let followObj = RestaurantFollowed()
self.restdataArray = followObj.getfollowData(dataArray: dataArray)
self.tableView.reloadData()
}
})
{ (error) in
print(error)
}
}
I am click first segment data show on tableview but I am click on second segment but data not show in tableview I can not understand what I can do
Related
I retrieve data from MySql via PHP file to get users information and scores to load them in a table. I need to get the value of the first 3 users and put them in a Label outside the Table, it is like game leaders list. I attached an image to explain the idea.
Here is the structure code:
import Foundation
protocol HomeModelProtocol: AnyObject {
func itemsDownloaded(items: NSArray)
}
class HomeModel: NSObject, URLSessionDataDelegate {
weak var delegate: HomeModelProtocol!
let urlPath = "https://mywebsite.com/folder/callUserList.php" //this will be changed to the path where service.php lives
func downloadItems() {
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON(data!)
}
}
task.resume()
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let users = NSMutableArray()
for i in 0 ..< jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let user = UsersModel()
//the following insures none of the JsonElement values are nil through optional binding
if let name = jsonElement["name"] as? String,
let email = jsonElement["email"] as? String,
let phoneNumber = jsonElement["phone"] as? String,
let userImage = jsonElement["image"] as? String
{
user.name = name
user.email = email
user.phoneNumber = phoneNumber
user.userImage = userImage
}
users.add(user)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsDownloaded(items: users)
})
}
}
Here is the model:
import Foundation
class UsersModel: NSObject {
//properties
var name: String?
var email: String?
var phoneNumber: String?
var userImage: String?
//empty constructor
override init()
{
}
//construct with #name, #address, #latitude, and #longitude parameters
init(name: String, email: String, phoneNumber: String, userImage: String) {
self.name = name
self.email = email
self.phoneNumber = phoneNumber
self.userImage = userImage
}
//prints object's current state
override var description: String {
return "Name: \(String(describing: name)), Email: \(String(describing: email)), Phone Number: \(String(describing: phoneNumber)), User Image: \(String(describing: userImage))"
}
}
Here is the code in the TableView controller:
var feedItems: NSArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
let homeModel = HomeModel()
homeModel.delegate = self
homeModel.downloadItems()
}
func itemsDownloaded(items: NSArray) {
feedItems = items
self.listTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of feed items
return feedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Retrieve cell
let cellIdentifier: String = "BasicCell"
let myCell: WinnerTableCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! WinnerTableCell
// Get the location to be shown
let item: UsersModel = feedItems[indexPath.row] as! UsersModel
// Get references to labels of cell
myCell.lbTextName!.text = item.name
return myCell
}
The data shows in the Table but I have no idea how to fill the 3 label with the 3 first users from the Table.
How can I get these values from the table and pass it to a label in the same ViewController?
Thanks
When adding this code:
if feedItems.count >= 3 {
lblFirstWinner.text = feedItems[0].name // 1st winner
lblSecondWinner.text = feedItems[1].name // 2nd winner
lblThirdWinner.text = feedItems[2].name // 3rd winner
}
it shows error: Value of type 'Any' has no member 'name'
Change itemsDownloaded method as
func itemsDownloaded(items: NSArray) {
feedItems = items
self.listTableView.reloadData()
for (index, user) in items.enumerated() {
let user = user as! UserModel
switch index {
case 0: // 1st winner
lblFirstWinner.text = user.name
case 1: // 2nd winner
lblSecondWinner.text = user.name
case 2: // 3rd winner
lblThirdWinner.text = user.name
}
}
}
OR
Change your HomeModelProtocol method and feedItems type to [UsersModel]
protocol HomeModelProtocol: AnyObject {
func itemsDownloaded(items: [UsersModel]) // Changed
}
var feedItems =[UsersModel]() // Changed
override func viewDidLoad() {
super.viewDidLoad()
let homeModel = HomeModel()
homeModel.delegate = self
homeModel.downloadItems()
}
func itemsDownloaded(items: [UsersModel]) {
feedItems = items
self.listTableView.reloadData()
if feedItems.count >= 3 {
lblFirstWinner.text = feedItems[0].name // 1st winner
lblSecondWinner.text = feedItems[1].name // 2nd winner
lblThirdWinner.text = feedItems[2].name // 3rd winner
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of feed items
return feedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Retrieve cell
let cellIdentifier: String = "BasicCell"
let myCell: WinnerTableCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! WinnerTableCell
// Get references to labels of cell
myCell.lbTextName!.text = feedItems[indexPath.row].name // Changed
return myCell
}
Just you need to add a few lines in the below function and your solution will be done.
func itemsDownloaded(items: NSArray) {
feedItems = items
self.listTableView.reloadData()
if feedItems.count >= 3 {
lblFirstWinner.text = feedItems[0].name // 1st winner
lblSecondWinner.text = feedItems[1].name // 2nd winner
lblThirdWinner.text = feedItems[2].name // 3rd winner
}
}
Let me know... is it working for you? and please also refer to #vadian comment on your question.
I tried to update TableView cell when click cell from CollectionView with key word of class.
For example, when I click "all", it should perform all data.
When I click "a", it should perform class with "a".
It looks like all perfect until I scroll down TableView.
All data display which is not my intension, it should only show specify data even scroll up/down TableView.
Is it related to dequeueReusableCell issue?
I use FMDB to query data when click CollectionView cell.
I attach gif
and hope it could be better to understand my problem.
Can someone help me out with this please? Thanks.
add cellForRow function here.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! ListTableViewCell
if navigationItem.searchController?.isActive == true{
cell.itemImage.image = searchArray[indexPath.row].thumbnailImage()
cell.nameLBL.text = "name:\(searchArray[indexPath.row].name ?? "")"
cell.quantityLBL.text = "Qty:\(searchArray[indexPath.row].quantity ?? 0)pcs"
cell.amountLBL.text = "amount:\(searchArray[indexPath.row].amount ?? 0)"
cell.dateLBL.text = "date:\(searchArray[indexPath.row].date ?? "")"
cell.storeLBL.text = "store:\(searchArray[indexPath.row].store ?? "")"
cell.classLBL.text = "class:\(searchArray[indexPath.row].itemClass ?? "")"
if let reminder = searchArray[indexPath.row].reminder {
let reminderText = ""
cell.reminderLBL.text = "\(reminder)" + reminderText
reminderStatus = true
}else{
cell.reminderLBL.text = "reminder:NO"
if self.array[indexPath.row].reminder == nil{
cell.reminderLBL.text = "reminder:NO"
}
reminderStatus = false
}
}else{
cell.itemImage.image = array[indexPath.row].thumbnailImage()
cell.nameLBL.text = "name:\(array[indexPath.row].name ?? "")"
cell.quantityLBL.text = "Qty:\(array[indexPath.row].quantity ?? 0)pcs"
cell.amountLBL.text = "amount:\(array[indexPath.row].amount ?? 0)"
cell.dateLBL.text = "date:\(array[indexPath.row].date ?? "")"
cell.storeLBL.text = "store:\(array[indexPath.row].store ?? "")"
cell.classLBL.text = "class:\(array[indexPath.row].itemClass ?? "")"
if let reminder = array[indexPath.row].reminder {
let reminderText = ""
cell.reminderLBL.text = "\(reminder)" + reminderText
reminderStatus = true
}else{
cell.reminderLBL.text = "reminder:NO"
if self.array[indexPath.row].reminder == nil{
cell.reminderLBL.text = "reminder:NO"
}
reminderStatus = false
}
print(array.count)
}
return cell
}
add didSelectItemAt function here.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
reloadTableViewAndDatabase()
case 1:
reloadTableViewAndDatabase(itemClass: searchStringOfDaily)
case 2:
reloadTableViewAndDatabase(itemClass: searchStringOfCare)
case 3:
reloadTableViewAndDatabase(itemClass: searchStringOfCosmetic)
default:
reloadTableViewAndDatabase()
}
}
And function which may be factor.
let searchStringOfDaily = "SELECT * FROM Data where itemClass = 'a';"
let searchStringOfCare = "SELECT * FROM Data where itemClass = 'b';"
let searchStringOfCosmetic = "SELECT * FROM Data where itemClass = 'c';"
func reloadTableViewAndDatabase()
{
self.dbHelper.searchAllDataFromDatabase { (dataArray) in
self.array = dataArray
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
func reloadTableViewAndDatabase(itemClass:String)
{
self.dbHelper.searchDataFromDatabase(completionHandler: { (dataArray) in
self.array = dataArray
DispatchQueue.main.async {
self.tableView.reloadData()
}
}, search: itemClass)
}
public func searchDataFromDatabase(completionHandler:([Data]) -> (),search:String) {
var searchResultArray:[Data] = []
if self.database == nil{
self.database = FMDatabase(path: self.databasePath)
}
if self.database.open(){
let searchString = search
do{
let resultNext = try self.database.executeQuery(searchString, values: nil)
while resultNext.next(){
let dataName = resultNext.string(forColumn: "name")
let dataQuantity = resultNext.int(forColumn: "quantity")
let dataAmount = resultNext.int(forColumn: "amount")
let dataDate = resultNext.string(forColumn: "date")
let dataStore = resultNext.string(forColumn: "store")
let dataImageName = resultNext.string(forColumn: "imageName")
let dataItemClass = resultNext.string(forColumn: "itemClass")
let dataReminder = resultNext.string(forColumn: "reminder")
let data = Data(name: dataName!, quantity: Int(dataQuantity), amount: Int(dataAmount), date: dataDate!, store: dataStore!, imageName: dataImageName ?? "", reminder: Int(dataReminder!), itemClass: dataItemClass!)
searchResultArray.append(data)
}
print("query success")
}catch{
print(error.localizedDescription)
}
self.database.close()
}
completionHandler(searchResultArray)
}
my table has 03 sections, 1) has no row, 2) has no row 3) has 04 segcons.
when segcon changed then the data changes then reload the section 03. the issue is when the data is not fill the screen then the table moves down automatically. what i want is, the table will not move down automatically eventhough the data is not enough to fill the screen.
i try to use the footer but no help
self.tableView.tableFooterView = UIView()
see here for more detail
https://youtu.be/40IqAh42nxM
media segcon
let mediaCell: MediaCell = tableView.dequeueReusableCell(withIdentifier: "mediaCell", for: indexPath) as! MediaCell
mediaCell.showImage(url: self.photoNsurlArray[indexPath.row]!)
mediaCell.reportButtonProgram.addTarget(self, action: #selector(self.funcToHandleReportButton), for: .touchUpInside)
let timestampe = funcConvertEpocTimeToDate(timeData: self.timestampsGlobal, atIndex: indexPath.row)
mediaCell.timestampLabel.text = "\(timestampe)"
let uid = self.uidkeys[indexPath.row]!
Utils.getUserDetail(uid: uid) { (user) in
let displayName = user?[Constants.User.display_name] as? String
if let name = displayName,!(displayName?.isEmpty)! {
mediaCell.timestampLabel.text = "by " + "\(name) on " + "\(timestampe)"
}
print("getUserDetail display name: ", displayName)
}
returnCell = mediaCell
near segcon
let locationcell: LocationCellDesign = tableView.dequeueReusableCell(withIdentifier: "locationCellDesign", for: indexPath) as! LocationCellDesign
let elementOfLocations = self.nearlocations[indexPath.row]!
print("***elementOfLocations \(String(describing: elementOfLocations))")
let locationDescriptionText = "\(String(describing: elementOfLocations["description"]!))"
if locationDescriptionText.characters.count != 0 {
locationcell.descriptionLabel.text = locationDescriptionText
} else {
locationcell.descriptionLabel.text = "No Description"
}
locationcell.address.text = "\(String(describing: elementOfLocations["address"]!))"
let ownerID = "\(String(describing: elementOfLocations["owner"]!))"
if ownerID == "ApperSystem" {
locationcell.owner.text = "Owner: " + "ApperSystem"
} else {
Utils.getOwnerDetail(uid: ownerID) { (user) -> Void in
let userProperties = user!
let userDisplayName = userProperties["displayName"] as! String
locationcell.owner.text = "Owner: " + userDisplayName
}
}
let userArray = elementOfLocations["users"]! as! [String]
locationcell.users.text = "Users: " + "\(String(describing: userArray.count))"
locationcell.nearLocationAvatarImageView.image = UIImage(named: "no-image")
if elementOfLocations[Constants.LocationDataFields.media_urls] != nil {
let avatarForLocation = elementOfLocations[Constants.LocationDataFields.media_urls] as! NSDictionary
let numberOfPitureInLocation = avatarForLocation.allKeys(for: 1).sorted { ($0 as! String) < ($1 as! String) }
if numberOfPitureInLocation.count > 0 {
Utils.loadImageFromFireBase(key: numberOfPitureInLocation.last! as! String) { (string) -> Void in
print("***loadImageFromFireBase string: \(String(describing: string))")
if let imageUrlString = string, !(string?.isEmpty)! {
let imageUrl:NSURL = NSURL(string: imageUrlString)!
locationcell.nearLocationAvatarImageView.sd_setImage(with: imageUrl as URL)
} else {
print("***loadImageFromFireBase mediaKey has no mediaUrl")
}
}
}
}
returnCell = locationcell
at first sorry for my bad english.
My problem is that my tableview will be misrepresented as soon as I save a new file in Firebase.
When saving, a new AddViewController is called.
After saving is automatically returned to the TableviewController.
However, if I stop and restart the app so that the TableviewController is recreated, my tableview will be displayed correctly.
I create a header from an array.
Then I create the cell from another array.
I do not understand why my tableview is displayed incorrectly when I return after saving, but when I recreate the view after the app has finished everything is shown correctly.
My sample pictures:
that's right:
that's bad
My Code from TableViewController:
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: #selector(TagebuchViewController.refresh), for: UIControlEvents.valueChanged)
tableView.addSubview(refresher)
loadTableview()
}
Load data from Firebase, loadTableView():
func loadTableview(){
let userID = Firebase.Auth.auth().currentUser?.uid
databaseRef = Database.database().reference().child("DiabetesIOS").child(userID!)
databaseRef.observe(.value, with: {(snapshot) in
var newItems = [Post]()
var newItemsDate = [String]()
var aNewTime = [String]()
var aNewBl = [String]()
var aNewK = [String]()
var aNewBo = [String]()
var aNewBa = [String]()
var aNewBlu = [String]()
var aNewP = [String]()
var aNewN = [String]()
var dimArrayNewTime = [[String]]()
var dimArrayNewBl = [[String]]()
var dimArrayNewK = [[String]]()
var dimArrayNewBo = [[String]]()
var dimArrayNewBa = [[String]]()
var dimArrayNewBlu = [[String]]()
var dimArrayNewP = [[String]]()
var dimArrayNewN = [[String]]()
for year in snapshot.children.allObjects as! [DataSnapshot] {
for month in year.children.allObjects as! [DataSnapshot] {
for day in month.children.allObjects as! [DataSnapshot] {
for date in day.children.allObjects as! [DataSnapshot] {
for time in date.children.allObjects as! [DataSnapshot] {
let newPost = Post(snapshot: time)
newItems.append(newPost)
let newDate = Post(snapshot: time)
newItemsDate.append(newDate.snap6Date!)
if self.snapshotCheck == 0{
self.snapshotCheckDate = newDate.snap6Date
self.snapshotCheck += 1
}
else{
}
if self.snapshotCheckDate == newDate.snap6Date{
aNewTime.append(newDate.time)
aNewBl.append(newDate.blutzucker)
aNewKe.append(newDate.ke)
aNewBo.append(newDate.bolusInsulin)
aNewBa.append(newDate.basalInsulin)
aNewBlu.append(newDate.blutdruck)
aNewP.append(newDate.puls)
aNewN.append(newDate.notiz)
}
else{
dimArrayNewTime.append(aNewTime)
dimArrayNewBl.append(aNewBlutzucker)
dimArrayNewK.append(aNewKe)
dimArrayNewBo.append(aNewBolusinsulin)
dimArrayNewBa.append(aNewBasalinsulin)
dimArrayNewBlu.append(aNewBlutdruck)
dimArrayNewP.append(aNewPuls)
dimArrayNewN.append(aNewNotiz)
aNewTime.removeAll()
aNewBl.removeAll()
aNewK.removeAll()
aNewBo.removeAll()
aNewBa.removeAll()
aNewBlu.removeAll()
aNewP.removeAll()
aNewN.removeAll()
aNewTime.append(newDate.time)
aNewBl.append(newDate.blutzucker)
aNewK.append(newDate.ke)
aNewBo.append(newDate.bolusInsulin)
aNewBa.append(newDate.basalInsulin)
aNewBlu.append(newDate.blutdruck)
aNewP.append(newDate.puls)
aNewN.append(newDate.notiz)
self.snapshotCheckDate = newDate.snap6Date
}
}
}
}
}
}
self.postArrayValue = newItems
self.aHeaderDate = newItemsDate
self.aHeaderDate = self.uniq(source: self.aHeaderDate)
dimArrayNewTime.append(aNewTime)
dimArrayNewBl.append(aNewBl)
dimArrayNewK.append(aNewK)
dimArrayNewBo.append(aNewBo)
dimArrayNewBa.append(aNewBa)
dimArrayNewBlu.append(aNewBlu)
dimArrayNewP.append(aNewP)
dimArrayNewN.append(aNewN)
self.dimArrayTime = dimArrayNewTime
self.dimArrayBl = dimArrayNewBl
self.dimArrayK = dimArrayNewK
self.dimArrayBo = dimArrayNewBo
self.dimArrayBa = dimArrayNewBa
self.dimArrayBlu = dimArrayNewBlu
self.dimArrayP = dimArrayNewP
self.dimArrayN = dimArrayNewN
newItems.removeAll()
newItemsDate.removeAll()
aNewTime.removeAll()
aNewBl.removeAll()
aNewK.removeAll()
aNewBo.removeAll()
aNewBa.removeAll()
aNewBlu.removeAll()
aNewP.removeAll()
aNewN.removeAll()
dimArrayNewTime.removeAll()
dimArrayNewBl.removeAll()
dimArrayNewK.removeAll()
dimArrayNewBo.removeAll()
dimArrayNewBa.removeAll()
dimArrayNewBlu.removeAll()
dimArrayNewP.removeAll()
dimArrayNewN.removeAll()
self.tableView.reloadData()
}){
(error) in
print(error.localizedDescription)
}
}
For my Header:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = Bundle.main.loadNibNamed("TableViewCell1", owner: self, options: nil)?.first as! TableViewCell1
headerView.date.text = aHeaderDate[section]
headerView.backgroundColor = UIColor.white
return headerView
}
NumberOfRows:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dimArrayTime[section].count
}
Number of Headers:
override func numberOfSections(in tableView: UITableView) -> Int {
return aHeaderDate.count
}
Number of Cells:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dimArrayTime[section].count
}
Section:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell2 = Bundle.main.loadNibNamed("TableViewCell2", owner: self, options: nil)?.last as! TableViewCell2
let sectionTime = dimArrayTime[indexPath.section][indexPath.row]
let sectionBl = dimArrayBl[indexPath.section][indexPath.row]
let sectionK = dimArrayK[indexPath.section][indexPath.row]
let sectionBo = dimArrayBo[indexPath.section][indexPath.row]
let sectionBa = dimArrayBa[indexPath.section][indexPath.row]
let sectionBlu = dimArrayBlu[indexPath.section][indexPath.row]
let sectionP = dimArrayP[indexPath.section][indexPath.row]
let sectionN = dimArrayN[indexPath.section][indexPath.row]
cell2.time.text = sectionTime
cell2.bl.text = sectionBl
cell2.k.text = sectionK
cell2.bo.text = sectionBo
cell2.ba.text = sectionBa
cell2.blu.text = sectionBlu
cell2.p.text = sectionP
cell2.n.text = sectionN
return cell2
}
addViewController:
#IBAction func saveInDatabaseFirebase(_ sender: Any) {
let userID = Firebase.Auth.auth().currentUser?.uid
let postRef = dataRef.child("DIOS").child(userID!).child(stringForDbYear).child(stringForDbMonth).child(stringForDbDay).child(stringForDbDate).child(stringForDbTime)
sDate = tFDate.text!
if tFBl.text == "" {
sBl = "-"
}
else{
sBl = tFBl.text!
}
if tFK.text == "" {
sK = "-"
}
else{
sK = tFK.text!
}
if tFBo.text == "" {
sBo = "-"
}
else{
sBo = tFBo.text!
}
if tFBa.text == "" {
sBa = "-"
}
else{
sBa = tFBa.text!
}
if tfBlu.text == "" {
sBlu = "-"
}
else{
sBlu = tfBlu.text!
}
if tFP.text == "" {
sP = "-"
}
else{
sP = tFP.text!
}
if tFN.text == "" {
sN = "-"
}
else{
sN = tFN.text!
}
let post = Post (date: stringForDbDate, time: stringForDbTime, day: stringForDbDay, bl: sBl, k: sK, bo: sBo, ba: sBa, blu: sBlu, p: sP, n: sN, snap1DIOS: "DIOS", snap2UserID: userID!, snap3Year: stringForDbYear, snap4Month: stringForDbMonth, snap5Day: stringForDbDay, snap6Date: stringForDbDate, snap7Time: stringForDbTime)
postRef.setValue(post.toAnyObject())
self.dismiss(animated: true, completion: nil);
}
Thank you very much for help
I get this error:
This is my code:
I am using refresh in the tableView section of the project. What could be causing this error during the refresh?
But in which phase it falls to the fault I could not solve that part
var kategoriId = ""
var refresher = UIRefreshControl()
var arrayKonularData = [konularData]()
let singleton = konularClass.sharedGlobal
override func viewDidLoad() {
super.viewDidLoad()
refresher.attributedTitle = NSAttributedString(string: "Yükleniyor")
refresher.addTarget(self, action: #selector(KonuDetayViewController.refresh), for: UIControlEvents.valueChanged)
self.tableview.addSubview(refresher)
KonulariGetir(sirala: "order by tarih desc")
navigationController?.delegate = self
tableview.layer.cornerRadius = 10
}
func refresh()
{
DispatchQueue.main.async {
if self.segmentControl.selectedSegmentIndex == 0
{
self.arrayKonularData.removeAll()
self.KonulariGetir(sirala: "order by tarih desc")
}
if self.segmentControl.selectedSegmentIndex == 1
{
self.arrayKonularData.removeAll()
self.KonulariGetir(sirala: "order by indirimpuani desc")
}
}
DispatchQueue.main.async {
self.refresher.endRefreshing()
}
}
I am taking data from web service in this section
func KonulariGetir(sirala:String)
{
var request = URLRequest(url: URL(string:"http://212.xxx.xxx.xxx:7001/IndirimiKovala/KonuGetir")!)
request.httpMethod = "POST"
let postString = "filtre="+sirala
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil
{
print("error")
}
if let urlContent = data
{
do
{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let gelenDizi = jsonResult as? NSArray
{
for i in 0..<gelenDizi.count
{
if let baslik = (gelenDizi[i] as? NSDictionary)?["baslik"] as? String
{
self.singleton.baslik = baslik
}
if let indirimPuani = (gelenDizi[i] as? NSDictionary)?["indirimpuani"] as? Int
{
self.singleton.indirimPuani = String(indirimPuani)
}
if let konuId = (gelenDizi[i] as? NSDictionary)?["id"] as? Int
{
self.singleton.konuId = String(konuId)
}
if let haberVeren = (gelenDizi[i] as? NSDictionary)?["uye"] as? String
{
self.singleton.haberVerenUye = haberVeren
}
if let gelenTarih = (gelenDizi[i] as? NSDictionary)?["tarih"] as? String
{
self.singleton.tarih = gelenTarih
}
if let gelenAktif = (gelenDizi[i] as? NSDictionary)?["aktif"] as? Int
{
self.singleton.aktif = gelenAktif
}
self.arrayKonularData.append(konularData.init(baslik: self.singleton.baslik, indirimPuani: self.singleton.indirimPuani, konuId: self.singleton.konuId,haberVeren:self.singleton.haberVerenUye , tarih:self.singleton.tarih,aktif:self.singleton.aktif))
}
}
DispatchQueue.main.async {
self.tableview.reloadData()
}
}
catch
{
print("server hatası")
}
}
}
task.resume()
}
I guess the problem comes from the part of code where you try to populate tableview. So the possible solution can be in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) delegate methode check if arrayKonularData array is not empty like this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: orderCell, for: indexPath)
if !arrayKonularData.isEmpty {
.....// Your code
}
return cell
}
Another solution (which I thing will be the right solution in your case) add completion function of
func KonulariGetir(sirala:String)
and reload tableview in the completion method