Prepare for segue not sending all of the information (Swift) - ios

When trying to pass String variables to a new ViewController, only one of the variables is being sent. I'm not sure what is going on here, because when I print object["eventDescription"], the console does indeed print the description. Only eventName is being passed to the new view controller.
Sending view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "detailSegue") {
if let destination = segue.destinationViewController as? EventDetailViewController {
if let eventIndex = self.tableView.indexPathForCell(sender as! FeedCustomCell) {
var object = self.eventsArray[eventIndex.row]
destination.nameText = object["eventName"] as! String
destination.descriptionText = object["eventDescription"] as! String
print(object["eventDescription"])
The destination view controller (EventDetailViewController):
class EventDetailViewController: UIViewController {
#IBOutlet weak var eventName: UILabel!
#IBOutlet weak var descLabel: UILabel!
var descriptionText = String()
var nameText = String()
override func viewDidLoad() {
super.viewDidLoad()
self.eventName.text = nameText
self.descLabel.text = descriptionText
}
}

Sorry for wasting anybody's time, but I had to place constraints onto the description UILabel in the EventDetailController, and then I could see the description.

Related

Expression resolves to an unused property

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetails" {
if let indexPath = sender as? IndexPath {
if let nextVC = segue.destination as? JobDetailViewController {
let valueToPass = jobs[indexPath.row].text <- Thread1
let passUserName = jobs[indexPath.row].addedByUser
nextVC.jobDetail.text = valueToPass
nextVC.userLabel.text = passUserName
}
}
}
}
EDIT: I'm now getting "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" as an Error.
This is the code of my DestinationVC
#IBOutlet weak var jobDetail: RoundLabel!
#IBOutlet weak var userLabel: UILabel!
var valueToPass: String = ""
var passUserName: String!
override func viewDidLoad() {
super.viewDidLoad()
jobDetail.text = valueToPass
userLabel.text = passUserName
}
}
Expression resolves to an unused property
This error means, that you wrote code with reference for some property of some item in jobs array, but you haven't done anything with it (declare some constant, change some variable, etc.)
You probably just wanted to declare Job item for specific row, so you can do it like this
let job = jobs[indexPath.row]

Swift 3 Data from main Controller to view controller with Firebase and segue

I'm new to ios dev and i'm trying to develop my first app! :)
so far so good...
Now I'm trying to pass data from main controller to the item details view.
It seems i can't figure out what i'm doing wrong but i keep getting an error:
"fatal error: unexpectedly found nil while unwrapping an Optional value"
now i understand that the value is not assigned but i don't understand why...
here's my code:
-------> MainVC
struct Ananlysys {
var descrizione: String!
var data: String!
var immagine: String!
var seganle: String!
var oraUpload: String!
var valuta: String!
}
var analysisList = [Ananlysys]()
var alertsRef = FIRDatabase.database().reference().child("analisi")
override func viewDidLoad() {
super.viewDidLoad()
fetchDataFromDB()
}
func fetchDataFromDB(){
alertsRef.observe(.childAdded, with: { snapshot in
if let dict = snapshot.value as? [String: AnyObject] {
let descrizione = dict["descrizione"] as! String
let data = dict["data"] as! String
let stato = dict["stato"] as! String
let immagine = dict["imageURL"] as! String
let seganle = dict["segnale"] as! String
let oraUpload = dict["oraupload"] as! String
let valuta = dict["valuta"] as! String
self.analysisList.insert(Ananlysys(descrizione: descrizione,
data:data, immagine:immagine, seganle: seganle, oraUpload: oraUpload,
valuta: valuta), at: 0)
self.tableView.reloadData()
}
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ItemDetailVC"{
if let indexPath = self.tableView.indexPathForSelectedRow {
let destination = segue.destination as! ItemDetailVC
let cell = tableView.cellForRow(at: indexPath) as? ItemCell
destination.valuta = (cell?.valutaLabel.text)!
destination.segnale = (cell?.signalLabel.text)!
destination.desc = (cell?.descriptionLabel.text)!
destination.immagine = (cell?.imageThumb.image)!
}
}
And in My ItemDetailsVC controller (which is the destination) i've just created the IBoutlet. Here' the code:
class ItemDetailVC: OpenAlertsVC {
#IBOutlet weak var crossLabel: UILabel!
#IBOutlet weak var signalLbl: UILabel!
#IBOutlet weak var imageDetail: UIImageView!
#IBOutlet weak var analysisDesc: UILabel!
var valuta = ""
var segnale = ""
var immagine: UIImage!
var desc = ""
}
override func viewDidLoad() {
super.viewDidLoad()
crossLabel.text = valuta
signalLbl.text = segnale
analysisDesc.text = desc
imageDetail.image = immagine
}
Probably i'm just doing some stupid error... :) but it's my first app and i really don't know how to figure this out!
If anybody could help that would be much appreciate! :)
Thank you!
Cheers!
UPDATE:
I think my problems is because of the image.
I have an url which i retrive from firebase in this way:
let url = analysisList[indexPath.row].immagine
and then i download async the images:
cell.imageThumb.downloadImageFrom(link: url!, contentMode:
UIViewContentMode.scaleToFill)
in the segue i do this:
destination.immagine = (cell?.imageThumb.image)!
and in my DetailVC:
var immagine: UIImage!
imageDetail.image = immagine
this is the screen of the error
enter image description here
Saw this recently passing variables between views. I was able to get them moving by first setting the value to a top level variable (when a row is selected) and then re-reference that variable during the segue prepare function. Hope this helps.
Set a top level variable:
var valuta: String!
Breakout the self.tableView.indexPathForSelectedRow section into it's own delegate. This tutorial is a great example. (http://shrikar.com/swift-ios-tutorial-uisearchbar-and-uisearchbardelegate)
Using the "didSelectRowAt indexPath" delegate, set the top level variable value.
func tableView(_ tableView: UITableView, didSelectRowAt IndexPath: IndexPath){
let cell = tableView.cellForRow(at: indexPath)!
valuta = cell?.valutaLabel.text
}
Sample adjustments to the prepare function:
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if segue.identifier == "ItemDetailVC"{
if let destination =
segue.destination as? name_of_your_next_view_controller {
destination.passedValuta = valuta
}
}
Make sure to put a receiving variable in the next view
var passedValuta: String!

My Array Restarts and Not Append

class NewCourseViewController: UIViewController {
#IBOutlet weak var courseNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "newClassComplete" {
if let vcSendingToo = segue.destination as? CoursesTableViewController {
// Pass courseName to nameOfCourses Array
// Course Name
let courseName = courseNameTextField.text!
vcSendingToo.nameOfCourse = courseName
vcSendingToo.nameOfCourses.append(vcSendingToo.nameOfCourse)
}
class CoursesTableViewController: UITableViewController {
var nameOfCourses = [String]()
var nameOfCourse = ""
}
It restarts to a blank array rather than add a value to the same array. I can't find any examples that are online that'll help resolve my issue. It was working fin then stopped all of a su
Have you tried to change this line
let courseName = courseNameTextField.text!
vcSendingToo.nameOfCourse = courseName
vcSendingToo.nameOfCourses.append(vcSendingToo.nameOfCourse)
to this?
let courseName = courseNameTextField.text ?? "" //validate for nil
vcSendingToo.nameOfCourse = courseName
vcSendingToo.nameOfCourses = [courseName]
I made the variables global and removed the "vcSendingToo" properties.

How to get rid of "Optional(...)" in my output when transferring data to another ViewController

Im tring to transfer the first name of the user to another view controller when a button is pressed, and have been able to do so successfully. But i have encountered the problem of seeing "Optional(first name)" in my output. How do i get rid of this?
1st View Controller :
#IBOutlet weak var firstName: UITextField!
#IBOutlet weak var lastName: UITextField!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
var userFirstName: String = ""
var userLastName = ""
var userEmail = ""
var userPassword = ""
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AccountViewController.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
// Do any additional setup after loading the view.
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
#IBAction func createAccountBtn(_ sender: Any) {
userFirstName = String(describing: firstName.text)
userLastName = String(describing: lastName.text)
userEmail = String(describing: email.text)
userPassword = String(describing: password.text)
print(userFirstName)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let newVC: WelcomingViewController = segue.destination as! WelcomingViewController
newVC.userFirstName = userFirstName
2nd view controller :
#IBOutlet weak var firstNameLabel: UILabel!
var userFirstName: String? = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
firstNameLabel.text = userFirstName!
}
More than a solution you need to get the basic idea about the optional in Swift.
Swift Optional
You can go for
Forced Unwrapping: Do this if you are very sure about the content. Otherwise App will crash
firstNameLabel.text = userFirstName!
Optional Binding: This is more secure way
if let firstName = userFirstName {
firstNameLabel.text = firstName
}
Besides the if let approach, you can use nil coalescing like this:
firstNameLabel.text = userFirstName ?? "n/a"
This provides fallback string (or empty string, if you prefer) in case the original variable is nil.
Try this:
if let firstName = userFirstName {
firstNameLabel.text = firstName
}
This makes sure that userFirstName is not nil before it is passed to your label.
Edit
However, one thing to notice is that unless you are specifically setting userFirstName to nil at some point, you don't need it to be an optional because you give it an initial value of "". An optional is for something that may or may not have a value, and thus needs to be treated more carefully.

Images not showing up while attempting to convert PFFile to UIImage and segue it

My code isnt functioning correctly when I click a cell and want it to segue and show the same information on a new screen.
The Text is working perfectly and showing up in the new view but the images just wont appear. I am attempting to convert a PFFile from Parse into a UIImage and use it in a array so that when I click into the cell and it displays the view it will load the correct images and data. I am on Xcode 7 Beta 5. It is giving me no error but still isnt displaying the data correctly.
Here is the necessary Code, if any more is required to solve the issue I will be glad to provide it.
(Whats in the first class)
import Foundation
import Parse
class mainScreen: UIViewController, UICollectionViewDataSource {
var imageArray = [PFFile]()
var theDownloadedImages = [UIImage()]
var nameArray = [String]()
var priceArray = [String]()
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "cellInfo"
{
let indexPaths = self.collectionView!.indexPathsForSelectedItems()!
let indexPath = indexPaths[0] as NSIndexPath
let CI = segue.destinationViewController as! cellInfo
let imageForCell = self.imageArray[indexPath.row] as PFFile
imageForCell.getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
self.theDownloadedImages.append(downloadedImage)
CI.image = self.theDownloadedImages[indexPath.row]
CI.name = self.nameArray[indexPath.row]
CI.price = self.priceArray[indexPath.row]
}
}
}
}
(For the second Class)
class cellInfo: UIViewController {
#IBOutlet weak var CILocation: UILabel!
#IBOutlet weak var CIImage: UIImageView!
#IBOutlet weak var CIPrice: UILabel!
#IBOutlet weak var CIName: UILabel!
var image = UIImage()
var name = String()
var price = String()
var location = String()
override func viewDidLoad() {
super.viewDidLoad()
self.CIImage.image = self.image
self.CIName.text = self.name
self.CIPrice.text = self.price
self.CILocation.text = self.location
}

Resources