My requirement : I will be having a list of chat details in a table view.On top of table view ,there will be a search functionality using text field.based on unique id of user, search should get done.if there is no chat with the unique id, which the user entered,then it has to redirect to another screen which is called chatcreatepage. when ever we are searching chat, we will be using an api called FIND API and in that FIND API there is a chat dictionary,if it is null,then create chat will get called.If that chat dictionary is not nil then need to display that chat details in chat list table view. When the chat list page is loading then ,we will be calling Chat list Api.when we are searching the chat by entering the unique id in textfield,we will be getting the corresponding details of that entered unique id & that unique id details we have to show in the table view.
This is the task and i have done till the chat list showing in the table.I am really not aware of this search result showing after calling the FIND API.If anyone helps me to solve it, would be really great.Thank in advance.I am providing the code below.
import UIKit
import Alamofire
import SwiftyJSON
import SDWebImage
class ChatlistViewController: UIViewController{
var pro = [[String:Any]]()
var dict:[String:Any]!
var idd = ""
var id = ""
var chatt:Dictionary = [String:Any]()
var searchActive : Bool = false
var filtered:[String] = []
var data:[String] = []
#IBOutlet weak var search-text: UITextField!
#IBOutlet weak var chatlisttable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
apical()
}
func apical(){
let acce:String = UserDefaults.standard.string(forKey: "access-tokenn")!
print(acce)
let headers:HTTPHeaders = ["Authorization":"Bearer \(acce)","Content-Type":"application/X-Access-Token"]
Alamofire.request(Constants.Chatlist, method: .get, encoding: URLEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
print(response)
if response.result.value != nil{
var maindictionary = NSDictionary()
maindictionary = response.result.value as! NSDictionary
print(maindictionary)
var userdata = NSDictionary()
userdata = maindictionary.value(forKey: "data") as! NSDictionary
var productsdetails = [[String:Any]]()
productsdetails = userdata.value(forKey: "chat") as! [[String:Any]]
self.pro = productsdetails
print(self.pro)
self.chatlisttable.reloadData()
}else{
let Alertcontroller = UIAlertController(title: "Alert", message: "No data found ", preferredStyle: .alert)
let CancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
Alertcontroller.addAction(CancelAction)
self.present(Alertcontroller, animated: true, completion: nil)
}
break
case .failure(let error):
print(error)
}
}
}
func searchapicall(){
idd = searchtext.text!
let acce:String = UserDefaults.standard.string(forKey: "access-tokenn")!
print(acce)
let headers:HTTPHeaders = ["Authorization":"Bearer \(acce)","Content-Type":"application/X-Access-Token"]
print((Constants.Chatlistsearch)+(idd))
Alamofire.request((Constants.Chatlistsearch+idd), method: .get, encoding: URLEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
//print(response)
if response.result.value != nil{
var maindictionary = NSDictionary()
maindictionary = response.result.value as! NSDictionary
var chat:Dictionary = maindictionary.value(forKey: "data") as! [String:Any]
var chattt:Dictionary = chat["chat"] as! [String:Any]
if (chattt != nil) {
print("Find Action")
self.chatt = chat["user"] as! [String:Any]
print(self.chatt)
//var uniqued:String = self.chatt["unique_id"] as! String
}else{
let viewc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ChatViewController") as? ChatViewController
self.navigationController?.pushViewController(viewc!, animated: true)
}
}else{
let Alertcontroller = UIAlertController(title: "Alert", message: "No data found on this unique id", preferredStyle: .alert)
let CancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
Alertcontroller.addAction(CancelAction)
self.present(Alertcontroller, animated: true, completion: nil)
}
break
case .failure(let error):
print(error)
}
}
}
}
extension ChatlistViewController: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.searchapicall()
return true
}
}
extension ChatlistViewController: UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (searchActive == false){
return self.pro.count
}else{
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = chatlisttable.dequeueReusableCell(withIdentifier: "ChatlistTableViewCell", for: indexPath) as! ChatlistTableViewCell
if (searchActive == false){
dict = pro[indexPath.row]
var recepient = dict["recipient"] as! [String:Any]
print(recepient)
var name = recepient["name"] as! String
print(name)
id = recepient["unique_id"] as! String
print(id)
var image = recepient["avatar"] as! String
print(image)
cell.namelbl.text = name
cell.idlbl.text = id
cell.imageView!.sd_setImage(with: URL(string:image), placeholderImage: UIImage(named: "Mahi.png"))
}else{
cell.namelbl.text = chatt["name"] as! String
cell.idlbl.text = chatt["unique_id"] as! String
}
return cell
self.chatlisttable.reloadData()
}
}
//Response format
{
"success": 1,
"status": 200,
"data": {
"user": {
"id": 3,
"unique_id": "10002",
"name": "nani",
"avatar": "https://www.planetzoom.co.in/storage/user/avatar/AkgcUFF3QIejMhZuLF4OXnSFHjxNAOo4FuXV3Mgi.jpeg"
},
"chat": null
}
}
You have to use UISearchBar and in call your api in delegate method of searchbar func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String).
For reference use this https://guides.codepath.com/ios/Search-Bar-Guide
Related
I am making an app that takes inputs from textFields in an alertController, then stored into CoreData and eventually be displayed in a tableView.
The plan for now is to create a string to create a CSV by combining the textField.text together, something like
let string CSV = textField.text + " ," + textField2.text + " ," + ...
However, when I tried to do this, they say that I cannot force unwrap an optional value.
I tried to put a "!" in textField.text, etc but they are all still seen as optional values. The textFields, when employed in the app must always be filled, but I could not find a way to provide an error that forces the user of the app to fill in a value.
Here is my ViewController:
import UIKit
import CoreData
class ViewController: UITableViewController {
var alarmItems: [NSManagedObject] = []
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
navigationController?.navigationBar.barTintColor = UIColor(red: 21/255, green: 101/255, blue: 192/255, alpha: 1)
navigationController?.navigationBar.tintColor = .white
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add Alarm", style: .plain, target: self, action: #selector(addAlarmItem))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "AlarmItems")
do {
alarmItems = try managedContext.fetch(fetchRequest)
} catch let err as NSError {
print("Failed to fetch items", err)
}
}
//now to figure out how to add multiple text fields
#objc func addAlarmItem(_ sender: AnyObject) {
print("this works")
let alertController = UIAlertController(title: "Add New Item", message: "Please fill in the blanks", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in
guard let textField = alertController.textFields!.first, let itemToAdd = textField.text else { return }
//guard let textField2 = alertController.textFields?.first, let itemToAdd2 = textField2.text else { return } //tried this to get the input of a second textField
/*
one thing I tried:
let textField1 = alertController.textFields[0]
let textField1String = textField1.text!
let textField2 = alertController.textFields![1]
let textField2String = textField2.text
let itemToAdd = textField1String + textField2String
*/
//var textField1String = textField1.text
//let textField2 = alertController.textFields![1]
//var textField2String = textField2.text
self.save(itemToAdd)
//self.save(itemToAdd2)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
//alertController.addTextField(configurationHandler: nil)
alertController.addTextField { (textField) in
textField.placeholder = "First"
}
alertController.addTextField { (textField) in
textField.placeholder = "Second"
}
//let combinedString = UITextField[0] + " ," + UITextField[1]
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
func save(_ itemName: String) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "AlarmItems", in: managedContext)!
let item = NSManagedObject(entity: entity, insertInto: managedContext)
item.setValue(itemName, forKey: "alarmAttributes")
do {
try managedContext.save()
alarmItems.append(item)
} catch let err as NSError {
print("Failed to save an item", err)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return alarmItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let alarmItem = alarmItems[indexPath.row]
cell.textLabel?.text = alarmItem.value(forKeyPath: "alarmAttributes") as? String
return cell
}
}
You can use compactMap to easily convert an array of optionals into an array of non-optionals.
let myStrings: [String] = alert.textfields!.compactMap { $0.text }
let myText = myStrings.joined(separator: ", ")
To learn more about compactMap, head over to https://developer.apple.com/documentation/swift/sequence/2950916-compactmap
One of the ways you can do the error validation is that when save is pressed, do empty checks on the textfields values in a separate function and show an error alert box.
I don't think you can show some kind of error inside your initial textfield alert controller. You have to validated the text separately and then show a separate alert error alert box.
You can use String extension to unwrap text this way:
extension Optional where Wrapped == String{
func safe() -> String{
if self == nil{
return ""
}else{
return self.unsafelyUnwrapped
}
}
Hope this helps.
My requirement : I will be having a list of chat details in a table view.On top of table view ,there will be a search functionality using text field.based on unique id of user, search should get done.if there is no chat with the unique id, which the user entered,then it has to redirect to another screen which is called chatcreatepage. when ever we are searching chat, we will be using an api called FIND API and in that FIND API there is a chat dictionary,if it is null,then create chat will get called.If that chat dictionary is not nil then need to display that chat details in chat list table view. When the chat list page is loading then ,we will be calling Chat list Api.when we are searching the chat by entering the unique id in textfield,we will be getting the corresponding details of that entered unique id & that unique id details we have to show in the table view.
This is the task and i have done till the chat list showing in the table.FIND API Integration is also done.When i am reloading the data with search result(find api response),I am getting fatal error like "Unexpectedly found nil while unwrapping an Optional value" at the line of "var recepient = dict["recipient"] as! [String:Any]" . If anyone helps me to solve it, would be really great.Thank in advance.I am providing the code below.
import UIKit
import Alamofire
import SwiftyJSON
import SDWebImage
class ChatlistViewController: UIViewController{
var pro = [[String:Any]]()
var dict:[String:Any]!
var idd = ""
var id = ""
var chatt:Dictionary = [String:Any]()
var searchActive : Bool = false
var filtered:[String] = []
var data:[String] = []
#IBOutlet weak var searchtext: UITextField!
#IBOutlet weak var chatlisttable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
apicall()
}
func apicall(){
let acce:String = UserDefaults.standard.string(forKey: "access-tokenn")!
print(acce)
let headers:HTTPHeaders = ["Authorization":"Bearer \(acce)","Content-Type":"application/X-Access-Token"]
Alamofire.request(Constants.Chatlist, method: .get, encoding: URLEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
print(response)
if response.result.value != nil{
var maindictionary = NSDictionary()
maindictionary = response.result.value as! NSDictionary
print(maindictionary)
var userdata = NSDictionary()
userdata = maindictionary.value(forKey: "data") as! NSDictionary
var productsdetails = [[String:Any]]()
productsdetails = userdata.value(forKey: "chat") as! [[String:Any]]
self.pro = productsdetails
print(self.pro)
self.chatlisttable.reloadData()
}else{
let Alertcontroller = UIAlertController(title: "Alert", message: "No data found ", preferredStyle: .alert)
let CancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
Alertcontroller.addAction(CancelAction)
self.present(Alertcontroller, animated: true, completion: nil)
}
break
case .failure(let error):
print(error)
}
}
}
func searchapicall(){
idd = searchtext.text!
let acce:String = UserDefaults.standard.string(forKey: "access-tokenn")!
print(acce)
let headers:HTTPHeaders = ["Authorization":"Bearer \(acce)","Content-Type":"application/X-Access-Token"]
print((Constants.Chatlistsearch)+(idd))
Alamofire.request((Constants.Chatlistsearch+idd), method: .get, encoding: URLEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
//print(response)
if response.result.value != nil{
var maindictionary = NSDictionary()
maindictionary = response.result.value as! NSDictionary
var chat:Dictionary = maindictionary.value(forKey: "data") as! [String:Any]
var chattt:Dictionary = chat["chat"] as! [String:Any]
if (chattt != nil) {
// print("Find Action")
self.chatt = chat["user"] as! [String:Any]
print(self.chatt)
self.pro = [self.chatt]
// print(self.pro)
self.chatlisttable.reloadData()
}else{
let viewc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ChatViewController") as? ChatViewController
self.navigationController?.pushViewController(viewc!, animated: true)
}
}else{
let Alertcontroller = UIAlertController(title: "Alert", message: "No data found on this unique id", preferredStyle: .alert)
let CancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
Alertcontroller.addAction(CancelAction)
self.present(Alertcontroller, animated: true, completion: nil)
}
break
case .failure(let error):
print(error)
}
}
}
}
extension ChatlistViewController: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.searchapicall()
return true
}
}
extension ChatlistViewController: UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (searchActive == false){
return self.pro.count
}else{
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = chatlisttable.dequeueReusableCell(withIdentifier: "ChatlistTableViewCell", for: indexPath) as! ChatlistTableViewCell
if (searchActive == false){
dict = pro[indexPath.row]
var recepient = dict["recipient"] as! [String:Any]
print(recepient)
var name = recepient["name"] as! String
print(name)
id = recepient["unique_id"] as! String
print(id)
var image = recepient["avatar"] as! String
print(image)
cell.namelbl.text = name
cell.idlbl.text = id
cell.imageView!.sd_setImage(with: URL(string:image), placeholderImage: UIImage(named: "Mahi.png"))
}else{
cell.namelbl.text = chatt["name"] as! String
cell.idlbl.text = chatt["unique_id"] as! String
}
return cell
self.chatlisttable.reloadData()
}
}
//Response format
{
"success": 1,
"status": 200,
"data": {
"user": {
"id": 3,
"unique_id": "10002",
"name": "nani",
"avatar": "https://www.planetzoom.co.in/storage/user/avatar/AkgcUFF3QIejMhZuLF4OXnSFHjxNAOo4FuXV3Mgi.jpeg"
},
"chat": null
}
}
//Response with chat dictionary data
{
"success": 1,
"status": 200,
"data": {
"user": {
"id": 8,
"unique_id": "10007",
"name": "Mahitha",
"avatar": "https://www.planetzoom.co.in/storage/user/avatar/cZt9yQlBzIEewOdQ1lYZhl3dFiOv2k3bxG7HLOzR.jpeg"
},
"chat": {
"id": 4,
"status": 0,
"created_at": "2019-02-27 12:26:24",
"updated_at": "2019-02-27 12:26:24"
}
}
}
You should update you code to get chat details as follow due to I have seen chat in nil in your response
if var productsdetails = userdata.value(forKey: "chat") as? [[String:Any]] {
// Code to display chat
} else {
// Code to display nil error
}
I hope this will fix you issue.
From your response chat is null. So productsdetails = userdata.value(forKey: "chat") as! [[String:Any]] you are doing like that, you have set a null value in userdefaults across the key 'chat', and you are retrieving the null value as [[String : Any]]
So you have to check this using the block
if let productsdetails = userdata.value(forKey: "chat") as? [[String:Any]] {
// write code that for chat
} else {
// write code for chat is null
}
This is called Optional Chaining, you may find this link
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
Or you may solve using guard statement
guard let productsdetails = userdata.value(forKey: "chat") as? [[String:Any]] else {
// write code for chat is null
return
}
\\ write code that for chat
\\ you can use productsdetails variable here
I would like to provide two feedback to you:
Please try to make a habit to avoid forced casting or forced unwrap how much ever is possible.
Use Camel Case Naming Convention
So, you can change
var recepient = dict["recipient"] as! [String:Any]
to
guard let recepient = dict["recipient"] as? [String:Any] else {return cell}
Similar way you can have a condition before loading the tableView
if let productsDetails = userdata.value(forKey: "chat") as? [[String:Any]] {
// write code
} else {
// write code to handle else
}
I am Trying to add an instance of ServerValue.timestamp() into my firebase database, when i run the app , the time stamps continuously increase here is the code, im not sure how to stop the timestamp from increasing in firebase
here is my custom class and my tableview class
class Story
{
var text: String = ""
var timestamp: String = ""
let ref: DatabaseReference!
init(text: String) {
self.text = text
ref = Database.database().reference().child("People").child("HomeFeed").child("Posts").childByAutoId()
}
init(snapshot: DataSnapshot)
{
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
text = value["Post"] as! String
ref.updateChildValues(["timestamp":ServerValue.timestamp()])
let id = ref.key
Database.database().reference().child("People").child("HomeFeed").child("Posts").child("\(id)").child("timestamp").observeSingleEvent(of: .value) { (snapshot) in
let dope = snapshot.value as! Double
let x = dope / 1000
let date = NSDate(timeIntervalSince1970: x)
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .medium
DispatchQueue.main.async {
self.timestamp = formatter.string(from: date as Date)
self.timestamp = "\(value["timestamp"])"
}
}
}
}
func save() {
ref.setValue(toDictionary())
}
func toDictionary() -> [String : Any]
{
return [
"Post" : text,
"timestamp" : timestamp
]
}
}
here is the tableview class
class TableViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
let databaseRef = Database.database().reference()
#IBOutlet weak var tableView: UITableView!
var rub: StorageReference!
#IBAction func createpost(_ sender: Any) {
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("ProfilePic").observe(DataEventType.value) { (snapshot) in
let profpic = snapshot.value as? String
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("Full Name").observe(DataEventType.value) { (snapshot) in }
let fullname = snapshot.value as? String
if profpic == nil && fullname == nil {
let alert = UIAlertController(title: "Need to create profile", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "To create profile", style: UIAlertActionStyle.default, handler: { action in self.performSegue(withIdentifier: "ToCreateprof", sender: nil)}))
alert.addAction(UIAlertAction(title: "Dissmiss", style: UIAlertActionStyle.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}else {
self.performSegue(withIdentifier: "ToPost", sender: nil)
}
} //if no prof pic and name, no posting
}
#IBAction func toCreateorprofile(_ sender: Any) {
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("ProfilePic").observe(DataEventType.value) { (snapshot) in
let profpic = snapshot.value as? String
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("Full Name").observe(DataEventType.value) { (snapshot) in }
let fullname = snapshot.value as? String
if profpic != nil && fullname != nil {
self.performSegue(withIdentifier: "olduser", sender: nil)
}else {
self.performSegue(withIdentifier: "ToCreateprof", sender: nil)
}
}
}
let storiesRef = Database.database().reference().child("People").child("HomeFeed").child("Posts")
var stories = [Story]()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// download stories
storiesRef.observe(.value, with: { (snapshot) in
self.stories.removeAll()
for child in snapshot.children {
let childSnapshot = child as! DataSnapshot
let story = Story(snapshot: childSnapshot)
self.stories.insert(story, at: 0)
}
self.tableView.reloadData()
})
}
#objc func handleRefresh(_ refreshControl: UIRefreshControl) {
self.tableView.reloadData()
refreshControl.endRefreshing()
}
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action:
#selector(TableViewController.handleRefresh(_:)),
for: UIControlEvents.valueChanged)
refreshControl.tintColor = UIColor.purple
return refreshControl
}()
override func viewDidLoad()
{
super.viewDidLoad()
self.tableView.reloadData()
self.tableView.addSubview(self.refreshControl)
tableView.delegate = self
tableView.dataSource = self
self.tableView.estimatedRowHeight = 92.0
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return stories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Story Cell", for: indexPath) as! StoryTableviewcell
let story = stories[indexPath.row]
cell.story = story
self.databaseRef.child("ProfileInfo").child(Auth.auth().currentUser!.uid).child("Full Name").observe(.value) { (snapshot) in
let name = snapshot.value as? String
if name != nil {
cell.fullnamepost.text = name
}
}
rub = Storage.storage().reference().storage.reference(forURL:"gs://people-3b93c.appspot.com").child("ProfilePic").child(Auth.auth().currentUser!.uid)
if rub != nil {
// Create a UIImage, add it to the array
rub.downloadURL(completion: { (url, error) in
if error != nil {
print(error?.localizedDescription as Any)
return
}
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error as Any)
return
}
guard let imageData = UIImage(data: data!) else { return }
DispatchQueue.main.async {
cell.profimage.image = imageData
}
}).resume()
})
}
return cell
}
}
Hi when posting a picture in my swift 3 and firebase app how do I add a comment to it like before the picture is actually posted? Like in Instagram and how do I allow other users to comment on the pictures that other people have posted as well? below is every code I have on posting
Post Cell
import UIKit
import Firebase
import FirebaseStorage
import FirebaseDatabase
import SwiftKeychainWrapper
class PostCell: UITableViewCell {
#IBOutlet weak var userImg: UIImageView!
#IBOutlet weak var username: UILabel!
#IBOutlet weak var postImg: UIImageView!
#IBOutlet weak var likesLbl: UILabel!
var post: Post!
var userPostKey: FIRDatabaseReference!
let currentUser = KeychainWrapper.standard.string(forKey: "uid")
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configCell(post: Post, img: UIImage? = nil, userImg: UIImage? = nil) {
self.post = post
self.likesLbl.text = "\(post.likes)"
self.username.text = post.username
if img != nil {
self.postImg.image = img
} else {
let ref = FIRStorage.storage().reference(forURL: post.postImg)
ref.data(withMaxSize: 10 * 10000, completion: { (data, error) in
if error != nil {
print(error)
} else {
if let imgData = data {
if let img = UIImage(data: imgData){
self.postImg.image = img
}
}
}
})
}
if userImg != nil {
self.postImg.image = userImg
} else {
let ref = FIRStorage.storage().reference(forURL: post.userImg)
ref.data(withMaxSize: 100000000, completion: { (data, error) in
if error != nil {
print("couldnt load img")
} else {
if let imgData = data {
if let img = UIImage(data: imgData){
self.userImg.image = img
}
}
}
})
}
_ = FIRDatabase.database().reference().child("users").child(currentUser!).child("likes").child(post.postKey)
}
#IBAction func liked(_ sender: Any) {
let likeRef = FIRDatabase.database().reference().child("users").child(currentUser!).child("likes").child(post.postKey)
likeRef.observeSingleEvent(of: .value, with: { (snapshot) in
if let _ = snapshot.value as? NSNull {
self.post.adjustLikes(addlike: true)
likeRef.setValue(true)
} else {
self.post.adjustLikes(addlike: false)
likeRef.removeValue()
}
})
}
}
FeedVC
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage
import SwiftKeychainWrapper
import CoreImage
class FeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var postBtn: UIButton!
var posts = [Post]()
var post: Post!
var imagePicker: UIImagePickerController!
var imageSelected = false
var selectedImage: UIImage!
var userImage: String!
var userName: String!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self
FIRDatabase.database().reference().child("posts").observe(.value, with: {(snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
self.posts.removeAll()
for data in snapshot {
print(data)
if let postDict = data.value as? Dictionary<String, AnyObject> {
let key = data.key
let post = Post(postKey: key, postData: postDict)
self.posts.append(post)
}
}
}
self.tableView.reloadData()
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
cell.configCell(post: post)
return cell
} else {
return PostCell()
}
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
selectedImage = image
imageSelected = true
} else {
print("A valid image wasnt selected")
}
imagePicker.dismiss(animated: true, completion: nil)
guard imageSelected == true else {
print("An image must be selected")
return
}
if let imgData = UIImageJPEGRepresentation(selectedImage, 0.2) {
let imgUid = NSUUID().uuidString
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
FIRStorage.storage().reference().child("post-pics").child(imgUid).put(imgData, metadata: metadata) { (metadata, error) in
if error != nil {
print("image did not save to firebase storage")
} else {
print("uploded to firebase storage")
let downloadURL = metadata?.downloadURL()?.absoluteString
if let url = downloadURL {
self.postToFirebase(imgUrl: url)
}
}
}
}
}
func postToFirebase(imgUrl: String) {
let userID = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let data = snapshot.value as! Dictionary<String, AnyObject>
let username = data["username"]
let userImg = data["userImg"]
let post: Dictionary<String, AnyObject> = [
"username": username as AnyObject,
"userImg": userImg as AnyObject,
"imageUrl": imgUrl as AnyObject,
"likes": 0 as AnyObject
]
let firebasePost = FIRDatabase.database().reference().child("posts").childByAutoId()
firebasePost.setValue(post)
self.imageSelected = false
self.tableView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
}
#IBAction func postImageTapped(_ sender: AnyObject)
{
let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
self.openCamera()
}))
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.openGallary()
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func openGallary()
{
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
#IBAction func SignOutPressed(_ sender: AnyObject) {
try! FIRAuth.auth()?.signOut()
KeychainWrapper.standard.removeObject(forKey: "uid")
dismiss(animated: true, completion: nil)
}
}
Post
import Foundation
import Firebase
import FirebaseDatabase
class Post {
private var _username: String!
private var _userImg: String!
private var _postImg: String!
private var _likes: Int!
private var _postKey: String!
private var _postRef: FIRDatabaseReference!
var username: String {
return _username
}
var userImg: String {
return _userImg
}
var postImg: String {
get {
return _postImg
} set {
_postImg = newValue
}
}
var likes: Int {
return _likes
}
var postKey: String {
return _postKey
}
init(imgUrl: String, likes: Int, username: String, userImg: String) {
_likes = likes
_postImg = imgUrl
_username = username
_userImg = userImg
}
init(postKey: String, postData: Dictionary<String, AnyObject>) {
_postKey = postKey
if let username = postData["username"] as? String {
_username = username
}
if let userImg = postData["userImg"] as? String {
_userImg = userImg
}
if let postImage = postData["imageUrl"] as? String {
_postImg = postImage
}
if let likes = postData["likes"] as? Int {
_likes = likes
}
_postRef = FIRDatabase.database().reference().child("posts").child(_postKey)
}
func adjustLikes(addlike: Bool) {
if addlike {
_likes = likes + 1
} else {
_likes = likes - 1
}
_postRef.child("likes").setValue(_likes)
}
}
Hope this is enough information provided.
Still looking for answer? You could probably add some king of view to your post that would hold comments. Instagram only shows a few and then displays the comments in a separate viewController
The orders are being stored as Order objects: let orders = [Order]()
The idea is to call my API every second and when a new cell is created, the table should show the new cell.
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: "GetOrders", userInfo: nil, repeats: true)
this code does refresh my function to get data but repeats the cell !!
so in the beginning of GetOrders function I erase the array then upload it with new array from API.
func GetOrders (){
orders = []
but the code crushes when the new order is deleted from database. it shows int he table. When I click on it to returns ' index out of range' because of this function
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let order = orders[indexPath.row]
guard orders.count > indexPath.row else {
print("Index out of range")
return
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! OrderDetailsController
viewController.passedValue = order.id
self.present(viewController, animated: true , completion: nil)
}
UPDATE
func GetOrders (){
orders = []
print("hi")
let urlStr = "api/orders"
let url = URL(string: urlStr)
let user = "api"
let password = "Apipass"
var headers: HTTPHeaders = [
"Authorization": "Basic YXBpdXNlcjpBcGlBdXRoUGFzczIwMTchQCM="
]
Alamofire.request(url!, method: .get ,encoding: URLEncoding.default, headers: headers).responseJSON { response in
if let value: AnyObject = response.result.value as AnyObject? {
//Handle the results as JSON
let data = JSON(value)
for (key,subJson):(String, JSON) in data[0] {
//Do something you want
let logo = subJson["family"]["logo"]
let logoString = "img/\(logo)"
if let date = subJson["family"]["updated_at"].string {
print(date)
if let cleintName = subJson["client"]["name"].string {
let info = Order(shopname: shopname, shopaddress: shopaddr, clientName: cleintName, ClientAddress: clientAddres, PerferTime: time, Cost: subtotal , date : time , Logo : logoString ,id : id)
self.orders.append(info)
}
self.tableview.reloadData()
}
}
Have you tried going on the mainthread?
DispatchQueue.main.async {
self.tableView.reloadData()
}