So like the title says I am getting information from parse and displaying it but i can't figure out how to do this with a date. I need to cover it to a String to display in a label. Ive done a bit or research and understand I will need to use a date formatter but What I don't understand is where I put it and once its formatted how i display it. Any help would be much appreciated!
var names = [String]()
var locations = [String]()
var dates = [NSDate]()
var imageFiles = [PFFile]()
var abouts = [String]()
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint, error) -> Void in
if let geoPoint = geoPoint {
PFUser.currentUser()?["location"] = geoPoint
PFUser.currentUser()?.saveInBackground()
var getLocalPostsQuery = PFQuery(className: "publicPosts")
if let latitude = PFUser.currentUser()!["location"].latitude {
if let longitude = PFUser.currentUser()!["location"].longitude {
getLocalPostsQuery.whereKey("searchLocation", withinGeoBoxFromSouthwest: PFGeoPoint(latitude: latitude - 0.5, longitude: longitude - 0.5), toNortheast: PFGeoPoint(latitude: latitude + 0.5, longitude: longitude + 0.5))
getLocalPostsQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
self.names.removeAll(keepCapacity: true)
self.locations.removeAll(keepCapacity: true)
self.abouts.removeAll(keepCapacity: true)
self.dates.removeAll(keepCapacity: true)
self.imageFiles.removeAll(keepCapacity: true)
for object in objects {
self.names.append(object["name"] as! String)
self.locations.append(object["location"] as! String)
self.dates.append(object["date"] as! String)
self.abouts.append(object["about"] as! String)
self.imageFiles.append(object["imageFile"] as! PFFile)
//self.attendings.append(object["attending"].count)
self.tableView.reloadData()
}
}
}
}
}
}
}
}
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 names.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let LECell = tableView.dequeueReusableCellWithIdentifier("LocalPostsCell", forIndexPath: indexPath) as! LocalPostsTableViewCell
imageFiles[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
LECell.postImage.image = downloadedImage
}
}
LECell.postName.text = names[indexPath.row]
LECell.postLocation.text = locations[indexPath.row]
LECell.postDate.text = dates[indexPath.row]
return LECell
}
let localPostsDetailSegue = "showLocalPostsDetailView"
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == localPostsDetailSegue {
let detailScene = segue.destinationViewController as! LocalPostsDetailViewController
if let indexPath = self.tableView.indexPathForSelectedRow {
let row = Int(indexPath.row)
detailScene.name = names[row]
detailScene.location = locations[row]
detailScene.date = dates[row]
detailScene.about = abouts[row]
detailScene.photo = imageFiles[row]
}
}
}
}
You can easily get string from NSDate and show it.
func getStringFromDate(date:NSDate)->String{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yy, H:mm"
return dateFormatter.stringFromDate(yourDate) // yourDate is your parse date
}
you can make a category too.
Swift 3:
func getFormattedDate(string: String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz" // 2017-04-20T09:40:30+0000
let formateDate = dateFormatter.date(from: string)!
dateFormatter.dateFormat = "dd-MM-yyyy"
return dateFormatter.string(from: formateDate)
}
let CreatedDates = "\(Date.getFormattedDate(string: "\(records["creationDate"]!)"))"
print("Date : \(CreatedDates)")
//OutPut
20-04-2017
Related
I'm trying do delete the note from Realm in my NotesApp and facing this error: "Can only delete an object from the Realm it belongs to". This note has been saved before also in Realm and
could display it in my TableView by tapping on the date in my FSCalendar. I tried to replace realm.add(item) with realm.create(item), but also got the error: "Cannot convert value of type 'T' to expected argument type 'Object.Type' (aka 'RealmSwiftObject.Type')". I'm new in programming, so any help would be appreciated. Here's the relevant code code:
in my ToDoListItem.swift
class ToDoListItem: Object {
#objc dynamic var noteName: String = ""
#objc dynamic var date: Date = Date()
#objc dynamic var descriptionText: String = ""
#objc dynamic var noteImage = Data()
init(date: Date, noteName: String) {
self.date = date
self.noteName = noteName
}
override init() {
self.noteName = ""
self.date = Date()
self.descriptionText = ""
self.noteImage = Data()
}
}
in my RealmManager.swift
class RealmManager {
static let shared = RealmManager()
private let realm = try! Realm()
func write<T: Object>(item: T) {
realm.beginWrite()
realm.add(item)
try! realm.commitWrite()
}
func getObjects<T: Object>(type: T.Type) -> [T] {
return realm.objects(T.self).map({ $0 })
}
func delete<T: Object>(item: T) {
try! realm.write {
realm.delete(item)
}
}
}
in my ViewController where i can edit and delete the notes
#IBAction func didTapDelete() {
let note = ToDoListItem()
RealmManager.shared.delete(item: note)
self.deletionHandler?()
navigationController?.popToRootViewController(animated: true)
}
and finally in my TableViewController where the notes are displayed (honestly i think the problem is hidden here but cannot find it...
#IBOutlet var tableViewPlanner: UITableView!
#IBOutlet var calendarView: FSCalendar!
private var data = [ToDoListItem]()
var datesOfEvents: [String] {
return self.data.map { DateFormatters.stringFromDatestamp(datestamp: Int($0.date.timeIntervalSince1970)) }
}
var items: [ToDoListItem] = []
func getCount(for Date: String) -> Int {
var count: [String : Int] = [:]
for date in datesOfEvents {
count[date] = (count[date] ?? 0) + 1
}
return count[Date] ?? 0
}
func getEventsForDate(date: Date) -> [ToDoListItem] {
let string = DateFormatters.stringFromDatestamp(datestamp: Int(date.timeIntervalSince1970))
return self.data.filter {DateFormatters.stringFromDatestamp(datestamp: Int($0.date.timeIntervalSince1970)) == string }.sorted(by: {$0.date < $1.date})
}
override func viewDidLoad() {
super.viewDidLoad()
calendarView.rounding()
tableViewPlanner.rounding()
data = RealmManager.shared.getObjects(type: ToDoListItem.self)
self.items = self.getEventsForDate(date: Date())
calendarView.delegate = self
calendarView.dataSource = self
tableViewPlanner.delegate = self
tableViewPlanner.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.calendarView.select(Date())
self.calendarView.reloadData()
refresh()
}
//MARK:- TableView Data Source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count //data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: K.plannerCellIdentifier, for: indexPath) as! NoteTableViewCell
let note = self.items[indexPath.row]
cell.configureCell(note: note)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let note = data[indexPath.row]
guard
let vc = storyboard?.instantiateViewController(identifier: K.infoVCIdentifier) as? InfoViewController else { return }
vc.note = note
vc.deletionHandler = { [weak self] in
self?.refresh()
}
vc.title = note.noteName
navigationController?.pushViewController(vc, animated: true)
}
//MARK:- User Interaction
#IBAction func didTapAddButton() {
guard
let vc = storyboard?.instantiateViewController(identifier: K.entryVCIdentifier) as? EntryViewController else { return }
vc.completionHandler = { [weak self] in
self?.refresh()
}
vc.title = K.entryVCTitle
navigationController?.pushViewController(vc, animated: true)
}
func refresh() {
DispatchQueue.main.async {
self.data = RealmManager.shared.getObjects(type: ToDoListItem.self)
self.tableViewPlanner.reloadData()
self.calendarView.reloadData()
}
}
}
extension PlannerViewController: FSCalendarDelegateAppearance & FSCalendarDataSource {
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventDefaultColorsFor date: Date) -> [UIColor]? {
let dateString = DateFormatters.yearAndMonthAndDateFormatter.string(from: date)
if self.datesOfEvents.contains(dateString) {
return [UIColor.blue]
}
return [UIColor.white]
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
self.items = self.getEventsForDate(date: date)
self.tableViewPlanner.reloadData()
}
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
let dateString = DateFormatters.yearAndMonthAndDateFormatter.string(from: date)
let count = self.getCount(for: dateString)
self.tableViewPlanner.reloadData()
return count
}
}
The real problem is the didTapDelete function -- Why are you creating a new note just to delete it (I hope it was only to test out realm delete syntax). You should delete the note object that you passed to the view controller to edit / delete. (vc.note in did select row -> self.note in the other VC - where didTapDelete is)
So your did tap delete will look like --
RealmManager.shared.delete(item: note)
//show deleted alert & go back
A little explanation on the error - Just instantiating a Realm object (ToDoListItem()) does not add it to Realm (the Database system). To delete / edit a realm object, it has to be either fetched from a realm (RealmManager.shared.getObjects(type: ToDoListItem.self)) or added to the realm.
I'd advise going through a Realm tutorial before jumping in the code (there are plenty of them)
I have a tableview that is being populated with who a user is following. Problem is that I need to pass that cells data to "var otherUser: NSDictionary!" but because I am populating the cell using a data structure file called "Information" I get this error - "Cannot assign value of type 'Information' to type 'NSDictionary?'" in the prepareForSegue. I am unsure if I can repackage the information I need into a NSDictionary so I can successfully do a data pass. I just don't know if this is a easy solution or an actual problem because of my ignorance.
Following TableViewController Code
import UIKit
import Firebase
class BusinessFollowing: UITableViewController {
#IBOutlet var noDataView: UIView!
#IBOutlet var followingTableView: UITableView!
var yourFollowing = [Information]()
var listFollowing = [NSDictionary?]()
var databaseRef = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
var loggedInUser = Auth.auth().currentUser
var loggedInUserData:NSDictionary?
var following = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.followingTableView.backgroundView = nil
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.followingTableView.reloadData()
self.yourFollowing.removeAll()
self.following.removeAll()
getFollowingData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == "following" {
// gotta check if we're currently searching
if let indexPath = followingTableView.indexPathForSelectedRow {
let user = self.yourFollowing[indexPath.row]
let controller = segue.destination as? ExploreBusinessProfileSwitchView
controller?.otherUser = user
}
}
}
override func numberOfSections(in 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 self.yourFollowing.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! BusinessFollowingCell
let following = yourFollowing[indexPath.row]
let businessName = following.businessName
let businessStreet = following.businessStreet
let businessCity = following.businessCity
let businessState = following.businessState
cell.businessName.text = businessName
cell.businessStreet.text = businessStreet
cell.businessCity.text = businessCity
cell.businessState.text = businessState
// cell.businessName?.text = self.listFollowing[indexPath.row]?["businessName"] as? String
// cell.businessStreet?.text = self.listFollowing[indexPath.row]?["businessStreet"] as? String
// cell.businessCity?.text = self.listFollowing[indexPath.row]?["businessCity"] as? String
// cell.businessState?.text = self.listFollowing[indexPath.row]?["businessState"] as? String
return cell
}
func getFollowingData() {
self.yourFollowing.removeAll()
self.following.removeAll()
self.followingTableView.reloadData()
Database.database().reference().child("Businesses").child((loggedInUser?.uid)!).child("following").observe(.value, with: { snapshot in
if snapshot.exists() {
MBProgressHUD.showAdded(to: self.view, animated: true)
let databaseRef = Database.database().reference()
databaseRef.child("Businesses").queryOrderedByKey().observeSingleEvent(of: .value, with: { (usersSnapshot) in
let users = usersSnapshot.value as! [String: AnyObject]
for (_, value) in users {
if let userID = value["uid"] as? String {
if userID == Auth.auth().currentUser?.uid {
print(value)
if let followingUsers = value["following"] as? [String : String] {
for (_,user) in followingUsers {
self.following.append(user)
}
}
databaseRef.child("following").queryOrderedByKey().observeSingleEvent(of: .value, with: { (postsSnapshot) in
let posts = postsSnapshot.value as! [String: AnyObject]
for (_, post) in posts {
for (_, postInfo) in post as! [String: AnyObject] {
if let followingID = postInfo["uid"] as? String {
for each in self.following {
if each == followingID {
guard let uid = postInfo["uid"] as! String? else {return}
guard let name = postInfo["businessName"] as! String? else {return}
guard let address = postInfo["businessStreet"] as! String? else {return}
guard let state = postInfo["businessState"] as! String? else {return}
guard let city = postInfo["businessCity"] as! String? else {return}
self.yourFollowing.append(Information(uid: uid, businessName: name, businessStreet: address, businessCity: city, businessState: state))
}
self.followingTableView.backgroundView = nil
self.followingTableView.reloadData()
}
}
}
}
MBProgressHUD.hide(for: self.view, animated: true)
}) { (error) in
print(error.localizedDescription)
}
}
}
}
})
} else {
print("Not following anyone")
self.followingTableView.backgroundView = self.noDataView
MBProgressHUD.hide(for: self.view, animated: true)
}
})
}
}
"Information" Data Structure File
import UIKit
class Information {
var uid: String
var businessName: String
var businessStreet: String
var businessCity: String
var businessState: String
init(uid: String, businessName: String, businessStreet: String, businessCity: String, businessState: String){
self.uid = uid
self.businessName = businessName
self.businessStreet = businessStreet
self.businessCity = businessCity
self.businessState = businessState
}
}
The error is pretty clear.
user in ExploreBusinessProfileSwitchView is obviously declared as NSDictionary, declare it as Information.
By the way don't use NSArray / NSDictionary in Swift. Use native types.
People tell me how to get out of my position and do so that when a new event is added it becomes the beginning, not the end.I will be very grateful for the help.
I have three arrays and I had to sort them out by the parent cells, and in this line I very much played func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
import UIKit
import Parse
class PrognozSegmentViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var soccerString = [Soccer]()
var basketString = [Basketball]()
var tennisString = [Tennis]()
var refresh : UIRefreshControl!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var segmentControl: UISegmentedControl!
#IBAction func btnSegment(_ sender: Any) {
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
refresh = UIRefreshControl()
refresh.attributedTitle = NSAttributedString(string: "Потяните вниз чтоб обновить ресурс")
refresh.tintColor = UIColor.green
refresh.addTarget(self, action: #selector(PrognozSegmentViewController.refreshing), for: UIControlEvents.valueChanged)
tableView.addSubview(refresh)
setupSeg()
tableView.tableFooterView = UIView()
tableView.estimatedRowHeight = 88
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
tableView.register(UINib(nibName:"TableViewCell",bundle:nil), forCellReuseIdentifier: "sportCell")
loadObjects1()
loadObjects2()
loadObjects3()
}
func setupSeg() {
let attributes = [ NSAttributedStringKey.foregroundColor : UIColor.yellow,
NSAttributedStringKey.font : UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.bold)];
let attributesSelected = [ NSAttributedStringKey.foregroundColor : UIColor.black,
NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.bold)];
segmentControl.setTitleTextAttributes(attributes, for: UIControlState.normal)
segmentControl.setTitleTextAttributes(attributesSelected, for: UIControlState.selected)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var returnSport = 0
switch (segmentControl.selectedSegmentIndex) {
case 0 :
returnSport = soccerString.count
break
case 1 :
returnSport = basketString.count
break
case 2 :
returnSport = tennisString.count
break
default :
break
}
return returnSport
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sportCell = tableView.dequeueReusableCell(withIdentifier: "sportCell", for: indexPath) as! TableViewCell
switch (segmentControl.selectedSegmentIndex) {
case 0 :
let soccer = soccerString[indexPath.row]
sportCell.matchLabel.text = soccer.matchS
soccerString[indexPath.row].imagePrS.getDataInBackground {(data, error) in
sportCell.imageMatch.image = error == nil ? UIImage(data: data!) : nil
}
break
case 1 :
let basket = basketString[indexPath.row]
sportCell.matchLabel.text = basket.matchB
basketString[indexPath.row].imagePrB.getDataInBackground {(data, error) in
sportCell.imageMatch.image = error == nil ? UIImage(data: data!) : nil
}
break
case 2:
sportCell.matchLabel.text = tennisString[indexPath.row].matchT
tennisString[indexPath.row].imagePrT.getDataInBackground {(data, error) in
sportCell.imageMatch.image = error == nil ? UIImage(data: data!) : nil
}
break
default:
break
}
sportCell.selectionStyle = UITableViewCellSelectionStyle.none
let date = Date()
let calendar = Calendar.current
let yesterday = calendar.date(byAdding: .day, value: -1, to: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM:d, yyyy"
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
dateFormatter.locale = Locale(identifier: "ru_UA")
dateFormatter.doesRelativeDateFormatting = true
let dataFormater2 = DateFormatter()
dataFormater2.dateFormat = "EEEE, MMM:d, yyyy"
dataFormater2.dateStyle = .short
dataFormater2.timeStyle = .short
dataFormater2.locale = Locale(identifier: "ru_UA")
dataFormater2.doesRelativeDateFormatting = true
sportCell.dataSave.text! = dateFormatter.string(from: date)
sportCell.dataSave.text = dateFormatter.string(from: yesterday!)
return sportCell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func loadObjects1() {
let query = Soccer.query() as! PFQuery<Soccer>
query.findObjectsInBackground { (objects, error) in
if error == nil {
self.soccerString.removeAll()
self.soccerString = objects!
self.tableView.reloadData()
} else {
print(error!)
}
}
}
func loadObjects2() {
let query = Basketball.query() as! PFQuery<Basketball>
query.findObjectsInBackground { (objects, error) in
if error == nil {
self.basketString.removeAll()
self.basketString = objects!
self.tableView.reloadData()
} else {
print(error!)
}
}
}
func loadObjects3() {
let query = Tennis.query() as! PFQuery<Tennis>
query.findObjectsInBackground { (objects, error) in
if error == nil {
self.tennisString.removeAll()
self.tennisString = objects!
self.tableView.reloadData()
} else {
print(error!)
}
}
}
#objc func refreshing() {
loadObjects1()
loadObjects2()
loadObjects3()
tableView.reloadData()
refresh.endRefreshing()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch (segmentControl.selectedSegmentIndex) {
case 0 :
if segue.identifier == "showSoccer" {
if let indexPath = tableView.indexPathForSelectedRow {
let destationViewController = segue.destination as! DetailSoccerTableViewController
destationViewController.detailSoccer = self.soccerString[indexPath.row]
}
}
case 1 :
if segue.identifier == "showBasket" {
let dvc = segue.destination as! DetailBasketViewController
if let indexPath = tableView.indexPathForSelectedRow {
let row = Int(indexPath.row)
dvc.baskets = basketString[row]
}
}
case 2 :
let destationVC: DetailTennisViewController = segue.destination as! DetailTennisViewController
if let indexPath = self.tableView.indexPathForSelectedRow {
let row = Int(indexPath.row)
destationVC.tenises = tennisString[row]
}
self.present(destationVC, animated: true, completion: nil)
default :
break
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch ( segmentControl.selectedSegmentIndex) {
case 0 :
let soccer = soccerString[indexPath.row]
performSegue(withIdentifier: "showSoccer", sender: soccer)
break
case 1 :
let basket = basketString[indexPath.row]
let destinationVC = DetailBasketViewController()
destinationVC.baskets = basket
self.performSegue(withIdentifier: "showBasket", sender: self)
break
case 2 :
let tennis = tennisString[indexPath.row]
let destTenVC = DetailTennisViewController()
destTenVC.tenises = tennis
self.performSegue(withIdentifier: "showTennis", sender: self)
break
default :
break
}
}
}
If your problem is the new object becomes the last
I assume you're talking about an array and you're doing
array.append(item)
If you want to have the item at the beginning do:
array.insert(item, at: 0)
And then
tableView.reloadData()
I have been trying to create multidimensional arrays and display each array under each section .. but I keep ending up with a fatal error index out of range . The code that i display below is how I access my firebase data and print each array from the database.. issue is I get the data I assign an array to it create it but can’t seem to display it due to the error . Hope someone helps for reference regarding the error I have attached a screenshot as well.
#IBOutlet weak var tableview: UITableView!
var yourArray = [String]()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var sundaycoursenamearray = [String]()
var sundaycoursecodearray = [String]()
var sundaycourselocationarray = [String]()
var sundayfromarray = [String]()
var sundaytoarray = [String]()
var mondaycoursenamearray = [String]()
var mondaycoursecodearray = [String]()
var mondaycourselocationarray = [String]()
var mondayfromarray = [String]()
var mondaytoarray = [String]()
var tuesdaycoursenamearray = [String]()
var tuesdaycoursecodearray = [String]()
var tuesdaycourselocationarray = [String]()
var tuesdayfromarray = [String]()
var tuesdaytoarray = [String]()
var wednesdaycoursenamearray = [String]()
var wednesdaycoursecodearray = [String]()
var wednesdaycourselocationarray = [String]()
var wednesdayfromarray = [String]()
var wednesdaytoarray = [String]()
var thursdaycoursenamearray = [String]()
var thursdaycoursecodearray = [String]()
var thursdaycourselocationarray = [String]()
var thursdayfromarray = [String]()
var thursdaytoarray = [String]()
var fridaycoursenamearray = [String]()
var fridaycoursecodearray = [String]()
var fridaycourselocationarray = [String]()
var fridayfromarray = [String]()
var fridaytoarray = [String]()
var saturdaycoursenamearray = [String]()
var saturdaycoursecodearray = [String]()
var saturdaycourselocationarray = [String]()
var saturdayfromarray = [String]()
var saturdaytoarray = [String]()
var coursecodes = [[String]]()
var coursenames = [[String]]()
var courselocations = [[String]]()
var fromtimes = [[String]]()
var totimes = [[String]]()
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
override func viewWillAppear(_ animated: Bool) {
let uid = Auth.auth().currentUser?.uid
if(uid == nil){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nextviewController = storyboard.instantiateViewController(withIdentifier: "loginscreen")
//self.present(profileViewController, animated: true, completion: nil)
self.present(nextviewController, animated: true, completion: nil)
}
for j in days {
for i in 1 ..< 10 {
let ref1 = Database.database().reference().child("users").child((uid)!).child("courses").child(j).child(String(i))
ref1.observeSingleEvent(of: .value, with: { snapshot in
if let dictionary = snapshot.value as? [String: AnyObject] {
// print(dictionary)
if j == "Sunday" {
if let points = dictionary["coursname"] as? String {
self.sundaycoursecodearray.append(points)
print(self.sundaycoursecodearray)
}
if let points1 = dictionary["coursecode"] as? String {
self.sundaycoursenamearray.append(points1)
print(self.sundaycoursenamearray)
}
if let points1 = dictionary["courseroomlocation"] as? String {
self.sundaycourselocationarray.append(points1)
print(self.sundaycourselocationarray)
}
if let points1 = dictionary["fromtime"] as? String {
self.sundayfromarray.append(points1)
print(self.sundayfromarray)
}
if let points1 = dictionary["totime"] as? String {
self.sundaytoarray.append(points1)
print(self.sundaytoarray)
}
}
if j == "Monday" {
if let points = dictionary["coursname"] as? String {
self.mondaycoursecodearray.append(points)
print(self.mondaycoursecodearray)
}
if let points1 = dictionary["coursecode"] as? String {
self.mondaycoursenamearray.append(points1)
print(self.mondaycoursenamearray)
}
if let points1 = dictionary["courseroomlocation"] as? String {
self.mondaycourselocationarray.append(points1)
print(self.mondaycourselocationarray)
}
if let points1 = dictionary["fromtime"] as? String {
self.mondayfromarray.append(points1)
print(self.mondayfromarray)
}
if let points1 = dictionary["totime"] as? String {
self.mondaytoarray.append(points1)
print(self.mondaytoarray)
}
}
if j == "Tuesday" {
if let points = dictionary["coursname"] as? String {
self.tuesdaycoursecodearray.append(points)
print(self.tuesdaycoursecodearray)
}
if let points1 = dictionary["coursecode"] as? String {
self.tuesdaycoursenamearray.append(points1)
print(self.tuesdaycoursenamearray)
}
if let points1 = dictionary["courseroomlocation"] as? String {
self.tuesdaycourselocationarray.append(points1)
print(self.tuesdaycourselocationarray)
}
if let points1 = dictionary["fromtime"] as? String {
self.tuesdayfromarray.append(points1)
print(self.tuesdayfromarray)
}
if let points1 = dictionary["totime"] as? String {
self.tuesdaytoarray.append(points1)
print(self.tuesdaytoarray)
}
}
if j == "Wednesday" {
if let points = dictionary["coursname"] as? String {
self.wednesdaycoursecodearray.append(points)
print(self.wednesdaycoursecodearray)
}
if let points1 = dictionary["coursecode"] as? String {
self.wednesdaycoursenamearray.append(points1)
print(self.wednesdaycoursenamearray)
}
if let points1 = dictionary["courseroomlocation"] as? String {
self.wednesdaycourselocationarray.append(points1)
print(self.wednesdaycourselocationarray)
}
if let points1 = dictionary["fromtime"] as? String {
self.wednesdayfromarray.append(points1)
print(self.wednesdayfromarray)
}
if let points1 = dictionary["totime"] as? String {
self.wednesdaytoarray.append(points1)
print(self.wednesdaytoarray)
}
}
if j == "Thursday" {
if let points = dictionary["coursname"] as? String {
self.thursdaycoursecodearray.append(points)
print(self.thursdaycoursecodearray)
}
if let points1 = dictionary["coursecode"] as? String {
self.thursdaycoursenamearray.append(points1)
print(self.thursdaycoursenamearray)
}
if let points1 = dictionary["courseroomlocation"] as? String {
self.thursdaycourselocationarray.append(points1)
print(self.thursdaycourselocationarray)
}
if let points1 = dictionary["fromtime"] as? String {
self.thursdayfromarray.append(points1)
print(self.thursdayfromarray)
}
if let points1 = dictionary["totime"] as? String {
self.thursdaytoarray.append(points1)
print(self.thursdaytoarray)
}
}
if j == "Friday" {
if let points = dictionary["coursname"] as? String {
self.fridaycoursecodearray.append(points)
print(self.fridaycoursecodearray)
}
if let points1 = dictionary["coursecode"] as? String {
self.fridaycoursenamearray.append(points1)
print(self.fridaycoursenamearray)
}
if let points1 = dictionary["courseroomlocation"] as? String {
self.fridaycourselocationarray.append(points1)
print(self.fridaycourselocationarray)
}
if let points1 = dictionary["fromtime"] as? String {
self.fridayfromarray.append(points1)
print(self.fridayfromarray)
}
if let points1 = dictionary["totime"] as? String {
self.fridaytoarray.append(points1)
print(self.fridaytoarray)
}
}
if j == "Saturday" {
if let points = dictionary["coursname"] as? String {
self.saturdaycoursecodearray.append(points)
print(self.saturdaycoursecodearray)
}
if let points1 = dictionary["coursecode"] as? String {
self.saturdaycoursenamearray.append(points1)
print(self.saturdaycoursenamearray)
}
if let points1 = dictionary["courseroomlocation"] as? String {
self.saturdaycourselocationarray.append(points1)
print(self.saturdaycourselocationarray)
}
if let points1 = dictionary["fromtime"] as? String {
self.saturdayfromarray.append(points1)
print(self.saturdayfromarray)
}
if let points1 = dictionary["totime"] as? String {
self.saturdaytoarray.append(points1)
print(self.saturdaytoarray)
}
}
self.coursecodes.append(self.sundaycoursenamearray)
self.coursecodes.append(self.mondaycoursenamearray)
self.coursecodes.append(self.tuesdaycoursenamearray)
self.coursecodes.append(self.wednesdaycoursenamearray)
self.coursecodes.append(self.thursdaycoursenamearray)
self.coursecodes.append(self.fridaycoursenamearray)
self.coursecodes.append(self.saturdaycoursenamearray)
self.coursenames.append(self.sundaycoursecodearray)
self.coursenames.append(self.mondaycoursecodearray)
self.coursenames.append(self.tuesdaycoursecodearray)
self.coursenames.append(self.wednesdaycoursecodearray)
self.coursenames.append(self.thursdaycoursecodearray)
self.coursenames.append(self.fridaycoursecodearray)
self.coursenames.append(self.saturdaycoursecodearray)
self.courselocations.append(self.sundaycourselocationarray)
self.courselocations.append(self.mondaycourselocationarray)
self.courselocations.append(self.tuesdaycourselocationarray)
self.courselocations.append(self.wednesdaycourselocationarray)
self.courselocations.append(self.thursdaycourselocationarray)
self.courselocations.append(self.fridaycourselocationarray)
self.courselocations.append(self.saturdaycourselocationarray)
self.fromtimes.append(self.sundayfromarray)
self.fromtimes.append(self.mondayfromarray)
self.fromtimes.append(self.tuesdayfromarray)
self.fromtimes.append(self.wednesdayfromarray)
self.fromtimes.append(self.thursdayfromarray)
self.fromtimes.append(self.fridayfromarray)
self.fromtimes.append(self.saturdayfromarray)
self.totimes.append(self.sundaytoarray)
self.totimes.append(self.mondaytoarray)
self.totimes.append(self.tuesdaytoarray)
self.totimes.append(self.wednesdaytoarray)
self.totimes.append(self.thursdaytoarray)
self.totimes.append(self.fridaytoarray)
self.totimes.append(self.saturdaytoarray)
self.tableview.reloadData()
}
})
} }
super.viewWillAppear(animated)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return days[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return days.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return coursenames[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! homeTableViewCell
// Configure the cell...
// cell.classcode?.text = sundaycoursenamearray[indexPath.section]
cell.classcode?.text = coursenames[indexPath.section][indexPath.row]
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
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 to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
You should create a model for your data then create arrays that include the model.
You can create a simple struct like so:
struct Course {
var name : String?
var code: String?
var location: String?
var toTime: String?
var fromTime: String?
}
After you create the model you can create an array that contains this type of struct.
Also for numberOfRowsInSection you don't have to use subscript. Just return:
return coursenames.count
That is why you get the error.
I try to sort my tableView by distance form the current location. I search on the website but is it very difficult for me to adapte on my projet what I find
Can you help me please?
Here is my first files for data "Cables.swift":
import Foundation
import MapKit
class Person {
var identifier:Int
var name:String
var country:String
var email:String
var website:String
var facebook:String
var adress:String
var phone:String
var latitude:Double
var longitude:Double
var lac:Int
var poulie1:Int
var rotation1:String
var module1:Int
var poulie2:Int
var rotation2:String
var module2:Int
var distance:Double
var smallPhotoUrl:URL! {
return URL(string: "http://wakefinder.16mb.com/full/\(self.identifier).jpg")
}
var largePhotoUrl:URL! {
return URL(string: "http://wakefinder.16mb.com/full/\(self.identifier).jpg")
}
//var coordinate: CLLocationCoordinate2D
init?(fromData personData:[String:AnyObject]) {
guard let identifier = personData["id"] as? Int,
let name = personData["name"] as? String,
let country = personData["country"] as? String,
let email = personData["email"] as? String,
let website = personData["website"] as? String,
let facebook = personData["facebook"] as? String,
let adress = personData["adress"] as? String,
let phone = personData["phone"] as? String,
let latitude = personData["lat"] as? Double,
let longitude = personData["lng"] as? Double,
let lac = personData["lac"] as? Int,
let poulie1 = personData["poulie1"] as? Int,
let rotation1 = personData["rotation1"] as? String,
let module1 = personData["module1"] as? Int,
let poulie2 = personData["poulie2"] as? Int,
let rotation2 = personData["rotation2"] as? String,
let module2 = personData["module2"] as? Int
else {
return nil
}
self.identifier = identifier
self.name = name
self.country = country
self.email = email
self.website = website
self.facebook = facebook
self.adress = adress
self.phone = phone
self.latitude = latitude
self.longitude = longitude
self.lac = lac
self.poulie1 = poulie1
self.rotation1 = rotation1
self.module1 = module1
self.poulie2 = poulie2
self.rotation2 = rotation2
self.module2 = module2
}
// Function to calculate the distance from given location.
func calculateDistance(fromLocation: CLLocation?) {
let location = CLLocation(latitude: self.latitude, longitude: self.longitude)
distance = location.distance(from: fromLocation!)
}
}
and the file for my TableView:
import UIKit
import Alamofire
import CoreLocation
class cableViewController: UITableViewController, UISearchResultsUpdating {
var _personList:[Person] = []
var _personFiltered:[Person] = []
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Alamofire.request("http://wakefinder.16mb.com/users.json")
.validate()
.responseJSON { (response) in
if response.result.isSuccess {
let rawPersonList = response.result.value as! [[String:AnyObject]]
for personData in rawPersonList {
if let personObject = Person(fromData: personData) {
self._personList.append(personObject)
}
}
self.tableView.reloadData()
} else {
print(response.result.error as Any)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
return _personFiltered.count
}
return _personList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:cablesTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cable_cell") as! cablesTableViewCell
if searchController.isActive && searchController.searchBar.text != "" {
let person:Person = _personFiltered[indexPath.row]
cell.display(person: person)
//_personList[indexPath.row] = _personFiltered[indexPath.row]
} else {
let person:Person = _personList[indexPath.row]
cell.display(person: person)
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let cell = sender as? UITableViewCell {
if let indexPath = self.tableView.indexPath(for: cell) {
let selectedPerson: Person
if searchController.isActive && searchController.searchBar.text != "" {
selectedPerson = _personFiltered[indexPath.row]
} else {
selectedPerson = _personList[indexPath.row]
}
let personViewController:fichesViewController = segue.destination as! fichesViewController
personViewController._person = selectedPerson
}
}
}
}
func updateSearchResults(for searchController: UISearchController) {
filterContent(searchText: self.searchController.searchBar.text!)
}
func filterContent(searchText:String) {
_personFiltered = _personList.filter { user in
let username = user.name
return(username.lowercased().contains(searchText.lowercased()))
}
self.tableView.reloadData()
}
}