UITableViewCell has duplicates from document folder [duplicate] - ios

This question already has an answer here:
UITableViewCell shows incorrect results from document folder
(1 answer)
Closed 7 years ago.
I have several UITableViewControllers and they have data from document folder into iOS Device. I export names of artists from mp3 files with help AVMetaDataItem. I get several names and I have duplicates. How can I remove duplicates from UITableViewCell?
var cellStrings: String!
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
var dataForCell = mp3Files[indexPath.row]
var generalURL: NSURL!
var documentFolder = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
if var urlFromFolder: NSURL = documentFolder.first as? NSURL {
generalURL = urlFromFolder.URLByAppendingPathComponent(dataForCell)
println("general \(generalURL)")
}
var player = AVPlayerItem(URL: generalURL)
var metaData = player.asset.commonMetadata as! [AVMetadataItem]
for item in metaData {
if item.commonKey == "artist" {
nameArtist = item.stringValue
}
}
cell.textLabel?.text = nameArtist
return cell
}

I solved my problem
var superArray = [String]()
var filterArray = [String]()
func filter() {
var proString: String!
for proItem in mp3Files {
var proFolder = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
var americaURL: NSURL!
if var proURL: NSURL = proFolder.first as? NSURL {
americaURL = proURL.URLByAppendingPathComponent(proItem)
}
var proPlayerItem = AVPlayerItem(URL: americaURL)
var proData = proPlayerItem.asset.commonMetadata as! [AVMetadataItem]
for proFiles in proData {
if proFiles.commonKey == "artist" {
superArray.append(proFiles.stringValue)
}
}
}
filterArray = Array(Set(superArray))
filterArray.sort(){ $0 < $1 }
}

Related

Fetching Image Url's From Realtime Database - Firebase / Swift

I am trying to display images onto a collection view. The image url's are saved in the realtime database in Firebase and was wondering, what I am doing wrong? Essentially, users have a node called 'Images' where images they have uploaded are saved inside that node. The names depend on the image Title and the url is the image they have uploaded. Below is my code and a photo of how my database looks like it. If someone could help me out, I would appreciate that a lot. Thanks!
The Issue is that the images are not being displayed. It is successfully able to display the correct amount of images the user has in their account but does not read the image url. My guess is that because each url is under a different value (imageTitle). Any ideas?
My ViewController:
class PicturesViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var imageCollection: UICollectionView!
var customImageFlowLayout: CustomImageFlowLayout!
var images = [UserImages]()
var dbRef: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
dbRef = Database.database().reference().child("users/\(Auth.auth().currentUser!.uid)/Images")
loadDB()
}
func loadDB() {
dbRef.observe(DataEventType.value, with: { (snapshot) in
var newImages = [UserImages]()
for UserImagesSnapshot in snapshot.children {
let UserImagesObject = UserImages(snapshot: UserImagesSnapshot as! DataSnapshot)
newImages.append(UserImagesObject)
}
self.images = newImages
self.imageCollection.reloadData()
})
}
func collectionView(_ imageCollection: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ imageCollection: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
let image = images[indexPath.row]
cell.imageView.sd_setImage(with: URL(string: image.url), placeholderImage: UIImage(named: "image1"))
return cell
}
My Array - UserImages
struct UserImages {
let key: String!
let url: String!
let itemsRef: DatabaseReference!
init (url:String, key:String) {
self.key = key
self.url = url
self.itemsRef = nil
}
init(snapshot: DataSnapshot) {
key = snapshot.key
itemsRef = snapshot.ref
let snapshotValue = snapshot.value as? NSDictionary
if let imageUrl = snapshotValue?[""] as? String {
url = imageUrl
} else {
url = ""
}
}
}
Replace
let snapshotValue = snapshot.value as? NSDictionary
if let imageUrl = snapshotValue?[""] as? String {
url = imageUrl
} else {
url = ""
}
with
url = snapshot.value as! String

My data from firebase database is not loading into my tableview

I have a tableview loading data from firebase database. When I open my app the data does not populate. when I create a new post I can see the tableview cells modifying like changed were made but the post doesn't populate. I can't figure it out.
import UIKit
import FirebaseAuth
import FirebaseDatabase
class EventsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var eventsRef: DatabaseReference?
var eventsDatabaseHandle:DatabaseHandle?
var eventsTitles = [String]()
var eventTimestamps = [String]()
var eventsLocations = [String]()
var eventsImages = [UIImage]()
#IBOutlet weak var addEventsButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
adminAuth()
eventsRef = Database.database().reference()
tableView.reloadData()
tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
tableView.delegate = self
tableView.dataSource = self
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { (snaphot) in
let eventPost = snaphot.value as! [String: Any]
self.eventTimestamps.append(eventPost["eventdate"] as! String)
self.eventsTitles.append(eventPost["eventtitle"] as! String)
self.eventsLocations.append(eventPost["eventlocation"] as! String)
let task = URLSession.shared.dataTask(with: URL(string: eventPost["ImageUrl"] as! String)!) {(data, response, error) in
if let image: UIImage = UIImage(data: data!) {
self.eventsImages.append(image)
}
}
self.tableView.reloadData()
task.resume()
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventsImages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
let image = eventsImages[indexPath.row]
cell.flyerImages.image! = image
cell.eventTitle.text! = eventsTitles[indexPath.row]
cell.eventDate.text! = eventTimestamps[indexPath.row]
cell.eventLocation.text! = eventsLocations[indexPath.row]
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
tableView.reloadData()
return cell
}
func adminAuth() {
if (Auth.auth().currentUser!.displayName != "Neil Leon") {
self.addEventsButton.tintColor = UIColor.clear
self.addEventsButton.isEnabled = false
}
else{
self.addEventsButton.isEnabled = true
}
}
}
image of empty tableview
]
So the code below is not tested as I don't have firebase setup currently.
However, observing childAdded... the documentation says it will pass all of the current records in the database at first and will then just post new additions. So all you need to do is loop through them, setup your tableView data source and reload the table.
Rather than use multiple arrays for values I've created an array of ChurchEvent objects instead.
struct ChurchEvents {
let title: String
let location: String?
let date: Date?
let imageUrlString: String?
init(dict: [String: Any]) {
self.title = dict["title"] as String
self.location = dict["location"] as? String
// etc
}
}
var events = [ChurchEvents]()
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { snapshot in
let list = snapshot.value as? [[String : AnyObject]]
let newEvents = list.map { ChurchEvent(dict: $0) }
events.append(newEvents)
tableView.reloadData()
}
Other improvements you could make:
class EventsTableViewCell: UICollectionViewCell {
func configure(with event: ChurchEvent {
eventDate.text = event.date
eventTitle.text = event.title
eventLocation.text = event.location
// etc
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
let event = events[indexPath.row]
cell.configure(with: event)
return cell
}

Dribble Api returning wrong data

Hi guys so recently there has been a bug of getting data from Dribble..
My Dribbble client IOS shows shots on the main screen and if you click on a collectionView Cell it takes you to the detail of the shot..
And i am getting Dribble Data through its api with this method.
The Code for the getShots Method
class func getShots(url: String, callback:(([Shot]) -> Void)){
var shots = [Shot]()
let url = url + "&access_token=" + Config.ACCESS_TOKEN
HttpService.getJSON(url){ (jsonData) -> Void in
for shotData in jsonData {
let shot = Shot(data: shotData as! NSDictionary)
shots.append(shot)
}
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0), { () -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
callback(shots)
})
})
}
}
The Code for the getJSON method..
class HttpService {
class func getJSON(url: String, callback:((NSArray) -> Void)) {
let nsURL = NSURL(string: url)!
Alamofire.request(.GET, nsURL).response { (request, response, data, error) -> Void in
if error != nil{
print("error")
}
if data != nil {
let jsonData = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSArray
callback(jsonData)
}
}
}
}
This code is above which loads The Shot JSON Data successfully..
So when i debug it on the self.shots = shots line it returns something like this..
The log when debugging on the self.shots = shots line
It all works fine.. and the code for the class of Detail of a Shot...
I have been using dynamic tableView to show the Shot Detail
The code in ShotDetail the code where the label are allocated their text.. basically The TableView Data Source Method..
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return 9
} else {
return comments.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! vlcTableViewCell
// Configure the cell
// the views . likes. and the comment Count label are allocated
cell.viewsCount.text = "\(shot.viewsCount)"
cell.likesCount.text = "\(shot.likesCount)"
cell.commentCount.text = "\(shot.commentCount)"
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell2", forIndexPath: indexPath) as! descCell
// Configure the Cell
// the text for the labels
cell.usernameLabel.text = "\(shot.user.username)"
cell.descriptionLabel.text = "\(shot.description)"
cell.profileImageView.sd_setImageWithURL(NSURL(string: shot.user.avatarUrl), placeholderImage: UIImage(named: "2"))
return cell
} else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell4", forIndexPath: indexPath) as! teamCell
if shot.team == nil{
cell.teamNameLabel.text = "Team"
} else {
cell.teamNameLabel.text = "\(shot.team.name)"
}
return cell
} else if indexPath.row == 4 {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell5", forIndexPath: indexPath) as! reboundShotsCount
cell.reboundCountLabel.text = "\(shot.reboundCount)"
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell10", forIndexPath: indexPath) as! CommentCell
let comment = comments[indexPath.row]
cell.nameLabel.text = comment.user.name
cell.commentLabel.text = comment.body
cell.avatarImageView.alpha = 0.0
cell.avatarImageView.sd_setImageWithURL(NSURL(string: comment.user.avatarUrl), placeholderImage: UIImage(named: "2"), completed: { (image, error, cacheType, url) -> Void in
cell.avatarImageView.alpha = 1.0
// Animate the imageView after the image is loaded
cell.animationView.layer.cornerRadius = 25
cell.animationView.delay = 0
cell.animationView.duration = 0.5
cell.animationView.type = "popAlpha"
cell.animationView.startCanvasAnimation()
})
cell.dateLabel.text = comment.date
return cell
}
}
and the Code for the Shot Class.. From where i get all the data to set to the labels
import Foundation
class Shot: DribbbleBase {
var imageUrl : String!
var htmlUrl : String!
var commentsUrl : String!
var bucketsUrl : String!
var likesUrl : String!
var attachmentUrl : String!
var reboundUrl : String!
var title : String!
var date : String!
var description : String!
var commentCount : Int!
var viewsCount : Int!
var likesCount : Int!
var bucketsCount : Int!
var attachmentsCount : Int!
var reboundCount : Int!
var imageUrll : String!
var teamUrl : String!
var user : User!
var team : Team!
override init(data: NSDictionary) {
super.init(data: data)
self.commentCount = data["comments_count"] as! Int
self.likesCount = data["likes_count"] as! Int
self.viewsCount = data["views_count"] as! Int
self.bucketsCount = data["buckets_count"] as! Int
self.attachmentsCount = data["attachments_count"] as! Int
self.reboundCount = data["rebounds_count"] as! Int
self.commentsUrl = Utils.getStringFromJSON(data, key: "comments_url")
self.bucketsUrl = Utils.getStringFromJSON(data, key: "buckets_url")
self.likesUrl = Utils.getStringFromJSON(data, key: "likes_url")
self.title = Utils.getStringFromJSON(data, key: "title")
self.attachmentUrl = Utils.getStringFromJSON(data, key: "attachments_url")
self.reboundUrl = Utils.getStringFromJSON(data, key: "rebounds_url")
self.teamUrl = Utils.getStringFromJSON(data, key: "teams_url")
let dateInfo = Utils.getStringFromJSON(data, key: "created_at")
self.date = Utils.formatDate(dateInfo)
let desc = Utils.getStringFromJSON(data, key: "description")
self.description = Utils.stripHTML(desc)
let images = data["images"] as! NSDictionary
self.imageUrl = Utils.getStringFromJSON(images, key: "normal")
self.imageUrll = Utils.getStringFromJSON(images, key: "hidpi")
let tags = data["tags"] as! NSArray
if let userData = data["user"] as? NSDictionary {
self.user = User(data: userData)
}
if let teamData = data["team"] as? NSDictionary {
self.team = Team(data: teamData)
}
}
}
Now the problem occurs when i tap on the cell to go to the next cell.
before that if i debug in the Shot class..
The data looks like this
The Log Which shows the data returned
and now whenever i click on the cell. to go to the detail. the data returns only 7 value for the exact thing which in the first was returning all the values needed..
the code i am using to push the data in PopularShotsCollectionViewController is this.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "1"){
let selectedItems = collectionView!.indexPathsForSelectedItems()
if let sItem = selectedItems as [NSIndexPath]!{
let shot = shots[sItem[0].row]
let controller = segue.destinationViewController as! ShotDetail
controller.shot = shot
}
}
}
But the log only returns 7 value in that..
https://www.dropbox.com/s/4vkgg7a3f44fg35/Screen%20Shot%202016-03-28%20at%2014.40.23.png?dl=0
I have put the link in a code block as i cant post more than 2 links.
Any help will be really appreciated..
Thanks
Aryan
let shot = shots[sItem[0].row] Might be the issue. You're passing the same index to the DetailVC. You could save an array of the selected shots then pass it to shot variable in your DetailVC (If the shot variable is an array of shots)
var selectedIndex = NSIndexPath()
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectedIndex = indexPath
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "1"){
let selectedItems = collectionView!.indexPathsForSelectedItems()
let selectedShots = shots[selectedIndex.row]
let controller = segue.destinationViewController as! ShotDetail
controller.shot = selectedShots
}
}
}

Swift - Construct a sentence from array of <AnyObject>

Good day! I'm building an app that needs to construct a sentence from the data from Core Data. I have this:
var players = Array<AnyObject> = []
#IBOutlet weak var sentenceLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.managedObjectContext!
let freq = NSFetchRequest(entityName: "Orders")
players = context.executeFetchRequest(freq, error: nil)!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return players.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("checkCell") as! SummaryCustomCell!
if cell == nil {
cell = SummaryCustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "checkCell")
}
var data: NSManagedObject = players[indexPath.row] as! NSManagedObject
cell.playerNameLabel.text = data.valueForKey("playerName") as? String
cell.teamLabel.text = data.valueForKey("team") as? String
cell.yearsLabel.text = data.valueForKey("yearsOfPlaying") as? String
for var i = 0; i < players.count;i++ {
var dataLooped: NSManagedObject = myOrders[i] as! NSManagedObject
var playerName = dataLooped.valueForKey("playerName") as? String
var team = dataLooped.valueForKey("team") as? String
var years = dataLooped.valueForKey("yearsOfPlaying") as? String
var constructedSentence: NSString = NSString(format: "%# was playing for %# for %# years.", playerName, team, years)
sentenceLabel.text = constructedSentence as! String
}
}
return cell
}
Then it gives only the last row in the database. It must loop the sentence in a single string. For example. "Kobe Bryant was playing for LA Lakers for 5 years; Lebron James was playing for Cavs for 3 years." and so on..
How can I implement this? Thank you very much!

UITableViewCell shows incorrect results from document folder

I have UITableViewController with files from document folder. I name the cells by artist name. I have three artist and four songs. UITableViewCell shows two cells with the same artist. How can I fix it?
This code export data from document folder
var mp3Files: Array<String!>!
func exportData() {
var generalURL: [AnyObject]?
var arrayFiles: Array<NSURL!>!
var directory = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
var urlFromDirectory = directory.first as! NSURL
var file = fileManager.contentsOfDirectoryAtURL(urlFromDirectory, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: nil)!
println("file \(file)")
mp3Files = file.map(){ $0.lastPathComponent }.filter(){ $0.pathExtension == "mp3" }
println("mp3 files \(mp3Files)")
}
and code fill the UITableViewCell
var cellStrings: String!
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
var dataForCell = mp3Files[indexPath.row]
var generalURL: NSURL!
var documentFolder = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
if var urlFromFolder: NSURL = documentFolder.first as? NSURL {
generalURL = urlFromFolder.URLByAppendingPathComponent(dataForCell)
println("general \(generalURL)")
}
var player = AVPlayerItem(URL: generalURL)
var metaData = player.asset.commonMetadata as! [AVMetadataItem]
for item in metaData {
if item.commonKey == "artist" {
nameArtist = item.stringValue
}
}
cell.textLabel?.text = nameArtist
//
cellStrings = cell.textLabel?.text
println("cell strings \(cellStrings)")
// Configure the cell...
return cell
}
var superArray = [String]()
var filterArray = [String]()
func filter() {
var proString: String!
for proItem in mp3Files {
var proFolder = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
var americaURL: NSURL!
if var proURL: NSURL = proFolder.first as? NSURL {
americaURL = proURL.URLByAppendingPathComponent(proItem)
}
var proPlayerItem = AVPlayerItem(URL: americaURL)
var proData = proPlayerItem.asset.commonMetadata as! [AVMetadataItem]
for proFiles in proData {
if proFiles.commonKey == "artist" {
superArray.append(proFiles.stringValue)
}
}
}
filterArray = Array(Set(superArray))
filterArray.sort(){ $0 < $1 }
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1 ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return filterArray.count ?? 0
}
var name: String!
var nameArtist: String!
//
var cellStrings: String!
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
nameArtist = filterArray[indexPath.row]
cell.textLabel?.text = nameArtist
return cell
}

Resources