my self.tableView reload data function is not being called for some reason. Here is my whole tableview code:
class NewMessageController: UITableViewController {
let currentUser: String = (FIRAuth.auth()?.currentUser?.uid)!
var ref = FIRDatabaseReference()
let cellId = "cellId"
var users = [User]()
var groupUserArray = [GlobalVariables.UserArray]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
getCurrentUserSchoolOrWorkAddressAndDisplayOtherUsers()
navigationItem.title = "New Message"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(cancelButton))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Select", style: .Plain, target: self, action: #selector(selectButton))
// fetchUserAndDisplay()
tableView.registerClass(UserCell.self, forCellReuseIdentifier: cellId)
}
var messagesController2 = MessagingViewController?()
func selectButton() {
tableView.allowsMultipleSelectionDuringEditing = true
tableView.setEditing(true, animated: false)
if tableView.allowsMultipleSelectionDuringEditing == true {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Create", style: .Plain, target: self, action: #selector(createGroupMessagesButton))
}
}
func cancelButton() {
if tableView.allowsMultipleSelectionDuringEditing == true {
tableView.allowsMultipleSelectionDuringEditing = false
tableView.setEditing(false, animated: true)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Select", style: .Plain, target: self, action: #selector(selectButton))
}
else {
dismissViewControllerAnimated(true, completion: nil)
}
}
func fetchUserAndDisplay() {
FIRDatabase.database().reference().child("users").observeEventType(.ChildAdded, withBlock: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.id = snapshot.key
user.setValuesForKeysWithDictionary(dictionary)
self.users.append(user)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}, withCancelBlock: nil)
}
func createGroupMessagesButton() {
dismissViewControllerAnimated(true) {
if let selectedUserRows = self.tableView.indexPathsForSelectedRows {
self.groupUserArray.append(selectedUserRows)
for index in selectedUserRows {
let text = self.users[index.row]
self.messagesController?.showChatLogController(text)
}
}
}
}
func getCurrentUserSchoolOrWorkAddressAndDisplayOtherUsers() {
let currentUser = (FIRAuth.auth()?.currentUser!)
let userID = currentUser?.uid
FIRDatabase.database().reference().child("users").child(userID!).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
let schoolOrWorkAddress = snapshot.value!["schoolOrWorkAddress"] as! String
FIRDatabase.database().reference().child("schoolOrWorkAddress").child(schoolOrWorkAddress).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if(!snapshot.exists()){
return
}
let locations = snapshot.value! as! NSDictionary
for (index, location) in locations.enumerate() {
FIRDatabase.database().reference().child("users").child(location.key as! String).observeEventType(.ChildAdded, withBlock: { (snapshot: FIRDataSnapshot) in
if(snapshot.exists()){
print(snapshot)
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.id = snapshot.key
user.setValuesForKeysWithDictionary(dictionary)
self.users.append(user)
print(self.users)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}
}, withCancelBlock: nil)
}
})
})
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
var messagesController = MessagingViewController?()
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView.allowsMultipleSelectionDuringEditing != true {
dismissViewControllerAnimated(true) {
let user = self.users[indexPath.row]
self.messagesController?.showChatLogController(user)
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as! UserCell
let user = users[indexPath.row]
cell.textLabel?.text = user.fullName
cell.detailTextLabel?.text = user.email
if let userPhoto = user.userPhoto {
cell.profileImageView.loadImageUsingCacheWithUrlString(userPhoto)
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 72
}
}
The problem however is occurring right here:
for (index, location) in locations.enumerate() {
FIRDatabase.database().reference().child("users").child(location.key as! String).observeEventType(.ChildAdded, withBlock: { (snapshot: FIRDataSnapshot) in
if(snapshot.exists()){
print(snapshot)
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.id = snapshot.key
user.setValuesForKeysWithDictionary(dictionary)
self.users.append(user)
print(self.users)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}
}, withCancelBlock: nil)
}
The above reloadData function is not being called for some reason!
The following is a breakpoint picture:
Does anyone have any thoughts on why this is happening?
Any help would be appreciated
Related
I am using Xcode and for some reason my app is crashing without showing any debug information in the console. It prints code until "distance: (distance)", but after that there is nothing. I am not sure what to fix as there is nothing there to help me in the console. Here is my code:
//
// TableViewController.swift
// grosseries
//
// Created by Amish Tyagi on 5/29/20.
// Copyright © 2020 grosseries. All rights reserved.
//
import UIKit
import Firebase
import FirebaseFirestore
import FirebaseAuth
import FirebaseCore
import FirebaseDatabase
import CoreLocation
import MapKit
class TableViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet var tableView: UITableView!
var ref : DatabaseReference! = Database.database().reference()
var volunteer : Bool = false
let locationManager = CLLocationManager()
var destinationCord = CLLocationCoordinate2D()
#IBOutlet weak var addItemButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
let defaults = UserDefaults.standard
Constants.Storyboard.food = defaults.object(forKey: "foodArray") as? [String] ?? [String]()
print(Constants.Storyboard.food)
// Do any additional setup after loading the view.
let db = Firestore.firestore()
let userID = Auth.auth().currentUser?.uid
let usersRef = ref.child("Users")
let thisUserRef = usersRef.child(userID!)
let docRef = db.collection("Users").document(userID!)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
let userData = document.data()!["userType"]
if (userData as? String == "Volunteer") {
self.volunteer = true
self.addItemButton.isEnabled = false
self.addItemButton.alpha = 0
print("hi!")
}
} else {
print("Document does not exist")
}
}
// Force the SDK to fetch the document from the cache. Could also specify
// FirestoreSource.server or FirestoreSource.default.
docRef.getDocument(source: .cache) { (document, error) in
if let document = document {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Cached document data: \(dataDescription)")
} else {
print("Document does not exist in cache")
}
}
thisUserRef.observe(.value) { (snapshot) in
let value = snapshot.value as? NSDictionary
let username = value?["firstName"] as? String ?? ""
print(value)
print("username: " + username)
// let user = User(username: username)
// if (user == "Volunteer") {
// self.volunteer = true
// }
}
// ref.observeSingleEvent(of: .value, with: { snapshot in
//
// if !snapshot.exists() { return }
//
// //print(snapshot)
// let value = snapshot.value as? NSDictionary
// if let userName = value?["userType"] as? String ?? "" {
// print(userName)
// }
// if let email = snapshot.value["email"] as? String {
// print(email)
// }
//
// // can also use
// // snapshot.childSnapshotForPath("full_name").value as! String
// })
}
override func viewWillAppear(_ animated: Bool) {
tableView.reloadData()
}
#IBAction func addItemTapped(_ sender: Any) {
transitionToNext()
}
func transitionToNext() {
let nextViewController = storyboard?.instantiateViewController(identifier: "AddFoodViewController") as? AddFoodViewController
view.window?.rootViewController = nextViewController
view.window?.makeKeyAndVisible()
}
func transitionToInfo() {
let infoViewController = storyboard?.instantiateViewController(identifier: "InfoViewController") as? InformationViewController
view.window?.rootViewController = infoViewController
view.window?.makeKeyAndVisible()
}
func getAddress(address: String) {
let geoCoder = CLGeocoder()
// var distance = 0.0
geoCoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks, let location = placemarks.first?.location
else{
print("No Location Found")
let alert = UIAlertController(title: "No Location Found, Please enter an valid address or location", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
// self.textFieldForAddress.text = ""
self.present(alert, animated: true)
return
}
// self.tableView(tableView, cellForRowAt: tableView.indexPath(for: "cell"))
self.destinationCord = location.coordinate
}
// if (distance <= 8046) {
// return true
// }
// else {
// return false
// }
}
}
extension TableViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// This part is for later make sure to come back to it
if (volunteer == true) {
transitionToInfo()
}
else {
let alertController = UIAlertController(title: "Sorry, you are not a volunteer", message: "Since you are not a volunteer, you cannot deliver groceries to anybody else. To do this, create another account.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
}
extension TableViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("insideNumberOfRows")
return Constants.Storyboard.addressHardCode.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("begin..........")
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var count = 0
for address in Constants.Storyboard.addressHardCode {
DispatchQueue.main.sync {
getAddress(address: address)
}
// print(location.coordinate)
print("destinationCord: \(self.destinationCord)")
let sourceLocation = (self.locationManager.location?.coordinate)!
let coord1 = CLLocation(latitude: sourceLocation.latitude, longitude: sourceLocation.longitude)
let coord2 = CLLocation(latitude: self.destinationCord.latitude, longitude: self.destinationCord.longitude)
var distance = coord1.distance(from: coord2)
print("distance \(distance)")
if (distance<8046) {
print("count: \(count)")
cell.textLabel?.text = Constants.Storyboard.namesHardCode[count]
}
count+=1
}
return cell
}
}
Here is a picture of my console:
Any help would be greatly appreciated!
i want to delete the line of text in the list file given under the if editMode == delete function which ever one was swiped on to delete i want it to delete that line of text in the file.
i read the file and parse it into the table view then when the user swipes to delete i want to delete the certain line of text in the file that cell.labelText?.text is if that makes sense. I cant seem to find anywhere that explains my particualr case. so please help me!!!
import UIKit
import Firebase
class ManageVC: UIViewController, UITabBarDelegate, UITableViewDataSource {
#IBOutlet var table: UITableView!
//parse sources text file
var sourcesList = [String:String]()
var sourcesArray = NSMutableArray()
var editMode = false
var refresher: UIRefreshControl!
var idgen = ""
func generateRandomDigits(_ digitNumber: Int) -> String {
var number = ""
for i in 0..<digitNumber {
var randomNumber = arc4random_uniform(10)
while randomNumber == 0 && i == 0 {
randomNumber = arc4random_uniform(10)
}
number += "\(randomNumber)"
}
return number
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sourcesArray.count
}
func tableSetup(){
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let source = sourcesArray[indexPath.row]
cell.textLabel?.text = "\((source as AnyObject).value(forKey: "sourcename")!)"
//cell.detailTextLabel?.text = "\((source as AnyObject).value(forKey: "sourceurl")!)"
return cell
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let source = sourcesArray[indexPath.row]
cell.textLabel?.text = "\((source as AnyObject).value(forKey: "sourcename")!)"
//cell.detailTextLabel?.text = "\((source as AnyObject).value(forKey: "sourceurl")!)"
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editMode == true {
if editingStyle == .delete{
sourcesArray.removeObject(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
var sourceUrlText: UITextField?
var ref: DatabaseReference!
#IBOutlet weak var addBtn: UIBarButtonItem!
#IBOutlet weak var editBtn: UIBarButtonItem!
override func viewDidLoad() {
DispatchQueue.main.async{
self.table.reloadData()
}
self.navigationItem.leftBarButtonItem = self.editButtonItem
refresher = UIRefreshControl()
refresher.addTarget(self, action: #selector(ManageVC.sourceRefresh), for: UIControl.Event.valueChanged)
table.addSubview(refresher)
ref = Database.database().reference()
super.viewDidLoad()
table.dataSource = self
let dir:NSURL = FileManager.default.urls(for: .documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last! as NSURL
let fileurl = dir.appendingPathComponent("sources.list")
let mgr = FileManager.default
if mgr.fileExists(atPath: fileurl!.path) {
do {
let contents = try String(contentsOfFile: fileurl!.path, encoding: String.Encoding.utf8)
let reading = contents.components(separatedBy: "\n") as [String]
for i in 0..<reading.count {
let data : [String] = reading[i].components(separatedBy: ", ")
sourcesList["sourcename"] = "\(data[0])"
//sourcesList["sourceurl"] = "\(data[1])"
sourcesArray.add(sourcesList)
}
} catch let error as NSError {
print("Error: \(error)")
}
}
}
#IBAction func addBtnClicked(_ sender: Any) {
let addSource = UIAlertController(title: "Add Source:", message: nil, preferredStyle: .alert)
addSource.addTextField(configurationHandler: sourceUrlText)
let okAction = UIAlertAction(title: "Add", style: .default, handler: self.okHandler)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
addSource.addAction(cancelAction)
addSource.addAction(okAction)
self.present(addSource, animated: true)
}
func okHandler(alert: UIAlertAction!){
if idgen == "" {
source()
performSegue(withIdentifier: "refreshingShow", sender: self)
}
}
func sourceUrlText(textField: UITextField!){
sourceUrlText = textField
sourceUrlText?.text = "http://"
}
#IBAction func editBtnClicked(_ sender: Any) {
addBtn.isEnabled = true
editBtn.isEnabled = false
editMode = true
}
override func viewDidAppear(_ animated: Bool) {
addBtn.isEnabled = false
editBtn.isEnabled = true
editMode = false
}
func source(){
let dir:NSURL = FileManager.default.urls(for: .documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last! as NSURL
let fileurl = dir.appendingPathComponent("sources.list")
let string = ((self.sourceUrlText?.text)!) + "\n"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)!
if FileManager.default.fileExists(atPath: fileurl!.path) {
var err:NSError?
if let fileHandle = FileHandle(forWritingAtPath: fileurl!.path) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
do {
self.table.reloadData()
refresher.endRefreshing()
let readSources = try String(contentsOfFile: fileurl!.path, encoding: String.Encoding.utf8)
print(readSources)
} catch {
}
}
else {
print("Can't open fileHandle \(err)")
}
}
else {
}
}
#objc func sourceRefresh() {
DispatchQueue.main.async{
self.tableSetup()
self.table.reloadData()
}
refresher.endRefreshing()
}
}
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
}
}
I'm having a problem regarding a feature where You can delete a cell and so delete and event using an Alamofire JSON request.
When I swipe the cell and click delete, the app crashes, but the event get deleted successfully and with no errors, in facts on Laravel side I get the event deleted.
I tried everything, but I really can't figure out how to fix the crash.
Can someone help me please?
here is my .Swift code:
import UIKit
import Alamofire
class EventViewController: UITableViewController {
#objc var transition = ElasticTransition()
#objc let lgr = UIScreenEdgePanGestureRecognizer()
#objc let rgr = UIScreenEdgePanGestureRecognizer()
let rc = UIRefreshControl()
#IBOutlet weak var myTableView: UITableView!
var myTableViewDataSource = [NewInfo]()
let url = URL(string: "http://ns7records.com/staffapp/api/events/index")
override func viewDidLoad() {
super.viewDidLoad()
loadList()
// Add Refresh Control to Table View
if #available(iOS 10.0, *) {
tableView.refreshControl = rc
} else {
tableView.addSubview(rc)
}
// Configure Refresh Control
rc.addTarget(self, action: #selector(refreshTableData(_:)), for: .valueChanged)
let attributesRefresh = [kCTForegroundColorAttributeName: UIColor.white]
rc.attributedTitle = NSAttributedString(string: "Caricamento ...", attributes: attributesRefresh as [NSAttributedStringKey : Any])
DispatchQueue.main.async {
}
// MENU Core
// customization
transition.sticky = true
transition.showShadow = true
transition.panThreshold = 0.3
transition.transformType = .translateMid
// menu// gesture recognizer
lgr.addTarget(self, action: #selector(MyProfileViewController.handlePan(_:)))
rgr.addTarget(self, action: #selector(MyProfileViewController.handleRightPan(_:)))
lgr.edges = .left
rgr.edges = .right
view.addGestureRecognizer(lgr)
view.addGestureRecognizer(rgr)
}
#objc private func refreshTableData(_ sender: Any) {
// Fetch Table Data
//myTableViewDataSource.removeAll()
tableView.reloadData()
loadList()
}
func loadList(){
var myNews = NewInfo()
// URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
//
// })
let task = URLSession.shared.dataTask(with:url!) {
(data, response, error) in
if error != nil
{
print("ERROR HERE..")
}else
{
do
{
if let content = data
{
let myJson = try JSONSerialization.jsonObject(with: content, options: .mutableContainers)
//print(myJson)
if let jsonData = myJson as? [String : Any]
{
if let myResults = jsonData["data"] as? [[String : Any]]
{
//dump(myResults)
for value in myResults
{
if let myTitle = value["title"] as? String
{
//print(myTitle)
myNews.displayTitle = myTitle
}
if let myLocation = value["local"] as? String
{
myNews.location = myLocation
}
if let myDate = value["date"] as? String
{
myNews.date = myDate
}
if let myDescription = value["description"] as? String
{
myNews.description = myDescription
}
if let myCost = value["cost"] as? String
{
myNews.cost = myCost
}
if let myNumMembers = value["num_members"] as? String
{
myNews.num_members = myNumMembers
}
if let myNumMembers_conf = value["num_members_confirmed"] as? String
{
myNews.num_members_confirmed = myNumMembers_conf
}
if let myStartEvent = value["time_start"] as? String
{
myNews.startEvent = myStartEvent
}
if let myEndEvent = value["time_end"] as? String
{
myNews.endEvent = myEndEvent
}
if let myId = value["id"] as? Int
{
myNews.idEvent = myId
}
//x img
// if let myMultimedia = value["data"] as? [String : Any]
// {
if let mySrc = value["event_photo"] as? String
{
myNews.event_photo = mySrc
print(mySrc)
}
self.myTableViewDataSource.append(myNews)
}//end loop
dump(self.myTableViewDataSource)
DispatchQueue.main.async
{
self.tableView.reloadData()
self.rc.endRefreshing()
}
}
}
}
}
catch{
}
}
}
task.resume()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath)->CGFloat {
return 150
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myTableViewDataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "reuseCell", for: indexPath)
let myImageView = myCell.viewWithTag(11) as! UIImageView
let myTitleLabel = myCell.viewWithTag(12) as! UILabel
let myLocation = myCell.viewWithTag(13) as! UILabel
let DateLabelCell = myCell.viewWithTag(14) as! UILabel
let numMembLabel = myCell.viewWithTag(15) as! UILabel
let numMembConfLabel = myCell.viewWithTag(16) as! UILabel
myTitleLabel.text = myTableViewDataSource[indexPath.row].displayTitle
myLocation.text = myTableViewDataSource[indexPath.row].location
DateLabelCell.text = myTableViewDataSource[indexPath.row].date
numMembLabel.text = myTableViewDataSource[indexPath.row].num_members
numMembConfLabel.text = myTableViewDataSource[indexPath.row].num_members_confirmed
if let imageURLString = myTableViewDataSource[indexPath.row].event_photo,
let imageURL = URL(string: AppConfig.public_server + imageURLString) {
myImageView.af_setImage(withURL: imageURL)
}
return myCell
}
//per passare da un viewcontroller a detailviewcontroller
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? EventDetailViewController {
destination.model = myTableViewDataSource[(tableView.indexPathForSelectedRow?.row)!]
// Effetto onda
let vc = segue.destination
vc.transitioningDelegate = transition
vc.modalPresentationStyle = .custom
}
//menu
if let vc = segue.destination as? MenuViewController{
vc.transitioningDelegate = transition
vc.modalPresentationStyle = .custom
//endmenu
}
}
//menu slide
#objc func handlePan(_ pan:UIPanGestureRecognizer){
if pan.state == .began{
transition.edge = .left
transition.startInteractiveTransition(self, segueIdentifier: "menu", gestureRecognizer: pan)
}else{
_ = transition.updateInteractiveTransition(gestureRecognizer: pan)
}
}
//endmenuslide
////ximg
func loadImage(url: String, to imageView: UIImageView)
{
let url = URL(string: url )
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else
{
return
}
DispatchQueue.main.async
{
imageView.image = UIImage(data: data)
}
}.resume()
}
/// star to: (x eliminare row e x muove row)
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObjTemp = myTableViewDataSource[sourceIndexPath.item]
myTableViewDataSource.remove(at: sourceIndexPath.item)
myTableViewDataSource.insert(movedObjTemp, at: destinationIndexPath.item)
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete){
// print(parameters)
let idEvent = (myTableViewDataSource[indexPath.item].idEvent)
let parameters = [
// "id": UserDefaults.standard.object(forKey: "userid")! ,
"id" : idEvent,
] as [String : Any]
let url = "http://www.ns7records.com/staffapp/public/api/deleteevent"
print(url)
Alamofire.request(url, method:.post, parameters:parameters,encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success:
print(response)
let JSON = response.result.value as? [String : Any]
//self.myTableView.reloadData()
let alert = UIAlertController(title: "Yeah!", message: "Evento modificato con successo!", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
// let data = JSON! ["data"] as! NSDictionary
if let jsonData = JSON as? [String : Any]
{
print(jsonData)
self.myTableViewDataSource.remove(at : indexPath.item)
self.myTableView.deleteRows(at: [indexPath], with: .automatic)
let indexPath = IndexPath(item: 0, section: 0)
//self.myTableView.deleteRows(at: [indexPath], with: .fade)
//self.myTableView.reloadData()
// }
// }
//}
}
case .failure(let error):
print(error)
let alert = UIAlertController(title: "Aia", message: "Non puoi cancellare questo evento!", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
#IBAction func EditButtonTableView(_ sender: UIBarButtonItem) {
self.myTableView.isEditing = !self.myTableView.isEditing
sender.title = (self.myTableView.isEditing) ? "Done" : "Edit"
}
/// end to: (x eliminare row e x muove row)
}
// MARK: -
// MARK: UITableView Delegate
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
I'm using a Parse account to post images, messages and username to a prototype cell. For some reason my username string is staying empty and thus not posting to the cell. Can you help? I'm fairly new to coding so this one has just stumped me.
import UIKit
import Parse
class FeedTableViewController: UITableViewController {
var messages = [String]()
var usernames = [String]()
var imageFiles = [PFFile]()
var users = [String: String]()
var refresher: UIRefreshControl!
#IBAction func logout(sender: AnyObject) {
PFUser.logOut()
var currentUser = PFUser.currentUser()
performSegueWithIdentifier("logout", sender: self)
}
func swiped(gesture:UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right:
performSegueWithIdentifier("feedSwipe", sender: self)
//case UISwipeGestureRecognizerDirection.Up:
//print("User Swiped Up")
//case UISwipeGestureRecognizerDirection.Down:
//print("User Swiped Down")
case UISwipeGestureRecognizerDirection.Left:
performSegueWithIdentifier("feedSwipe", sender: self)
default:
break
}
}
}
func refresh() {
var query = PFUser.query()
query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
self.messages.removeAll(keepCapacity: true)
self.users.removeAll(keepCapacity: true)
self.imageFiles.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
self.users[user.objectId!] = user.username!
}
}
}
var getFollowedUsersQuery = PFQuery(className: "followers")
getFollowedUsersQuery.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
getFollowedUsersQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
var followedUser = object["following"] as! String
var query = PFQuery(className: "Post")
query.whereKey("userId", equalTo: followedUser)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.messages.append(object["message"]! as! String)
self.imageFiles.append(object["imageFile"]! as! PFFile)
self.usernames.append(self.users[object["userId"] as! String]!)
//self.usernames.append(followedUser)
self.tableView.reloadData()
self.refresher.endRefreshing()
//print(followedUser)
}
}
})
}
}
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipeRight)
let swipeUp = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeUp.direction = UISwipeGestureRecognizerDirection.Up
self.view.addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeDown.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(swipeDown)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
self.view.addGestureRecognizer(swipeLeft)
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
imageFiles[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
myCell.postedImage.image = downloadedImage
}
}
myCell.username.text = usernames[indexPath.row]
myCell.message.text = messages[indexPath.row]
return myCell
}