I have to retrieve images from Parse, and I am working on this code:
class ViewControllerHome: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var MessageTable: UITableView!
let color = UIColor(red: 0.0/255.0, green: 105.0/255.0, blue: 92.0/255.0, alpha: 1)
let colore = UIColor.whiteColor()
let coloree = UIColor(red: 33.0/255.0, green: 33.0/255.0, blue: 33.0/255.0, alpha: 1)
var Username = [String]()
var Image = [PFFile]()
var Likes = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
var refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: Selector("refreshPulled"), forControlEvents: UIControlEvents.ValueChanged)
loadData()
self.MessageTable.reloadData()
self.navigationController?.navigationBar.barTintColor = color
self.navigationController?.navigationBar.tintColor = colore
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: colore]
UITabBar.appearance().barTintColor = coloree
UITabBar.appearance().tintColor = colore
UITabBar.appearance().translucent = false
self.MessageTable.delegate = self
self.MessageTable.dataSource = self
func refreshPulled() {
loadData()
self.MessageTable.reloadData()
refreshControl.endRefreshing()
}
}
func loadData() {
let query = PFQuery(className: "Messages")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil) {
if let posts = posts as [PFObject]? {
for post in posts{
self.Image.append(post["Post"] as! PFFile)
self.Username.append(post["Name"] as! String)
self.Likes.append(post["Vote"] as! Int)
}
}
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.MessageTable.dequeueReusableCellWithIdentifier("cell")! as! TableViewCellHome
var imagesToLoad = self.Image[indexPath.row] as PFFile
var imagesUser = self.Username[indexPath.row] as String
var imageLikes = self.Likes[indexPath.row] as Int
//This line gives me an error: call can throw, but is not marked with 'try' and the error is not handled
var imagesdata = imagesToLoad.getData()
var finalizedImage = UIImage(data: imagesdata)
cell.PostImage.image = finalizedImage
cell.UsernameLabel.text = imagesUser
cell.LikesLabel.text = "\(imageLikes)"
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Username.count
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
This code should get and display Image, string and Int Value from parse's backend. The problem is that nothing is displayed. How can I change the code so that this will display correctly? There is also an error at the line:
var imagesdata = imagesToLoad.getData()
This line tells me
call can throw, but is not marked with 'try' and the error is not handled
Thanks in advance to anyone that can help me solve this problem.
Related
I'm trying to using CallKit to add a feature to my app to add some phone numbers to blacklist!
the code below is my whole view!!
class BlacklistViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate {
var phoneNumbersArrCoreData = [BlockedPhoneNumbers]()
var listPhoneNumbers:[CXCallDirectoryPhoneNumber] = []
#IBOutlet weak var TableView: UITableView!
#IBOutlet weak var BtnAddO: UIButton!
#IBOutlet weak var EntPhonenumber: UITextField!
#IBAction func BtnAddA(_ sender: Any) {
if !(EntPhonenumber.text?.isEmpty)!
{
let blackedPhonenumbers_CoreData = BlockedPhoneNumbers(context: PersistanceService.context)
blackedPhonenumbers_CoreData.phoneNumber = Int64.init(EntPhonenumber.text!)!
PersistanceService.saveContext()
getCoreData()
TableView.reloadData()
}
}
var coreData = [BlockedPhoneNumbers]()
func getCoreData()
{
listPhoneNumbers.removeAll()
let fetchRequest : NSFetchRequest<BlockedPhoneNumbers> = BlockedPhoneNumbers.fetchRequest()
do
{
let FetchedResultFromDB = try PersistanceService.context.fetch(fetchRequest)
coreData = FetchedResultFromDB
print("============\n===========\n")
if coreData.count > 0
{
for i in 0..<coreData.count
{
listPhoneNumbers.append(coreData[i].phoneNumber)
}
}
print("============\n===========\n")
}
catch{
print("gettin blocked number from db got error")
}
}
override func viewDidLoad() {
BtnAddO.layer.cornerRadius = 5
BtnAddO.layer.borderColor = UIColor.white.cgColor
BtnAddO.layer.borderWidth = 0.8
EntPhonenumber.attributedPlaceholder = NSAttributedString(string: "Enter a phone number to block",attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightText])
getCoreData()
super.viewDidLoad()
view.backgroundColor = UIColor.init(red: 25/255, green: 28/255, blue: 46/255, alpha: 1)
TableView.delegate = self
TableView.dataSource = self
}
func beginRequest(with context: CXCallDirectoryExtensionContext) {
getCoreData()
let blockedPhoneNumbers: [CXCallDirectoryPhoneNumber] = listPhoneNumbers
for phoneNumber in blockedPhoneNumbers.sorted(by: <) {
context.addBlockingEntry(withNextSequentialPhoneNumber: phoneNumber)
}
context.completeRequest()
}
//MARK: - TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listPhoneNumbers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BlackListCell") as? BlackListTableViewCell
cell?.ContactImg.layer.masksToBounds = true
cell?.mainView.layer.cornerRadius = 10
cell?.mainView.backgroundColor = UIColor(red: 42/255, green: 48/255, blue: 66/255, alpha: 1)
cell?.ContactImg.layer.cornerRadius = 5
cell?.ContactImg.image = UIImage(named: "Blocked")
cell?.unBlock.imageView?.image = nil
cell?.unBlock.setTitle("UNBLOCK", for: UIControl.State.normal)
cell?.unBlock.layer.cornerRadius = (cell?.unBlock.frame.size.height)!/2
cell?.SetUnblockBtn {
I get the error here,below
let context:NSManagedObjectContext = PersistanceService.context
context.delete(self.phoneNumbersArrCoreData[indexPath.row] as NSManagedObject)
self.phoneNumbersArrCoreData.remove(at: indexPath.row)
print("data deleted!!!")
}
cell?.phoneNumber.text = String(listPhoneNumbers[indexPath.row])
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
}
to explain the code, I save each number that user will enter in a core data(entityName: BlockedPhoneNumbers). I'm not sure even if this is the right way to save numbers that they need to be blocked or not!!
when the user presses the button I save the number and it works fine( but I'm not sure if this is the right way or not!!).
and in getCoreData I get the core data and show them in a table view. which shows that core data works fine! but when user wanna unblock the contact and presses the button in CELL of the table view, I get an error and app crash and it says:
Thread 1: Fatal error: Index out of range
my problems are:
why do I get this error?
2.as I can not find any tutorial for callKit I believe that I'm doing this job wrong.
could anyone help me with this?
You have too many arrays:
listPhoneNumbers which contains your integer numbers
coreData which contains your Core Data items
phoneNumbersArrCoreData which could contain your Core Data items, but you don't add anything to it.
As a result, phoneNumbersArrCoreData is empty. When you try and remove an object from the empty array you get an array bounds exception.
You should eliminate two of the three arrays.
class BlacklistViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate {
var blockedNumbers = [BlockedPhoneNumbers]()
#IBOutlet weak var TableView: UITableView!
#IBOutlet weak var BtnAddO: UIButton!
#IBOutlet weak var EntPhonenumber: UITextField!
#IBAction func BtnAddA(_ sender: Any) {
if !(EntPhonenumber.text?.isEmpty)!
{
let blackedPhonenumbers_CoreData = BlockedPhoneNumbers(context: PersistanceService.context)
blackedPhonenumbers_CoreData.phoneNumber = Int64.init(EntPhonenumber.text!)!
PersistanceService.saveContext()
getCoreData()
TableView.reloadData()
}
}
func getCoreData()
{
let fetchRequest : NSFetchRequest<BlockedPhoneNumbers> = BlockedPhoneNumbers.fetchRequest()
do
{
let FetchedResultFromDB = try PersistanceService.context.fetch(fetchRequest)
blockedNumbers = FetchedResultFromDB
print("============\n===========\n")
}
catch{
print("gettin blocked number from db got error")
}
}
override func viewDidLoad() {
BtnAddO.layer.cornerRadius = 5
BtnAddO.layer.borderColor = UIColor.white.cgColor
BtnAddO.layer.borderWidth = 0.8
EntPhonenumber.attributedPlaceholder = NSAttributedString(string: "Enter a phone number to block",attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightText])
getCoreData()
super.viewDidLoad()
view.backgroundColor = UIColor.init(red: 25/255, green: 28/255, blue: 46/255, alpha: 1)
TableView.delegate = self
TableView.dataSource = self
}
//MARK: - TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return blockedNumbers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BlackListCell") as? BlackListTableViewCell
cell?.ContactImg.layer.masksToBounds = true
cell?.mainView.layer.cornerRadius = 10
cell?.mainView.backgroundColor = UIColor(red: 42/255, green: 48/255, blue: 66/255, alpha: 1)
cell?.ContactImg.layer.cornerRadius = 5
cell?.ContactImg.image = UIImage(named: "Blocked")
cell?.unBlock.imageView?.image = nil
cell?.unBlock.setTitle("UNBLOCK", for: UIControl.State.normal)
cell?.unBlock.layer.cornerRadius = (cell?.unBlock.frame.size.height)!/2
cell?.SetUnblockBtn {
let context:NSManagedObjectContext = PersistanceService.context
context.delete(self.blockedNumbers[indexPath.row] as NSManagedObject)
self.phoneNumbersArrCoreData.remove(at: indexPath.row)
print("data deleted!!!")
}
cell?.phoneNumber.text = blockedNumbers[indexPath.row].phoneNumber
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
}
The code to actually load data into the Call Kit block list needs to go into a CallKit extension in your app. You will need to use an application group to share the Core Data store with the extension.
I have a SWRevealViewController Application. I have been unsuccessfully trying to set the background color with self.view.backgroundColor. The specific example i show below is a UIViewController that contains a tableView with a empty UIView() footer to stop the tableView when it is finished. I am trying to set the backgroundColor to fill the remaining space. My code below.
import UIKit
class NewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSXMLParserDelegate {
#IBOutlet weak var tables: UITableView!
var parser: NSXMLParser = NSXMLParser()
var info: [newsarticle] = []
var postTitle: String = String()
var postDesc: String = String()
var eName: String = String()
var index: Int = Int()
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
var refreshControl: UIRefreshControl!
override func viewDidLoad() {
let navicon = UIButton(type: UIButtonType.System)
navicon.setImage(defaultMenuImage(), forState: UIControlState.Normal)
navicon.frame = CGRectMake(0, 0, 30, 30)
let menu = UIBarButtonItem(customView: navicon)
self.navigationItem.leftBarButtonItem = menu
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
navicon.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), forControlEvents: .TouchUpInside)
let url:NSURL = NSURL(string: "http://brrsd.k12.nj.us/rss/News.xml")!
parser = NSXMLParser(contentsOfURL: url)!
parser.delegate = self
parser.parse()
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(NewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
tables.separatorColor = UIColor.init(red: 217/255, green: 180/255, blue: 74/255, alpha: 1)
tables.addSubview(refreshControl)
//background.frame = self.view.frame
tables.tableFooterView = UIView()
self.view.backgroundColor = UIColor.init(red: 241/255, green: 241/255, blue: 242/255, alpha: 1)self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
func refresh(sender: AnyObject)
{
info = [newsarticle]()
let url:NSURL = NSURL(string: "http://brrsd.k12.nj.us/rss/News.xml")!
parser = NSXMLParser(contentsOfURL: url)!
parser.delegate = self
parser.parse()
tables.reloadData()
refreshControl.endRefreshing()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60;
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI namespaceURI: String?, qualifiedName qualifiedName: String?, attributes attributeDict: [String : String])
{
eName = elementName
if elementName == "item" {
postTitle = String()
postDesc = String()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return info.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
if let reusedCell = tableView.dequeueReusableCellWithIdentifier("Cell") {
cell = reusedCell
} else {
cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell")
}
let news: newsarticle = info[indexPath.row]
if let label = cell.textLabel {
label.text = news.title
}
cell.backgroundColor = UIColor.init(red: 241/255, green: 241/255, blue: 242/255, alpha: 1)
cell.textLabel!.font = UIFont(name:"Bodoni 72", size: 16)
cell.textLabel!.textColor = UIColor.init(red: 25/255, green: 149/255, blue: 173/255, alpha: 1)
return cell }
func parser(parser: NSXMLParser, foundCharacters string: String) {
let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if (!data.isEmpty) {
if eName == "title" {
postTitle += data
} else if eName == "description" {
postDesc += data
}
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "item" {
let newsart: newsarticle = newsarticle()
newsart.title = postTitle
newsart.description = postDesc
info.append(newsart)
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
index = indexPath.row
tables.deselectRowAtIndexPath(indexPath, animated:true)
performSegueWithIdentifier("NewsTransfer", sender:self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let Destination: FullNews = segue.destinationViewController as! FullNews
Destination.info = info[index]
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
In your viewDidLoad method, you have:
tables.tableFooterView = UIView()
Try this instead:
tables.tableFooterView = UIView(frame: CGRectZero)
Also, for the next line (the background color), try this:
self.view.window!.backgroundColor = UIColor(red: 241/255, green: 241/255, blue: 242/255, alpha: 1.0)
Okay, so I'm not sure whats been happening with my Table view, but it seems to act a bit strange now that I load images from parse onto it. At first, it ran smoothly, but now that I'm working in ios 9, the scrolling is horrible
Optimizations I've used to reduce this(Keep in mind they do not really help.)
-Removed transparent objects and set them to default background
-reused table cells
-Tried to use lower quality images
Here is my code
import UIKit
class mainVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var resultsTable: UITableView!
#IBOutlet weak var menuButton:UIBarButtonItem!
var deleteArray = [String]()
var followArray = [String]()
var resultsLocationArray = [String]()
var datetextfielArray = [String]()
var imageDates = [String]()
var resultsNameArray = [String]()
var resulltsImageFiles = [PFFile]()
var resultsTweetArray = [String]()
var resultsHasImageArray = [String]()
var resultsTweetImageFiles = [PFFile?]()
var refresher:UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
// Uncomment to change the width of menu
//self.revealViewController().rearViewRevealWidth = 62
}
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
resultsTable.frame = CGRectMake(0, 0, theWidth, theHeight)
let tweetBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: Selector("tweetBtn_click"))
let searchBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: Selector("searchBtn_click"))
let buttonArray = NSArray(objects: tweetBtn, searchBtn)
self.navigationItem.rightBarButtonItems = buttonArray as? [UIBarButtonItem]
refresher = UIRefreshControl()
refresher.tintColor = UIColor.blackColor()
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.resultsTable.addSubview(refresher)
}
func refresh() {
print("refresh table")
refreshResults()
}
func refreshResults() {
followArray.removeAll(keepCapacity: false)
resultsNameArray.removeAll(keepCapacity: false)
resulltsImageFiles.removeAll(keepCapacity: false)
resultsTweetArray.removeAll(keepCapacity: false)
resultsLocationArray.removeAll(keepCapacity: false)
resultsHasImageArray.removeAll(keepCapacity: false)
resultsTweetImageFiles.removeAll(keepCapacity: false)
datetextfielArray.removeAll(keepCapacity: false)
let followQuery = PFQuery(className: "follow")
followQuery.whereKey("user", equalTo: PFUser.currentUser()!.username!)
followQuery.addDescendingOrder("createdAt")
let objects = followQuery.findObjects()
for object in objects! {
self.followArray.append(object.objectForKey("userToFollow") as! String)
}
let query:PFQuery = PFQuery(className: "tweets")
query.whereKey("userName", containedIn: followArray)
query.addDescendingOrder("createdAt")
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
for object in objects! {
self.resultsNameArray.append(object.objectForKey("profileName") as! String)
self.resulltsImageFiles.append(object.objectForKey("photo") as! PFFile)
self.resultsTweetArray.append(object.objectForKey("tweet") as! String)
//resultsLocationArray
self.resultsLocationArray.append(object.objectForKey("tweetlocation") as! String)
self.resultsHasImageArray.append(object.objectForKey("hasImage") as! String)
self.resultsTweetImageFiles.append(object.objectForKey("tweetImage") as? PFFile)
self.datetextfielArray.append(object.objectForKey("datetextfield") as! String)
self.resultsTable.reloadData()
}
self.refresher.endRefreshing()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBarHidden = false
super.viewWillAppear(animated)
let nav = self.navigationController?.navigationBar
nav?.barStyle = UIBarStyle.Black
nav?.tintColor = UIColor.whiteColor()
nav?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationItem.hidesBackButton = true
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func viewDidAppear(animated: Bool) {
refreshResults()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsNameArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if resultsHasImageArray[indexPath.row] == "yes" {
return self.view.frame.size.width + 130
} else {
return 130
}
}
//var theDtS = dtFormater.stringFromDate(self.dateArray[i])
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:mainCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! mainCell
cell.tweetImg.hidden = true
cell.locationTxt.text = self.resultsLocationArray[indexPath.row]
cell.profileLbl.text = self.resultsNameArray[indexPath.row]
cell.messageTxt.text = self.resultsTweetArray[indexPath.row]
cell.datetextfield.text = self.datetextfielArray[indexPath.row]
resulltsImageFiles[indexPath.row].getDataInBackgroundWithBlock {
(imageData:NSData?, error:NSError?) -> Void in
//resultsLocationArray
if error == nil {
let image = UIImage(data: imageData!)
cell.imgView.image = image
}
}
if resultsHasImageArray[indexPath.row] == "yes" {
let theWidth = view.frame.size.width
cell.tweetImg.frame = CGRectMake(0, 0, theWidth, theWidth)
cell.tweetImg.hidden = false
resultsTweetImageFiles[indexPath.row]?.getDataInBackgroundWithBlock({
(imageData:NSData?, error:NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.tweetImg.image = image
}
})
}
return cell
}
func tweetBtn_click() {
print("tweet pressed")
self.performSegueWithIdentifier("gotoTweetVCFromMainVC", sender: self)
}
func searchBtn_click() {
print("search pressed")
self.performSegueWithIdentifier("gotoUsersVCFromMainVC", sender: self)
}
}
Good afternoon,
I'm trying to show a UIView when (in my case) there isn't any result to show in a tableView filled with products. When I detect 0 products, I show a UIView which contains a Label, a TextField and a Button, but I can't interact with my TextField and neither with the Button.
It's my first time using this technique to show a UIView when something went wrong with the tableView so I would like to know what's wrong in my code and what I'm missing because it's really weird.
Here is my code (when I print "Product not found" is where I show the UIView):
import UIKit
import Social
class ProductoCamViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var productoImageView:UIImageView!
#IBOutlet var tableView:UITableView!
#IBOutlet weak var noEncontrado:UIView!
var productoImage:String!
var ean:String!
var producto:Producto!
var productos = [Producto]()
#IBOutlet weak var toolBar: UIToolbar!
#IBOutlet weak var cargando: UIActivityIndicatorView!
override func viewDidLoad() {
toolBar.hidden = true
noEncontrado.hidden = true
cargando.hidden = false
super.viewDidLoad()
// Set table view background color
self.tableView.backgroundColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.2)
// Remove extra separator
self.tableView.tableFooterView = UIView(frame: CGRectZero)
// Change separator color
self.tableView.separatorColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.8)
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 88.0
requestPost()
cargando.hidden = true
tableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.hidesBarsOnSwipe = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func requestPost () {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.mywebsite.com/product.php")!)
request.HTTPMethod = "POST"
let postString = "ean="+ean
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// JSON RESULTADO ENTERO
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
if (responseString == "Product not found")
{
self.noEncontrado.hidden = false
self.tableView.reloadData()
return
}
else
{
self.productos = self.parseJsonData(data!)
self.toolBar.hidden = false
// Reload table view
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}
task.resume()
}
func parseJsonData(data: NSData) -> [Producto] {
var productos = [Producto]()
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
noEncontrado.hidden = true
// Parse JSON data
let jsonProductos = jsonResult?["lista_productos"] as! [AnyObject]
for jsonProducto in jsonProductos {
let producto = Producto()
producto.imagen = jsonProducto["imagen"] as! String
producto.nombre = jsonProducto["nombre"] as! String
producto.descripcion = jsonProducto["descripcion"] as! String
producto.modo_de_empleo = jsonProducto["modo_de_empleo"] as! String
producto.marca = jsonProducto["marca"] as! String
producto.linea = jsonProducto["linea"] as! String
producto.distribuidor = jsonProducto["distribuidor"] as! String
producto.tamano = jsonProducto["tamano"] as! String
producto.precio = jsonProducto["precio"] as! String
producto.codigo_nacional = jsonProducto["codigo_nacional"] as! String
productos.append(producto)
}
}
catch let parseError {
print(parseError)
}
return productos
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return productos.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
title = productos[indexPath.row].nombre
let cell = tableView.dequeueReusableCellWithIdentifier("CellDetail", forIndexPath: indexPath) as! ProductoTableViewCell
cell.selectionStyle = .None
if let url = NSURL(string: productos[indexPath.row].imagen) {
if let data = NSData(contentsOfURL: url) {
self.productoImageView.image = UIImage(data: data)
}
}
cell.nombre.text = productos[indexPath.row].nombre
cell.descripcion.text = productos[indexPath.row].descripcion
cell.modo_de_empleo.text = productos[indexPath.row].modo_de_empleo
cell.marca.text = productos[indexPath.row].marca
cell.linea.text = productos[indexPath.row].linea
cell.distribuidor.text = productos[indexPath.row].distribuidor
cell.tamano.text = productos[indexPath.row].tamano
cell.precio.text = productos[indexPath.row].precio
cell.codigo_nacional.text = productos[indexPath.row].codigo_nacional
cell.layoutIfNeeded()
return cell
}
}
Thanks in advance.
At first, please try to provide english code :) but anyways. I think the view what should appear is nonEncontrado.
There could be some issues but i need to see the storyboard.
The view has userInteraction not enabled. Its a property and can also be activated in the storyboard
The view is overlayed by something else. Maybe the empty tableView.
As an suggestion you could provide this fields in the tableView and just load another DataSource. Than you dont need to fight with extra views. If you provide screens from the Storyboard i could help a bit more.
Good Luck :)
I tried to reverse my table view in the view did load method by reversing the arrays but it's not working. I'm trying to make it so that it sorts the feed from the time it was created from top to bottom. Am I doing it wrong? If so what should I do?
class Feed: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var table: UITableView!
#IBOutlet var feedBar: UINavigationBar!
var titles = [String]()
var messages = [String]()
var usernames = [String]()
var types = [String]()
override func viewDidLoad() {
super.viewDidLoad()
table.dataSource = self
messages.reverse()
titles.reverse()
usernames.reverse()
types.reverse()
}
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
override func viewDidAppear(animated: Bool) {
println("View appeared")
self.messages.removeAll(keepCapacity: true)
self.titles.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
self.types.removeAll(keepCapacity: true)
var postQuery = PFQuery(className: "Post")
postQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.messages.append(object["message"] as! String)
self.titles.append(object["title"] as! String)
self.usernames.append(object["username"] as! String)
self.types.append(object["type"] as! String)
self.table.reloadData()
}
}
})
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let postCell = tableView.dequeueReusableCellWithIdentifier("feedPost", forIndexPath: indexPath) as! PostCell
var post = PFObject(className: "Post")
if messages.isEmpty == false {
postCell.message.text = messages[indexPath.row]
}
if titles.isEmpty == false {
postCell.postTtitle.text = titles[indexPath.row]
}
if usernames.isEmpty == false {
postCell.posterName.setTitle(usernames[indexPath.row], forState: .Normal)
}
if self.types[indexPath.row] == "post1" {
postCell.sideLeft.backgroundColor = self.UIColorFromRGB(0xFCFFBD)
postCell.sideRight.backgroundColor = self.UIColorFromRGB(0xFCFFBD)
} else if self.types[indexPath.row] == "post2" {
postCell.sideLeft.backgroundColor = self.UIColorFromRGB(0xFFB4AC)
postCell.sideRight.backgroundColor = self.UIColorFromRGB(0xFFB4AC)
} else if self.types[indexPath.row] == "post3" {
postCell.sideLeft.backgroundColor = self.UIColorFromRGB(0xFFD5A4)
postCell.sideRight.backgroundColor = self.UIColorFromRGB(0xFFD5A4)
}
postCell.selectionStyle = .None
postCell.message.scrollRangeToVisible(NSMakeRange(0, 0))
return postCell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return usernames.count
}
}
Observe that in the view's life cycle the viewDidAppear gets called after your viewDidLoad method. It appears that you try to reload the contents from within your viewDidAppear method, and there you are clearing those arrays which you had reversed earlier in viewDidLoad. This is the reason why you are not seeing any effect. You might want to reverse your arrays there.
You are reversing array in viewDidLoad, but you append something in viewDidAppear. viewDidAppear call after viewDidLoad. You should reverse array in the end of viewDidAppear before call self.table.reloadData()
override func viewDidAppear(animated: Bool) {
println("View appeared")
self.messages.removeAll(keepCapacity: true)
self.titles.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
self.types.removeAll(keepCapacity: true)
var postQuery = PFQuery(className: "Post")
postQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.messages.append(object["message"] as! String)
self.titles.append(object["title"] as! String)
self.usernames.append(object["username"] as! String)
self.types.append(object["type"] as! String)
}
messages.reverse()
titles.reverse()
usernames.reverse()
types.reverse()
self.table.reloadData()
}
})
}
I figured it out what I did was I did this instead of append...
self.messages.insert(object["message"] as! String, atIndex: 0)
What this basically does is appends the newest message to the beginning of the array.