Swift 3/iOS UIView not updating after retrieving remote JSON data - ios

I have a UITableView with a list of users. When you tap on a row, the uid of the user is passed to the UIViewController detail view. A URLRequest is made to retrieve JSON data of the user (username, avatar, etc). However, the detail view inconsistently updates the information. Sometimes it'll show the users' name, avatar, etc but other times it'll show nothing or it'll only show the username or only show the avatar, etc.
In the fetchUser() method, I have a print("Username: \(self.user.username)") that shows the correct data is being retrieved 100% of the time but it won't display it 100% of the time in the view.
Any help would be greatly appreciated.
Thanks!
class ProfileViewController: UIViewController {
#IBOutlet weak var avatarImageView: UIImageView!
#IBOutlet weak var usernameLabel: UILabel!
#IBOutlet weak var networthLabel: UILabel!
var user: User!
var uid: Int?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
fetchUser()
}
func reloadView() {
self.usernameLabel.text = user.username
self.networthLabel.text = "$" + NumberFormatter.localizedString(from: Int((user.networth)!)! as NSNumber, number: NumberFormatter.Style.decimal)
self.avatarImageView.downloadImage(from: user.avatar!)
circularImage(photoImageView: self.avatarImageView)
}
func fetchUser() {
// Post user data to server
let myUrl = NSURL(string: "http://localhost/test/profile")
let urlRequest = NSMutableURLRequest(url: myUrl! as URL);
urlRequest.httpMethod = "POST"
let postString = "uid=\(uid!)"
urlRequest.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) { (data, response, error) in
if (error != nil) {
print("error=\(String(describing: error))")
return
} // end if
self.user = User()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String : AnyObject]
if let parseJSON = json?["data"] as? [[String : AnyObject]] {
for userFromJson in parseJSON {
let userData = User()
if let uid = userFromJson["uid"] as? String,
let username = userFromJson["username"] as? String,
let networth = userFromJson["networth"] as? String,
let avatar = userFromJson["avatar"] as? String {
userData.uid = Int(uid)
userData.username = username
userData.networth = networth
userData.avatar = avatar
self.usernameLabel.text = username
self.networthLabel.text = networth
self.avatarImageView.downloadImage(from: avatar)
circularImage(photoImageView: self.avatarImageView)
} // end if
self.user = userData
} // end for
} // end if
DispatchQueue.main.async {
print("Username: \(self.user.username)")
self.reloadView()
}
} catch let error {
print(error)
}
}
task.resume()
}

Firstly, call fetch user in viewWillAppear like this:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchUser()
}
Then, change the code here like I did, don't use the reloadView function you had, instead, update the UI elements on the main thread at the end of the fetchUser function. I also changed it so you weren't updating the UI twice because you have 4 lines at the bottom of the if let uid = ... statement in fetchUser which updated UI elements that wasn't in the main thread which is why in my version I removed those 4 lines of code. Let me know if this worked for you.
let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) { (data, response, error) in
if (error != nil) {
print("error=\(String(describing: error))")
return
} // end if
self.user = User()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String : AnyObject]
if let parseJSON = json?["data"] as? [[String : AnyObject]] {
for userFromJson in parseJSON {
let userData = User()
if let uid = userFromJson["uid"] as? String,
let username = userFromJson["username"] as? String,
let networth = userFromJson["networth"] as? String,
let avatar = userFromJson["avatar"] as? String {
userData.uid = Int(uid)
userData.username = username
userData.networth = networth
userData.avatar = avatar
} // end if
self.user = userData
} // end for
} // end if
DispatchQueue.main.async {
self.usernameLabel.text = user.username
self.networthLabel.text = "$" + NumberFormatter.localizedString(from: Int((user.networth)!)! as NSNumber, number: NumberFormatter.Style.decimal)
self.avatarImageView.downloadImage(from: user.avatar!)
circularImage(photoImageView: self.avatarImageView)
}
} catch let error {
print(error)
}
}
task.resume()

Two suggestions:
strictly speaking, all accesses to UIView object should be on the main thread. You're dispatching to the main thread to call reloadView, but should probably also do it when you're settings the "username" and "net worth" values on the labels
are you sure that the labels are blank? Could it be an autolayout problem instead? (Try setting the background colour of the labels to yellow, to check that they're the correct size. Sometimes autolayout can squash views down to nothing if there are conflicting constraints)

Related

Get JSON data and display in tableview Xcode

I'm creating a IOS program to download json data from url and display in table view of ios. i have issue to download JSON (every 10 second )in loginpage view controller and parse JSON data to tableview controller. Before posting this, i have try to search many times but can't find solution. Below is StoryBoad and the code
Story Board
User will login, after login success, JSON data will be loaded (userlogin = true). Below code in login class loginPage: UIViewController
#IBOutlet weak var usernameLogin: UITextField!
#IBOutlet weak var passwordLogin: UITextField!
#IBAction func loginPress(_ sender: Any) {
username = usernameLogin.text!
password = passwordLogin.text!
let request = NSMutableURLRequest(url: NSURL(string: "http://talectric.com/wp-admin/a_p/users/userlogin.php")! as URL)
request.httpMethod = "POST"
let postString = "username=\(username)&password=\(password)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error!)")
return
}
else
{
do {
let respondString = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(respondString!)
let message = respondString?["message"] as! String
if message == "Check Pass" {
userlogin = true
DispatchQueue.main.async {
let TabViewPageController = self.storyboard?.instantiateViewController(withIdentifier: "TabViewPageID") as! TabViewPage
self.present(TabViewPageController, animated: true, completion: nil)
}
}
else {
DispatchQueue.main.async {
let alertController = UIAlertController(title: "Login", message:
"Username or Password is not correct", preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
}
catch let error as NSError {
print(error.debugDescription)
}
}
}
task.resume()
}
after userlogin = true, #objc func taskdo() will load JSON data to nodeidArray but second download not overwrite first element of nodeidArray and nodeidArray is inserted after last element ( i just want nodeidArray to be overwrited)
import UIKit
var timer = Timer()
var userlogin = false
struct Data {}
var username = String()
var password = String()
class loginPage: UIViewController{
var nodeidArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
timerstart()
}
func timerstart()
{
timer = Timer.scheduledTimer(timeInterval: 5, target: self,selector: #selector(loginPage.taskdo),userInfo:nil,repeats: true)
}
#objc func taskdo()
{
if userlogin == true{
let request = NSMutableURLRequest(url: NSURL(string: "http://talectric.com/wp-admin/a_p/iot/read_all.php")! as URL)
request.httpMethod = "POST"
let postString = "username=\(username)&password=\(password)&authen=wdwfesf9329140dsvfxkciospdkm"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error!)")
return
}
else
{
do {
if let respondString = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
if let nodedata = respondString.value(forKey: "nodedata") as? NSArray {
for node in nodedata{
if let nodeDict = node as? NSDictionary {
if let nodeid = nodeDict.value(forKey: "nodeid"){
self.nodeidArray.insert(nodeid as! String, at: 0)
}
}
}
}
}
// print(respondString!)
//let message = respondString?["numberofnodeid"] as! Int
//let nodedata = respondString!.value(forKey: "nodedata")//
// let nodeid = (nodedata as AnyObject).value(forKey: "nodeid")
// print(respondString!.value(forKey: "nodedata")!)
print(self.nodeidArray)
let defaults = UserDefaults.standard
defaults.set(self.nodeidArray, forKey: "YourKey")
}
catch let error as NSError {
print(error.debugDescription)
}
}
}
task.resume()
}
}
}
After download JSON in LoginViewController, i can not paste data to tableview controller. I have try to change nodeidArray to static in LoginPage but can't use static variable in #objc func taskdo(). I try UserDefaults also but can't get data in TableViewController (NodeDataPage)
i have test tableview success with Local Variable in Class NodeDataPage but can't test variable from other viewcontroller
import UIKit
class NodeDataPage:
UIViewController,UITableViewDelegate,UITableViewDataSource {
//var nodeidname = ["nodeid1","nodeid2","nodeid3"]
var testArray : [String]() = UserDefaults.standard.objectForKey("YourKey") {
var nodeidname : [NSString] = testArray! as! [NSString]
println(readArray)
}
#IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nodeidname.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"nodeCell",for: indexPath)
cell.textLabel?.text = nodeidname[indexPath.row]
return cell
}}
I specify the questions:
How can i transfer JSON data (download in LoginPage VC) to Table View VC (NodeDataPage VC) ?
How can i run JSON download function in LoginPage VC every 10s with Question 1 also (i try static variable to get in other view and can't run in #objc func taskdo() ?
I want to run JSON download data every 10s after userlogin. Should i put this function in LoginPage VC or other view because i need to get data from server continuously ?
How can i run JSON download func when the app is hidden (not be killed) ?
i have tried to research small part but now it become more complicated. Please help me.
Thank you
Create a separate class like "DataManager" which holds all your data (nodeidArray) as well as makes calls to server to fetch from web service every 10 seconds.
Once user logs in successfully, show the NodeDataPage. In viewDidLoad of this class, create DataManager object and call the method that handles the timer and fetching data from server.
Use notification or observer design pattern to intimate the NodeDataPage to get the data from DataManager and reload the tableview.
Hope I am able to answer your questions.

Performing Segue after Login

So I'm designing an application where, like most apps, takes users to the "home page" after a successful login. However, I can't quite figure out how to get it to work. The code for my Login page is as follows:
import UIKit
class LoginVC: UIViewController {
#IBOutlet weak var usernameTxt: UITextField!
#IBOutlet weak var passwordTxt: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//#IBAction func userLogin(_ sender: AnyObject) {
#IBAction func userLogin(_ sender: AnyObject) {
// if textboxes are empty
if usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty {
// red placeholders
usernameTxt.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.red])
passwordTxt.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.red])
} else {
// shortcuts
let username = usernameTxt.text!.lowercased()
let password = passwordTxt.text!
// send request to mysql db
// Create a user in the mySQL db
// the exclamation at the end means we insist to launch it
// url to php file
let url = NSURL(string: "https://cgi.soic.indiana.edu/~team7/login.php")!
// request to the file
let request = NSMutableURLRequest(url: url as URL)
// method to pass data to this file via the POST method
request.httpMethod = "POST"
// what occurs after the question mark in the url
// body to be appended to url from values in textboxes
let body = "username=\(username)&password=\(password)"
// appends body to request that will be sent
request.httpBody = body.data(using: String.Encoding.utf8)
// launching
URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in
if error == nil {
// get main queue in code process to communicate back
DispatchQueue.main.async(execute: {
// do this unless some error which is caught by catch
do {
// get json result
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// guard let is the same thing as if let
// asign json to new variable in secure way
// original guard let used
guard let parseJSON = json else {
print("Error while parsing")
return
}
// get id from parseJSON dictionary
let id = parseJSON["id"] as? String
// if there is some id value
if id != nil && response != nil {
print(parseJSON)
// successfully logged in
//let userID = parseJSON["id"] as! String
//let userN = parseJSON["username"] as! String
//let eMail = parseJSON["email"] as! String
//print(parseJSON["username"] ?? String.self)
//let myVC = self.storyboard?.instantiateViewController(withIdentifier: "RetrievalVC") as! RetrievalVC
//myVC.id_Outlet.text = userID
//myVC.full_Outlet.text = userN
//myVC.email_Outlet.text = eMail
//
//self.navigationController?.pushViewController(myVC, animated: true)
}
} catch {
print("Caught an error \(error)")
}
})
// if unable to process request
} else {
print("error: \(error)")
}
}).resume()
//performSegue(withIdentifier: "loginSuccess", sender: LoginVC.self)
}
}
}
I am trying to use
performSegue(withIdentifier: "loginSuccess", sender: LoginVC.self)
In order to perform the segue but I'm not sure where in the code it should go.
Any suggestions or changes I need to make to the code?
It depends on back end logic.I assume that parseJSON["id"] is returned only if user is verified. So you can use this
let id = parseJSON["id"] as? String
// if there is some id value
if id != nil {
// perform segue here
}
You can perform a segue when error is nil and you are response contains data...
if id != nil && response != nil {
performSegue(withIdentifier: "loginSuccess", sender: LoginVC.self)
}

How to set JSON output into UILabel in Swift 3.0 ?

I have these JSON data.
(
{
email = "b#p.com.my";
login = ID001;
pw = 1234;
},
{
email = "p#d.com.my";
login = ID002;
pw = 12345;
}
)
Right now, I can only print myJSON value in x code output.
My question is, how to display each JSON into UILabel _email, _login, _pw?
Someone said that I need to store as variable and set into UILabel but i don't know how to do it. Appreciate if someone can help me on this matters.
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet var _email: UILabel!
#IBOutlet var _login: UILabel!
#IBOutlet var _pw: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://localhost/get.php")
let task = URLSession.shared.dataTask(with: url!) {
(data, response, error) in
if error != nil {
print("Error")
return
}
else {
if let content = data {
do {
let myJSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJSON)
}
catch {}
}
}
}
task.resume()
}
}
Thanks.
EDIT:
After the block where you print your myJSON, try this:
for eachItem in myJSON {
if let emailParsed = eachItem["email"] as? String {
print(emailParsed)
_email.text = emailParsed
}
}
This loop runs between all the dictionaries and
This solution could be helpful for you. Please go through it!
Hi Please try this one
for i..0 < myJson.count {
let object = myJson[i] as AnyObject
if let emailParsed = myJSON["email"] as? String {
_email.text = emailParsed
}
}
EDITED
for i..0 < myJson.count {
let object = myJson[i] as [String : AnyObject]
if let emailParsed = myJSON["email"] as? String {
_email.text = emailParsed
}
}
It's simple because your json object gives an array of dictionary so first you have to take first object from array and after that you can take the string passing the key
override func viewDidLoad()
{
super.viewDidLoad()
let url = URL(string: "http://localhost/get.php")
let task = URLSession.shared.dataTask(with: url!)
{
(data, response, error) in
if error != nil
{
print("Error")
return
}
else
{
if let content = data
{
do {
let myJSON = try JSONSerialization.jsonObject(with: content, options:JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
// print(myJSON)
for data in myJSON
{
let email = data.1["email"] as? String
_email.text = email
}
}
catch {}
}
}
}
task.resume()
}
}
For batter option you can use some predefined libraries like swiftyJSON. To get best result.

Trying to append JSON items to array but not working

I am trying to serialize a GET request then make a movie object, then appending that movie object to a movies array which I will use to show info on the UI.
I am new and have struggled with this problem for some time now :(
If you look at the self.movies?.append(movie) shouldnt that work? I dont see any reasons as to when i try to get the first item i get fatal error index out of bounds which means I the Array is not filled yet.... Dont know what i am doing wrong :(
import UIKit
class ViewController: UIViewController {
var movies:[Movie]? = []
#IBOutlet weak var uiMovieTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getMovieData()
print(self.movies?.count)
setUI()
}
#IBAction func yesBtn(_ sender: UIButton) {
print(movies?[5].title ?? String())
}
#IBAction func seenBtn(_ sender: UIButton) {
}
#IBAction func noBtn(_ sender: UIButton) {
}
#IBOutlet weak var moviePoster: UIImageView!
let urlString = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acbfed4b9e5534ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=12"
func getMovieData(){
//Set up URL
let todoEndPoint: String = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acbfed4b9e5534ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=12"
guard let url = URL(string: todoEndPoint) else {
print("Cant get URL")
return
}
let urlRequest = URLRequest(url: url)
//Setting up session
let config = URLSessionConfiguration.default
let session = URLSession.shared
//Task setup
let task = session.dataTask(with: urlRequest) { (data, URLResponse, error) in
//Checking for errors
guard error == nil else{
print("Error calling GET")
print(error)
return
}
//Checking if we got data
guard let responseData = data else{
print("Error: No data")
return
}
self.movies = [Movie]()
do{//If we got data, if not print error
guard let todo = try JSONSerialization.jsonObject(with: responseData, options:.mutableContainers) as? [String:AnyObject] else{
print("Error trying to convert data to JSON")
return
}//if data is Serializable, do this
if let movieResults = todo["results"] as? [[String: AnyObject]]{
//For each movieobject inside of movieresult try to make a movie object
for moviesFromJson in movieResults{
let movie = Movie()
//If all this works, set variables
if let title = moviesFromJson["title"] as? String, let movieRelease = moviesFromJson["release_date"] as? String, let posterPath = moviesFromJson["poster_path"] as? String, let movieId = moviesFromJson["id"] as? Int{
movie.title = title
movie.movieRelease = movieRelease
movie.posterPath = posterPath
movie.movieId = movieId
}
self.movies?.append(movie)
}
}
}//do end
catch{
print(error)
}
}
////Do Stuff
task.resume()
}
func setUI(){
//uiMovieTitle.text = self.movies![0].title
//print(self.movies?[0].title)
}
}
my Movie class:
import UIKit
class Movie: NSObject {
var title:String?
var movieRelease: String?
var posterPath:String?
var movieId:Int?
var movieGenre:[Int] = []
//public init(title:String, movieRelease:String, posterPath:String,movieId:Int) {
// self.movieId = movieId
//self.title = title
//self.movieRelease = movieRelease
//self.posterPath = posterPath
//self.movieGenre = [movieGenre]
//}
}
getMovieData calls the network asynchronously. Your viewDidLoad invokes this, then calls setUI() - but the networking is still ongoing when setUI is called.
Instead, call setUI when the networking is complete - after the self.movies?.append(movie) line. The UI code will need to happen on the main thread. So...
for moviesFromJson... // your existing code
...
self.movies?.append(movie)
}
// Refresh UI now movies have loaded.
DispatchQueue.main.async {
setUI()
}
import UIKit
class ViewController: UIViewController {
var movies:[Movie]? = []
#IBOutlet weak var uiMovieTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getMovieDataCall(completionHandler: {data, error in self. getMovieDataCallBack(data: data, error: error)})
}
func getMovieDataCallBack(data: Data?, error: Error?) {
if error == nil {
let dictionary = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, AnyObject>
//do your appending here and then call setUI()
print("dictionaryMovie \(dictionary)")
} else {
showAlertView("", error?.localizedDescription)
}
}
func getMovieDataCall(completionHandler: #escaping (Data?, Error?) -> Void)){
//Set up URL
let todoEndPoint: String = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acbfed4b9e5534ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=12"
guard let url = URL(string: todoEndPoint) else {
print("Cant get URL")
return
}
let urlRequest = URLRequest(url: url)
//Setting up session
let config = URLSessionConfiguration.default
let session = URLSession.shared
//Task setup
let task = session.dataTask(with: urlRequest) { (data, URLResponse, error) in
if error != nil {
NSLog("GET-ERROR", "=\(error)");
completionHandler(nil, error)
} else {
let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
print(dataString!)
completionHandler(data, nil)
}
task.resume()
}
func setUI(){
}

How come I can't pass any calculations and variables I define in ViewDidAppear/ViewDidLoad with preparetosegue method? And how can I achieve this?

Exactly, as title. I started by putting my HTTP request session in the viewdidload, until I realized it was a terrible place to put it, as it's way low in the hierarchy of methods called, and essentially it was hopeless to define variables there to pass to another VC.
However, I switched to Viewdidappear, but I still get nil, when I pass the variables through prepareforsegue. Is there another method I can use, or how do you suggest I achieve what I want? I could possibly post request whenever i press a button, that would surely pass variables down?
override func viewDidLoad() {
super.viewDidLoad()
activityIndicatorView.startAnimating()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let request = NSMutableURLRequest(URL: NSURL(string: "http://127.0.0.1:5000")!)
request.HTTPMethod = "POST"
let postString = "color=\(self.finalDataPassed)&location=\(self.thirdDataPassed)&weather=\(self.dataPassed)&city=\(self.secondDataPassed)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(responseString)
var error: NSError?
let result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
var dict: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
if(error != nil) {
println(error!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
if let results = result?.valueForKey("result") as? NSArray {
dispatch_async(dispatch_get_main_queue(), {
println(results)
})
}
let parseJSON: AnyObject? = result!.valueForKey("result")
var stuff: AnyObject! = parseJSON!.valueForKey("price")
var otherstuff: NSString! = parseJSON!.valueForKey("YlowestURL") as! NSString
}
self.activityIndicatorView.stopAnimating()
self.performSegueWithIdentifier("calculateToDisplaySegue", sender: nil)
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var stuff: String!
var otherstuff: String!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "calculateToDisplaySegue"){
var svc = segue.destinationViewController as! PriceViewController;
svc.dataPassed = self.stuff
svc.secondDataPassed = self.otherstuff
}
}
stuff and otherstuff are defined local to the method, not in the class instance variables.
IOW use:
self.stuff = parseJSON!.valueForKey("price")
self.otherstuff = parseJSON!.valueForKey("YlowestURL") as! NSString
Of course stuff and otherstuff must be declared as ivars of the appropriate type in place of:
var stuff: String!
var otherstuff: String!
It seems you're redefining your class properties with local variables inside the handler. You should replace
var stuff: AnyObject! = parseJSON!.valueForKey("price")
var otherstuff: NSString! = parseJSON!.valueForKey("YlowestURL") as! NSString
by
self.stuff = parseJSON!.valueForKey("price") as! String
self.otherstuff = parseJSON!.valueForKey("YlowestURL") as! String

Resources