Post

Replies

Boosts

Views

Activity

Swift user online status updates but it repeats on cells that is not supposed to
I'm working on a chat app and I configured a function to check if a user is online. I'm able to see if another user is active or not, but, the issue I'm having is that if I scroll down (I'm using a UITableView) other users show as active and they are not. I placed the code inside the UITableViewCell class. Any suggestions as to what could be the problem are greatly appreciated. Here is my code: UITableViewCell `func configureHomeFeedCell(member: Member) { profileImage.loadImage(with: member.imageURL) profileName.text = "\(member.name)" + ", " + "\(member.age)" checkUserOnlineStatus(with: member.documentId) { _ in } } func checkUserOnlineStatus(with userId: String, completion: @escaping(Bool) -> Void) { let query = USERS_COLLECTION.document(userId).collection(IS_ONLINE) query.getDocuments { (snapshot, error) in if let error = error { print("ERROR..\(error.localizedDescription)") } else { snapshot?.documents.forEach({ diff in let isOnline = diff.get(USER_IS_ONLINE) as? Bool self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red completion(isOnline!) })}} query.addSnapshotListener { (snapshot, error) in snapshot?.documentChanges.forEach { diff in let isOnline = diff.document.get(USER_IS_ONLINE) as? Bool if (diff.type == .modified) { self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red completion(isOnline!) }}} }`
6
0
804
Jan ’23
push notifications open specific tab controller when the app is closed
Hi, I'm having a problem when opening a push notification to a specific tab when the app is closed/killed. The code below works properly when the app is in the background or in another tab. If closed and I open the push notification, the app opens to the main screen. Any ideas on how can I get it to open to the correct tab when is completely closed? any help is greatly appreciated.    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {              let scene = UIApplication.shared.connectedScenes.first             if let sceneDelegate = scene?.delegate as? SceneDelegate {               if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {                 tabController.selectedIndex = 1               }             } }
0
0
899
Nov ’22
Snapshot listener duplicating data
Hello, I'm working on this chat app and I have a snapshot listener to keep track the number of messages (with a badge) each user receives. I'm using a table view with pagination. The problem I'm having that I can't figure out is when a user gets a message, the table view duplicates the user, increases the badge number every time a message is received. Then, if i open the messages and then i go back to the first VC, there is another duplicate of the user but with no badge number because it was cleared. Any help is greatly appreciated. VC override func viewDidAppear(_ animated: Bool) {     super.viewDidAppear(animated)           fetchMatches()   } func fetchMatches() {     fetchInfo { matches in       self.match = matches       self.matchedMessagesTV.reloadData()     }   }       func fetchInfo(completion: @escaping([Match]) -> Void) {     if lastDocument == nil {       let query = MATCH_INFO_COLLECTION.document(currentUID!)         .collection("info").order(by: MATCH_TIMESTAMP, descending: false)       query.limit(to: 10).addSnapshotListener { (snapshot, error) in                   guard let last = snapshot?.documents.last else { return }         guard let snap = snapshot else { return }         snap.documentChanges.forEach({ diff in                       let dictionary = diff.document.data()           let memberId = dictionary[DOCUMENT_ID] as? String ?? ""           let memberAge = dictionary[AGE] as? Int ?? 0           let memberName = dictionary[FIRST_NAME] as? String ?? ""           let memberImageUrl = dictionary[PROFILE_IMAGE_URL] as? String ?? ""           let memberCurrentCity = dictionary[CURRENT_CITY] as? String ?? ""           let matchTimestamp = dictionary[MATCH_TIMESTAMP] as? Double ?? 0.0           let messageCounter = dictionary[MESSAGE_COUNTER] as? Int ?? 0                       let matches = Match(memberId: memberId, memberAge: memberAge ,memberName: memberName, memberImageUrl: memberImageUrl, memberCurrentCity: memberCurrentCity, matchTimestamp: Date(timeIntervalSince1970: matchTimestamp), messageCounter: messageCounter)                       self.match.append(matches)           self.memberId = matches.memberId           self.lastDocument = last           completion(self.match)         })       }     } else {       matchedMessagesTV.tableFooterView = createSpinnerFooter()       let query = MATCH_INFO_COLLECTION.document(currentUID!)         .collection("info").order(by: MATCH_TIMESTAMP, descending: false)               DispatchQueue.main.async {         self.matchedMessagesTV.tableFooterView = nil       }       query.start(afterDocument: self.lastDocument!)         .limit(to: 10).addSnapshotListener { (snapshot, error) in                       guard let last = snapshot?.documents.last else { return }           guard let snap = snapshot else { return }           snap.documentChanges.forEach({ diff in                           let dictionary = diff.document.data()             let memberId = dictionary[DOCUMENT_ID] as? String ?? ""             let memberAge = dictionary[AGE] as? Int ?? 0             let memberName = dictionary[FIRST_NAME] as? String ?? ""             let memberImageUrl = dictionary[PROFILE_IMAGE_URL] as? String ?? ""             let memberCurrentCity = dictionary[CURRENT_CITY] as? String ?? ""             let matchTimestamp = dictionary[MATCH_TIMESTAMP] as? Double ?? 0.0             let messageCounter = dictionary[MESSAGE_COUNTER] as? Int ?? 0                           let matches = Match(memberId: memberId, memberAge: memberAge ,memberName: memberName, memberImageUrl: memberImageUrl, memberCurrentCity: memberCurrentCity, matchTimestamp: Date(timeIntervalSince1970: matchTimestamp), messageCounter: messageCounter)                           self.match.append(matches)             self.memberId = matches.memberId             self.lastDocument = last             completion(self.match)                         })         }}   } class Match {       var memberId: String   let memberAge: Int   let memberName: String   let memberImageUrl: String   let memberCurrentCity: String   let matchTimestamp: Date!   let messageCounter: Int       init(memberId: String, memberAge: Int, memberName: String, memberImageUrl: String, memberCurrentCity: String, matchTimestamp: Date, messageCounter: Int) {           self.memberId = memberId     self.memberAge = memberAge     self.memberName = memberName     self.memberImageUrl = memberImageUrl     self.memberCurrentCity = memberCurrentCity     self.matchTimestamp = matchTimestamp     self.messageCounter = messageCounter   } }
3
0
680
Dec ’21
Zoom in/out an image inside of a table view
I'm trying to replicate the image zoom in/out feature we find in IG, the only issue I'm having is when I zoom-in, the image is not covering the entire screen, it only zooms-in inside the cell. This is a regular setup, a table view, a cell, an image view and a label. I'm not sure what I'm missing here. Any help is greatly appreciated: View Controller import UIKit class ViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var picArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.rowHeight = 300 } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return picArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! cell let data = picArray[indexPath.item] cell.backgroundColor = .red cell.setupCell(image: data) cell.clipsToBounds = false cell.selectionStyle = .none return cell } } Cell Class import UIKit class cell: UITableViewCell, UIScrollViewDelegate { @IBOutlet var picture: UIImageView! @IBOutlet var caption: UILabel! var zoomEnabled = false var imgCenter:CGPoint? override func awakeFromNib() { super.awakeFromNib() picture.contentMode = .scaleAspectFill picture.isUserInteractionEnabled = true picture.clipsToBounds = false caption.layer.zPosition = -1 let pinch = UIPinchGestureRecognizer(target: self, action: #selector(self.pinch(sender:))) pinch.delegate = self self.picture.addGestureRecognizer(pinch) let pan = UIPanGestureRecognizer(target: self, action: #selector(self.pan(sender:))) pan.delegate = self self.picture.addGestureRecognizer(pan) } override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } @objc func pan(sender: UIPanGestureRecognizer) { if self.zoomEnabled && sender.state == .began { self.imgCenter = sender.view?.center } else if self.zoomEnabled && sender.state == .changed { let translation = sender.translation(in: self) if let view = sender.view { view.center = CGPoint(x:view.center.x + translation.x, y:view.center.y + translation.y) } sender.setTranslation(CGPoint.zero, in: self.picture.superview) } } @objc func pinch(sender: UIPinchGestureRecognizer) { if sender.state == .began { let currentScale = self.picture.frame.size.width / self.picture.bounds.size.width let newScale = currentScale * sender.scale if newScale > 1 { self.zoomEnabled = true } } else if sender.state == .changed { guard let view = sender.view else {return} let pinchCenter = CGPoint(x: sender.location(in: view).x - view.bounds.midX, y: sender.location(in: view).y - view.bounds.midY) let transform = view.transform.translatedBy(x: pinchCenter.x, y: pinchCenter.y) .scaledBy(x: sender.scale, y: sender.scale) .translatedBy(x: -pinchCenter.x, y: -pinchCenter.y) let currentScale = self.picture.frame.size.width / self.picture.bounds.size.width var newScale = currentScale * sender.scale if newScale < 1 { newScale = 1 let transform = CGAffineTransform(scaleX: newScale, y: newScale) self.picture.transform = transform sender.scale = 1 }else { view.transform = transform sender.scale = 1 } } else if sender.state == .ended { guard let center = self.imgCenter else {return} UIView.animate(withDuration: 0.3, animations: { self.picture.transform = CGAffineTransform.identity self.picture.center = center }, completion: { _ in self.zoomEnabled = false }) } } func setupCell(image: String) { if let image : UIImage = UIImage(named: image) { picture.image = image } } }
0
0
1.3k
Nov ’21
Swift user online status updates but it repeats on cells that is not supposed to
I'm working on a chat app and I configured a function to check if a user is online. I'm able to see if another user is active or not, but, the issue I'm having is that if I scroll down (I'm using a UITableView) other users show as active and they are not. I placed the code inside the UITableViewCell class. Any suggestions as to what could be the problem are greatly appreciated. Here is my code: UITableViewCell `func configureHomeFeedCell(member: Member) { profileImage.loadImage(with: member.imageURL) profileName.text = "\(member.name)" + ", " + "\(member.age)" checkUserOnlineStatus(with: member.documentId) { _ in } } func checkUserOnlineStatus(with userId: String, completion: @escaping(Bool) -> Void) { let query = USERS_COLLECTION.document(userId).collection(IS_ONLINE) query.getDocuments { (snapshot, error) in if let error = error { print("ERROR..\(error.localizedDescription)") } else { snapshot?.documents.forEach({ diff in let isOnline = diff.get(USER_IS_ONLINE) as? Bool self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red completion(isOnline!) })}} query.addSnapshotListener { (snapshot, error) in snapshot?.documentChanges.forEach { diff in let isOnline = diff.document.get(USER_IS_ONLINE) as? Bool if (diff.type == .modified) { self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red completion(isOnline!) }}} }`
Replies
6
Boosts
0
Views
804
Activity
Jan ’23
push notifications open specific tab controller when the app is closed
Hi, I'm having a problem when opening a push notification to a specific tab when the app is closed/killed. The code below works properly when the app is in the background or in another tab. If closed and I open the push notification, the app opens to the main screen. Any ideas on how can I get it to open to the correct tab when is completely closed? any help is greatly appreciated.    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {              let scene = UIApplication.shared.connectedScenes.first             if let sceneDelegate = scene?.delegate as? SceneDelegate {               if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {                 tabController.selectedIndex = 1               }             } }
Replies
0
Boosts
0
Views
899
Activity
Nov ’22
Snapshot listener duplicating data
Hello, I'm working on this chat app and I have a snapshot listener to keep track the number of messages (with a badge) each user receives. I'm using a table view with pagination. The problem I'm having that I can't figure out is when a user gets a message, the table view duplicates the user, increases the badge number every time a message is received. Then, if i open the messages and then i go back to the first VC, there is another duplicate of the user but with no badge number because it was cleared. Any help is greatly appreciated. VC override func viewDidAppear(_ animated: Bool) {     super.viewDidAppear(animated)           fetchMatches()   } func fetchMatches() {     fetchInfo { matches in       self.match = matches       self.matchedMessagesTV.reloadData()     }   }       func fetchInfo(completion: @escaping([Match]) -> Void) {     if lastDocument == nil {       let query = MATCH_INFO_COLLECTION.document(currentUID!)         .collection("info").order(by: MATCH_TIMESTAMP, descending: false)       query.limit(to: 10).addSnapshotListener { (snapshot, error) in                   guard let last = snapshot?.documents.last else { return }         guard let snap = snapshot else { return }         snap.documentChanges.forEach({ diff in                       let dictionary = diff.document.data()           let memberId = dictionary[DOCUMENT_ID] as? String ?? ""           let memberAge = dictionary[AGE] as? Int ?? 0           let memberName = dictionary[FIRST_NAME] as? String ?? ""           let memberImageUrl = dictionary[PROFILE_IMAGE_URL] as? String ?? ""           let memberCurrentCity = dictionary[CURRENT_CITY] as? String ?? ""           let matchTimestamp = dictionary[MATCH_TIMESTAMP] as? Double ?? 0.0           let messageCounter = dictionary[MESSAGE_COUNTER] as? Int ?? 0                       let matches = Match(memberId: memberId, memberAge: memberAge ,memberName: memberName, memberImageUrl: memberImageUrl, memberCurrentCity: memberCurrentCity, matchTimestamp: Date(timeIntervalSince1970: matchTimestamp), messageCounter: messageCounter)                       self.match.append(matches)           self.memberId = matches.memberId           self.lastDocument = last           completion(self.match)         })       }     } else {       matchedMessagesTV.tableFooterView = createSpinnerFooter()       let query = MATCH_INFO_COLLECTION.document(currentUID!)         .collection("info").order(by: MATCH_TIMESTAMP, descending: false)               DispatchQueue.main.async {         self.matchedMessagesTV.tableFooterView = nil       }       query.start(afterDocument: self.lastDocument!)         .limit(to: 10).addSnapshotListener { (snapshot, error) in                       guard let last = snapshot?.documents.last else { return }           guard let snap = snapshot else { return }           snap.documentChanges.forEach({ diff in                           let dictionary = diff.document.data()             let memberId = dictionary[DOCUMENT_ID] as? String ?? ""             let memberAge = dictionary[AGE] as? Int ?? 0             let memberName = dictionary[FIRST_NAME] as? String ?? ""             let memberImageUrl = dictionary[PROFILE_IMAGE_URL] as? String ?? ""             let memberCurrentCity = dictionary[CURRENT_CITY] as? String ?? ""             let matchTimestamp = dictionary[MATCH_TIMESTAMP] as? Double ?? 0.0             let messageCounter = dictionary[MESSAGE_COUNTER] as? Int ?? 0                           let matches = Match(memberId: memberId, memberAge: memberAge ,memberName: memberName, memberImageUrl: memberImageUrl, memberCurrentCity: memberCurrentCity, matchTimestamp: Date(timeIntervalSince1970: matchTimestamp), messageCounter: messageCounter)                           self.match.append(matches)             self.memberId = matches.memberId             self.lastDocument = last             completion(self.match)                         })         }}   } class Match {       var memberId: String   let memberAge: Int   let memberName: String   let memberImageUrl: String   let memberCurrentCity: String   let matchTimestamp: Date!   let messageCounter: Int       init(memberId: String, memberAge: Int, memberName: String, memberImageUrl: String, memberCurrentCity: String, matchTimestamp: Date, messageCounter: Int) {           self.memberId = memberId     self.memberAge = memberAge     self.memberName = memberName     self.memberImageUrl = memberImageUrl     self.memberCurrentCity = memberCurrentCity     self.matchTimestamp = matchTimestamp     self.messageCounter = messageCounter   } }
Replies
3
Boosts
0
Views
680
Activity
Dec ’21
Zoom in/out an image inside of a table view
I'm trying to replicate the image zoom in/out feature we find in IG, the only issue I'm having is when I zoom-in, the image is not covering the entire screen, it only zooms-in inside the cell. This is a regular setup, a table view, a cell, an image view and a label. I'm not sure what I'm missing here. Any help is greatly appreciated: View Controller import UIKit class ViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var picArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.rowHeight = 300 } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return picArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! cell let data = picArray[indexPath.item] cell.backgroundColor = .red cell.setupCell(image: data) cell.clipsToBounds = false cell.selectionStyle = .none return cell } } Cell Class import UIKit class cell: UITableViewCell, UIScrollViewDelegate { @IBOutlet var picture: UIImageView! @IBOutlet var caption: UILabel! var zoomEnabled = false var imgCenter:CGPoint? override func awakeFromNib() { super.awakeFromNib() picture.contentMode = .scaleAspectFill picture.isUserInteractionEnabled = true picture.clipsToBounds = false caption.layer.zPosition = -1 let pinch = UIPinchGestureRecognizer(target: self, action: #selector(self.pinch(sender:))) pinch.delegate = self self.picture.addGestureRecognizer(pinch) let pan = UIPanGestureRecognizer(target: self, action: #selector(self.pan(sender:))) pan.delegate = self self.picture.addGestureRecognizer(pan) } override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } @objc func pan(sender: UIPanGestureRecognizer) { if self.zoomEnabled && sender.state == .began { self.imgCenter = sender.view?.center } else if self.zoomEnabled && sender.state == .changed { let translation = sender.translation(in: self) if let view = sender.view { view.center = CGPoint(x:view.center.x + translation.x, y:view.center.y + translation.y) } sender.setTranslation(CGPoint.zero, in: self.picture.superview) } } @objc func pinch(sender: UIPinchGestureRecognizer) { if sender.state == .began { let currentScale = self.picture.frame.size.width / self.picture.bounds.size.width let newScale = currentScale * sender.scale if newScale > 1 { self.zoomEnabled = true } } else if sender.state == .changed { guard let view = sender.view else {return} let pinchCenter = CGPoint(x: sender.location(in: view).x - view.bounds.midX, y: sender.location(in: view).y - view.bounds.midY) let transform = view.transform.translatedBy(x: pinchCenter.x, y: pinchCenter.y) .scaledBy(x: sender.scale, y: sender.scale) .translatedBy(x: -pinchCenter.x, y: -pinchCenter.y) let currentScale = self.picture.frame.size.width / self.picture.bounds.size.width var newScale = currentScale * sender.scale if newScale < 1 { newScale = 1 let transform = CGAffineTransform(scaleX: newScale, y: newScale) self.picture.transform = transform sender.scale = 1 }else { view.transform = transform sender.scale = 1 } } else if sender.state == .ended { guard let center = self.imgCenter else {return} UIView.animate(withDuration: 0.3, animations: { self.picture.transform = CGAffineTransform.identity self.picture.center = center }, completion: { _ in self.zoomEnabled = false }) } } func setupCell(image: String) { if let image : UIImage = UIImage(named: image) { picture.image = image } } }
Replies
0
Boosts
0
Views
1.3k
Activity
Nov ’21