In my Swift code to handle push notification I have this image:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableView:UITableView?
var items = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
let frame:CGRect;(x:0, y: 100, width: self.view.frame.width, height: self.view.frame.height-100)
self.tableView = UITableView(frame: frame)
self.tableView?.dataSource = self
self.tableView?.delegate = self
self.view.addSubview(self.tableView!)
let btn = UIButton(frame: CGRect(x: 0, y: 25, width: self.view.frame.width, height: 50))
btn.backgroundColor = UIColor.cyanColor()
btn.setTitle("EKLE", forState: UIControlState.Normal)
btn.addTarget(self, action: "addData", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
}
func addData(){
RestApiManager.sharedInstance.getRandomUser { json -> Void in
let results = json["results"]
for (index: String, subJson: JSON) in results{
let user: AnyObject = subJson["user"].object
self.items.addObject(user)
dispatch_async(dispatch_get_main_queue(), {
tableView?.reloadData()
})
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell?
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "cell")
}
let user:JSON = JSON(self.items[indexPath.row])
let picURL = user["picture"]["medium"].string
let url = NSURL(string: picURL!)
let data = NSData(contentsOfURL: url!)
cell?.textLabel?.text = user["username"].string
cell?.imageView?.image = UIImage(data: data!)
return cell!
}
}
Here is the error:
Use of unresolved identifier 'subJson'
in line let user: AnyObject = subJson["user"].object
How would this be fixed?
If you are using Swift 2 (Xcode 7) the syntax for looping over a dictionary with typed parameters has changed.
Now you should do like this:
for (index, subJson):(String, JSON) in results {
let user: AnyObject = subJson["user"].object
self.items.addObject(user)
dispatch_async(dispatch_get_main_queue(), {
tableView?.reloadData()
})
}
Old way:
(index: String, subJson: JSON)
New way:
(index, subJson):(String, JSON)
Related
I'm facing an error with parisng a JSON.
I can see that I have type mismatch however I'm not sure how to fix it:
typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))
var dataModel = [Model]()
This is my model:
import Foundation
struct Model: Codable {
let basepath: String
let items: [Item]
}
struct Item: Codable {
let title: String
let abstract: String
let thumbnail: String
}
And this is my root view controller within which I'm parsing JSON.
import UIKit
class ViewController: UIViewController {
private let hostingView = UIView()
let cellID = "cell"
var dataModel = [Country]()
let tableView: UITableView = {
let table = UITableView()
table.rowHeight = 100
table.translatesAutoresizingMaskIntoConstraints = false
return table
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.showSpinner(on: hostingView)
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
configureConstraints()
tableView.delegate = self
tableView.dataSource = self
tableView.register(TableViewCell.self, forCellReuseIdentifier: cellID)
performRequest()
}
private func configureView(){
view.backgroundColor = .white
title = "Game Of Thrones"
navigationController?.navigationBar.prefersLargeTitles = true
}
private func configureConstraints(){
view.addSubview(tableView)
tableView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
private func performRequest(){
let url = "https://gameofthrones.fandom.com/api/v1/Articles/Top?expand=1&category=Articles&limit=75"
let urlString = URL(string: url)
guard urlString != nil else {return}
print(String("URL: \(urlString)"))
let session = URLSession(configuration: .default)
let dataTask = session.dataTask(with: urlString!) { (data, response, error) in
if error == nil && data != nil {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode([Country].self, from: data!)
self.dataModel = decodedData
print(self.dataModel)
DispatchQueue.main.async {
self.removeSpinner()
self.tableView.reloadData()
}
} catch {
DispatchQueue.main.async {
print(error)
self.performRequestError()
}
}
}
}
dataTask.resume()
}
private func performRequestError(){
let ac = UIAlertController(title: "Error", message: "Cannot load data", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(ac, animated: true)
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if dataModel.count > 0 {
// return dataModel[0].items.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! TableViewCell
cell.textLabel?.text = "title"
return cell
}
}
I am in a bind.
My regular developer has secured a full time gig, and I am trying to finish a project.
Literally stuck on the last line of code.....
I have a tableview that parses a json file to populate and open a pdf file when a row is selected.
I reworked the tableview in order to add a searchbar and associated code, which works when running the bundle.
I am, however, stuck with connecting the didSelectRow with the appropriate pdf file.
Can someone please lend a hand? Thanks
import UIKit
import WebKit
// Model
struct Section {
var section: String
var pdfs: [PDF]
}
struct PDF {
var code: String
var name: String
var airport: String
}
class PdfVC: UIViewController {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var webView: WKWebView!
#IBOutlet weak var tableViewLeft: NSLayoutConstraint!
#IBOutlet weak var btnMenuLeft: NSLayoutConstraint!
#IBOutlet weak var btnMenu: UIButton!
#IBOutlet weak var searchBar: UISearchBar!
//json
var jsonData: [Section] = []
var filtedJsonData: [Section] = []
//WebView
var fileName: String?
var isVideo: Bool = false
var btnMenuClose:UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
// Setup TableView
tableView.delegate = self
tableView.dataSource = self
setupData()
tableView.reloadData()
// Setup SearchBar
searchBar.delegate = self
// Setup WebView
if let fileName = fileName {
isVideo = fileName.contains(".mp4")
if let range = fileName.range(of: isVideo ? ".mp4" : ".pdf") {
self.fileName!.removeSubrange(range)
}
}
if let file = Bundle.main.url(forResource: fileName ?? "", withExtension: isVideo ? ".mp4" : ".pdf", subdirectory: nil, localization: nil) {
let request = URLRequest(url: file)
webView.load(request)
}
if let image = UIImage(named: "ico_close") {
navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(onWebTap))
//self.navigationItem.leftItemsSupplementBackButton = true
btnMenuClose = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(onWebTap))
self.navigationItem.rightBarButtonItems = [btnMenuClose!];
}
//navigationItem.title = "Airport Maps"
}
private func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
#objc private func dismissKeyboard() {
view.endEditing(true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
// title color to white
let titleTextAttributed: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.white, .font: UIFont(name: "HelveticaNeue-Light", size: 20) as Any]
self.navigationController?.navigationBar.titleTextAttributes = titleTextAttributed
// back arrow white
self.navigationController?.navigationBar.tintColor = UIColor.white
// blueish navigation bar
self.navigationController?.navigationBar.barTintColor = UIColor(red: 0.00, green: 0.54, blue: 0.92, alpha: 1.00)
self.navigationController?.navigationBar.isTranslucent = false
showMenu(false, animated: false)
}
private func setupData() {
// Parse data from local json file
if let path = Bundle.main.path(forResource: "airports", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? [Dictionary<String, String>] {
for result in jsonResult {
if !jsonData.contains(where: { $0.section == result["Section"] }) {
let section = Section(section: result["Section"] ?? "", pdfs: [])
jsonData.append(section)
}
let pdf = PDF(code: result["Code"] ?? "", name: result["Filename"] ?? "", airport: result["Name"] ?? "")
let index = jsonData.firstIndex(where: { $0.section == result["Section"] })
if let index = index {
jsonData[index].pdfs.append(pdf)
}
}
}
} catch {
// Handle error
print("error parsing json")
}
}
// Sort data before use
jsonData.sort(by: { $0.section < $1.section })
for index in 0..<jsonData.count {
jsonData[index].pdfs.sort(by: { $0.airport < $1.airport } )
}
filtedJsonData = jsonData
}
#objc func onWebTap() {
var left:CGFloat = 0
if tableViewLeft.constant == 0 {
left = -320
}
tableViewLeft.constant = left
showMenu(left != 0, animated: true)
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
func showMenu(_ show:Bool, animated:Bool) {
if let image = UIImage(named: show ? "ico_open" : "ico_close") {
btnMenuClose?.image = image
//navigationItem.rightBarButtonItem?.image = image
//}
//var left:CGFloat = 20
//if show == false {
// left = -64
}
//btnMenuLeft.constant = left
UIView.animate(withDuration: animated ? 0.3 : 0.0, delay: 0, options: .curveEaseInOut, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
// TableView
extension PdfVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return filtedJsonData.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if filtedJsonData[section].pdfs.count == 0 {
return nil
}
return filtedJsonData[section].section
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filtedJsonData[section].pdfs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PdfCell", for: indexPath) as! PdfCell
let pdf = filtedJsonData[indexPath.section].pdfs[indexPath.row]
cell.setupCell(pdf: pdf)
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
dismissKeyboard()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let pdf = filtedJsonData[indexPath.section].pdfs[indexPath.row]
//THIS IS WHERE I'M STUCK<<<<<<<<<
self.title = pdf.airport
}
}
// SearchBar
extension PdfVC: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
for (index, data) in jsonData.enumerated() {
// Filter pdfs by code and name
let filtedPdf = data.pdfs.filter { $0.code.lowercased().prefix(searchText.count) == searchText.lowercased() || $0.airport.lowercased().prefix(searchText.count) == searchText.lowercased() }
filtedJsonData[index].pdfs = filtedPdf
}
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
tableView.reloadData()
}
}
Got it figured out. Thanks for all who spent some time reading my issue. I changed as follows
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let pdf = filtedJsonData[indexPath.section].pdfs[indexPath.row]
self.fileName = pdf.name
self.title = pdf.airport
DispatchQueue.main.async {
self.reloadWebView()
}
}
and added
private func reloadWebView() {
// Setup WebView
if let fileName = fileName {
isVideo = fileName.contains(".mp4")
if let range = fileName.range(of: isVideo ? ".mp4" : ".pdf") {
self.fileName!.removeSubrange(range)
}
}
if let file = Bundle.main.url(forResource: fileName ?? "", withExtension: isVideo ? ".mp4" : ".pdf", subdirectory: nil, localization: nil) {
let request = URLRequest(url: file)
webView.load(request)
}
}
I would like some help with the search bar functionality. I am stuck and not sure where to take it from here. I am trying to update the tableview when search text word is contained in a recipe title. I am not sure how to do this because of the depreciated searchDisplay controller. Help would be appreciated.
import UIKit
import SwiftyJSON
class Downloader {
class func downloadImageWithURL(_ url:String) -> UIImage! {
let data = try? Data(contentsOf: URL(string: url)!)
return UIImage(data: data!)
}
}
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchDisplayDelegate{
#IBOutlet weak var recipeTable: UITableView!
// search functionality Need help with my search functionality
var filteredRecipes = [Recipe]()
func filterContentForSearch(searchText:String) {
// need help here
self.filteredRecipes = self.recipes.filter({(title:Recipe) -> Bool in
return (title.title!.lowercased().range(of: searchText.lowercased()) != nil)
})
}
private func searchDisplayController(controller: UISearchController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
self.filterContentForSearch(searchText: searchString)
return true
}
//end search parameters
// tableview functionionalitys
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == searchDisplayController!.searchResultsTableView {
return filteredRecipes.count
}else{
return recipes.count
}
// recipeTable.reloadData()
}
// tableview functionalities
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RecipeTableViewCell
if tableView == self.searchDisplayController!.searchResultsTableView{
//get images from download
DispatchQueue.main.async { () ->Void in
cell.imageLabel.image = Downloader.downloadImageWithURL(self.filteredRecipes[indexPath.row].imageUrl)
}
cell.recipeLabel.text = self.filteredRecipes[indexPath.row].title
recipeTable.reloadData()
}else{
//get image from download
DispatchQueue.main.async { () ->Void in
cell.imageLabel.image = Downloader.downloadImageWithURL(self.recipes[indexPath.row].imageUrl)
}
cell.recipeLabel.text = recipes[indexPath.row].title
}
//recipeTable.reloadData()
return cell
}
// structs for json
struct Root : Decodable {
let count : Int
let recipes : [Recipe]
}
struct Recipe : Decodable { // It's highly recommended to declare Recipe in singular form
let recipeId : String
let imageUrl, sourceUrl, f2fUrl : String
let title : String?
let publisher : String
let socialRank : Double
let page : Int?
let ingredients : [String]?
}
//recipes is array of Recipes
var recipes = [Recipe]() // array of recipes
//unfiltered recipes to put into search
fileprivate func getRecipes() {
let jsonURL = "https://www.food2fork.com/api/search?key=264045e3ff7b84ee346eb20e1642d9d9"
//.data(using: .utf8)!
guard let url = URL(string: jsonURL) else{return}
URLSession.shared.dataTask(with: url) {(data, response , err) in
if let response = response as? HTTPURLResponse, response.statusCode != 200 {
print(response.statusCode)
return
}
DispatchQueue.main.async {
if let err = err{
print("failed to get data from URL",err)
return
}
guard let data = data else{return}
//print(String(data: data, encoding: .utf8))
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(Root.self, from: data)
self.recipes = result.recipes
//print(result.recipes)
self.recipeTable.reloadData()
}catch let jsonERR {
print("Failed to decode",jsonERR)
}
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
//recipeTable.reloadData()
//search bar
//filteredRecipes = recipes
//call json object
getRecipes()
}
}
You could take this approach:
Add a Boolean variable to indicate whether searching or not
var searching: Bool = false
Use this for numberOfRowsInSection for the tableview
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return filteredRecipes.count
} else {
return recipes.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RecipeTableViewCell
var recipe: Recipe
if searching {
recipe = filteredRecipes[indexPath.row]
} else {
recipe = recipes[indexPath.row]
}
DispatchQueue.main.async { () ->Void in
cell.imageLabel.image = Downloader.downloadImageWithURL(recipe.imageUrl)
}
cell.recipeLabel.text = recipe.title
return cell
}
And add this for the searchBar (set searching for other funcs like searchBarCancelButtonClicked)
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
searching = false
filteredRecipes.removeAll()
view.endEditing(true)
} else {
searching = true
filteredRecipes = recipes.filter{$0.title.contains(searchBar.text!)}
}
tableView.reloadData()
}
Here i have created table view with labelName and labelUsername,
and i have downloaded Json data and saving it in core data entity called Details which contains attributes name and username..
here table view showing its data in online...
but how can i show fetched data in table view while in offline..
please help me in the code...
import UIKit
import CoreData
struct JsonData {
var nameS: String
var usernameS: String
init(name: String, username: String) {
self.nameS = name
self.usernameS = username
}
}
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var iteamsArray = [JsonData]()
override func viewDidLoad() {
downloadJson()
}
func downloadJson(){
let urlStr = "https://jsonplaceholder.typicode.com/users"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
guard error == nil else {
print("error")
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String: Any]]
for items in jsonObj {
let nameJson = items["name"] as? String
let usernameJson = items["username"] as? String
let coreData = NSEntityDescription.insertNewObject(forEntityName: "Details", into: self.context) as! Details
coreData.name = nameJson
coreData.username = usernameJson
self.iteamsArray.append(JsonData(name: nameJson!, username: usernameJson!))
}
try self.context.save()
//fetching from core data
let fetchRequest : NSFetchRequest<Details> = Details.fetchRequest()
let details = try self.context.fetch(fetchRequest)
if details.count > 0 {
for detail in details as [NSManagedObject] {
let nameCore = detail.value(forKey: "name")
let usernameCore = detail.value(forKey: "username")
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
}
// MARK: - TableView
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return iteamsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "JsonCell", for: indexPath) as! JsonTableViewCell
let aData = iteamsArray[indexPath.row]
cell.labelName.text = aData.nameS
cell.labelUsername.text = aData.usernameS
cell.selectionStyle = .none
return cell
}
}
First of all forget the custom struct. Use the NSManagedObject class as data source array.
var iteamsArray = [Details]()
In viewDidLoad first fetch the data, if the array is empty load it from the web service
override func viewDidLoad() {
let fetchRequest : NSFetchRequest<Details> = Details.fetchRequest()
do {
iteamsArray = try self.context.fetch(fetchRequest)
if iteamsArray.isEmpty {
downloadJson()
} else {
self.tableView.reloadData()
}
} catch { print(error) }
}
In downloadJson() replace
self.iteamsArray.append(JsonData(name: nameJson!, username: usernameJson!))
with
self.iteamsArray.append(coreData)
and remove these lines
//fetching from core data
let fetchRequest : NSFetchRequest<Details> = Details.fetchRequest()
let details = try self.context.fetch(fetchRequest)
if details.count > 0 {
for detail in details as [NSManagedObject] {
let nameCore = detail.value(forKey: "name")
let usernameCore = detail.value(forKey: "username")
}
}
In cellForRow get the values directly from the NSManagedObject objects
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "JsonCell", for: indexPath) as! JsonTableViewCell
let aData = iteamsArray[indexPath.row]
cell.labelName.text = aData.name
cell.labelUsername.text = aData.userName
cell.selectionStyle = .none
return cell
}
I have parsed a json string and i want to use it in a tableview. when i try to append the json string into an array the append method is not working. Here is the code that i have used. Can anyone help me with this?
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var userName = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// 1
let urlAsString = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
}
// 3
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
/*let err: NSError!
if (err != nil) {
print("JSON Error \(err.localizedDescription)")
}*/
// 4
//let fname: String! = jsonResult["firstname"] as! String
//let lname: String! = jsonResult["lastname"] as! String
//let usrname: String! = jsonResult["username"] as! String
dispatch_async(dispatch_get_main_queue(), {
if let users = jsonResult.objectForKey("Users") as? [[String:AnyObject]]
{
for user in users
{
print("First Name:")
print(user["firstname"]!)
print("Last Name:")
print(user["lastname"]!)
print("User Name:")
let nameUser = user["username"]! as! String
print(nameUser)
self.userName.append(nameUser)
print("***************")
}
}
//print(jsonResult["Users"]!)
//print(lname)
//print(usrname)
})
}
catch {
print("error");
}
})
jsonQuery.resume()
//self.userName.append("ganesh")
// 5
print(userName)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userName.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
cell.textLabel?.text = userName[indexPath.row]
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
userName.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You are appending right in the array,Just call self.tableView.reloadData() to refresh table view at the end of dispatch to show the data in the tableView.
The append function works fine but you are filling the array in the background and never reloading the tableView when you have the data in the array
for user in users
{
if let nameUser = user["username"] as? String {
self.userName.append(nameUser)
}
}
self.tableView.reloadData()
Try this inside the if let users = jsonResult.objectForKey("Users") as? [[String:AnyObject]] block