push data from UITableView to view controller programmatically - ios

I am trying to push data from a tableView to a View controller. I can successfully transfer some of the data over, but I am still missing some key points. I will try to illustrate my question to the best of my abilities. In my notificationTableView, I have data that is stored such as a userName, userImage, jobName and jobImage. I can succesfully push over the users image and name, however The jobName and JobImage fails to be transferred over as we can see in the Images below.
In this image, we can see the tableView sections that have the userName, userImage, jobName and jobImage.
In the second image, we can see that the usersName, and Image is succesfully pushed. However, the jobImage and name are not transferred.
the code that I use to push over the information is
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let notification = notifications[indexPath.row]
if notification.notificationType != .swipe {
let acceptWorker = jobProgressViewController()
acceptWorker.workerUser = myUser
acceptWorker.workerUser = notification.user
jobProgressView?.myParentViewController = self
let navController = UINavigationController(rootViewController: acceptWorker)
present(navController, animated: true, completion: nil)
} else {
print("something else should go here")
}
and the code that I use to retrieve the information is below. which is my jobProgressViewController
var notification: userNotifications?
var workerUser: User? {
didSet {
let name = workerUser?.name
workerNameLabel.text = name
guard let profileImage = workerUser?.profileImageUrl else { return }
workerImageView.loadImageUsingCacheWithUrlString(profileImage)
if let post = notification?.poster {
jobImageView.loadImageUsingCacheWithUrlString(post.imageUrl1!)
jobLabel.text = post.category
addressLabel.text = post.category
}
}
}
fileprivate func setupView(){
let postUser = workerUser.self
let uid = Auth.auth().currentUser?.uid
let userName = postUser?.name
let posterId = postUser?.uid
let post = notification?.poster
guard let userImage = workerUser?.profileImageUrl else { return }
Database.database().reference().child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String : Any] else { return }
let user = User(dictionary: dictionary as [String : AnyObject])
let currentUser = MyUser(dictionary: dictionary as [String : AnyObject])
self.posterImageView.image = #imageLiteral(resourceName: "user")
self.posterImageView.loadImageUsingCacheWithUrlString(userImage)
self.userNameLabel.text = userName
self.userNameLabel.font = UIFont.systemFont(ofSize: 30)
self.userNameLabel.textColor = UIColor.black
self.workerImageView.image = #imageLiteral(resourceName: "user")
self.workerImageView.loadImageUsingCacheWithUrlString(currentUser.profileImageUrl!)
self.workerNameLabel.text = currentUser.name
self.workerNameLabel.font = UIFont.systemFont(ofSize: 30)
self.workerNameLabel.textColor = UIColor.black
self.addressLabel.text = postUser?.address
self.addressLabel.font = UIFont.systemFont(ofSize: 30)
self.addressLabel.textColor = UIColor.black
self.jobLabel.text = post?.category
self.jobLabel.font = UIFont.systemFont(ofSize: 30)
self.jobLabel.textColor = UIColor.black
}, withCancel: { (err) in
print("attempting to load information")
})
print("this is your uid \(posterId!)")
}
below is how I populate my notificationCell which shows the users information in my tableView
var jobProgressView: jobProgressViewController? = nil
var delegate: NotificationCellDelegate?
var notification: userNotifications? {
didSet {
guard let user = notification?.user else { return }
guard let profileImageUrl = user.profileImageUrl else { return }
profileImageView.loadImageUsingCacheWithUrlString(profileImageUrl)
configureNotificationLabel()
configureNotificationType()
if let post = notification?.poster {
postImageView.loadImageUsingCacheWithUrlString(post.imageUrl1!)
}
}
}
func configureNotificationLabel() {
guard let notification = self.notification else { return }
guard let user = notification.user else { return }
guard let poster = notification.poster else { return }
guard let username = user.name else { return }
guard let notificationDate = configureNotificationTimeStamp() else { return }
guard let jobName = poster.category else { return }
let notificationMessage = notification.notificationType.description
let attributedText = NSMutableAttributedString(string: username, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14)])
attributedText.append(NSAttributedString(string: notificationMessage , attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.black]))
attributedText.append(NSAttributedString(string: jobName, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.black]))
attributedText.append(NSAttributedString(string: " \(notificationDate).", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.gray]))
notificationLabel.attributedText = attributedText
}
if there is anyInformation I may have left out to help with getting an answer please let me know. please and thank you.

As discusstion, you forget set notification for jobProgressViewController
In func didSelectRowAt indexPath add below code:
acceptWorker.notification = notification

Related

Buggy UI Tableview

I want the view to be like Apple maps UI Tableview when you click on a map annotation, the UI Tableview moves up with the loaded information and it is smooth. I created a UITableView to load data from a Yelp API and Firebase database. While I do have the data loaded in the UI Tableview, there seems to be choppiness in the movement of the tableview. For example, when I first click on a map annotation, the UI Tableview will pop up, but in a random position and then after the Yelp API loads, it will move again to its default position. Another thing is that if I use a swipe gesture before the Yelp API loads, the UI Tableview will move accordingly, but then reset to its original position when the Yelp API data loads, which then I have to redo the swipe gesture.
There are many parts of this tableview, so I will provide a list of pieces of code that I use:
Note: The UI Tableview (locationInfoViews) is configured in the ViewDidLoad
Swiping up/down
func configureGestureRecognizer() {
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGesture))
swipeUp.direction = .up
addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGesture))
swipeDown.direction = .down
addGestureRecognizer(swipeDown)
}
func animateInputView(targetPosition: CGFloat, completion: #escaping(Bool) -> ()) {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {self.frame.origin.y = targetPosition}, completion: completion)
}
// MARK: - Handlers
#objc func handleSwipeGesture(sender: UISwipeGestureRecognizer) {
if sender.direction == .up {
if expansionState == .Disappeared {
animateInputView(targetPosition: self.frame.origin.y - 100) { (_) in
self.expansionState = .NotExpanded
}
}
if expansionState == .NotExpanded {
animateInputView(targetPosition: self.frame.origin.y - 200) { (_) in
self.expansionState = .PartiallyExpanded
}
}
if expansionState == .PartiallyExpanded {
animateInputView(targetPosition: self.frame.origin.y - 250) { (_) in
self.expansionState = .FullyExpanded
}
}
} else {
if expansionState == .FullyExpanded {
animateInputView(targetPosition: self.frame.origin.y + 250) { (_) in
self.expansionState = .PartiallyExpanded
}
}
if expansionState == .PartiallyExpanded {
animateInputView(targetPosition: self.frame.origin.y + 200) { (_) in
self.expansionState = .NotExpanded
}
}
if expansionState == .NotExpanded {
animateInputView(targetPosition: self.frame.origin.y + 100) { (_) in
self.expansionState = .Disappeared
}
}
}
}
When select annotation, information from Yelp and Firebase will be loaded into the location info view and the animation should move up
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
self.locationPosts.removeAll()
self.inLocationInfoMode = true
if view.annotation is MKUserLocation {
print("selected self")
} else {
self.selectedAnnotation = view.annotation as? Annotation
let coordinates = selectedAnnotation.coordinate
let coordinateRegion = MKCoordinateRegion(center: coordinates, latitudinalMeters: 1000, longitudinalMeters: 100)
mapView.setRegion(coordinateRegion, animated: true)
self.locationInfoViews.locationTitle = self.selectedAnnotation.title
// Fetch Location Post
guard let currentUid = Auth.auth().currentUser?.uid else {return}
LOCATION_REF.child(self.selectedAnnotation.title).child(currentUid).observe(.childAdded) { (snapshot) in
let postId = snapshot.key
Database.fetchLocationPost(with: postId) { (locationPost) in
self.locationPosts.append(locationPost)
self.locationPosts.sort { (post1, post2) -> Bool in
return post1.creationDate > post2.creationDate
}
self.locationInfoViews.locationResults = self.locationPosts
// self.locationInfoViews.tableView.reloadData()
// Fetch Location Information
guard let locationName = locationPost.locationName else {return}
guard let locationAddress = locationPost.address else {return}
let locationRef = COORDINATES_REF.child(locationName).child(locationAddress)
locationRef.child("mainTypeOfPlace").observe(.value) { (snapshot) in
guard let mainTypeOfPlace = snapshot.value as? String else {return}
// self.locationInfoViews.typeOfPlace = mainTypeOfPlace
locationRef.child("shortAddress").observe(.value) { (snapshot) in
guard let address1 = snapshot.value as? String else {return}
locationRef.child("city").observe(.value) { (snapshot) in
guard let city = snapshot.value as? String else {return}
locationRef.child("state").observe(.value) { (snapshot) in
guard let state = snapshot.value as? String else {return}
locationRef.child("countryCode").observe(.value) { (snapshot) in
guard let country = snapshot.value as? String else {return}
// fetch Yelp API Data
self.service.request(.match(name: locationName, address1: address1, city: city, state: state, country: country)) {
(result) in
switch result {
case .success(let response):
let businessesResponse = try? JSONDecoder().decode(BusinessesResponse.self, from: response.data)
let firstID = businessesResponse?.businesses.first?.id
self.information.request(.BusinessID(id: firstID ?? "")) {
(result) in
switch result {
case .success(let response):
if let jsonResponse = try? JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any] {
// print(jsonResponse)
if let categories = jsonResponse["categories"] as? Array<Dictionary<String, AnyObject>> {
var mainCategory = ""
for category in categories {
mainCategory = category["title"] as? String ?? ""
break
}
self.locationInfoViews.typeOfPlace = mainCategory
}
let price = jsonResponse["price"] as? String ?? ""
if let hours = jsonResponse["hours"] as? Array<Dictionary<String, AnyObject>> {
for hour in hours {
let isOpen = hour["is_open_now"] as? Int ?? 0
if isOpen == 1 {
let attributedText = NSMutableAttributedString(string: "open ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor(rgb: 0x066C19)])
attributedText.append(NSAttributedString(string: " \(price)", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.black]))
self.locationInfoViews.hoursLabel.attributedText = attributedText
} else {
let attributedText = NSMutableAttributedString(string: "closed ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.red])
attributedText.append(NSAttributedString(string: " \(price)", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.darkGray]))
self.locationInfoViews.hoursLabel.attributedText = attributedText
}
}
}
}
case .failure(let error):
print("Error: \(error)")
}
}
case .failure(let error):
print("Error: \(error)")
}
}
}
}
}
}
}
self.locationInfoViews.tableView.reloadData()
}
}
// enable the goButton
if inLocationInfoMode {
locationInfoViews.goButton.isEnabled = true
locationInfoViews.coordinates = selectedAnnotation.coordinate
}
// the movement of the location info view
if self.locationInfoViews.expansionState == .Disappeared {
self.locationInfoViews.animateInputView(targetPosition: self.locationInfoViews.frame.origin.y - 335) { (_) in
self.locationInfoViews.expansionState = .PartiallyExpanded
}
}
}
}
Try adding a completion block for the fetching, first extract it into a separate function. On tap on the annotation show some loading state, while you load the data. Once you receive the completion block, decide what to do depending on the result. The fetching will be done while the user sees a loading state, and no flickering will occur.

Chat messages does not update properly

This is the full code for the chatViewController. Every time when I click send button, the text messages will have some duplicate and fly out of text box as shown in this picture.
However, when I exit the chat and re-enters,those message that fly out of the box are gone. It is not because of duplicated messages in Array, I believe it should be due to either Cache issue or the updating mechanism is wrong.
Every time when I close chat and re-enter, the fly out of text box chat does not exist, everything is fine. If I do not click on send Message,the Messages all reload fine.
It is only when I click send message, there will be a few (not all) messages that duplicate and fly out of box. When I exit the chat, and re-enter,the out of box chat will be gone and everything is normal.
I consulted with other programmers who saw my code and said it is most likely because when you click send button, it fetches complete dataset, and when it display on your screen, the old data on your screen (even though you have removed them from your array) messed up with the new data. I asked them how to solve it, they are not sure because they are Android developers.
A train of thought I was thinking: cache the old messages, add the new messages but make sure they do not conflict with the old messages in the cache?
import UIKit
import Firebase
import FirebaseStorage
import FirebaseDatabase
import FirebaseFirestore
import CoreData
class ChatViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var messageText: UITextField!
#IBAction func back(_ sender: Any) {
back()
}
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var usernameLabel: UILabel!
#IBAction func sendTextMessage(_ sender: Any) {
chats.removeAll()
self.sendDataToDatabase(message: messageText.text!)
messageText.text = nil
self.loadPosts()
self.loadPostsReceivedMessage()
delayCompletionHandler {
self.collectionView.reloadData()
}
}
let cellIdentifier = "chatNow"
var chats = [Chat]()
var posts = [Post]()
var receiverIDNumber = ""
var profileImageUrl = ""
var senderString = ""
var conversationsCounterInt = 0
var timestamp = String(Int(Date().timeIntervalSince1970))
let db = Firestore.firestore()
override func viewDidLoad() {
super.viewDidLoad()
let yourNibName = UINib(nibName: "ChatCollectionViewCell", bundle: nil)
collectionView.register(yourNibName, forCellWithReuseIdentifier: cellIdentifier)
self.collectionView.dataSource = self
self.collectionView.delegate = self
print(receiverIDNumber)
usernameLabel.text! = receiverIDNumber
setUpProfile()
set()
print("is there anything"+profileImageUrl)
//Making circular profile picture
profileImage.layer.borderWidth = 1.0
profileImage.layer.masksToBounds = false
profileImage.layer.borderColor = UIColor.white.cgColor
profileImage.layer.cornerRadius = profileImage.frame.size.width / 2
profileImage.clipsToBounds = true
print("waka"+senderString)
self.loadPosts()
self.loadPostsReceivedMessage()
delayCompletionHandler {
self.collectionView.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationItem.title = "Chat"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func back() {
let storyboard = UIStoryboard(name: "Main" , bundle: nil)
let tabViewController = storyboard.instantiateViewController(withIdentifier: "tab")
present(tabViewController, animated: true,completion: nil)
}
func set() {
let uid = Auth.auth().currentUser?.uid
let ref = Database.database().reference()
ref.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if let dic = snapshot.value as? [String: AnyObject] {
self.senderString = dic["username"] as! String
print("this"+self.senderString)
}
})
}
func sendDataToDatabase(message: String){
let ref = Database.database().reference()
let senderIDNumber = Auth.auth().currentUser?.uid
let timeStampString = String(Int(Date().timeIntervalSince1970))
db.collection("chats").addDocument(data: ["message": messageText.text!, "senderID": senderIDNumber!,"receiverID": receiverIDNumber,"timestamp": timeStampString,"profileUrl": profileImageUrl, "sender": self.senderString])
{ err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
}
func logout(){
let storyboard = UIStoryboard(name: "Main" , bundle: nil)
let loginViewController = storyboard.instantiateViewController(withIdentifier: "login")
present(loginViewController, animated: true,completion: nil)
}
func delayCompletionHandler(completion:#escaping (() -> ())) {
let delayInSeconds = 0.3
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
completion()
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return chats.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ChatCollectionViewCell
let senderIDNumber = Auth.auth().currentUser?.uid
//Setup the messageReceived and messageSent
if chats[indexPath.row].senderID == senderIDNumber {
if let chatsText = chats[indexPath.row].message{
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: chatsText).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
cell.messageSend.frame = CGRect(x:8,y:0,width:estimatedFrame.width + 16, height:estimatedFrame.height + 20)
cell.textBubbleView.frame = CGRect(x:0,y:0,width:estimatedFrame.width + 16 + 8, height:estimatedFrame.height + 20)
//showOutgoingMessage(text: chats[indexPath.row].message)
cell.messageSend.text = chats[indexPath.row].message
}
}
else {
cell.messageReceived.text = chats[indexPath.row].message
let chatsText = chats[indexPath.row].message
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: chatsText!).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
cell.messageReceived.frame = CGRect(x:view.frame.width - estimatedFrame.width - 30,y:0,width:estimatedFrame.width + 16, height:estimatedFrame.height + 20)
cell.textBubbleView.frame = CGRect(x:view.frame.width - estimatedFrame.width - 30,y:0,width:estimatedFrame.width + 16 + 4, height:estimatedFrame.height + 20)
}
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
if let chatsText = chats[indexPath.row].message {
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: chatsText).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
return CGSize(width: view.frame.width, height: estimatedFrame.height + 20)
}
return CGSize(width: view.frame.width, height: 200)
}
//Get Message sent
func loadPosts() {
let senderIDNumber = Auth.auth().currentUser?.uid
let chatsRef = db.collection ("chats").order (by: "timestamp", descending: false)
let sentListener = chatsRef.whereField ("senderID", isEqualTo: senderIDNumber!)
.whereField ("receiverID", isEqualTo: receiverIDNumber)
.addSnapshotListener() {
querySnapshot,
error in
guard let documentChanges = querySnapshot?.documentChanges else {
print ("Error fetching documents: \(error!)")
return
}
for documentChange in documentChanges {
if (documentChange.type == .added) {
let data = documentChange.document.data ()
print("Message send: \(data)")
let messageText = data["message"] as? String
let senderIDNumber = data["senderID"] as? String
let receiverIDNumber = data["receiverID"] as? String
let timestamp = data["timestamp"] as? String
guard let sender = data["sender"] as? String else {return}
// let conversationsCounter = document.data()["conversationsCounter"] as? Int
guard let profileUrl = data["profileUrl"] as? String else { return}
let chat = Chat(messageTextString: messageText!, senderIDNumber: senderIDNumber!, receiverIDNumber: receiverIDNumber!, timeStampString: timestamp!, profileImageUrl: profileUrl, senderString: sender)
self.chats.append(chat)
print(self.chats)
}
}
}
}
//Get message received
func loadPostsReceivedMessage() {
let chatsRef = db.collection("chats").order(by: "timestamp", descending: false)
print("thecurrentreceiver"+senderString)
print("thecurrentsender"+receiverIDNumber)
let receivedListener = chatsRef.whereField("receiverID", isEqualTo: senderString).whereField("sender", isEqualTo: receiverIDNumber)
.addSnapshotListener() {
querySnapshot,
error in
guard let documentChanges = querySnapshot?.documentChanges else {
print ("Error fetching documents: \(error!)")
return
}
for documentChange in documentChanges {
if (documentChange.type == .added) {
let data = documentChange.document.data ()
print("Message received: \(data)")
let messageText = data["message"] as? String
let senderIDNumber = data["senderID"] as? String
let receiverIDNumber = data["receiverID"] as? String
let timestamp = data["timestamp"] as? String
guard let sender = data["sender"] as? String else {return}
// let conversationsCounter = document.data()["conversationsCounter"] as? Int
guard let profileUrl = data["profileUrl"] as? String else { return}
let chat = Chat(messageTextString: messageText!, senderIDNumber: senderIDNumber!, receiverIDNumber: receiverIDNumber!, timeStampString: timestamp!, profileImageUrl: profileUrl, senderString: sender)
self.chats.append(chat)
print(self.chats)
self.chats.sort{$0.timestamp < $1.timestamp}
}
}
}
}
func setUpProfile() {
guard let url = URL(string: profileImageUrl) else { return}
let task = URLSession.shared.dataTask(with: url){ data, reponse, error in
if error != nil {
print(error!)
} else{
DispatchQueue.main.async(execute: {
self.profileImage.image = UIImage(data: data!)
})
}
}
task.resume()
}
}

how to pass the json values to rating control in swift 3?

here is my stack view code where I had got this code from apple developer site in this rating control was manually giving but I am having the data coming from web services how to pass to the rating control to display the stars as got from the web services can anyone help me ?
var number = 0
private var ratingButtons = [UIButton]()
var rating = 0 {
didSet {
updateButtonSelectionStates()
}
}
#IBInspectable var starSize: CGSize = CGSize(width: 20.0, height: 10.0) {
didSet {
setupButtons()
}
}
#IBInspectable var starCount: Int = 5 {
didSet {
setupButtons()
}
}
//MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setupButtons()
}
required init(coder: NSCoder) {
super.init(coder: coder)
setupButtons()
}
//MARK: Button Action
func ratingButtonTapped(button: UIButton) {
guard let index = ratingButtons.index(of: button) else {
fatalError("The button, \(button), is not in the ratingButtons array: \(ratingButtons)")
}
// Calculate the rating of the selected button
let selectedRating = index + 1
if selectedRating == rating {
// If the selected star represents the current rating, reset the rating to 0.
rating = 0
} else {
// Otherwise set the rating to the selected star
rating = selectedRating
}
}
//MARK: Private Methods
private func setupButtons() {
// Clear any existing buttons
for button in ratingButtons {
removeArrangedSubview(button)
button.removeFromSuperview()
}
ratingButtons.removeAll()
// Load Button Images
let bundle = Bundle(for: type(of: self))
let filledStar = UIImage(named: "filledStar", in: bundle, compatibleWith: self.traitCollection)
let emptyStar = UIImage(named:"emptyStar", in: bundle, compatibleWith: self.traitCollection)
for index in 0..<starCount {
// Create the button
let button = UIButton()
// Set the button images
button.setImage(emptyStar, for: .normal)
button.setImage(filledStar, for: .selected)
// Add constraints
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true
button.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true
// Set the accessibility label
button.accessibilityLabel = "Set \(index + 1) star rating"
button.isUserInteractionEnabled = true
// Setup the button action
button.addTarget(self, action: #selector(starRatingControl.ratingButtonTapped(button:)), for: .touchUpInside)
// Add the button to the stack
addArrangedSubview(button)
// Add the new button to the rating button array
ratingButtons.append(button)
}
updateButtonSelectionStates()
}
private func updateButtonSelectionStates() {
for (index, button) in ratingButtons.enumerated() {
// If the index of a button is less than the rating, that button should be selected.
button.isSelected = index < rating
// Set accessibility hint and value
let hintString: String?
if rating == index + 1 {
hintString = "Tap to reset the rating to zero."
} else {
hintString = nil
}
let valueString: String
switch (rating) {
case 0:
valueString = "No rating set."
case 1:
valueString = "1 star set."
default:
valueString = "\(rating) stars set."
}
button.accessibilityHint = hintString
button.accessibilityValue = valueString
}
}
this is my json response where I am getting the data from url in view controller
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
if let detailsArray = jsonObj!.value(forKey: "Detail") as? NSArray {
for item in detailsArray {
if let detailDict = item as? NSDictionary {
if let name = detailDict.value(forKey: "productName") {
self.productName.append(name as! String)
}
if let image1 = detailDict.value(forKey: "image1"){
self.imageArray.append(image1 as! String)
}
if let image2 = detailDict.value(forKey: "image2"){
self.imageArray.append(image2 as! String)
}
if let image3 = detailDict.value(forKey: "image3"){
self.imageArray.append(image3 as! String)
}
if let image4 = detailDict.value(forKey: "image4"){
self.imageArray.append(image4 as! String)
}
if let image5 = detailDict.value(forKey: "image5"){
self.imageArray.append(image5 as! String)
}
if let image6 = detailDict.value(forKey: "image6"){
self.imageArray.append(image6 as! String)
}
if let image7 = detailDict.value(forKey: "image7"){
self.imageArray.append(image7 as! String)
}
if let image8 = detailDict.value(forKey: "image8"){
self.imageArray.append(image8 as! String)
}
if let image9 = detailDict.value(forKey: "image9"){
self.imageArray.append(image9 as! String)
}
if let image10 = detailDict.value(forKey: "image10"){
self.imageArray.append(image10 as! String)
}
if let price = detailDict.value(forKey: "productPrice") {
self.productprice.append(price as! String)
}
if let image = detailDict.value(forKey: "img"){
self.imagesArray.append(image as! String)
}
if let review = detailDict.value(forKey: "productReview"){
self.reviewArray.append(review as! Int)
}
}
}
}
OperationQueue.main.addOperation({
self.navigationBar.topItem?.title = self.productName[0]
self.priceLabel?.text = self.productprice[0]
self.nameLabel?.text = self.productName[0]
let x = self.reviewArray[0]
var mystring = String(x) + " Reviews"
self.reviewLabel.text = mystring
let star = starRatingControl()
star.isUserInteractionEnabled = false
star.rating = self.reviewArray[0]
print(star.rating)
self.view.addSubview(star)
let imgURL = NSURL(string:self.imageArray[0])
let data = NSData(contentsOf: (imgURL as URL?)!)
self.imageView.image = UIImage(data: data! as Data)
self.collectionView.reloadData()
})
}
}).resume()
}

JSQMessagesViewController: How to get senderId in viewDidLoad?

I have a function for avatars that's called in viewDidLoad (this is the function if it helps although I think the problem is not the function itself: https://pastebin.com/ksHmucTX).
In viewDidLoad I call it:
createAvatar(senderId: self.senderId, senderDisplayName: self.senderDisplayName, user: self.currentUser!, color: UIColor.lightGray)
But since I am only passing in my information (as the current user), when using the app I only see my avatar and not the avatars of everyone else in the chat.
In the avatarImageDataForItemAt function, there is an index path to figure out which message is which:
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
let message = messages[indexPath.row]
return avatars[message.senderId]
}
So I'm wondering how to get the proper senderId (i.e. the ID of whoever sent a message) in viewDidLoad so I can plug it into the createAvatars call, as opposed to what I have now, where senderId is ONLY my ID - thus making everyone's avatar appear, and not only mine (or whoever is the current user).
Thanks for any help!
EDIT:
func getParticipantInfo() {
let groupRef = databaseRef.child("groups").child(currentRoomIdGlobal)
groupRef.observe(.childAdded, with: { snapshot in
if let snapDict = snapshot.value as? [String : AnyObject] {
for each in snapDict {
let uid = each.key
let avatar = each.value["profilePicture"] as! String
let gender = each.value["gender"] as! String
let handle = each.value["handle"] as! String
let name = each.value["name"] as! String
let status = each.value["status"] as! String
// Set those to the dictionaries [UID : value]
self.avatarDictionary.setValue(avatar, forKey: uid)
self.nameDictionary.setValue(name, forKey: uid)
self.genderDictionary.setValue(gender, forKey: uid)
self.handleDictionary.setValue(handle, forKey: uid)
self.statusDictionary.setValue(status, forKey: uid)
DispatchQueue.main.async {
self.createAvatar(senderId: uid, senderDisplayName: name, photoUrl: avatar, color: UIColor.lightGray)
self.navCollectionView?.collectionView?.reloadData()
}
}
}
})
}
createAvatar:
func createAvatar(senderId: String, senderDisplayName: String, photoUrl: String, color: UIColor) {
if self.avatars[senderId] == nil {
let img = MyImageCache.sharedCache.object(forKey: senderId as AnyObject) as? UIImage
if img != nil {
self.avatars[senderId] = JSQMessagesAvatarImageFactory.avatarImage(with: img, diameter: 30)
} else if photoUrl != "" {
// the images are very small, so the following methods work just fine, no need for Alamofire here
if photoUrl.contains("https://firebasestorage.googleapis.com") {
self.storage.reference(forURL: photoUrl).data(withMaxSize: 1 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
assertionFailure("Error with Firebase Storage")
}
else {
let newImage = UIImage(data: data!)
self.avatars[senderId] = JSQMessagesAvatarImageFactory.avatarImage(with: newImage, diameter: 30)
MyImageCache.sharedCache.setObject(newImage!, forKey: senderId as AnyObject, cost: data!.count)
}
}
} else if let data = NSData(contentsOf: NSURL(string:photoUrl)! as URL) {
let newImage = UIImage(data: data as Data)!
self.avatars[senderId] = JSQMessagesAvatarImageFactory.avatarImage(with: newImage, diameter: 30)
MyImageCache.sharedCache.setObject(newImage, forKey: senderId as AnyObject, cost: data.length)
} else {
// Initials
let senderName = nameDictionary.value(forKey: senderId) as! String
let initials = senderName.components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.characters.first!)") + "\($1.characters.first!)" }
let placeholder = JSQMessagesAvatarImageFactory.avatarImage(withUserInitials: initials, backgroundColor: UIColor.gray, textColor: UIColor.white, font: UIFont.systemFont(ofSize: 14), diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))
MyImageCache.sharedCache.setObject(placeholder!, forKey: senderId as AnyObject)
}
}
} else {
// Initials
let senderName = nameDictionary.value(forKey: senderId) as! String
let initials = senderName.components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.characters.first!)") + "\($1.characters.first!)" }
let placeholder = JSQMessagesAvatarImageFactory.avatarImage(withUserInitials: initials, backgroundColor: UIColor.gray, textColor: UIColor.white, font: UIFont.systemFont(ofSize: 14), diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))
MyImageCache.sharedCache.setObject(placeholder!, forKey: senderId as AnyObject)
}
}
As far as I know, the JSQMessage contains the senderId of the sender, so the function below already specifies what avatar to be returned:
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
let message = messages[indexPath.row]
return avatars[message.senderId]
}
You will need to add an avatar to
var avatars = [String: JSQMessagesAvatarImage]()
I assume you have the userId of that user, so get the avatar the same way every time someone joins the conversation. Lets say userToChatWith:
createAvatar(userToChatWith.userKey, senderDisplayName: userToChatWithName, user: userToChatWith, color: UIColor.lightGray)

Pull to refresh not working

I am building my app in Swift 3 with Alamofire. I have JSON data coming into a list view. Every time I pull to refresh the content, instead of refreshing the content, it just adds more items to the bottom of the list in list view, instead of refreshing the visible list. I don't know what I could be doing wrong, my code so far is:
import UIKit
import Alamofire
import SVProgressHUD
struct postinput {
let mainImage : UIImage!
let name : String!
let author : String!
let summary : String!
let content : String!
}
class TableViewController: UITableViewController {
//var activityIndicatorView: UIActivityIndicatorView!
var postsinput = [postinput]()
var refresh = UIRefreshControl()
var mainURL = "https://www.example.com/api"
typealias JSONstandard = [String : AnyObject]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
self.tableView.addSubview(refresh)
//;refresh.attributedTitle = NSAttributedString(string: "Refreshing...", attributes:[NSForegroundColorAttributeName : UIColor.black])
refresh.backgroundColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0)
//refresh.tintColor = UIColor.white
refresh.addTarget(self, action: #selector(self.refreshData), for: UIControlEvents.valueChanged)
//refresh.addTarget(self, action: #selector(getter: TableViewController.refresh), for: UIControlEvents.valueChanged)
refresh.attributedTitle = NSAttributedString(string: "Updated: \(NSDate())")
//activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
//tableView.backgroundView = activityIndicatorView
callAlamo(url: mainURL)
}
func refreshData() {
Alamofire.request("https://www.example.com/api").responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
DispatchQueue.main.async {
self.tableView.reloadData()
self.refresh.endRefreshing()
}
})
}
func callAlamo(url : String){
//activityIndicatorView.startAnimating()
SVProgressHUD.show(withStatus: "Loading...")
SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.dark)
SVProgressHUD.setDefaultAnimationType(SVProgressHUDAnimationType.native)
SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.black)
Alamofire.request(url).responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
//self.activityIndicatorView.stopAnimating()
SVProgressHUD.dismiss()
})
}
func parseData(JSONData : Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard
// print(readableJSON)
if let posts = readableJSON["posts"] as? [JSONstandard] {
for post in posts {
let title = post["title"] as! String
let author = post["author"] as! String
guard let dic = post["summary"] as? [String: Any], let summary = dic["value"] as? String else {
return
}
let str = summary.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
print(str)
guard let dic1 = post["content"] as? [String: Any], let content = dic1["value"] as? String else {
return
}
let str1 = content.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
print(str1)
//print(author)
if let imageUrl = post["image"] as? String {
let mainImageURL = URL(string: imageUrl )
let mainImageData = NSData(contentsOf: mainImageURL!)
let mainImage = UIImage(data: mainImageData as! Data)
postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary, content: content))
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
catch {
print(error)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postsinput.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
// cell?.textLabel?.text = titles[indexPath.row]
let mainImageView = cell?.viewWithTag(2) as! UIImageView
mainImageView.image = postsinput[indexPath.row].mainImage
mainImageView.layer.cornerRadius = 5.0
mainImageView.clipsToBounds = true
//(cell?.viewWithTag(2) as! UIImageView).image = postsinput[indexPath.row].mainImage
let mainLabel = cell?.viewWithTag(1) as! UILabel
mainLabel.text = postsinput[indexPath.row].name
mainLabel.font = UIFont.boldSystemFont(ofSize: 18)
mainLabel.sizeToFit()
mainLabel.numberOfLines = 0;
let autLabel = cell?.viewWithTag(3) as! UILabel
autLabel.text = postsinput[indexPath.row].author
autLabel.font = UIFont(name: "Helvetica", size:16)
autLabel.textColor = UIColor(red: 0.8784, green: 0, blue: 0.1373, alpha: 1.0) /* #e00023 */
let sumLabel = cell?.viewWithTag(4) as! UILabel
sumLabel.text = (postsinput[indexPath.row].summary).replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
sumLabel.font = UIFont(name: "Helvetica", size:16)
sumLabel.textColor = UIColor(red:0.27, green:0.27, blue:0.27, alpha:1.0)
//let contentLabel = cell?.viewWithTag(0) as! UILabel
//contentLabel.text = (postsinput[indexPath.row].content).replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
//(cell?.viewWithTag(3) as! UILabel).text = postsinput[indexPath.row].author
return cell!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
SVProgressHUD.show()
let indexPath = self.tableView.indexPathForSelectedRow?.row
let vc = segue.destination as! nextVC
vc.articleImage = postsinput[indexPath!].mainImage
vc.articleMainTitle = postsinput[indexPath!].name
vc.articleContent = postsinput[indexPath!].content
SVProgressHUD.dismiss()
let backItem = UIBarButtonItem()
backItem.title = "Back"
navigationItem.backBarButtonItem = backItem // This will show in the next view controller being pushed
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
postsinput.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Your issue is here:
postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary, content: content))
You keep appending new data to the old data. If you want to completely clear out the old data before adding new data, just remove all of the elements from the postsinput array.
Your task here in pull to refresh is to just refresh the data existing in your list and also add the new items if any. So what you have to do is instead of keep on adding the items to your list everytime you pull-to-refresh, you just provide a new list coming from server to your tableView. Which you have the array aleready postsinput so make sure to remove all the items before you add it. Below is your code where you can do the changes.
func parseData(JSONData : Data) {
postsinput.removeAll()
do {
...
...
if let imageUrl = post["image"] as? String {
let mainImageURL = URL(string: imageUrl )
let mainImageData = NSData(contentsOf: mainImageURL!)
let mainImage = UIImage(data: mainImageData as! Data)
postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary, content: content))
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
...
...
}

Resources