I did a parse json in my listingshopvc and it shows.Now I want to select a row and it pops up another view controller but there's error just a blank page with no error. I just want to press a row and convert it to show up on another view controller.
I have listing in the following view controller: ListingShopVc,ProductDetail,TableCellData
ListingShopVC
import UIKit
import CoreData
class ListingShopVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var creditsdisplay: UILabel!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var myUser:[User] = []
var mySecond:[Product] = []
var id:String = ""
var name:String = ""
var price:Double = 0.0
var image:String = ""
var details:String = ""
override func viewDidLoad() {
super.viewDidLoad()
fetch()
tableView.delegate = self
tableView.dataSource = self
extracted()
creditsdisplay.text = "You have 200 credits"
}
// MARK: - Table view data source
func numberOfSections(in 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 mySecond.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "hello", for: indexPath) as! TableCellData
// Configure the cell...
cell.shopTitle.text = mySecond[indexPath.row].name
cell.shopPrice.text = "$" + String(mySecond[indexPath.row].price) + "0"
cell.shopDesc.text = mySecond[indexPath.row].description
if let url = URL(string: mySecond[indexPath.row].image){
DispatchQueue.global().async {
let data = try? Data(contentsOf: url)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.shopImageView.image = image
}
}
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
id = mySecond[indexPath.row].id
name = mySecond[indexPath.row].name
price = mySecond[indexPath.row].price
details = mySecond[indexPath.row].description
image = mySecond[indexPath.row].image
performSegue(withIdentifier: "toDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetails"{
let vc = segue.destination as! ProductDetail
vc.productPicture = image
vc.productName = name
vc.productPrice = price
vc.productDetails = details
vc.productID = id
print(vc.productName)
}
}
func extracted(){
guard let url = URL(string: "http://rajeshrmohan.com/sport.json")
else {return}
let task = URLSession.shared.dataTask(with: url){
(data,response,error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
do {
let decoder = JSONDecoder()
let model:[Product] = try decoder.decode([Product].self, from: dataResponse)
//print(model)
for i in 0..<model.count{
self.mySecond.append(model[i])
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
func fetch(){
userList = try! context.fetch(User.fetchRequest())
tableView.reloadData()
}
}
TableViewCell
import UIKit
class TableCellData: UITableViewCell {
#IBOutlet weak var shopImageView: UIImageView!
#IBOutlet weak var shopTitle: UILabel!
#IBOutlet weak var shopPrice: UILabel!
#IBOutlet weak var shopDesc: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
ProductDetail
import UIKit
import CoreData
class ProductDetail: UIViewController {
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var myArray:[Cart] = []
var mySecondArray:[Products] = []
var newTots:Double = 0.0
#IBOutlet weak var AddImage: UIImageView!
#IBOutlet weak var AddTitle: UILabel!
#IBOutlet weak var AddPrice: UILabel!
#IBOutlet weak var AddDesc: UILabel!
var productID = String()
var productName = String()
var productPrice:Double = 0.0
var productPicture = String()
var productDetails:String = ""
override func viewDidLoad() {
super.viewDidLoad()
AddTitle.text = productName
AddDesc.text = productDetails
AddPrice.text = String(productPrice)
if let imageUrl = URL(string: productPicture),
let imageData = try? Data(contentsOf: imageUrl) {
AddImage.image = UIImage(data: imageData)
}
}
#IBAction func add2Cart(_ sender: Any) {
let neww = Cart(context: context)
neww.image = productPicture
neww.name = productName
neww.desc = productDetails
neww.price = productPrice
neww.total = productPrice
try! context.save()
performSegue(withIdentifier: "gotoCheckout", sender: nil)
}
func fetch(){
self.mySecondArray = try! context.fetch(Products.fetchRequest())
}
}
What it shows it this [1]: https://i.stack.imgur.com/XWUt0.png
-> You just need to call a delegate method of table view didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let tag = projectEquipmentList?[indexPath.row].tag // Object data to take in next VC
let QR = R.storyboard.main.qrScannerVC()! // View Controller
QR.manageVC(projectEquipmentTag: tag!) // setter method of View controller to set data
navigationController?.pushViewController(QR, animated: true) // push to next view controller
}
Related
When I click on it, I want to show the picture title and year part in the cell section in the tableview, how can I do this? When we click on the row go detail page and big picture, title and year I want to show the big title and year. How can I populate the DetailViewController page?
ViewController
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var table: UITableView!
#IBOutlet var field: UITextField!
var movies = [Movie]()
override func viewDidLoad() {
super.viewDidLoad()
table.register(MovieTableViewCell.nib(), forCellReuseIdentifier: MovieTableViewCell.identifier)
table.delegate = self
table.dataSource = self
field.delegate = self
}
// Field
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
searchMovies()
return true
}
func searchMovies() {
field.resignFirstResponder()
guard let text = field.text, !text.isEmpty else {
return
}
let query = text.replacingOccurrences(of: " ", with: "%20")
movies.removeAll()
URLSession.shared.dataTask(with: URL(string: "https://www.omdbapi.com/?apikey=3aea79ac&s=\(query)&type=movie")!,
completionHandler: { data, response, error in
guard let data = data, error == nil else {
return
}
// Convert
var result: MovieResult?
do {
result = try JSONDecoder().decode(MovieResult.self, from: data)
}
catch {
print("error")
}
guard let finalResult = result else {
return
}
// Update our movies array
let newMovies = finalResult.Search
self.movies.append(contentsOf: newMovies)
// Refresh our table
DispatchQueue.main.async {
self.table.reloadData()
}
}).resume()
}
// Table
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MovieTableViewCell.identifier, for: indexPath) as! MovieTableViewCell
cell.configure(with: movies[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Show movie details
if let vc = storyboard?.instantiateViewController(identifier: "detailViewController") as? detailViewController{
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
struct MovieResult: Codable {
let Search: [Movie]
}
struct Movie: Codable {
let Title: String
let Year: String
let imdbID: String
let _Type: String
let Poster: String
private enum CodingKeys: String, CodingKey {
case Title, Year, imdbID, _Type = "Type", Poster
}
}
MovieTableViewCell
class MovieTableViewCell: UITableViewCell {
#IBOutlet var movieTitleLabel: UILabel!
#IBOutlet var movieYearLabel: UILabel!
#IBOutlet var moviePosterImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
static let identifier = "MovieTableViewCell"
static func nib() -> UINib {
return UINib(nibName: "MovieTableViewCell",
bundle: nil)
}
func configure(with model: Movie) {
self.movieTitleLabel.text = model.Title
self.movieYearLabel.text = model.Year
let url = model.Poster
if let data = try? Data(contentsOf: URL(string: url)!) {
self.moviePosterImageView.image = UIImage(data: data)
}
}
}
DetailViewController
import UIKit
class detailViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var titleLbl: UILabel!
#IBOutlet weak var yearLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
You can pass the data there when you create your UIViewController
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Show movie details
if let vc = storyboard?.instantiateViewController(identifier: "detailViewController") as? detailViewController{
vc.item = movies[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
}
But you need to pass data first, and when you controller initialized (loaded) you can assign value to loaded views
class detailViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var titleLbl: UILabel!
#IBOutlet weak var yearLbl: UILabel!
var item: Movie? = nil
override func viewDidLoad() {
super.viewDidLoad()
if (let movie = item) {
titleLbl.text = item.title
yearLbl.tex = item.Year
// also image
}
}
}
I'm having a hard time trying to pass JSON to another view controller using a segue. So for I have only been able to use prepare(for segue, sender), but I can't get my data to populate my outlets on my view controller. Below is my first view controller. Within the prepare(for segue, sender) method you can see my commented out code that's not working. Any advice?
class ViewController2 : UIViewController, UITableViewDelegate, UITableViewDataSource {
var pictures : [Hit] = []
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
NetworkMananger.shared.getInfo { [weak self] (results) in
guard let self = self else {return }
switch results {
case .failure(let error):
print(error)
case .success(let pictures):
self.pictures = pictures
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ViewController1"{
if let indexPath = self.tableView.indexPathForSelectedRow{
let vc = segue.destination as! ViewController1
// vc.downloadLabel = String(pictures[indexPath.row].downloads)
// vc.tagsLabel = pictures[indexPath.row].tags
// vc.imageData = UIImage(named: pictures[indexPath.row].previewURL)
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(identifier: "ViewController1") as? ViewController1
navigationController?.pushViewController(vc!, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pictures.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell123", for: indexPath) as! firstTableViewCell
cell.label?.text = String(pictures[indexPath.row].downloads)
cell.downloadPictureFromURL(from: pictures[indexPath.row].previewURL)
return cell
}
}
Below is my second view controller I want to pass my JSON to :
class ViewController1: UIViewController {
var picture : Hit!
#IBOutlet weak var label: UILabel!
#IBOutlet weak var imageData:
UIImageView!
#IBOutlet weak var tagsLabel: UILabel!
#IBOutlet weak var downloadLabel: UILabel!
var cap : String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
}
JSON
struct Response : Codable {
let hits : [Hit]
}
struct Hit : Codable {
let tags : String
let previewURL : String
let downloads : Int
}
There are a couple of things getting in your way:
Right now, in your commented code, you have a type mismatch with each property you're trying to set. For example, you're trying to set a String to downloadLabel, which is a UILabel.
At the time of prepareForSegue, the IBOutlets may not be loaded.
To get around these issues, you could set properties on ViewController1 and then initialize the views in viewDidLoad:
struct ViewController1Input {
var downloadLabelText : String
var tagsLabelText: String
var imageName: String
}
class ViewController1: UIViewController {
var picture : Hit! //careful here -- I'm not sure where this is coming from and you aren't setting it in your segue
var input : ViewController1Input?
#IBOutlet weak var label: UILabel!
#IBOutlet weak var imageData: UIImageView!
#IBOutlet weak var tagsLabel: UILabel!
#IBOutlet weak var downloadLabel: UILabel!
var cap : String = ""
override func viewDidLoad() {
super.viewDidLoad()
if let input = input {
downloadLabel.text = input.downloadLabelText
tagsLabel.text = input.tagsLabelText
imageData.image = UIImage(named: input.imageName)
}
}
}
And in your segue:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ViewController1"{
if let indexPath = self.tableView.indexPathForSelectedRow{
let vc = segue.destination as! ViewController1
vc.input = ViewController1Input(downloadLabelText: String(pictures[indexPath.row].downloads),
tagsLabelText: pictures[indexPath.row].tags,
imageName: pictures[indexPath.row].previewURL)
}
}
}
I'm trying to save the data from func getCoinData to an array sympolsCoin and array sympolsCoin to use it in my TableView
I create this class in the same ViewController.swift file :
struct Coin: Decodable {
let symbol : String
let price_usd : String }
And this in my View controller class :
var coins = [Coin]()
var sympolsCoin = [String]()
var priceUSDcoin = [String]()
func getCoinData(completion: #escaping () -> ()) {
let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
let url = URL(string: jsonURL)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data!)
for info in self.coins {
self.sympolsCoin.append(info.symbol)
self.priceUSDcoin.append(info.price_usd)
print("\(self.sympolsCoin) : \(self.priceUSDcoin)")
completion()
}
}
catch {
print("Error is : \n\(error)")
}
}.resume()
}
And when i use the array in my TableView i got blank table !
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BitcoinTableViewCell", for: indexPath) as! BitcoinTableViewCell
cell.coinNameLable.text = sympolsCoin[indexPath.row]
cell.priceLable.text = priceUSDcoin[indexPath.row]
return cell
}
Since you are using JSONDecoder the entire logic to create and populate sympolsCoin and priceUSDcoin is pointless and redundant.
struct Coin: Decodable {
private enum CodingKeys: String, CodingKey {
case symbol, priceUSD = "price_usd"
}
let symbol : String
let priceUSD : String
}
var coins = [Coin]()
The completion handler is redundant, too. Just reload the table view on the main thread after receiving the data:
func getCoinData() {
let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
let url = URL(string: jsonURL)
URLSession.shared.dataTask(with: url!) { [unowned self] (data, response, error) in
guard let data = data else { return }
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print("Error is : \n\(error)")
}
}.resume()
}
In viewDidLoad load the data
override func viewDidLoad() {
super.viewDidLoad()
getCoinData()
}
In cellForRow update the UI
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BitcoinTableViewCell", for: indexPath) as! BitcoinTableViewCell
let coin = coins[indexPath.row]
cell.coinNameLable.text = coin.symbol
cell.priceLable.text = coin.priceUSD
return cell
}
Create an Outlet of tableView in ViewController Class and give it name "tableView" then
Try this code: Swift 4
func getCoinData() {
let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
let url = URL(string: jsonURL)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data!)
for info in self.coins {
self.sympolsCoin.append(info.symbol)
self.priceUSDcoin.append(info.price_usd)
print("\(self.sympolsCoin) : \(self.priceUSDcoin)")
self.tableView.reloadData()
}
}
catch {
print("Error is : \n\(error)")
}
}.resume()
}
Call this function in ViewDidLoad like this
override func viewDidLoad() {
super.viewDidLoad()
getCoinData()
}
You need to update the tableView from the main thread. As a good lesson to learn: Always update the UI from the Main Thread. Always.
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data!)
for info in self.coins {
self.sympolsCoin.append(info.symbol)
self.priceUSDcoin.append(info.price_usd)
DispatchQueue.main.async {
self.tableView.reloadData()
}
print("\(self.sympolsCoin) : \(self.priceUSDcoin)")
completion()
}
}
There is, however another problem with your code the way you have your labels setup won't work. TableViewCells get reused so I'm guessing you have #IBOutlets for them somewhere else. What you should do is declare a label constant in cellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
let coinNameLabel = cell.viewWithTag(100) as! UILabel
coinNameLabel.text = sympolsCoin[indexPath.row]
let priceNameLabel = cell.viewWithTag(101) as! UILabel
priceNameLabel.text = priceUSDcoin[indexPath.row]
}
The above code assumes you've setup two labels with the tags 100 and 101 in your storyboard(assuming your using one)
**
// First View Controller
//
//
//
import UIKit
struct Countory : Decodable {
let name: String
let capital: String
let region: String
let alpha2Code: String
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var listArr = [Countory]()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
let url = "https://restcountries.eu/rest/v2/all"
let urlObj = URL(string: url)!
URLSession.shared.dataTask(with: urlObj) {(data, responds, Error) in
do {
self.listArr = try JSONDecoder().decode([Countory].self, from: data!)
for country in self.listArr {
print("Country",country.name)
print("###################")
print("Capital",country.capital)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} catch {
print(" not ")
}
}.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.listArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
cell.label1.text = "Name: \(listArr[indexPath.row].name)"
cell.lable2.text = listArr[indexPath.row].capital
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let homeView = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
homeView.res = listArr[indexPath.row].region
homeView.alpha = listArr[indexPath.row].alpha2Code
self.navigationController?.pushViewController(homeView, animated: true)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
// SecondViewController
class SecondViewController: UIViewController {
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label3: UILabel!
var res = ""
var alpha = ""
override func viewDidLoad() {
super.viewDidLoad()
self.label3.text = res
self.label4.text = alpha
}
}
**
I have some code for a uitableview with works pretty well. Here's the code.
import UIKit
import Alamofire
import ObjectMapper
import SwiftyJSON
import FirebaseAuth
import FirebaseStorage
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
// #IBOutlet weak var symbolLbl: UILabel!
// #IBOutlet weak var BidLbl: UILabel!
var NumberofRows = 0
let stockURL = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22+GRPN+SIRI+TVIX+EVOK+ZNGA+EPRS+TKAI+EBIO+DELT+SQNM+ALIM+ODP+ASTI+GBSN+FATE+BLDP+ETRM+GALE+VSTM+BIND+GEVO+DRAM+AMDA+BIOD+VNR+GLUU+AXAS+INFI+BLDP+SGYP+HLIT+ZIOP+XGTI+CIDM+CPLP+ORIG+DRRX+MNKD+GLBS+GERN+IMGN+IMMU+GLBS+GERN+IMGN+IMMU+GLBL+REXX+VIP+NETE+EXTR+CLNE+EBIO+ULTR+AAPL+TSLA+%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json"
//var StockArray = [String]()
var BidArray = [Double]()
var ChangeArray = [Double]()
struct combinedStock {
var symbol: String = ""
var bid : Double = 0.0
var change: Double = 0.0
}
var stockArray = [combinedStock]()
#IBOutlet weak var tableView: UITableView!
// #IBOutlet weak var StockSymbolLbl: UILabel!
// #IBOutlet weak var BidSymbolLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
getJSON()
automaticallyAdjustsScrollViewInsets = false
tableView.dataSource = self
tableView.delegate = self
tableView.registerNib(UINib(nibName: "StockHome", bundle: NSBundle.mainBundle()),forCellReuseIdentifier: "stockHome")
tableView.rowHeight = 60
// StockSymbolLbl.text = ""
// BidSymbolLbl.text = ""
}
#IBAction func logout(sender: AnyObject) {
let actionSheetController = UIAlertController(title: "Please Selecet", message: "Option to select", preferredStyle: UIAlertControllerStyle.ActionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (action) in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
let profileActionButton = UIAlertAction(title: "Profile", style: UIAlertActionStyle.Default) { (action) in
let profileVC = self.storyboard?.instantiateViewControllerWithIdentifier("profileViewConrtoller") as! ProfileTableViewController
self.navigationController?.pushViewController(profileVC, animated: true)
}
actionSheetController.addAction(profileActionButton)
let logoutAction = UIAlertAction(title: "Log Out", style: UIAlertActionStyle.Default) { (action) in
print("log out")
self.logoutDidTapped()
}
actionSheetController.addAction(logoutAction)
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
func logoutDidTapped() {
DataService.dataService.logout()
}
func getJSON(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let url = NSURL(string: self.stockURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
let swiftyJSON = JSON(data: data!)
let Symbol: String? = swiftyJSON["query"]["results"]["quote"][0]["symbol"].stringValue
let bid: String? = swiftyJSON["query"]["results"]["quote"][0]["Bid"].stringValue
let change: String? = swiftyJSON["query"]["results"]["quote"][0]["Change"].stringValue
print(change!)
print(Symbol!)
print(bid!)
dispatch_async(dispatch_get_main_queue()) {
// self.StockSymbolLbl.text? = "\(Symbol!)"
// self.BidSymbolLbl.text? = "\(bid!)"
self.NumberofRows = swiftyJSON["query"]["results"]["quote"].count
for i in 0...self.NumberofRows {
var stockcount = 0
stockcount += i
let Stock = swiftyJSON["query"]["results"]["quote"][stockcount]["symbol"].stringValue
let Bid = swiftyJSON["query"]["results"]["quote"][stockcount]["Bid"].doubleValue
let Change = swiftyJSON["query"]["results"]["quote"][stockcount]["Change"].doubleValue
let homestocks = combinedStock(symbol: Stock, bid: Bid, change: Change)
// self.StockArray.append(Stock)
// print(Stock)
// self.BidArray.append(Bid)
// print(Bid)
// self.ChangeArray.append(Change)
// p
print(Change)
self.stockArray.append(homestocks)
}
self.stockArray = self.stockArray.sort({
return $0.change > $1.change
})
self.tableView.reloadData()
}
}else{
print("There was an error")
}
}
task.resume()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NumberofRows
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: StockHome = tableView.dequeueReusableCellWithIdentifier("stockHome", forIndexPath: indexPath) as! StockHome
if stockArray.count != 0{
cell.symbolLbl?.text = stockArray[indexPath.row].symbol
let bid = stockArray[indexPath.row].bid
let changeRate = stockArray[indexPath.row].change
cell.bidLbl?.text = "\(bid)" + " USD "
cell.changeLbl?.text = "\(changeRate)" + " %"
}
print(self.stockArray)
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
switch stockArray[indexPath.row].change {
case let x where x < 0.0:
cell.backgroundColor = UIColor(red: 255.0/255.0, green: 59.0/255.0, blue: 48.0/255.0, alpha: 1.0)
case let x where x > 0.0:
cell.backgroundColor = UIColor(red: 76.0/255.0, green: 217.0/255.0, blue: 100.0/255.0, alpha: 1.0)
case let x:
cell.backgroundColor = UIColor(red: 44.0/255.0, green: 186.0/255.0, blue: 231.0/255.0, alpha: 1.0)
}
cell.textLabel!.textColor = UIColor.whiteColor()
}
}
I am trying to change the view from a tableview to a collection view. I did so, but nothing is displayed. I was greeted with a black screen until I changed the background to white. Here is the code for my collection view
import UIKit
import Alamofire
import ObjectMapper
import SwiftyJSON
import FirebaseAuth
import FirebaseStorage
class StockViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var NumberofRows = 0
let stockURL = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22+GRPN+SIRI+TVIX+EVOK+ZNGA+EPRS+TKAI+EBIO+DELT+SQNM+ALIM+ODP+ASTI+GBSN+FATE+BLDP+ETRM+GALE+VSTM+BIND+GEVO+DRAM+AMDA+BIOD+VNR+GLUU+AXAS+INFI+BLDP+SGYP+HLIT+ZIOP+XGTI+CIDM+CPLP+ORIG+DRRX+MNKD+GLBS+GERN+IMGN+IMMU+GLBS+GERN+IMGN+IMMU+GLBL+REXX+VIP+NETE+EXTR+CLNE+EBIO+ULTR+AAPL+TSLA+%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json"
var BidArray = [Double]()
var ChangeArray = [Double]()
struct combinedStock {
var symbol: String = ""
var bid : Double = 0.0
var change: Double = 0.0
}
var stockArray = [combinedStock]()
#IBOutlet weak var collectionview: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
collectionview.dataSource = self
collectionview.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getJSON(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let url = NSURL(string: self.stockURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
let swiftyJSON = JSON(data: data!)
let Symbol: String? = swiftyJSON["query"]["results"]["quote"][0]["symbol"].stringValue
let bid: String? = swiftyJSON["query"]["results"]["quote"][0]["Bid"].stringValue
let change: String? = swiftyJSON["query"]["results"]["quote"][0]["Change"].stringValue
print(change!)
print(Symbol!)
print(bid!)
dispatch_async(dispatch_get_main_queue()) {
// self.StockSymbolLbl.text? = "\(Symbol!)"
// self.BidSymbolLbl.text? = "\(bid!)"
self.NumberofRows = swiftyJSON["query"]["results"]["quote"].count
for i in 0...self.NumberofRows {
var stockcount = 0
stockcount += i
let Stock = swiftyJSON["query"]["results"]["quote"][stockcount]["symbol"].stringValue
let Bid = swiftyJSON["query"]["results"]["quote"][stockcount]["Bid"].doubleValue
let Change = swiftyJSON["query"]["results"]["quote"][stockcount]["Change"].doubleValue
let homestocks = combinedStock(symbol: Stock, bid: Bid, change: Change)
// self.StockArray.append(Stock)
// print(Stock)
// self.BidArray.append(Bid)
// print(Bid)
// self.ChangeArray.append(Change)
// p
print(Change)
self.stockArray.append(homestocks)
}
self.stockArray = self.stockArray.sort({
return $0.change > $1.change
})
self.collectionview.reloadData()
}
}else{
print("There was an error")
}
}
task.resume()
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return NumberofRows
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionview.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! homeCollectionViewCell
if stockArray.count != 0{
cell.symbolLbl?.text = self.stockArray[indexPath.item].symbol
let bid = stockArray[indexPath.item].change
let changeRate = stockArray[indexPath.item].change
cell.bidLbl?.text = "\(bid)" + " USD "
cell.percentLbl?.text = "\(changeRate)" + " %"
}
print(self.stockArray)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
}
As you can tell they are quite similar. I was curious to know what I am missing or doing wrong. Thank you.
P.S. here is the code for the uicollectionviewcell
import UIKit
class homeCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var symbolLbl: UILabel!
#IBOutlet weak var percentLbl: UILabel!
#IBOutlet weak var bidLbl: UILabel!
}
Thank you.
I have a (large amount) of data that I want to send to Table View with alamofire and siftyJSON
web request :
let postEndPoint :String = "http://jsonplaceholder.typicode.com/posts/"
code Alamofire and SwiftyJSON:
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, postEndPoint).responseJSON { response in
// handle json
guard response.result.error == nil else{
print("error calling Get on /posts/1")
print(response.result.error)
return
}
if let value: AnyObject = response.result.value{
let post = JSON(value)
// for i in 0...post.count{
if let title = post["data"].arrayValue as? [JSON]{
self.datas = title
self.tableView.reloadData()
print("the title is :\(title)" )
}else{
print("eror parsing /post/1 ")
}
// }
}
}
}
code table view :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell")!
var dict = datas[indexPath.row]
cell.textLabel?.text = dict["userId"] as? String
cell.detailTextLabel?.text = dict["id"] as? String
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
}
web request :enter link description here
I am trying to post some json data to table view but when I send the data it returns nothing . why??
this is the code working for me. main thing is you have to reload the table at the end of api calling. and you are printing nuber as a string so you have to convert it to string
my code is here
import UIKit
class customcell: UITableViewCell {
#IBOutlet weak var lbl1: UILabel!
#IBOutlet weak var lbl2: UILabel!
}
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tabledata: UITableView!
let postEndPoint :String = "http://jsonplaceholder.typicode.com/posts/"
var arr:NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
web()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("customcell") as! customcell
let dict = arr[indexPath.row] as! NSDictionary
print(dict)
print(dict["userId"])
cell.lbl1?.text = String (dict["userId"]! )
cell.lbl2?.text = String (dict["id"]! )
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func web()
{
request(.GET, postEndPoint, parameters: nil, encoding:
.JSON).responseJSON { (response:Response<AnyObject, NSError>) -> Void in
print(response.result.value)
if (response.result.value != nil)
{
self.arr = (response.result.value) as! NSMutableArray
}
self.tabledata.reloadData()
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (tableView == tabledata)
{
let cell = tableView.dequeueReusableCellWithIdentifier("customcell") as! customcell
let dict = arr[indexPath.row] as! NSDictionary
cell.lbl1?.text = String (dict["userId"]! )
cell.selectionStyle = .None
return cell
}
else if(tableView == tablefactoryoption)
{
let cell1:Facturyoptioncell = tableView.dequeueReusableCellWithIdentifier("Facturyoptioncell") as! Facturyoptioncell
let dict = arr[indexPath.row] as! NSDictionary
cell1.lbl2?.text = String (dict["Id"]! )
cell1.selectionStyle = .None
cell1.selectionStyle = .None
return cell1
}
else
{
let cell2:Technicalcell = tableView.dequeueReusableCellWithIdentifier("Technicalcell") as! Technicalcell
let dict = arr[indexPath.row] as! NSDictionary
cell2.lbl3?.text = String (dict["userId"]! )
return cell2
}
}
This is how you can use multiple tableview for display data.