app crashes when a button is clicked --- in SWIFT - ios

Good Morning
I've a table view with multipel selection enabled of maximum 5 cells .. above it there is a list of 5 buttons and images .. when the user clicked on a cell a photo shall appear in the first empty imageViewabove the table, and when the user clicks on that photo it should disaapear and the cell color return to clear or white color in my case.
my problem is, when i click on a photo which cell is not shown because of scrolling, the app crashes. can you please help me .. how can i check if the indexpath is shown or not because the problem happened when it is not
here is my code :
#IBAction func btnClicked (sender : UIButton)
{
let tester = sender
if (tester == btn1 && img1.image != nil)
{
img1.image = nil
let cell1 = myTable.cellForRowAtIndexPath(img1IP)! as CustomCell
selectedIndexPaths.removeObject(img1IP)
configure(cell1, forRowAtIndexPath: img1IP)
counter--
}
else if (tester == btn2 && img2.image != nil)
{
img2.image = nil
let cell2 = myTable.cellForRowAtIndexPath(img2IP)! as CustomCell
selectedIndexPaths.removeObject(img2IP)
configure(cell2, forRowAtIndexPath: img2IP)
counter--
}
else if (tester == btn3 && img3.image != nil)
{
img3.image = nil
let cell3 = myTable.cellForRowAtIndexPath(img3IP)! as CustomCell
selectedIndexPaths.removeObject(img3IP)
configure(cell3, forRowAtIndexPath: img3IP)
counter--
}
else if (tester == btn4 && img4.image != nil)
{
img4.image = nil
let cell4 = myTable.cellForRowAtIndexPath(img4IP)! as CustomCell
selectedIndexPaths.removeObject(img4IP)
configure(cell4, forRowAtIndexPath: img4IP)
counter--
}
else if (tester == btn5 && img5.image != nil)
{
img5.image = nil
let cell5 = myTable.cellForRowAtIndexPath(img5IP)! as CustomCell
selectedIndexPaths.removeObject(img5IP)
configure(cell5, forRowAtIndexPath: img5IP)
counter--
}
else
{
println("its already empty")
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("intrest", forIndexPath: indexPath) as CustomCell
cell.selectionStyle = .None
cell.backgroundColor = UIColor.clearColor()
configure(cell, forRowAtIndexPath: indexPath)
return cell
}
func configure(cell: CustomCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.lblInCell.text = InterstArr[indexPath.row]
if selectedIndexPaths.containsObject(indexPath) {
// selected
cell.imgInCell.backgroundColor = UIColor.redColor()
}
else if (selectedIndexPaths.containsObject(indexPath) == false ) {
// not selected
cell.imgInCell.backgroundColor = UIColor.whiteColor()
cell.lblInCell.backgroundColor = UIColor.whiteColor()
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if selectedIndexPaths.containsObject(indexPath) {
// deselect
println("remove object")
selectedIndexPaths.removeObject(indexPath)
////////////
if (img1str == InterstArr[indexPath.row])
{
img1.image = nil
println("remove 1 object")
}
else if ( img2str == InterstArr[indexPath.row])
{
img2.image = nil
println("remove 2 object")
}
else if (img3str == InterstArr[indexPath.row])
{
img3.image = nil
println("remove 3 object")
}
else if (img4str == InterstArr[indexPath.row])
{
img4.image = nil
println("remove 4 object")
}
else if ( img5str == InterstArr[indexPath.row])
{
img5.image = nil
println("remove 5 object")
}
counter--
// println(counter)
}
else if !(selectedIndexPaths.containsObject(indexPath)) {
// select
if (counter <= 4){
if (img1.image == nil)
{
img1str = InterstArr[indexPath.row]
img1.image = UIImage(named: InterstArr[indexPath.row])
img1IP = indexPath
println("add 1 object")
}
else if (img2.image == nil)
{
img2str = InterstArr[indexPath.row]
img2IP = indexPath
img2.image = UIImage(named: InterstArr[indexPath.row])
println("add 2 object")
}
else if (img3.image == nil)
{
img3str = InterstArr[indexPath.row]
img3IP = indexPath
img3.image = UIImage(named: InterstArr[indexPath.row])
println("add 3 object")
}
else if (img4.image == nil)
{
img4str = InterstArr[indexPath.row]
img4IP = indexPath
img4.image = UIImage(named: InterstArr[indexPath.row])
println("add 4 object")
}
else if (img5.image == nil)
{
img5str = InterstArr[indexPath.row]
img5IP = indexPath
img5.image = UIImage(named: InterstArr[indexPath.row])
println("add 5 object")
}
selectedIndexPaths.addObject(indexPath)
counter++
}
else if (counter > 4)
{
println("you selected 5 already")
}
}
let cell = tableView.cellForRowAtIndexPath(indexPath)! as CustomCell
configure(cell, forRowAtIndexPath: indexPath)
}

Ok then .. the problem was how to check if the indexPath is shown, so here is my answer for those who have the same problem, as an example i posted only one part of the function and you can repeat if (tester == btn1 && img1.image != nil) for the other buttons .. the line to check if the indexPath is visible is this one if ((myTable.cellForRowAtIndexPath(img1IP)) != nil) :
#IBAction func btn1Clicked (sender : UIButton)
{
let tester = sender
if (tester == btn1 && img1.image != nil)
{
if ((myTable.cellForRowAtIndexPath(img1IP)) != nil)
{
println("1 exist")
let cell:CustomCell = myTable.cellForRowAtIndexPath(img1IP) as CustomCell!
cell.imgInCell.backgroundColor = UIColor.whiteColor()
img1.image = nil
selectedIndexPaths.removeObject(img1IP)
}
else
{
img1.image = nil
selectedIndexPaths.removeObject(img1IP)
}
}

Related

How to change multiple table height dynamically as per array data count

I have 3 array different array which is cricketMatchArray, soccerMatchArray and tennisMatchArray.I'm display these 3 array data in 3 tableview which is expanding after clicking on header.Now I'm facing an issue table height is not change according to array data.
This output is I'm getting and I want remove that red mark space
for e.g:
if cricket and tennis array having a data and soccer array is empty then soccer table height not changing
I want to change tables height dynamically asper array count.
for e.g
if cricket and tennis array having a data and soccer array is empty then soccer table height should be 0
Here is my code..
class AllLiveMatchesViewController: UIViewController {
#IBOutlet weak var cricketTableView: UITableView!
#IBOutlet weak var soccerTableView: UITableView!
#IBOutlet weak var tennisTableView: UITableView!
var selectedIndx = -1
var thereIsCellTapped = false
var cricketMatchArray = [LiveMatchesData]()
var soccerMatchArray = [LiveMatchesData]()
var tennisMatchArray = [LiveMatchesData]()
override func viewDidLoad() {
super.viewDidLoad()
cricketTableView.dataSource = self
cricketTableView.delegate = self
cricketTableView.separatorStyle = .none
cricketTableView.tableFooterView = UIView()
soccerTableView.dataSource = self
soccerTableView.delegate = self
soccerTableView.separatorStyle = .none
soccerTableView.tableFooterView = UIView()
tennisTableView.dataSource = self
tennisTableView.delegate = self
tennisTableView.separatorStyle = .none
tennisTableView.tableFooterView = UIView()
getCricketMatches()
getSoccerMatches()
getTennisMatches()
}
extension AllLiveMatchesViewController: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == cricketTableView
{
return cricketMatchArray.count
}
else if tableView == soccerTableView
{
return soccerMatchArray.count
}
else if tableView == tennisTableView
{
return tennisMatchArray.count
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == cricketTableView
{
return cricketMatchArray[section].score.count
}
else if tableView == soccerTableView
{
return soccerMatchArray[section].score.count
}
else if tableView == tennisTableView
{
return tennisMatchArray[section].score.count
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if tableView == cricketTableView
{
let obj = cricketMatchArray[section]
if cricketMatchArray.count == 0
{
return 0
}
else
{
if obj.inplay == true && obj.status == "OPEN"
{
return 50
}
else if obj.inplay == false && obj.status == "OPEN"
{
return 0
}
else
{
return 0
}
}
}
else if tableView == soccerTableView
{
let obj = soccerMatchArray[section]
if obj.inplay == true && obj.status == "OPEN"
{
return 50
}
else if obj.inplay == false && obj.status == "OPEN"
{
return 0
}
else
{
return 0
}
}
else if tableView == tennisTableView
{
let obj = tennisMatchArray[section]
if obj.inplay == true && obj.status == "OPEN"
{
return 50
}
else if obj.inplay == false && obj.status == "OPEN"
{
return 0
}
else
{
return 0
}
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == cricketTableView
{
if indexPath.section == selectedIndx && thereIsCellTapped{
return 106
}
else{
return 0
}
}
else if tableView == soccerTableView
{
if indexPath.section == selectedIndx && thereIsCellTapped{
return 106
}
else{
return 0
}
}
else if tableView == tennisTableView
{
if indexPath.section == selectedIndx && thereIsCellTapped{
return 106
}
else{
return 0
}
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if tableView == cricketTableView
{
if (self.selectedIndx != section) && thereIsCellTapped{
return 0
}
else if (self.selectedIndx == section) && thereIsCellTapped{
return 20
}
else
{
return 0
}
}
else if tableView == soccerTableView
{
if (self.selectedIndx != section) && thereIsCellTapped{
return 0
}
else if (self.selectedIndx == section) && thereIsCellTapped{
return 20
}
else
{
return 0
}
}
else if tableView == tennisTableView
{
if (self.selectedIndx != section) && thereIsCellTapped{
return 0
}
else if (self.selectedIndx == section) && thereIsCellTapped{
return 20
}
else
{
return 0
}
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ExpandExtTableViewCell.self)) as! ExpandExtTableViewCell
if section == selectedIndx && thereIsCellTapped{
cell.footerView.roundCorners(corners: [.bottomLeft,.bottomRight], radius: 10)
}
else
{
cell.footerView.roundCorners(corners: [.bottomLeft,.bottomRight], radius: 0)
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if tableView == cricketTableView
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ExpandTableViewCell.self)) as! ExpandTableViewCell
let obj = cricketMatchArray[section]
if obj.inplay == false && obj.status == "CLOSE"
{
cell.liveView.isHidden = true
}
else if obj.inplay == true && obj.status == "OPEN"
{
cell.liveView.isHidden = false
}
cell.sportIcon.image = UIImage(named: "whiteball")
cell.teamNameLabel.text = obj.name ?? ""
cell.btnSelection.tag = section
cell.btnSelection.addTarget(self, action: #selector(AllLiveMatchesViewController.btnSectionClick(sender:)), for: .touchUpInside)
if section == selectedIndx && thereIsCellTapped{
cell.headerView.roundCorners(corners: [.topLeft,.topRight], radius: 10)
}
else
{
cell.headerView.roundCorners(corners: [.topLeft,.topRight,.bottomLeft,.bottomRight], radius: 10)
}
return cell
}
else if tableView == soccerTableView
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: SoccerExpandTableViewCell.self)) as! SoccerExpandTableViewCell
let obj = soccerMatchArray[section]
if obj.inplay == false && obj.status == "CLOSE"
{
cell.liveView.isHidden = true
}
else if obj.inplay == true && obj.status == "OPEN"
{
cell.liveView.isHidden = false
}
cell.sportIcon.image = UIImage(named: "soccerball")
cell.teamNameLabel.text = obj.name ?? ""
cell.btnSelection2.tag = section
cell.btnSelection2.addTarget(self, action: #selector(AllLiveMatchesViewController.btnSectionClick2(sender:)), for: .touchUpInside)
if section == selectedIndx && thereIsCellTapped{
cell.headerView.roundCorners(corners: [.topLeft,.topRight], radius: 10)
}
else
{
cell.headerView.roundCorners(corners: [.topLeft,.topRight,.bottomLeft,.bottomRight], radius: 10)
}
return cell
}
else if tableView == tennisTableView
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: TennisExpandTableViewCell.self)) as! TennisExpandTableViewCell
let obj = tennisMatchArray[section]
if obj.inplay == false && obj.status == "CLOSE"
{
cell.liveView.isHidden = true
}
else if obj.inplay == true && obj.status == "OPEN"
{
cell.liveView.isHidden = false
}
cell.sportIcon.image = UIImage(named: "tennisracket")
cell.teamNameLabel.text = obj.name ?? ""
cell.btnSelection3.tag = section
cell.btnSelection3.addTarget(self, action: #selector(AllLiveMatchesViewController.btnSectionClick3(sender:)), for: .touchUpInside)
if section == selectedIndx && thereIsCellTapped{
cell.headerView.roundCorners(corners: [.topLeft,.topRight], radius: 10)
}
else
{
cell.headerView.roundCorners(corners: [.topLeft,.topRight,.bottomLeft,.bottomRight], radius: 10)
}
return cell
}
else
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ExpandTableViewCell.self)) as! ExpandTableViewCell
return cell
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ExpandInsideTableViewCell.self)) as! ExpandInsideTableViewCell
if tableView == cricketTableView
{
let ob = cricketMatchArray[indexPath.section]
let obj = cricketMatchArray[indexPath.section].score[indexPath.row]
if obj.spnnation1 == nil
{
let teamName = ob.name?.components(separatedBy: " v ")
let fTeamWords = teamName?[0].split { !$0.isLetter }
let sTeamWords = teamName?[1].split { !$0.isLetter }
if fTeamWords?.count == 1
{
let fTeam = teamName?[0].prefix(3)
cell.firstTeamName.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[0].getAcronyms()
cell.firstTeamName.text = fTeam
}
if sTeamWords?.count == 1
{
let fTeam = teamName?[1].prefix(3)
cell.secondTeamName.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[1].getAcronyms()
cell.secondTeamName.text = fTeam
}
cell.firstTeamScore.text = obj.score1
cell.secondTeamScore.text = obj.score2
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = true
}
else
{
cell.firstTeamName.text = obj.spnnation1
cell.secondTeamName.text = obj.spnnation2
cell.firstTeamScore.text = obj.score1
cell.secondTeamScore.text = obj.score2
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = true
}
}
else if tableView == soccerTableView
{
let ob = soccerMatchArray[indexPath.section]
let obj = soccerMatchArray[indexPath.section].score[indexPath.row]
if obj.spnnation1 == nil
{
let teamName = ob.name?.components(separatedBy: " v ")
let fTeamWords = teamName?[0].split { !$0.isLetter }
let sTeamWords = teamName?[1].split { !$0.isLetter }
if fTeamWords?.count == 1
{
let fTeam = teamName?[0].prefix(3)
cell.firstTeamScore.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[0].getAcronyms()
cell.firstTeamScore.text = fTeam
}
if sTeamWords?.count == 1
{
let fTeam = teamName?[1].prefix(3)
cell.secondTeamScore.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[1].getAcronyms()
cell.secondTeamScore.text = fTeam
}
cell.firstTeamName.isHidden = true
cell.secondTeamName.isHidden = true
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = false
cell.commonScore.text = "\(obj.score1 ?? "")-\(obj.score2 ?? "")"
}
else
{
cell.firstTeamName.isHidden = true
cell.secondTeamName.isHidden = true
cell.firstTeamScore.text = obj.spnnation1?.getAcronyms()
cell.secondTeamScore.text = obj.spnnation2?.getAcronyms()
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = false
cell.commonScore.text = "\(obj.score1 ?? "")-\(obj.score2 ?? "")"
}
}
else if tableView == tennisTableView
{
let ob = tennisMatchArray[indexPath.section]
let obj = tennisMatchArray[indexPath.section].score[indexPath.row]
if obj.spnnation1 == nil
{
let teamName = ob.name?.components(separatedBy: " v ")
let fTeamWords = teamName?[0].split { !$0.isLetter }
let sTeamWords = teamName?[1].split { !$0.isLetter }
if fTeamWords?.count == 1
{
let fTeam = teamName?[0].prefix(3)
cell.firstTeamScore.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[0].getAcronyms()
cell.firstTeamScore.text = fTeam
}
if sTeamWords?.count == 1
{
let fTeam = teamName?[1].prefix(3)
cell.secondTeamScore.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[1].getAcronyms()
cell.secondTeamScore.text = fTeam
}
cell.firstTeamName.isHidden = true
cell.secondTeamName.isHidden = true
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = false
cell.commonScore.text = "\(obj.score1 ?? "")-\(obj.score2 ?? "")"
}
else
{
cell.firstTeamName.isHidden = true
cell.secondTeamName.isHidden = true
cell.firstTeamScore.text = obj.spnnation1?.getAcronyms()
cell.secondTeamScore.text = obj.spnnation2?.getAcronyms()
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = false
cell.commonScore.text = "\(obj.score1 ?? "")-\(obj.score2 ?? "")"
}
}
return cell
}
Can someone help me out with this.
The problem is that you duplicate code but not properties :
if tableView == cricketTableView
{
// This is the problem :
// only one selectedIndx and one thereIsCellTapped but 3 tables, so it give the same result
// for the 3 tables
if (self.selectedIndx != section) && thereIsCellTapped{
return 0
}
else if (self.selectedIndx == section) && thereIsCellTapped{
return 20
}
else
{
return 0
}
}
You have this problem in :
heightForRowAt
heightForFooterInSection
viewForFooterInSection
viewForHeaderInSection
and may in didSelectRowAt
As a curiosity question - why do you have 3 separate tableviews instead of one with sections?
Having 3 different UITableViews in one ViewController is in this case - not needed.
By controlling number of cells in section we can simplify the logic of the view later on.
Tapping on the header should control the logic of "hiding" (= setting number of rows in given section to zero) of other sections.
You can use Single TableView with a cell having StackView in it by giving it Top, Leading, Trailing, Bottom.
Your number of rows in section should be 3. It means you have three cells in it now populate your arrays in each cell.
Your heightForRowAt should be UITableView.automaticDimension

Getting a "Cannot provide direction" in maps when passing address in swift 3?

I need some help when user clicks on the table view cell when there is a address to open maps and directions will happen.. Unfortunately, I get the error when user clicks on the address table view cell which is "Cannot provide direction from and to of the same direction". So, here is my code below.
Here is my code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cellId = infoCellId
if indexPath.section != 0 {
cellId = interactiveCellId
}
let cell: UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellId)! as UITableViewCell
var key = "Not Available"
var value = "Not Available"
if indexPath.section == 0 {
if indexPath.row == 0 {
key = "Name"
if self.place.placeName.characters.count > 0 {
value = self.place.placeName
}
} else if indexPath.row == 1 {
key = "Address"
if let address = self.place.address {
if address.characters.count > 0 {
value = address
}
}
} else if indexPath.row == 2 {
key = "Phone number"
if let phoneNumber = self.place.phoneNumber {
if phoneNumber.characters.count > 0 {
value = phoneNumber
}
}
} else if indexPath.row == 3 {
key = "Website"
if let website = self.place.website {
if website.characters.count > 0 {
value = website
}
}
}
}
else if indexPath.section == 2 {
key = "Get Directions"
} else {
key = "Photos of \(self.place.placeName)"
}
if indexPath.section == 0 {
cell.textLabel?.text = key
cell.detailTextLabel?.text = value
} else {
cell.textLabel?.text = key
}
return cell
}
// ---- didSelectRowAt Happpening here -----
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
if indexPath.row == 1 {
print("it works!")
if let location = place.location {
if let url = URL(string:"http://maps.apple.com/maps?daddr=\(location.coordinate.longitude),\(location.coordinate.latitude)") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
if indexPath.row == 2 {
guard let phoneNumber = self.place.phoneNumber,
phoneNumber.count > 0,
let url = URL(string: "tel:\(phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)")
else { return }
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
} else { return }
}
You are specifying the same location for the start and destination of your navigation, so the error message is to be expected.
If you want to provide directions from the user's current location, you need only provide the destination.
Also, you have transposed the latitude and longitude values in the URL.
Finally, you are using string interpolation with an optional, so the url you are going to get is something like http://maps.apple.com/maps?daddr=(optional)x,(optional)y
You should unwrap place.location first.
if let coordinate = place.location?.coordinate {
if let url = URL(string:"http://maps.apple.com/maps?daddr=\(coordinate.longitude),\(coordinate.latitude)") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}

Swift 3: Removing Duplicates / group them as 1 in uitableviewcell

I am trying to either remove the duplicate entries fetched from the external database /group them as one. Initially, my sql query had a group clause. When I used it as group clause, the query was working, but not appropriately. I then removed the group clause from the query, it now shows the duplicate entries.
I have four regions: - North, East, South,West and ALL
By default it shows all region. Now there could be a profile that appears in more than one region. So when it loads as default - all regions, the profile should only appear once there, but when we tab on the regions, the profile should also show up there if the profile belongs in that region.
At them moment, it is showing all random. Some profiles that are available in more than one region, they do appear and some they dont. Some profile that is meant to be only in one region, do appear in 2 regions.
I dont know how can I share the code or screenshots, but happy to provide more details to look at the call.
Thanks
My code:
func removeDuplicate (sourceArray: [String]) -> [String] {
var uniqueArray:[String] = []
for object in sourceArray {
if !uniqueArray.contains(object)
{
uniqueArray.append(object)
}
}
return uniqueArray
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0
{
let cell = self.bussinessTableView.dequeueReusableCell(withIdentifier: "bussinessCell", for: indexPath) as! BussinessCell
let tableObjects:StorageSubCatagoriezTwo = subCatagorizeDataTwo[indexPath.row]
let testing = removeDuplicate(sourceArray: [tableObjects.nameString])
print(testing.description)
//let charCheck = (tableObjects.address).replacingOccurrences(of: " ", with: "")
if reg == "North"
{
cell.bussinessName.text = " "
cell.addLabel.text = " "
cell.telLabel.text = " "
cell.emailLabel.text = " "
cell.webLabel.text = " "
let tableObjects:StorageSubCatagoriezTwoNorth = subCatagorizeDataTwoN[indexPath.row]
if tableObjects.address.characters.isEmpty != true
{
cell.addLabel.text = tableObjects.address
}
else
{
//nothing
}
if tableObjects.telephone.characters.isEmpty != true
{
cell.telLabel.text = tableObjects.telephone
}
else
{
}
if tableObjects.email.characters.isEmpty != true
{
cell.emailLabel.text = tableObjects.email
}
else
{
}
if tableObjects.website.characters.isEmpty != true{
cell.webLabel.text = tableObjects.website
}
else{
}
}
else if reg == "East"
{
cell.bussinessName.text = " "
let tableObjects:StorageSubCatagoriezTwoEast = subCatagorizeDataTwoE[indexPath.row]
cell.bussinessName.text = tableObjects.nameString
if tableObjects.address.characters.isEmpty != true
{
cell.addLabel.text = tableObjects.address
}
else
{
//nothing
}
if tableObjects.telephone.characters.isEmpty != true
{
cell.telLabel.text = tableObjects.telephone
}
else
{
}
if tableObjects.email.characters.isEmpty != true
{
cell.emailLabel.text = tableObjects.email
}
else
{
}
if tableObjects.website.characters.isEmpty != true
{
cell.webLabel.text = tableObjects.website
}
else{
}
}
else if reg == "South"
{
cell.bussinessName.text = " "
let tableObjects:StorageSubCatagoriezTwoSouth = subCatagorizeDataTwoS[indexPath.row]
cell.bussinessName.text = tableObjects.nameString
if tableObjects.address.characters.isEmpty != true
{
cell.addLabel.text = tableObjects.address
}
else
{
//nothing
}
if tableObjects.telephone.characters.isEmpty != true
{
cell.telLabel.text = tableObjects.telephone
}
else
{
}
if tableObjects.email.characters.isEmpty != true
{
cell.emailLabel.text = tableObjects.email
}
else
{
}
if tableObjects.website.characters.isEmpty != true{
cell.webLabel.text = tableObjects.website
}
else{
}
}
else if reg == "West"
{
cell.bussinessName.text = " "
let tableObjects:StorageSubCatagoriezTwoWest = subCatagorizeDataTwoW[indexPath.row]
cell.bussinessName.text = tableObjects.nameString
if tableObjects.address.characters.isEmpty != true
{
cell.addLabel.text = tableObjects.address
}
else
{
//nothing
}
if tableObjects.telephone.characters.isEmpty != true
{
cell.telLabel.text = tableObjects.telephone
}
else
{
}
if tableObjects.email.characters.isEmpty != true
{
cell.emailLabel.text = tableObjects.email
}
else
{
}
if tableObjects.website.characters.isEmpty != true{
cell.webLabel.text = tableObjects.website
}
}
else{
let tableObjects:StorageSubCatagoriezTwo = subCatagorizeDataTwo[indexPath.row]
cell.bussinessName.text = tableObjects.nameString
let charCheck = (tableObjects.address).replacingOccurrences(of: " ", with: "")
cell.bussinessName.text = tableObjects.nameString
cell.addLabel.text = tableObjects.address
cell.telLabel.text = tableObjects.telephone
cell.emailLabel.text = tableObjects.email
cell.webLabel.text = tableObjects.website
}
return cell
}
else if indexPath.section == 1
{
let cell = self.bussinessTableView.dequeueReusableCell(withIdentifier: "bussinessCell2")
cell?.textLabel?.textAlignment = .center
switch regId
{
case 0:
if subCatagorizeDataTwo.count != forAll
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
case 1:
if subCatagorizeDataTwoN.count != forN
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
case 2:
if subCatagorizeDataTwoE.count != forE
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
case 3:
if subCatagorizeDataTwoS.count != forS
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
case 4:
if subCatagorizeDataTwoW.count != forW
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
default:break
}
return cell!
}
else
{
let tableObjects:StorageSubCatagoriez3rd = SubCatagoriez3rd[indexPath.row]
let cell = self.bussinessTableView.dequeueReusableCell(withIdentifier: "bussinessCell3")
cell?.textLabel?.text = tableObjects.nameString
return cell!
}
}
As per my knowledge if you want to remove duplicate from array then use below logic with your datatype
func removeDublicate (sourceArray: [Int]) -> [Int] {
var uniqueArray:[Int] = []
for object in sourceArray {
if !uniqueArray.contains(object)
{
uniqueArray.append(object)
}
}
return uniqueArray
}
let testing = removeDublicate(sourceArray: [1,2,2,5,1,8,3,1,2,8,5])
print(testing)
OUTPUT
[1, 2, 5, 8, 3]
Replace this line
let tableObjects:StorageSubCatagoriezTwoNorth = subCatagorizeDataTwoN[indexPath.row]
With this
var tableObjects:StorageSubCatagoriezTwoNorth = subCatagorizeDataTwoN[indexPath.row]
tableObjects = removeDuplicate(sourceArray: [tableObjects.nameString ])
Do it for all regions
In swift 3 you can use this code for removing duplicate from array. Only this much code is needed. Try this code..
import UIKit
class ViewController2: UIViewController {
var myArray: [Int] = [1,2,3,4,3,2,5,7,5,8]
override func viewDidLoad()
{
super.viewDidLoad()
let uniqueArray = Array(Set(self.myArray))
print(uniqueArray) // This print result will be [2, 4, 5, 7, 1, 8]
}
}
OUTPUT
[2, 4, 5, 7, 1, 8]

First UICollectionViewCell doesn't update with firebase data on swift

When I go into the view with the collectionView my first cell have the same data of the second cell, but if i go back to the homeView and return into the collectionView it have the right data inside
I have this code for load posts from Firebase
func loadPosts(){
Toast(text:"User profile loaded").show()
let currentUser = Auth.auth().currentUser
let displayName = currentUser?.displayName
dbRef.queryOrdered(byChild: "username").queryEqual(toValue: displayName).observe(DataEventType.value, with: { (snapshot) in
var newUtente = [MyStruct]()
for snapshotValue in snapshot.children.allObjects {
let restObject = MyStruct(snapshot: snapshotValue as! DataSnapshot)
newUtente.append(restObject)
}
self.Utente = newUtente
self.Utente = self.Utente.sorted(by: { $0.trimtime?.compare($1.trimtime! as String) == .orderedDescending })
//print(self.Utente)
DispatchQueue.main.async(execute: {
self.collectionView.reloadData()
})
self.activityIndicatorView.stopAnimating()
})
}
In the code of the Cell i have this
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cella = collectionView.dequeueReusableCell(
withReuseIdentifier: "cella", for: indexPath) as! ChatViewCell
if (indexPath.row == 0){
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
cella.layer.backgroundColor = UIColor("#DAE3FB").cgColor
let user = user2[indexPath.row]
cella.Label1?.text = user.username
key = user.key
last = user.lastname
} else if (indexPath.row >= 1){
let user = Utente[indexPath.row]
cella.LabelEur.text = user.price+"€"
test19 = user.price
cella.LabelR.text = user.sender
cella.layer.backgroundColor = UIColor("#FFFFFF").cgColor
if (user.positionDef != nil) {
if (user.positionDef.hasPrefix("0")) {
cella.Distanza.text = "Nelle vicinanze"
} else {
cella.Distanza.text = user.positionDef+"KM"
}
}
cella.City?.text = user.city
self.Utente = self.Utente.sorted{ $0.price.compare($1.price, options: .numeric) == ComparisonResult.orderedAscending }
}
return cella
}
I have no idea why it happens.
After the back and the return between homeView and CollectionView
Anyone have some idea?

Update TableViewCell with Asynchronous data

I have a tableViewCell that contains 8 images total divided into two blocks (4 images in each block). These images are downloaded asynchronously and stored into an array and then used in the the tableViewCell's cellForRowAtIndexPath to populate the images. I reload the tableView when all the images for one block has been added to the array in the dictionary (groupTOImages). The way I am doing it, I am getting out of order inconsistent results with the loading of the data. Some images are loaded into places where they shouldn't be. Is there a way to download the images and get consistent results in the tableViewCell.
var groupNames = [NSManagedObject]()
var groupTOPeople = [NSManagedObject: [String]]()
var groupTOImages = [NSManagedObject: [UIImage]]()
func getGroups() {
...
for group in groupNames {
groupTOImages[group] = []
if let people = groupTOPeople[group] {
var mycount = 0
for peeps in people {
InstagramEngine.sharedEngine().getUserDetails(peeps, withSuccess: { user in
if let ppic = user.profilePictureURL {
let picUrl = ppic.absoluteString
print(picUrl)
ImageLoader.sharedLoader.imageForUrl(picUrl) { (image, url) -> () in
self.groupTOImages[group]?.append(image!)
mycount++
if mycount == people.count {
self.tableView.reloadData()
}
}
} else {
self.groupTOImages[group]?.append(UIImage())
mycount++
if mycount == people.count {
self.tableView.reloadData()
}
}
}, failure: nil )
}
}
}
var counter = 0
var groupCount = 0
var groupCounter = 0
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellInfo = GroupCellsArray[indexPath.section]
...
case .userGroups:
let cell = tableView.dequeueReusableCellWithIdentifier(cellInfo.description, forIndexPath: indexPath) as! GroupTableViewCell
if groupNames.count > 0 {
var gp = groupNames[groupCounter]
switch counter {
case 0:
cell.firstTitle.text = (gp.valueForKey("name") as! String)
if let ourImages = groupTOImages[gp] {
for image in ourImages {
print(image.description)
print("groupCount \(groupCounter)")
cell.firstUserButtons[groupCount].layer.borderWidth = 0
cell.firstUserButtons[groupCount].setImage(image, forState: .Normal)
groupCount++
if groupCount == ourImages.count {
groupCount = 0
counter++
groupCounter++
gp = groupNames[groupCounter]
}
}
}
case 1:
if let title = gp.valueForKey("name") as? String {
cell.secondTitle.text = title
if let ourImages = groupTOImages[gp] {
for image in ourImages {
cell.secondUserButtons[groupCount].layer.borderWidth = 0
cell.secondUserButtons[groupCount].setImage(image, forState: .Normal)
groupCount++
if groupCount == ourImages.count {
groupCount = 0
counter = 0
groupCounter++
gp = groupNames[groupCounter]
}
}
}
} else {
cell.secondTitle.text = "Title"
}
default:
break
}
Each row looks like the picture below:
Code using ImageLoader in cellForRowAtIndexPath:
var counter = 0
for group in groupNames {
print("in the second")
groupTOImages[group] = []
if let people = groupTOPeople[group] {
var mycount = 0
for peeps in people {
InstagramEngine.sharedEngine().getUserDetails(peeps, withSuccess: { user in
if let ppic = user.profilePictureURL {
let picUrl = ppic.absoluteString
self.groupTOImages[group]?.append(picUrl)
counter++
mycount++
if counter == self.groupNames.count && mycount == people.count
{
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
} else {
self.groupTOImages[group]?.append(nil)
counter++
mycount++
if counter == self.groupNames.count && mycount == people.count
{
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
}
}, failure: nil )
}
}
if groupNames.count > 0 {
var gp = groupNames[groupCounter]
print("counter!!!!")
print("groupCount \(counter)")
switch counter {
case 0:
if let ourImages = groupTOImages[gp] {
cell.firstTitle.text = (gp.valueForKey("name") as! String)
print(cell.firstTitle.text)
for image in ourImages {
if let url = image {
print("I get in here")
ImageLoader.sharedLoader.imageForUrl(url) { (image, url) -> () in
cell.firstUserButtons[self.groupCount].layer.borderWidth = 0
cell.firstUserButtons[self.groupCount].setImage(image, forState: .Normal)
self.groupCount++
if self.groupCount == ourImages.count {
self.groupCount = 0
self.counter++
self.groupCounter++
gp = self.groupNames[self.groupCounter]
}
}
} else {
self.groupCount++
if self.groupCount == ourImages.count {
self.groupCount = 0
self.counter++
self.groupCounter++
gp = self.groupNames[self.groupCounter]
}
}
}
}
case 1:
if let title = gp.valueForKey("name") as? String {
cell.secondTitle.text = title
if let ourImages = groupTOImages[gp] {
for image in ourImages {
if let url = image {
ImageLoader.sharedLoader.imageForUrl(url) { (image, url) -> () in
cell.secondUserButtons[self.groupCount].layer.borderWidth = 0
cell.secondUserButtons[self.groupCount].setImage(image, forState: .Normal)
self.groupCount++
if self.groupCount == ourImages.count {
self.groupCount = 0
self.counter++
self.groupCounter++
gp = self.groupNames[self.groupCounter]
}
}
} else {
self.groupCount++
if self.groupCount == ourImages.count {
self.groupCount = 0
self.counter = 0
self.groupCounter++
gp = self.groupNames[self.groupCounter]
}
}
}
}
} else {
cell.secondTitle.text = "Title"
}
You should replace the self.tableView.reloadData() with
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
Hope this helps!

Resources