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
}
}
}
Related
I am using below code for the UITableView, in every cell there are two buttons configured to perform certain actions as shown in the code. Earlier it was working fine, but now As I update this code to new version of Xcode it is not working, whenever I tap on the cell or the button in the cell it doesn't perform any action, neither it shows any error, but it just darkens the half of the cell with grey colour?
Xcode earlier was 10 and now 11, swift 5 version same in both cases
There is one fixed cell at the top and then there is list of cells as per the number of documents in the database
What could be the issue?
for information I am using Swift IOS and cloud firestore database
class HomeViewController: UITableViewController {
var posts = [Post]()
var db: Firestore!
var scores1 = [Scores]()
var postAuthorId:String = ""
var postAuthorname:String = ""
var CommentAuthorName:String = ""
var PostTitle:String = ""
var postAuthorGender:String = ""
var postAuthorEmail:String = ""
var postAuthorfullname:String = ""
var postAuthorSpinnerC:String = ""
var postContent:String = ""
var postCategory:String = ""
var postAuthorPicUrl:String = ""
var postTimeStamp:String = ""
var l11:Int = 0
var postKey:String = ""
private var documents: [DocumentSnapshot] = []
override func viewDidLoad() {
super.viewDidLoad()
db = Firestore.firestore()
tableView.dataSource = self
tableView.delegate = self
retrieveAllPosts()
getuserscores()
var AViewController: UIViewController = UIViewController()
var MyTabBarItem: UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "pencil")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), selectedImage: UIImage(named: "pencil"))
AViewController.tabBarItem = MyTabBarItem
// Do any additional setup after loading the view.
// navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleLogout))
}
func getuserscores(){
let userRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid)
userRef.getDocument{(document, error) in
if let document = document, document.exists{
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
let l1 = document.get("l1") as! Int
let l2 = document.get("l2") as! Int
let l3 = document.get("l3") as! Int
let l4 = document.get("l4") as! Int
let newScores = Scores(_l1: l1, _l2: l2, _l3: l3, _l4: l4)
self.scores1.append(newScores)
}
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func retrieveAllPosts(){
let postsRef = Firestore.firestore().collection("posts").order(by: "timestamp", descending: true).limit(to: 50)
postsRef.getDocuments { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let username = data["post_author_username"] as? String ?? ""
let postTitle = data["postTitle"] as? String ?? ""
let postcategory = data["postcategory"] as? String ?? ""
let postContent = data["postContent"] as? String ?? ""
let postAuthorProfilePicUrl = data["post_user_profile_pic_url"] as? String ?? ""
let postAuthorSpinnerC = data["post_author_spinnerC"] as? String
let newSourse = Post(_documentId: document.documentID, _username: username, _postTitle: postTitle, _postcategory: postcategory, _postContent: postContent, _postuserprofileImagUrl: postAuthorProfilePicUrl, _postAuthorSpinncerC: postAuthorSpinnerC)
self.posts.append(newSourse)
}
self.tableView.reloadData()
}
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableView.automaticDimension
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return scores1.count + posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 && scores1.count == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "SmileMiles") as! ScoresCellInHomeScreen
cell.set(scores: scores1[indexPath.row])
return cell
} else if posts.count > (indexPath.row - 1 ) {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.btnComment.tag = indexPath.row - 1
cell.btnComment.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)
cell.favoritebutton.tag = indexPath.row - 1
cell.favoritebutton.addTarget(self, action: #selector(favupdate(_:)), for: .touchUpInside)
cell.set(post: posts[indexPath.row - 1 ])
return cell
} else {
return UITableViewCell()
}
}
#objc func favupdate(_ sender: AnyObject) {
let commentbutton = sender as! UIButton
let post = posts[commentbutton.tag]
postKey = post._documentId // or what key value it is
let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("marked_posts").document(postKey)
let postRef = Firestore.firestore().collection("posts").document(postKey)
postRef.getDocument{(document, error) in
if let document = document, document.exists{
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
self.postAuthorId = document.get("post_author_id") as! String
self.postAuthorname = document.get("post_author_username") as! String
self.PostTitle = document.get("postTitle") as! String
self.postContent = document.get("postContent") as! String
self.postAuthorEmail = document.get("post_author_email") as! String
self.postCategory = document.get("postcategory") as! String
self.postAuthorfullname = document.get("post_author_fullname") as! String
self.postAuthorGender = document.get("post_author_gender") as! String
self.postAuthorPicUrl = document.get("post_user_profile_pic_url") as! String
// let l11:Bool = document.get("l1") as! Bool
// self.postTimeStamp = document.get("post_timeStamp") as! String
self.postAuthorSpinnerC = document.get("post_author_spinnerC") as! String
}
let postObject = [
"post_author_gender": self.postAuthorGender,
// "post_author_dateOfBirth": self.dateOfBirth,
"post_author_spinnerC": self.postAuthorSpinnerC,
"post_author_fullname": self.postAuthorfullname,
"post_author_id": self.postAuthorId,
"post_author_username": self.postAuthorname,
"post_author_email": self.postAuthorEmail,
"postTitle": self.PostTitle,
"postcategory": self.postCategory,
"postContent": self.postContent,
// "post_timestamp": FieldValue.serverTimestamp(),
"post_user_profile_pic_url":self.postAuthorPicUrl,
"post_id": self.postKey
] as [String : Any]
userMarkRef.setData(postObject, merge: true) { (err) in
if let err = err {
print(err.localizedDescription)
}
print("Successfully set new user data")
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 150
}
else{
return UITableView.automaticDimension
}
}
#objc func toComments(_ sender: AnyObject) {
let commentbutton = sender as! UIButton
let post = posts[commentbutton.tag]
postKey = post._documentId // or what key value it is
print(postKey + "hello")
performSegue(withIdentifier: "toCommentsList", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "toCommentsList"){
var vc = segue.destination as! CommentListViewController
vc.postId = postKey
}
}
}
Do this in tableview cellForRowAt function before return cell:
cell.selectionStyle = .none
return cell
this will fix the issue
I am having array in which selected name will be stored and passed to before view controller and when ever i need to go previous view controller then the previously selected check mark needs to be selected but here it is enabling the last selected element only the problem is if i select three then it is not selecting three it is check marking only the last element but i need the three selected can anyone help me how to make the check mark to be selected for three elements ?
protocol ArrayToPass: class {
func selectedArrayToPass(selectedStrings: [String])
}
class FilterSelectionViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var productName = [String]()
var productprice = [String]()
var imageArray = [String]()
var idArray = [Int]()
let urlString = "http://www.json-generator.com/api/json/get/bOYOrkIOSq?indent=2"
var values = [String]()
var selected: Bool?
var delegate: ArrayToPass?
var nameSelection: Bool?
var namesArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
tableDetails.separatorInset = UIEdgeInsets.zero
activityIndicator.startAnimating()
tableDetails.isHidden = true
tableDetails.dataSource = self
tableDetails.delegate = self
let rightBarButton = UIBarButtonItem(title: "Apply", style: UIBarButtonItemStyle.plain, target: self, action: #selector(applyBarButtonActionTapped(_:)))
self.navigationItem.rightBarButtonItem = rightBarButton
tableDetails.estimatedRowHeight = UITableViewAutomaticDimension
tableDetails.rowHeight = 60
// Do any additional setup after loading the view.
}
func applyBarButtonActionTapped(_ sender:UIBarButtonItem!){
self.delegate?.selectedArrayToPass(selectedStrings: values)
navigationController?.popViewController(animated: true)
}
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSArray {
for item in jsonObj! {
if let itemDict = item as? NSDictionary{
if let name = itemDict.value(forKey: "name") {
self.productName.append(name as! String)
}
if let price = itemDict.value(forKey: "value") {
self.productprice.append(price as! String)
}
if let image = itemDict.value(forKey: "img") {
self.imageArray.append(image as! String)
}
if let id = itemDict.value(forKey: "id") {
self.idArray.append(id as! Int)
}
}
}
OperationQueue.main.addOperation({
self.tableDetails.reloadData()
})
}
}).resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "filterSelectionCell", for: indexPath) as! FilterSelectionCell
activityIndicator.stopAnimating()
activityIndicator.hidesWhenStopped = true
tableDetails.isHidden = false
cell.brandProductName.text = productName[indexPath.row]
if nameSelection == true{
if namesArray.count != 0 {
print(namesArray)
for name in namesArray{
if productName[indexPath.row].contains(name){
print(productName[indexPath.row])
cell.accessoryType = .checkmark
}
else {
cell.accessoryType = .none
}
}
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
selected = false
if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
if cell.accessoryType == .checkmark{
cell.accessoryType = .none
print("\(productName[indexPath.row])")
values = values.filter{$0 != "\(productName[indexPath.row])"}
selected = true
}
else{
cell.accessoryType = .checkmark
}
}
if selected == true{
print(values)
}
else{
getAllTextFromTableView()
}
print(values)
}
func getAllTextFromTableView() {
guard let indexPaths = self.tableDetails.indexPathsForSelectedRows else { // if no selected cells just return
return
}
for indexPath in indexPaths {
values.append(productName[indexPath.row])
}
}
here is the image for this
Basically do not manipulate the view (the cell). Use a data model.
struct Product {
let name : String
let value : String
let img : String
let id : Int
var selected = false
init(dict : [String:Any]) {
self.name = dict["name"] as? String ?? ""
self.value = dict["value"] as? String ?? ""
self.img = dict["img"] as? String ?? ""
self.id = dict["id"] as? Int ?? 0
}
}
And never use multiple arrays as data source . That's a very bad habit.
Declare the data source array as
var products = [Product]()
Parse the JSON data and do a (better) error handling
func downloadJsonWithURL() {
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil { print(error!); return }
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
self.products = jsonObj.map{ Product(dict: $0) }
DispatchQueue.main.async {
self.tableDetails.reloadData()
}
}
} catch {
print(error)
}
}
task.resume()
}
in cellForRow... assign the name to the label and set the checkmark depending on selected
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "filterSelectionCell", for: indexPath)
let product = products[indexPath.row]
cell.textLabel!.text = product.name
cell.accessoryType = product.selected ? .checkmark : .none
return cell
}
In didSelect... toggle selected and reload the row
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selected = products[indexPath.row].selected
products[indexPath.row].selected = !selected
tableView.reloadRows(at: [indexPath], with: .none)
}
To get all selected items is very easy, too.
let selectedItems = products.filter{ $0.selected }
or get only the names
let selectedNames = products.filter{ $0.selected }.map{ $0.name }
There is no need at all to get any information from the view. The controller gets the information always from the model and uses tableview data source and delegate to update the view.
If you want to pass data to another view controller pass Product instances. They contain all relevant information.
I am trying to get an array of strings from JSON and I'm trying to figure out how to deal with it if the returned array is empty. In some cases, the returned value is [] and for other cases, the array contains string values. It is crashing because of unexpectedly finding a nil value.
For clarification, the gyms array is passed from another class and everything here works without the code for the images.
Here is my relevant code:
var gyms = [AnyObject]()
var imageArrays = [[String]?]()
In viewDidLoad()
getGymImages()
Methods to get JSON data:
func getGymImages() {
var index = 0
for dictionary in gyms {
let id = dictionary["id"] as! String
let urlString = String("https://gyminyapp.azurewebsites.net/api/GymImage/\(id)")
let url = NSURL(string: urlString)
let data = NSData(contentsOfURL: url!)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
for imageArray in json as! [AnyObject] {
imageArrays.append((imageArray as? [String])!)
}
} catch {
print("Error")
}
index += 1
}
addImagesToGyms()
}
func addImagesToGyms() {
var index = 0;
for array in imageArrays {
var dictionary = gyms[index] as! [String:AnyObject]
dictionary["images"] = array
gyms[index] = dictionary
index += 1
}
}
In cellForRowAtIndexPath()
let gymImages = dictionary["images"] as! [String]
if gymImages.count > 0 {
let firstImageURL = gymImages[0] as String
cell.cellImageView.sd_setImageWithURL(NSURL(string: firstImageURL))
}
EDIT: I was asked to show more of the file, so here it is.
import UIKit
class GymListTableViewController: UITableViewController {
var gyms = [AnyObject]()
var gymName: String?
var gymAddress: String?
var gymPhoneNumber: String?
var gymWebsite: String?
var gymID: String?
var gymLatitude: String?
var gymLongitude: String?
var maxDistance: Double?
var myLocation: CLLocation?
var milesArray = [Double]()
var imageArrays = [[String]?]()
var segmentedControl: UISegmentedControl?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Gyms"
tableView.registerNib(UINib(nibName: "GymListTableViewCell", bundle: nil), forCellReuseIdentifier: "gymCell")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "waypoint_map"), style: .Done, target: self, action: #selector(showMapView))
self.navigationItem.rightBarButtonItem?.tintColor = BarItems.greenTintColor
segmentedControl = UISegmentedControl(items: ["A-Z", "Z-A", "Rating", "Distance"])
segmentedControl?.sizeToFit()
segmentedControl?.selectedSegmentIndex = 0
segmentedControl!.setTitleTextAttributes([NSFontAttributeName: UIFont(name:"Helvetica-Light", size: 15)!],
forState: UIControlState.Normal)
segmentedControl?.addTarget(self, action: #selector(changeSelectedSegmentIndex), forControlEvents: .ValueChanged)
self.navigationItem.titleView = segmentedControl
sortAlphabetically()
let backgroundImage = UIImage(named: "gray_background")
let backgroundImageView = UIImageView(image: backgroundImage)
tableView.backgroundView = backgroundImageView
addDistancesToGyms()
getGymImages()
// geocodeAddresses()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addDistancesToGyms() {
var index = 0
for distance in milesArray {
var dictionary = gyms[index] as! [String:AnyObject]
dictionary["distance"] = distance
gyms[index] = dictionary
index += 1
}
}
func getGymImages() {
var index = 0
for dictionary in gyms {
let id = dictionary["id"] as! String
let urlString = String("https://gyminyapp.azurewebsites.net/api/GymImage/\(id)")
let url = NSURL(string: urlString)
let data = NSData(contentsOfURL: url!)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
for imageArray in json as! [AnyObject] {
imageArrays.append((imageArray as? [String])!)
}
} catch {
print("Error")
}
index += 1
}
addImagesToGyms()
}
func addImagesToGyms() {
var index = 0;
for array in imageArrays {
var dictionary = gyms[index] as! [String:AnyObject]
dictionary["images"] = array
gyms[index] = dictionary
index += 1
}
}
func changeSelectedSegmentIndex() {
let segmentTouched = segmentedControl?.selectedSegmentIndex
if segmentTouched == 0 {
sortAlphabetically()
} else if segmentTouched == 1 {
sortReverseAlphabetically()
} else if segmentTouched == 2 {
sortByRatingAscending()
} else {
sortByDistanceAscending()
}
}
func sortAlphabetically() {
gyms.sortInPlace{
(($0 as! Dictionary<String, AnyObject>)["name"] as? String) < (($1 as! Dictionary<String, AnyObject>)["name"] as? String)
}
tableView.reloadData()
}
func sortReverseAlphabetically() {
gyms.sortInPlace{
(($0 as! Dictionary<String, AnyObject>)["name"] as? String) > (($1 as! Dictionary<String, AnyObject>)["name"] as? String)
}
tableView.reloadData()
}
func sortByRatingAscending() {
// TODO: Sort by rating
}
func sortByDistanceAscending() {
gyms.sortInPlace{
(($0 as! Dictionary<String, AnyObject>)["distance"] as? Double) < (($1 as! Dictionary<String, AnyObject>)["distance"] as? Double)
}
tableView.reloadData()
}
func showMapView() {
self.performSegueWithIdentifier("displayMapSegue", sender: self.navigationController)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gyms.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 131
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("gymCell", forIndexPath: indexPath) as! GymListTableViewCell
let dictionary = gyms[indexPath.row]
let addressDictionary = dictionary["address"]
let street = addressDictionary!!["streetAddress"] as! String
let city = addressDictionary!!["city"] as! String
let state = addressDictionary!!["state"] as! String
let zipInt = addressDictionary!!["zipCode"] as! Int
let zipCode = String(zipInt)
let addressString = String("\(street) " + "\(city), " + "\(state) " + "\(zipCode)")
cell.backgroundColor = UIColor.clearColor()
cell.gymNameLabel.text = dictionary["name"] as? String
cell.gymAddressLabel.text = addressString
let miles = dictionary["distance"] as! Double
let milesString = String(format: "%.1f miles", miles)
let milesLabelString = milesString
cell.milesLabel.text = milesLabelString
let gymImages = dictionary["images"] as! [String]
if gymImages.count > 0 {
let firstImageURL = gymImages[0] as String
cell.cellImageView.sd_setImageWithURL(NSURL(string: firstImageURL))
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let dictionary = gyms[indexPath.row]
if dictionary["name"] as? String != nil {
self.gymName = dictionary["name"] as? String
}
let cell = tableView.cellForRowAtIndexPath(indexPath) as! GymListTableViewCell
self.gymAddress = cell.gymAddressLabel.text
if dictionary["phone"] as? String != nil {
self.gymPhoneNumber = dictionary["phone"] as? String
}
if dictionary["website"] as? String != nil {
self.gymWebsite = dictionary["website"] as? String
}
if dictionary["id"] as? String != nil {
self.gymID = dictionary["id"] as? String
}
if dictionary["latitude"] as? String != nil {
self.gymLatitude = dictionary["latitude"] as? String
}
if dictionary["longitude"] as? String != nil {
self.gymLongitude = dictionary["longitude"] as? String
}
self.performSegueWithIdentifier("detailFromListSegue", sender: self.navigationController)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detailFromListSegue" {
let gymDetailVC = segue.destinationViewController as! DetailTableViewController
if self.gymName != nil {
gymDetailVC.gymName = self.gymName
} else {
gymDetailVC.gymName = nil
}
if self.gymAddress != nil {
gymDetailVC.gymAddress = self.gymAddress
} else {
gymDetailVC.gymAddress = nil
}
if self.gymPhoneNumber != nil {
gymDetailVC.gymPhoneNumber = self.gymPhoneNumber
} else {
gymDetailVC.gymPhoneNumber = nil
}
if self.gymWebsite != nil {
gymDetailVC.gymWebsite = self.gymWebsite
} else {
gymDetailVC.gymWebsite = nil
}
if self.gymID != nil {
gymDetailVC.gymID = self.gymID!
} else {
// gymDetailVC.gymID = nil
}
if self.gymLatitude != nil {
gymDetailVC.gymLatitude = self.gymLatitude!
}
if self.gymLongitude != nil {
gymDetailVC.gymLongitude = self.gymLongitude!
}
}
}
}
numberOfRowsInSection should be returning gymImages.count if it isn't already.
Then as a safeguard you can always do
if indexPath.row < gymImages.count {
}
before accessing the content in cellForRowAtIndexPath
I have dynamically tableview with many section whitch is adding in run time by tap on button.
This button must send data from cells in last section (many type of custom cells).
How can i get cells or indexpath's of cells in last section?
I was trying to add these cells to array in cellForRowAtIndexPath, but i use dequeueReusableCellWithIdentifier to create this cells, so this is problematic.
Edit:
My code:
class ProcessViewController: UITableViewController, SWRevealViewControllerDelegate{
//this will be cell
struct field {
var name, type, id, hint, output, specialType:String
var selectOptions:NSMutableArray
var settings:NSArray
}
struct group {
var name:String
var fields:[field]
}
// this will be sections
struct block {
var groups:[group]
var id, name:String
}
var blocks:[block] = []
//fields in last (active) block
//var fields:[field] = []
//array of cells with some input
var cellsInTable:NSMutableArray = []
var cellWithCustomHeight:[NSIndexPath] = []
#IBOutlet var sendFormButton: UIButton!
var jsonData:NSDictionary?
#IBOutlet var menuButton: UIBarButtonItem!
var allfields:[field] = []
var numberOfOldCells = 0
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.barTintColor = UIColor(red: 62/255.0, green: 80/255.0, blue: 178/255.0, alpha: 1);
//print("json w srodku \(self.jsonData)")
if self.revealViewController() != nil {
self.revealViewController().delegate = self
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
//print(self.jsonData)
let data = self.jsonData?.valueForKey("data") as! NSMutableDictionary
//set title of the screen
self.title = data.valueForKey("name") as? String
//hide button if process is completed
if(data.valueForKey("progress") as! Int == 1){
sendFormButton.hidden = true
//print("asdasd")
}
parseData(data)
//print("Bloki: \(self.blocks)")
}
func parseData(data:NSMutableDictionary){
self.cellsInTable = []
//blocks is the sections in tableView, fields is a cells and groups (for now)
let blocks = data.valueForKey("blocks") as! NSMutableArray
self.blocks = []
self.allfields = []
blocks.enumerateObjectsUsingBlock {obj, i, stop in
//print( obj.valueForKey("input"))
var inputs:NSMutableArray = []
//get inputs from current block, if input is only one it is dictionary in swift
if let kinputs = obj.valueForKey("input") as? NSArray{
inputs = NSMutableArray(array:kinputs)
}else{
inputs.addObject(obj.valueForKey("input")!)
}
inputs.removeLastObject()
var outputs:NSArray = []
if let koutputs = obj.valueForKey("output") as? NSArray{
outputs = koutputs
}
//print("wrona \(outputs) kracze razy: \(outputs.count)")
var tmpGroups:[group] = []
//inupt is a group
inputs.enumerateObjectsUsingBlock({input, j, stop in
//print("input w petli: \(input)")
if(input.valueForKey("fields") != nil){
let forms = NSMutableArray(array:input.valueForKey("fields") as! NSArray)
var tmpFields:[field] = []
let groupField:field = field(name:
input.valueForKey("name") as! String,
type: "group",
id: "0",
hint: input.valueForKey("name") as! String,
output: "",
specialType: "group",
selectOptions: [],
settings:[]
)
tmpFields.append(groupField)
forms.enumerateObjectsUsingBlock({fieldObj, k, stop in
let fromId = fieldObj.valueForKey("id") as! String
var output:String = ""
let tmpOutputs = outputs.valueForKey(fromId) as! NSArray
print(tmpOutputs)
print(output)
if tmpOutputs.count != 0{
if let _ = tmpOutputs[0] as? NSString{
output = tmpOutputs[0] as! String
}
} else {
//print(outputs.valueForKey(String(k)))
}
let selectOptions = NSMutableArray(array: fieldObj.valueForKey("selectOptions") as! NSArray)
//print("asdasdad\(fieldObj)")
let tmpField:field = field(
name: fieldObj.valueForKey("name") as! String,
type: fieldObj.valueForKey("type") as! String,
id: fromId,
hint: fieldObj.valueForKey("hint") as! String,
output:output,
specialType: fieldObj.valueForKey("specialType") as! String,
selectOptions: selectOptions,
settings:fieldObj.valueForKey("settings") as! NSArray
)
tmpFields.append(tmpField)
})
let tmpGroup:group = group(name: input.valueForKey("name") as! String, fields: tmpFields)
tmpGroups.append(tmpGroup)
}
})
let tmpBlock:block = block(groups: tmpGroups,
id: obj.valueForKey("id") as! String,
name: obj.valueForKey("name") as! String
)
self.blocks.append(tmpBlock)
}
}
func revealController(revealController: SWRevealViewController!, willMoveToPosition position: FrontViewPosition) {
UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.blocks[section].name as String
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return blocks.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var formsInGroup:Int = 0;
for group in self.blocks[section].groups{
formsInGroup += group.fields.count
}
return formsInGroup
//return blocks[section].fields.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(self.cellWithCustomHeight.contains(indexPath)){
return CGFloat(132)
} else {
return CGFloat(47)
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//geting fields in current group
self.allfields = []
for group in self.blocks[indexPath.section].groups {
self.allfields.appendContentsOf(group.fields)
}
print("bloki \(self.blocks.count), sekcje: \(indexPath.section)")
//print(self.allfields.count)
let cellType = self.allfields[indexPath.row].type as String
//print("row: \(indexPath.row), sections: \(indexPath.section)")
switch cellType {
case "group":
let cell = tableView.dequeueReusableCellWithIdentifier("groupCell", forIndexPath: indexPath) as! groupCell
cell.groupName.text = self.allfields[indexPath.row].name
return cell
case "text":
if(self.allfields[indexPath.row].specialType == "date"){
let cell = tableView.dequeueReusableCellWithIdentifier("datePickerCell", forIndexPath: indexPath) as! datePickerCell
cell.hint.text = self.allfields[indexPath.row].name as String
let output = self.allfields[indexPath.row].output as String
cell.selectionStyle = UITableViewCellSelectionStyle.None
self.cellWithCustomHeight.append(indexPath)
if(output != ""){
print(self.allfields[indexPath.row].name)
//print( " output: \(output)")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-mm-yyyy"
let date = dateFormatter.dateFromString(self.allfields[indexPath.row].output)
cell.date.setDate(date!, animated: false)
cell.date.userInteractionEnabled = false
}
if !self.cellsInTable.containsObject(cell){
self.cellsInTable.addObject(cell)
}
setCellsToSend(indexPath.section)
return cell
}else{
let cell = tableView.dequeueReusableCellWithIdentifier("textCell", forIndexPath: indexPath) as! textCell
cell.hint.text = self.allfields[indexPath.row].name as String
let output = self.allfields[indexPath.row].output as String
cell.settings = self.allfields[indexPath.row].settings
if self.allfields[indexPath.row].specialType == "number" {
cell.input.keyboardType = UIKeyboardType.NumberPad
}
cell.input.text = ""
cell.selectionStyle = UITableViewCellSelectionStyle.None
if(output != ""){
//print(fields[indexPath.row].name)
//print(output)
cell.input.text = self.allfields[indexPath.row].output
cell.input.userInteractionEnabled = false
}
if !self.cellsInTable.containsObject(cell){
self.cellsInTable.addObject(cell)
} else {
print("kuuuuuurwa \(self.allfields[indexPath.row].name)")
}
setCellsToSend(indexPath.section)
return cell
}
case "checkbox":
let cell = tableView.dequeueReusableCellWithIdentifier("checkBoxCell", forIndexPath: indexPath) as! checkBoxCell
cell.selections = self.allfields[indexPath.row].selectOptions
cell.hint.text = self.allfields[indexPath.row].name as String
cell.settings = self.allfields[indexPath.row].settings
cell.indexPath = indexPath
cell.selectionStyle = UITableViewCellSelectionStyle.None
if !self.cellsInTable.containsObject(cell){
self.cellsInTable.addObject(cell)
} else {
print("kuuuuuurwa \(self.allfields[indexPath.row].name)")
}
setCellsToSend(indexPath.section)
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier("unknownCell", forIndexPath: indexPath)
cell.textLabel?.text = "niezaimplementowany typ pola: \(cellType)"
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
}
func setCellsToSend(sectionInTable:Int){
if(sectionInTable == self.blocks.count-2){
print("sekcja \(sectionInTable)")
self.numberOfOldCells = self.cellsInTable.count
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "showCheckBox"){
let checkBoxController = segue.destinationViewController as! CheckBoxController
let cell = sender as! checkBoxCell
//print(cell.settings)
checkBoxController.selections = cell.selections
checkBoxController.multiple = checkboxMultiValue(cell.settings)
checkBoxController.indexPath = cell.indexPath
checkBoxController.selected = cell.output
}
}
func checkboxMultiValue(settings:NSArray)->Bool{
var boolToReturn:Bool = false
settings.enumerateObjectsUsingBlock({obj, i, end in
if(obj.valueForKey("name") as! String == "multi_values"){
if( obj.valueForKey("checked") as! String == "multi_values"){
boolToReturn = true;
}
}
//print(i)
})
return boolToReturn
}
#IBAction func saveSelectedSelections(segue: UIStoryboardSegue) {
let checkBoxController = segue.sourceViewController as! CheckBoxController
let selectedRowsPath = checkBoxController.tableView.indexPathsForSelectedRows
var output:[String] = []
if(selectedRowsPath?.count > 0){
for rowPath in selectedRowsPath!{
let cell = checkBoxController.tableView.cellForRowAtIndexPath(rowPath) as! selectionCell
output.append(cell.nameLabel.text! as String)
}
}
let cell = self.tableView.cellForRowAtIndexPath(checkBoxController.indexPath!) as! checkBoxCell
cell.output = output
}
#IBAction func sendForm(sender: AnyObject) {
print("\(self.numberOfOldCells) i \(self.cellsInTable.count)")
var postData:Dictionary<Int, AnyObject> = [:]
var post = ""
var iterator:Int = 0
for var i = self.numberOfOldCells; i < self.cellsInTable.count; ++i{
if let cellText = self.cellsInTable[i] as? textCell{
//print("cellText \(cellText.input.text as String!)")
postData[iterator] = cellText.input.text as AnyObject!
post += "\(iterator):{'\(cellText.input.text! as String)'}&"
iterator++
} else if let cellCheckBox = self.cellsInTable[i] as? checkBoxCell{
//print(cellCheckBox.output)
let checkBoxOutput = cellCheckBox.output
var data:String = ""
for var i = 0; i < checkBoxOutput.count; ++i {
if ( i == 0) {
data += checkBoxOutput[i]
}else{
data += ";\(checkBoxOutput[i])"
}
}
post += "\(iterator):{'\(data)'}&"
postData[iterator] = data as AnyObject!
//postData.append(data as String!)
iterator++
}else if let cellDate = self.cellsInTable[i] as? datePickerCell{
//print(cellDate.date.date)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-mm-yyyy"
let date = dateFormatter.stringFromDate(cellDate.date.date)
postData[iterator] = date as AnyObject!
post += "\(iterator):{'\(date)'}&"
//postData.append(date as String!)
iterator++
}
}
//print("Post data:\(postData)")
//getNewBlock(NSKeyedArchiver.archivedDataWithRootObject(postData))
print(post)
getNewBlock(post.dataUsingEncoding(NSASCIIStringEncoding)!)
}
func getNewBlock(postData:NSData){
//print("Post data jako nsdata:\(postData)")
//var blockId = "a"
let blockId = blocks.last!.id
let url:NSURL = NSURL(string: "http://app.proces.io/Cloud/?Systems/Proces/Process/Block/makeAction/id-\(blockId)")!
print(url)
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
urlData, response, error in
var requestData: NSDictionary?
do{
requestData = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as? NSDictionary
//print(requestData)
if ( requestData != nil ) {
let success:NSInteger = requestData!.valueForKey("success") as! NSInteger
if(success == 1)
{
//print(self.blocks.count)
let data = requestData!.valueForKey("process") as! NSMutableDictionary
//print(self.allfields)
//self.numberOfOldCells = self.cellsInTable.count
//print(self.blocks)
self.allfields = []
self.parseData(data)
//print(self.blocks.count)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
} else {
print("cos poszlo nie tak \(requestData?.valueForKey("validation_errors")), values: \(requestData?.valueForKey("values"))")
}
}
} catch let error as NSError{
print("cos poszlo nie tak: \(error)")
}
}
task.resume()
}
Edit 2: minimal version with some explains:
class ProcessViewController: UITableViewController, SWRevealViewControllerDelegate{
//this will be cell
struct field {
var name, type, id, hint, output, specialType:String
var selectOptions:NSMutableArray
var settings:NSArray
}
struct group {
var name:String
var fields:[field]
}
// this will be sections
struct block {
var groups:[group]
var id, name:String
}
var blocks:[block] = []
var jsonData:NSDictionary?
#IBOutlet var menuButton: UIBarButtonItem!
var allfields:[field] = []
var numberOfOldCells = 0
override func viewDidLoad() {
super.viewDidLoad()
parseData(data)
}
func parseData(data:NSMutableDictionary){
//in this function i have a parsing data from json, whitch create me array of blocks (global variable "blocks")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.blocks[section].name as String
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return blocks.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var formsInGroup:Int = 0;
for group in self.blocks[section].groups{
formsInGroup += group.fields.count
}
return formsInGroup
//return blocks[section].fields.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(self.cellWithCustomHeight.contains(indexPath)){
return CGFloat(132)
} else {
return CGFloat(47)
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//geting fields in current group
self.allfields = []
for group in self.blocks[indexPath.section].groups {
self.allfields.appendContentsOf(group.fields)
}
let cellType = self.allfields[indexPath.row].type as String
switch cellType {
case "group":
let cell = tableView.dequeueReusableCellWithIdentifier("groupCell", forIndexPath: indexPath) as! groupCell
cell.groupName.text = self.allfields[indexPath.row].name
return cell
case "text":
if(self.allfields[indexPath.row].specialType == "date"){
let cell = tableView.dequeueReusableCellWithIdentifier("datePickerCell", forIndexPath: indexPath) as! datePickerCell
cell.hint.text = self.allfields[indexPath.row].name as String
let output = self.allfields[indexPath.row].output as String
cell.selectionStyle = UITableViewCellSelectionStyle.None
self.cellWithCustomHeight.append(indexPath)
if(output != ""){
print(self.allfields[indexPath.row].name)
//print( " output: \(output)")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-mm-yyyy"
let date = dateFormatter.dateFromString(self.allfields[indexPath.row].output)
cell.date.setDate(date!, animated: false)
cell.date.userInteractionEnabled = false
}
return cell
}else{
let cell = tableView.dequeueReusableCellWithIdentifier("textCell", forIndexPath: indexPath) as! textCell
cell.hint.text = self.allfields[indexPath.row].name as String
let output = self.allfields[indexPath.row].output as String
cell.settings = self.allfields[indexPath.row].settings
if self.allfields[indexPath.row].specialType == "number" {
cell.input.keyboardType = UIKeyboardType.NumberPad
}
cell.input.text = ""
cell.selectionStyle = UITableViewCellSelectionStyle.None
if(output != ""){
cell.input.text = self.allfields[indexPath.row].output
cell.input.userInteractionEnabled = false
}
return cell
}
case "checkbox":
let cell = tableView.dequeueReusableCellWithIdentifier("checkBoxCell", forIndexPath: indexPath) as! checkBoxCell
cell.selections = self.allfields[indexPath.row].selectOptions
cell.hint.text = self.allfields[indexPath.row].name as String
cell.settings = self.allfields[indexPath.row].settings
cell.indexPath = indexPath
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier("unknownCell", forIndexPath: indexPath)
cell.textLabel?.text = "niezaimplementowany typ pola: \(cellType)"
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
}
#IBAction func sendForm(sender: AnyObject) {
// in this function i must send data from cells in last section and add new section on the basis of request
}
This my code to filter data from my CoreData and it provides the corrected data but if I go to details of the record it gives me the wrong data.
Meaning I have detailed VC that shows a larger image of the camera. So if the index is lets say 1 with the filter data but the real index of the camera in index one is really 20 in CoreData. How can I correct for this issue?
func fetch() {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// Ref data
let context: NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest(entityName: "Cameras")
let predicate = NSPredicate(format: "locationname == %#", "lobby")
freq.predicate = predicate
let fetchResults = try! context.executeFetchRequest(freq) as? [NSManagedObject]
filteredData.removeAll(keepCapacity: false)
filteredData = fetchResults!
searchActive = true;
}
UPDATE
Request updated information.
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchActive {
return filteredData.count
} else {
return myData.count
}
}
Next item.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cameraCell", forIndexPath: indexPath) as! camerasTableViewCell
if searchActive {
let data = filteredData[indexPath.row]
cell.nameLabel.text = data.valueForKey("name") as? String
cell.roadName.text = data.valueForKey("locationname") as? String
let CamImage = data.valueForKey("dImage") as! NSData
let CameraImage: UIImage = UIImage(data: CamImage)!
cell.imageUrl?.image = CameraImage
} else {
let data = myData[indexPath.row]
cell.nameLabel.text = data.valueForKey("name") as? String
cell.roadName.text = data.valueForKey("locationname") as? String
let CamImage = data.valueForKey("dImage") as! NSData
let CameraImage: UIImage = UIImage(data: CamImage)!
cell.imageUrl?.image = CameraImage
}
return cell
}
Next item
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let selectedIndexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!
let vc = segue.destinationViewController as! largeCameraViewController
vc.row = selectedIndexPath.row
}
You should pass the object itself in prepareForSegue, not the row. Add a property to your LargeCameraViewController:
var camera : NSManagedObject?
Then in prepareForSegue, obtain the camera from the relevant row of either filteredData or myData, depending on whether searchActive is true or false:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let selectedIndexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!
let vc = segue.destinationViewController as! largeCameraViewController
if (searchActive) {
vc.camera = filteredData[selectedIndexPath.row] as! NSManagedObject
} else {
vc.camera = myData[selectedIndexPath.row] as! NSManagedObject
}
}
Then in LargeCameraViewController you can access the relevant attributes from the camera NSManagedObject.