How to use swiftyJson to get arrayvalue in TableView? - swift

I use swiftyJson to parse data and, but do not know how to parse array.
Here is code.
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var json:JSON = JSON.null
var urlSession = URLSession(configuration: .default)
#IBOutlet weak var myTableView: UITableView!
var pokamon = [[String:AnyObject]]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokamon.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
var dict = pokamon[indexPath.row]
cell.nameLbl.text = dict["name"] as? String
cell.typesLbl.text = dict["types"]?[0] as? String
cell.hpLbl.text = dict["hp"] as? String
cell.subtypeLbl.text = dict["subtype"] as? String
if let image = URL(string: dict["imageUrl"] as! String){
let task = urlSession.downloadTask(with: image) { (url, repsponse, error) in
if error != nil{
print("sorry")
return
}
if let okURL = url{
do{
let downloadImage = UIImage(data: try Data(contentsOf: okURL))
DispatchQueue.main.async {
cell.myImage.image = downloadImage
}
}catch{
print("error")
}
}
}
task.resume()
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 224
}
override func viewDidLoad() {
super.viewDidLoad()
myTableView.delegate = self
myTableView.dataSource = self
Alamofire.request("https://api.pokemontcg.io/v1/cards").responseJSON(completionHandler: { response in
if response.result.isSuccess {
let json:JSON = try! JSON(data: response.data!)
let swiftyJsonVar = JSON(response.result.value!)
if let resData = swiftyJsonVar["cards"].arrayObject{
self.pokamon = resData as! [[String:AnyObject]]
}
if self.pokamon.count > 0{
self.myTableView.reloadData()
}
} else {
print("error: \(response.error)")
}
})
}
}
From cellForRowAt in tableView, it shows "Ambiguous use of 'subscript'" with below code, have no idea how to solve it. The rest like "name", "hp", and "subtype" are no problem!
cell.typesLbl.text = dict["types"]?[0] as? String
Could anyone help me with this error?
Thanks!

The compiler must know the type of any subscripted object. Tell the compiler that you expect an array of strings.
cell.typesLbl.text = (dict["types"] as? [String])?.first
In Swift 3+ all JSON values are Any not AnyObject so declare the array
var pokamon = [[String:Any]]()

Related

Issue with TableView and Firebase implementation (Swift)

I want to connect my TableView to what I query from Firestore. The query works, but I can't get the TableView to show the content. Right now its just a blank tableView. The TableViewCell file also has no issues, since it worked before without the firebase implementation (The Cell is registered correctly).
I suspect that the issue is in cellForRowAt and tried played around in there, but couldn't get anything to work.
Can you find the issue?
import UIKit
import Firebase
class popularViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet var table: UITableView!
var texttt = [TextPost]()
override func viewDidLoad() {
super.viewDidLoad()
gettingPosts()
table.register(textTableViewCell.nib(), forCellReuseIdentifier: textTableViewCell.identifier)
table.delegate = self
table.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
gettingPosts()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let alle = models.count + texttt.count
return alle
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: textTableViewCell.identifier, for: indexPath) as! textTableViewCell
cell.configure(with: texttt[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 300
}
func gettingPosts(){
let db = Firestore.firestore()
let postsRef = db.collection("posts")
postsRef.addSnapshotListener { (querySnapshot, error) in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added){
let data = diff.document.data()
let Name = data["username"] as! String
let text = data["description"] as! String
let likes = data["likes"] as! Int
let typ = data["postType"] as! Int
let pfp = data["profileImage"] as! String
let uid = data["uid"] as! String
let pic = data["picture"]
let time = data["time"] as! String
if typ == 0{ // Text post
let dasDing = TextPost(numberOfComments: 0, username: Name, timestampName: time, userImageName: pfp, textName: text)
self.texttt.append(dasDing)
}
}
}
}
}
}
struct TextPost {
let numberOfComments: Int
let username: String
let timestampName: String
let userImageName: String
let textName: String
}
You need to reload data once you get data from firebase
func gettingPosts(){
let db = Firestore.firestore()
let postsRef = db.collection("posts")
postsRef.addSnapshotListener { (querySnapshot, error) in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added){
let data = diff.document.data()
let Name = data["username"] as! String
let text = data["description"] as! String
let likes = data["likes"] as! Int
let typ = data["postType"] as! Int
let pfp = data["profileImage"] as! String
let uid = data["uid"] as! String
let pic = data["picture"]
let time = data["time"] as! String
if typ == 0{ // Text post
let dasDing = TextPost(numberOfComments: 0, username: Name, timestampName: time, userImageName: pfp, textName: text)
self.texttt.append(dasDing)
}
}
}
DispatchQueue.main.async {
tableView.reloadData()
}
}
}

Is there any way to list user defaults datas with swift?

I am trying to do save datas like name, address with user default at main view controller. After saving data, I wanted to list all user default data at second view controller with tableview (PeopleViewController). I managed to save user default data with main view controller. But only last saved user default data can be showed at tableview while I would like to list all data at tableview. What am I doing wrong? Can you give an idea? Thank you in advance..
My second view controller / PeopleViewController
import UIKit
class PeopleListViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
var names = [String]()
var address = [String]()
let storage = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
let peopleData = storage.value(forKey: "people") as? Data
if peopleData != nil {
let decoder = JSONDecoder()
do {
let person = try decoder.decode(People.self, from: peopleData!)
names.append(person.name)
address.append(person.address)
}catch {
print(error)
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LocationCell",for: indexPath)
cell.textLabel?.text = names[indexPath.row]
cell.detailTextLabel?.text = address[indexPath.row]
return cell
}
}
My main view controller
import UIKit
class ViewController: UIViewController {
#IBOutlet var TextFields: [UITextField]!
let storage = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
let peopleData = storage.value(forKey: "people") as? Data
if peopleData != nil {
let decoder = JSONDecoder()
do {
TextFields[0].text = ""
TextFields[1].text = ""
}catch {
print(error)
}
}
}
#IBAction func createButtonTapped(_ sender: UIButton) {
let name = TextFields[0].text!
let address = TextFields[1].text!
let people = People(
name: name,
address: address
)
let encoder = JSONEncoder()
do {
let peopleData = try encoder.encode(people)
storage.setValue(peopleData, forKey: "people")
TextFields[0].text! = ""
TextFields[1].text! = ""
}catch {
print(error)
}
}
}
My People Model
import Foundation
struct People: Codable{
var name: String
var address: String
}
Right now, you are only storing one person in UserDefaults. Every time you create a new person, you are overwriting the previous value. To store many people, you need an [People]. When you decode and encode, you can encode the whole [People].
// main VC
let encoder = JSONEncoder()
let decoder = JSONDecoder()
do {
// first decode the array from the storage
let array = storage.data(forKey: "people").map { try decoder.decode([People].self, from: $0) } ?? []
array.append(people) // add the newly created person
let newArrayData = try encoder.encode(array)
storage.set(newArrayData, forKey: "people")
TextFields[0].text! = ""
TextFields[1].text! = ""
}catch {
print(error)
}
// table VC
// you don't need two parallel arrays
var people: [People] = []
let storage = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
do {
people = try storage.data(forKey: "people").map { try decoder.decode([People].self, from: $0) } ?? []
} catch let error {
print(error)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LocationCell",for: indexPath)
cell.textLabel?.text = people[indexPath.row].name
cell.detailTextLabel?.text = people[indexPath.row].address
return cell
}

Swift Fatal Error index out of range while using searchbar in tableview

i try to load an json data with tableView and i wanna add search data using uiSearchBar, data is search well but when i try to hit 'x' button on the searchBar or when i try to backspace the input it crash...Any help guys? or should i change my search method? thanks for the help. I'm still new in swift so if theres a better method to search please let me know:)
struct ProjectSumName: Decodable {
let id : Int
let name : String
enum CodingKeys : String, CodingKey {
case id = "id"
case name = "name"
}
}
class ProjectSumController: UIViewController {
#IBOutlet weak var SearchBar: UISearchBar!
#IBOutlet weak var ProjectSumTableView: UITableView!
var projectSum = [ProjectSumName]()
var filterProject : [ProjectSumName] = [ProjectSumName]()
var isSearch : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
SearchBar.delegate = self
Loading()
let jsonUrl = "http://\(GlobalVariable.ip):7000/api/projectApi?UserId=\(GlobalVariable.UserIdProjectSum)"
guard let url = URL(string: jsonUrl) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do{
let projectsum = try JSONDecoder().decode([ProjectSumName].self, from: data)
self.projectSum = projectsum
self.filterProject = projectsum
DispatchQueue.main.async {
SVProgressHUD.dismiss()
self.ProjectSumTableView.reloadData()
}
}catch {
print(error)
}
}.resume()
}
}
extension ProjectSumController : UISearchBarDelegate, UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearch{
return filterProject.count
}else{
return projectSum.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let proc = projectSum[indexPath.row]
let proc1 = filterProject[indexPath.row]
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? ProjectSumTableCell else {return UITableViewCell()}
if isSearch{
cell.NameLbl.text = proc1.name
}else{
cell.NameLbl.text = proc.name
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sum = projectSum[indexPath.row]
let sum1 = filterProject[indexPath.row]
if isSearch{
performSegue(withIdentifier: "Segue", sender: sum1)
let projectIDs = sum1.id
GlobalVariable.ProjectId = String(projectIDs)
}else{
performSegue(withIdentifier: "Segue", sender: sum)
let projectID = sum.id
GlobalVariable.ProjectId = String(projectID)
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty{
self.isSearch = false;
self.ProjectSumTableView.reloadData()
} else {
self.filterProject = self.projectSum.filter({ (ProjectSumName) -> Bool in
let tmp : NSString = NSString.init(string: ProjectSumName.name)
let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound && range.location == 0
})
if(self.filterProject.count == 0){
self.isSearch = false;
}else{
self.isSearch = true;
}
self.ProjectSumTableView.reloadData()
}
}
"Fatal error: Index out of range
2019-06-27 09:43:46.167472+0700 ImmobiTracker[806:30114] Fatal error: Index out of range"
that crash come up everything i try to clear my searchbar...so when i try to type the first time to search its filtering the data, but when i try to clear the search bar it pop crash
There are two places where you are getting this error.
in cellForRowAt:
let proc = projectSum[indexPath.row]
let proc1 = filterProject[indexPath.row]
didSelectRowAt
let sum = projectSum[indexPath.row]
let sum1 = filterProject[indexPath.row]
Why:
You are trying to get an element from filterProject without using isSearch i.e. filterPoject array is empty. When isSearch is false then the error occurs because you are trying to get the element from the empty array.
How to Solve this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sum: ProjectSumName
if isSearch{
sum = filterProject[indexPath.row]
}else{
sum = projectSum[indexPath.row]
}
GlobalVariable.ProjectId = String(sum.id)
performSegue(withIdentifier: "Segue", sender: sum)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? ProjectSumTableCell else {return UITableViewCell()}
let proc: ProjectSumName
if isSearch{
proc = filterProject[indexPath.row]
}else{
proc = projectSum[indexPath.row]
}
cell.NameLbl.text = proc.name
return cell
}

Index out of range custom cell TableViewController

I'm trying to populate 3 custom cells into a TableViewController.
but I always get index out of range error. I`m not sure whats wrong with my code. anyone can help me, I'm newbie in swift.
but when i use 0 for numberOfRowsInSection return, the output is the first cell.
here's my code :
class testResize: UITableViewController {
#objc var comments = [AnyObject]()
#objc var images = [UIImage]()
var getImg = [String]()
override func viewDidLoad() {
super.viewDidLoad()
loadPosts()
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let getCom = comments[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: testResizeHeadCell.self), for: indexPath) as! testResizeHeadCell
let user = getCom["nickname"] as! String
let ava = getCom["ava"] as! String
if ava != "" {
let resource = ImageResource(downloadURL: URL(string: ava)!, cacheKey: ava)
cell.avaImg.kf.setImage(with: resource)
}
cell.username.text = user
return cell
}else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: testResizeCell.self), for: indexPath) as! testResizeCell
cell.setCustomImage(image: images[indexPath.row])
return cell
}else {
let getCom = comments[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: testRezieTextCell.self), for: indexPath) as! testRezieTextCell
let text = getCom["text"] as! String
cell.explaination.text = text
return cell
}
}
here is my load function :
#objc func loadPosts() {
let uuid = "959D1073"
let url = URL(string: "some/url.php")!
self.tableView.reloadData()
var request = URLRequest(url: url)
request.httpMethod = "POST"
let body = "uuid=\(uuid)"
//print(body)
request.httpBody = body.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error == nil {
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
self.comments.removeAll(keepingCapacity: false)
self.images.removeAll(keepingCapacity: false)
self.tableView.reloadData()
guard let parseJSON = json else {
print("Error While Parsing")
return
}
guard let posts = parseJSON["posts"] as? [AnyObject] else {
print("Error while parseJSONing")
return
}
self.comments = posts.reversed()
print(self.comments)
for i in 0 ..< self.comments.count {
let path = self.comments[i]["path"] as? String
self.getImg = [path!]
if !path!.isEmpty {
let url = NSURL(string: path!)!
let imageData = try? Data(contentsOf: url as URL)
let image = UIImage(data: imageData! as Data)!
self.images.append(image)
} else {
let image = UIImage()
self.images.append(image)
}
}
self.tableView.reloadData()
//print(posts)
} catch {
print(error)
}
}else{
print(error!)
}
})
}.resume()
}
i think you have a single comment and 3 cell type and when you use indexPath.row happen some thing like this :
for example :
comments = {[{nickname : "mahdi" , ava : "url"} ]}
if indexPath.row == 0 {
let getCom = comments[0]
let user = getCom["nickname"] as! String
let ava = getCom["ava"] as! String
}else if indexPath.row == 1 {
images[1]
}else {
let getCom = comments[2]
let text = getCom["text"] as! String
}
but you have just one comment and when you call comments[1] or commens [2] , you get index out of range error
please try this code :
class testResize:UITableViewController {
#objc var comments = [AnyObject]()
#objc var images = [UIImage]()
var getImg = [String]()
override func viewDidLoad() {
super.viewDidLoad()
loadPosts()
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.comments.count == 0 ? 0 : self.comments.count + 2)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let getCom = comments[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: testResizeHeadCell.self), for: indexPath) as! testResizeHeadCell
let user = getCom["nickname"] as! String
let ava = getCom["ava"] as! String
if ava != "" {
let resource = ImageResource(downloadURL: URL(string: ava)!, cacheKey: ava)
cell.avaImg.kf.setImage(with: resource)
}
cell.username.text = user
return cell
}else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: testResizeCell.self), for: indexPath) as! testResizeCell
cell.setCustomImage(image: images[indexPath.row - 1])
return cell
}else {
let getCom = comments[indexPath.row - 2]
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: testRezieTextCell.self), for: indexPath) as! testRezieTextCell
let text = getCom["text"] as! String
cell.explaination.text = text
return cell
}
}
and change your numberOfRowInSection :
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return (self.comments.count == 0 ? 0 : self.comments.count + 2)
}
I am assuming that you load your posts asynchronously.
But you do not check if there are actually enough elements in the array. You should check if there are actually enough elements in the array before you access it with a fixed index.
Additionally, you should change your numberOfRows method to the following:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.comments.count
}
After you have loaded your posts, you can then call
self.tableView.reloadData()

Swift TableView doesn't return numbersOfRow

import UIKit
import SwiftyJSON
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var tableView: UITableView!
var mass = [String]()
var jDatas = datas()
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.quandl.com/api/v3/datasets/WIKI/AAPL.json")
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
if error != nil {
print("error")
} else {
if let content = data {
let myJson = JSON(data: content)
for item in myJson["dataset"]["data"] {
let dates = "open \(String(describing: item.1[1].string)))"
self.mass.append(dates)
}
}
}
}
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mass.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SimpleTableViewCell
cell.datasLabel?.text = "some text"
return cell
}
}
So my problem is that numberOfRowInSection doesn't work, I tried everything, can someone say whats the problem?
When I'm trying to debug the code it says that theres 0 in my massive
You forgot to reload the tableView after your for loop in dataTask's closure, so simply reload the tableView also on main thread.
for item in myJson["dataset"]["data"] {
let dates = "open \(String(describing: item.1[1].string)))"
self.mass.append(dates)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}