Segmentation fault: 11 after Xcode upgrade - swift

please help on this error message:
While silgen emitFunction SIL function "#$S6QRCart6CartVCC9tableView_12cellForRowAtSo07UITableE4CellCSo0jE0C_10Foundation9IndexPathVtF".
for 'tableView(_:cellForRowAt:)' at /Users/Stenly/Downloads/QRCartGeo/QRCart/CartVC.swift:89:5
error: Segmentation fault: 11
This is my code:
func tableView(_ tableView: UITableView, cellForRowAt indePath: IndexPath) -> UITableViewCell {
// Parents
let cellIdentifierParents = "cell"
let CartCell: CartCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifierParents) as? CartCell
let cellObject = loadedCart[indePath.row]
CartCell?.selectionStyle = .none
CartCell?.lblItem.text = (cellObject as AnyObject).object(forKey: "item") as? String
CartCell?.lblSize.text = (cellObject as AnyObject).object(forKey: "size") as? String
CartCell?.lblPrice.text = ((cellObject as AnyObject).object(forKey: "price") as? String!)! + " €"
CartCell?.lblPrice.text = CartCell?.lblPrice.text?.replacingOccurrences(of: ".", with: ",")
var total = Float()
for item in loadedCart {
let price : NSString = ((item as AnyObject).object(forKey: "price") as? NSString)!
let priceTruncate = price.replacingOccurrences(of: "€", with: "")
let a:Float? = Float(priceTruncate)
total = total + a!
self.lblTotalOfCart.text = String(format : "SE: %.2f €",total)
self.lblTotalOfCart.text = self.lblTotalOfCart.text?.replacingOccurrences(of: ".", with: ",")
}
let deleteItem = UITapGestureRecognizer(target: self, action: #selector(self.deleteItem(_:)))
CartCell?.btnRemoveOutlet.addGestureRecognizer(deleteItem)
CartCell?.btnRemoveOutlet.isUserInteractionEnabled = true;
return CartCell!
}

Related

How to retrieve a value from Firestore to change the text of button in table cell for every listen item?

I have tableview in which there is list item and every cell possess a button, I want to fix the text and color of the button based on a boolean value retrieved from firestore, every cell's button have certain text and color based on that value only, I know the syntax to set the text and color for the button in swift, I am just not able to do on the basis of the value from the firestore, below is the code
code for retrieving the list, concerned value is checkl1value
func getComments() {
//print(postId + "received")
let commentsRef = Firestore.firestore().collection("posts").document(postId).collection("comments")
commentsRef.getDocuments { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let username = data["comment_author_username"] as? String ?? ""
let comment = data["comment_author_comment"] as? String ?? ""
let spinnerC = data["comment_author_spinnerC"] as? String ?? ""
let fullname = data["comment_author_fullname"] as? String ?? ""
let email = data["comment_author_email"] as? String ?? ""
let commentUserImageUrl = data["comment_user_image"] as? String ?? ""
let commentuser_id = data["comment_author_id"] as? String ?? ""
self.checkl1value = data["l1"] as? DarwinBoolean
let newComment = Comment(_documentId: document.documentID, _commentAuthorUsername: username, _commentAuthorFullName: fullname, _commentAuthorComment: comment, _commentUserImage: commentUserImageUrl, _commentAuthorSpinnerC: spinnerC, _commentAuthorId:commentuser_id )
self.comments.append(newComment)
}
self.tableView.reloadData()
}
}
}
}
Code for cellForRowAt
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentCell
cell.commentLikebutton.tag = indexPath.row
cell.commentLikebutton.addTarget(self, action: #selector(likeaction1(_:)), for: .touchUpInside)
if checkl1value == true {
cell.commentLikebutton.setTitle("Text1", for: .normal)
// cell.commentLikebutton.backgroundColor = UIColor(red: 17.0/255.0, green: 119.0/255.0, blue: 151.0/255.0, alpha: 1.0)
cell.commentLikebutton.backgroundColor = UIColor.red
//cell.commentLikebutton.backgroundColor = UIColor?.red()
}
else{
cell.commentLikebutton.setTitle("Text2", for: .normal)
}
cell.set(comment: comments[indexPath.row])
return cell
}
Add something like this on the top of cellForRowAt
let thisComment = self.comments[indexPath.row]
let checkl1value = thisComment.checkl1value
I think the error is that your checkl1Value always get changed with the value of the last item in the array. You can do something like this:
var booleanValues = [DarwinBoolean]()
func getComments() {
let commentsRef = Firestore.firestore().collection("posts").document(postId).collection("comments")
commentsRef.getDocuments { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let username = data["comment_author_username"] as? String ?? ""
let comment = data["comment_author_comment"] as? String ?? ""
let spinnerC = data["comment_author_spinnerC"] as? String ?? ""
let fullname = data["comment_author_fullname"] as? String ?? ""
let email = data["comment_author_email"] as? String ?? ""
let commentUserImageUrl = data["comment_user_image"] as? String ?? ""
let commentuser_id = data["comment_author_id"] as? String ?? ""
// self.checkl1value = data["l1"] as? DarwinBoolean
booleanValues.append(data["l1"] as? DarwinBoolean ?? false)
let newComment = Comment(_documentId: document.documentID, _commentAuthorUsername: username, _commentAuthorFullName: fullname, _commentAuthorComment: comment, _commentUserImage: commentUserImageUrl, _commentAuthorSpinnerC: spinnerC, _commentAuthorId:commentuser_id )
self.comments.append(newComment)
}
self.tableView.reloadData()
}
}
}
}
CellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentCell
cell.commentLikebutton.tag = indexPath.row
cell.commentLikebutton.addTarget(self, action: #selector(likeaction1(_:)), for: .touchUpInside)
if booleanValues[indexPath.row] {
cell.commentLikebutton.setTitle("Text1", for: .normal)
// cell.commentLikebutton.backgroundColor = UIColor(red: 17.0/255.0, green: 119.0/255.0, blue: 151.0/255.0, alpha: 1.0)
cell.commentLikebutton.backgroundColor = UIColor.red
//cell.commentLikebutton.backgroundColor = UIColor?.red()
} else {
cell.commentLikebutton.setTitle("Text2", for: .normal)
}
cell.set(comment: comments[indexPath.row])
return cell
}

Displaying wrong data after scrolled TableView

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)
}

i am able to prrint all data in table but one field i can not abble to print

I am call api through alamofire and i am getting response perfectly and i am able to all data into label in tableview cell but there is one field in response that i can not able to print let me explain below
Response:
SUCCESS: {
data =(
{
"from_id" = 77;
"from_name" = Paresh;
image = "https://www.kwikmypay.com/mode_share/modeshare_admin/assets/images/business/userNotFound.png";
msg = hi;
"msg_date" = "18-07-2018 05:54:40 am";
"msg_id" = 1;
"new_msg" = 37;
"to_id" = 88;
"to_name" = Mihir;
}
from this response i am able to print all but there is one field "new_msg" that i can't able to print can any one explain me this problem below is my code
let serviceparam = ["user_id":u_id,"access_token":acc_tkn,"time_zone": currentTimeZone] as [String : Any]
SVProgressHUD.show(withStatus: "Loading...")
Alamofire.request(chatList, method: .post, parameters: serviceparam).responseJSON
{
response in
print(response)
let result = response.result
if let dict = result.value as? Dictionary<String,AnyObject>{
if let serlist = dict["data"]{
self.servicelist = serlist as! [AnyObject]
self.tbl_chatlist.reloadData()
//self.dropDown.items = categorylist as! [AnyObject] as! [String]
}
}
SVProgressHUD.dismiss()
//self.activityIndicator.stopAnimating()
}
my service list array is proprly fiil up and all data i get correctly but not able to print on label ca any one please help me
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "chatlistcell") as! ChatlistTableViewCell
let f_name = servicelist[indexPath.row]["from_name"]
let image = servicelist[indexPath.row]["image"]
let date = servicelist[indexPath.row]["msg_date"]
let newMSG = servicelist[indexPath.row]["new_msg"]
let lastMsg = servicelist[indexPath.row]["msg"]
cell.lblTime.text = date as? String
cell.lblTitle.text = f_name as? String
cell.lblMsgCount.text = newMSG as? String
cell.lblLastMsg.text = lastMsg as? String
let proimgurl = NSURL(string: image as! String)
cell.img_logo.image = UIImage(data: NSData(contentsOf: proimgurl! as URL)! as Data)
return cell
}
Here is the code and i have one label lblMsgCount and in response there is one filed new_msg that i can not able to print

swift - table is moving down when change the UISegmentedControl (segcon)

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

UISearchBar and Firebase Database

struct postStruct {
let title : String!
let author : String!
let bookRefCode : String!
let imageDownloadString : String!
let status : String!
let reserved : String!
let category : String!
let dueDate : String!
}
'Above is where i set up the structure for the post, and below, is how i reference and retrieve the data from the firebase database.
My problem is that when you set up the searcher, i do not know how to get it to search based off of the title of the post.'
class DirectoryTableView: UITableViewController {
var posts = [postStruct]()
override func viewDidLoad() {
let databaseRef = Database.database().reference()
databaseRef.child("Books").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
var snapshotValue = snapshot.value as? NSDictionary
let title = snapshotValue!["title"] as? String
snapshotValue = snapshot.value as? NSDictionary
let author = snapshotValue!["author"] as? String
snapshotValue = snapshot.value as? NSDictionary
let bookRefCode = snapshotValue!["bookRefCode"] as? String
snapshotValue = snapshot.value as? NSDictionary
let status = snapshotValue!["status"] as? String
snapshotValue = snapshot.value as? NSDictionary
let reserved = snapshotValue!["reserved"] as? String
snapshotValue = snapshot.value as? NSDictionary
let category = snapshotValue!["category"] as? String
snapshotValue = snapshot.value as? NSDictionary
let dueDate = snapshotValue!["dueDate"] as? String
snapshotValue = snapshot.value as? NSDictionary
self.posts.insert(postStruct(title: title, author: author, bookRefCode: bookRefCode, status: status, reserved: reserved, category: category, dueDate: dueDate) , at: 0)
self.tableView.reloadData()
})
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let databaseRef = Database.database().reference()
let label1 = cell?.viewWithTag(1) as! UILabel
label1.text = posts[indexPath.row].title
let label2 = cell?.viewWithTag(2) as! UILabel
label2.text = posts[indexPath.row].author
let label3 = cell?.viewWithTag(3) as! UILabel
label3.text = posts[indexPath.row].bookRefCode
let label4 = cell?.viewWithTag(4) as! UILabel
label4.text = posts[indexPath.row].status
let label5 = cell?.viewWithTag(5) as! UILabel
label5.text = posts[indexPath.row].category
let image1 = cell?.viewWithTag(6) as! UILabel
image1.text = posts[indexPath.row].imageDownloadString
let label6 = cell?.viewWithTag(7) as! UILabel
label6.text = posts[indexPath.row].reserved
let label9 = cell?.viewWithTag(9) as! UILabel
label9.text = posts[indexPath.row].dueDate
return cell!
}
'Also, does anyone know how to sort the tableview cells (posts in this case) alphabetically?'
You can get all data already ordered alphabetically
databaseRef.child("Books").queryOrdered(byChild: "title").observe(.childAdded, with: { snapshot in
var snapshotValue = snapshot.value as? NSDictionary
let title = snapshotValue!["title"] as? String
snapshotValue = snapshot.value as? NSDictionary
....
}
or sort your array before reload the tableView
var sortedArray = swiftArray.sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == ComparisonResult.orderedAscending }
Sample structure
for sorting data according to searchBar I had used an dictionary that having all my snapshot and I compared my searchBar text in that dict and after sorting reloaded tableView here is code that you can have a look at
//method to get all user Details in a dict
func getEmail() {
let databaseRef = Database.database().reference().child("users")
databaseRef.observe(.value, with: { (snapshot) in
if snapshot.exists(){
self.postData = snapshot.value as! [String : AnyObject]
let dictValues = [AnyObject](self.postData.values)
self.sarchDict = dictValues
}
})
}
//search bar delegate
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if self.mySearchBar.text!.isEmpty {
// set searching false
self.isSearching = false
}else{
// set searghing true
self.isSearching = true
self.names.removeAll()
self.uidArray.removeAll()
self.imageUrl.removeAll()
for key in self.sarchDict {
let mainKey = key
//I am making query against email in snapshot dict
let str = key["email"] as? String
//taking value of email from my dict lowerCased to make query as case insensitive
let lowercaseString = str?.lowercased()
//checking do my any email have entered letter or not
if(lowercaseString?.hasPrefix(self.mySearchBar.text!.lowercased()))!{
//here I have a check so to remove value of current logged user
if ((key["uID"] as! String) != (Auth.auth().currentUser?.uid)!){
//If value is found append it in some arrays
self.imageUrl.append( key["profilePic"] as! String )
self.names.append( key["name"] as! String )
self.uidArray.append( key["uID"] as! String )
//you can check which values are being added from which key
print(mainKey)
}
}
}
//reload TableView here
}
}
//TableView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell = self.myTableView.dequeueReusableCell(withIdentifier: "Cell")!
if self.isSearching == true {
let imageView = (cell.viewWithTag(1) as! UIImageView)
imageView.setRounded()
if imageUrl[indexPath.row] != "" {
self.lazyImage.showWithSpinner(imageView:imageView, url:imageUrl[indexPath.row])
}
else{
imageView.image = UIImage(named: "anonymous")
}
(cell.contentView.viewWithTag(2) as! UILabel).text = self.names[indexPath.row]
}
else {
}
return cell
}
I'm sure this will be helpful to some using FireStore. Here I'm just setting my reference to point to the right collection. "name" is my field I wish to search by and is greater than will be checked chronologically on my string. The further they type the more defined the search results are.
static func searchForProgramStartingWith(string: String) {
let programsRef = db.collection("programs")
programsRef.whereField("name", isGreaterThan: string).limit(to: 10).getDocuments { (snapshot, error) in
if error != nil {
print("there was an error")
} else {
let shots = snapshot?.documents
for each in shots! {
let data = each.data()
let name = data["name"]
print("The name is \(name!)")
}
}
}
}