I am receiving a JSON file from a remote server and I can display the result in a label. The JSON data is working fine when I call function processJSONData() and the tableview works fine with a simple array. How can I incorporate both to display the result from the JSON file in the tableview? Kindly look at the code below and edit. Many thanks:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var countryLabel: UILabel!
#IBOutlet weak var capitalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//processJSONData()
self.myTableView.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell")
self.myTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func processJSONData(){
let urlPath = "http://dubaisinan.host22.com/service1.php"
let url : NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url,completionHandler: {(data, respose, error) -> Void in
if error != nil {
println(error)
}
else {
self.abc(data)
}
})
task.resume()
}
func abc(data:NSData)
{
var parseError: NSError?
let result:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError);
if(parseError == nil){
if let dictResult = result as? NSArray{
dispatch_async(dispatch_get_main_queue()) {
self.countryLabel.text = dictResult[2]["Capital"] as? String
}
}
}
}
#IBOutlet weak var myTableView: UITableView!
var items = ["One","Two", "Three","Four"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.myTableView
.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
}
I don't see you assign your parsing result to global "items" and reload tableview with new data anywhere.
could be done here
if let dictResult = result as? NSArray{
self.items = dictResult
self.myTableView.reloadData()
///the rest of the code
}
You have to save the JSON data into a class-level variable, which you will define outside of any function, similar to how you defined "items". Assuming you have a list of countries with the capital of each, this might look like so:
var countryAndCapitalData = [(country: String, capital: String)]()
This could be improved by first defining a struct to contain your data:
struct CountryInfo
{
name: String
capital: String
init(name:String, capital:String)
{
self.name = name
self.capital = capital
}
}
which lets you define your data array as an array of CountryInfo:
var countryAndCapitalData = [CountryInfo]()
Then in your "abc" function (which I insist you rename to something like processCountryData), store the pairs of country name + capital name strings in countryAndCapitalData. For example:
countryAndCapitalData.append(CountryInfo(countryName, capitalName))
Use a For loop to loop through values in dictResult. Creating countryName and capitalName depends on the structure of your JSON, but from your example it might look like this:
for countryDictionary in dictResult[2]
{
if let countryName = countryDictionary["country"], let capitalName = countryDictionary["capital"]
{
countryAndCapitalData.append(CountryInfo(countryName, capitalName))
}
}
Then in tableView.cellForRowAtIndexPath, populate the cell label(s) with countryAndCapitalData[indexPath.row].name and countryAndCapitalData[indexPath.row].capital.
And finally, be sure to reload the table after the loop (thanks Eugene):
dispatch_async(dispatch_get_main_queue()) {
self.myTableView.reloadData()
}
Apologies for any compilation errors, as I'm typing this from a Windows machine.
You should update your items property in abc method call and then refresh the table:
func abc(data: NSData) {
// Do something with data
items = .. // processed data
}
var items: [String]? {
didSet {
NSOperationQueue.mainQueue.addOperationWithBlock {
self.tableView.reloadData()
}
}
}
Related
My scenario I am using multiple array's for multiple cell label's. Per cell two different label's I am maintaining. I assigned separate array's for cell labels.
Like:
cell.accessibilityValue = String(id[indexPath.row])
cell.name_Label.text = name[indexPath.row]
cell.city_Label.text = city[indexPath.row]
here, all array values I am getting from my JSON and appending separately. Only name and city I am going to show but cell.accessibilityValue "ID" I am trying to store that ID within cell.accessibilityValue because I am maintaining two buttons within cell ADD and Plus. First Add will show, once user clicked that add button, It will call JSON and get ID values after that only ID values appending within cell.accessibilityValue = String(id[indexPath.row]) then reloading also I will.
Issues I am facing:
Initially no values in
cell.accessibilityValue = String(id[indexPath.row]) so I am
getting out of range error.
After add button I am trying to append the ID values into id array
and it should assign into my cell because after add clicked it will
hide and plus button will be display, for plus button click to get
that stored ID.
NOTE: here ID may have chance to come null, so if values available need to assign otherwise null.
Here my code
protocol CustomCellDelegate {
func cellButtonTapped(cell: CustomOneCell)
}
class CustomOneCell: UITableViewCell {
// Link those IBOutlets with the UILabels in your .XIB file
#IBOutlet weak var name_Label: UILabel!
#IBOutlet weak var city_Label: UILabel!
#IBOutlet weak var add_Button: UIButton!
var delegate: CustomCellDelegate?
#IBAction func add_buttonTapped(_ sender: Any) {
delegate?.cellButtonTapped(cell: self)
}
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CustomCellDelegate {
var id = [Int]() // This is from JSON but Initially no values
var name = [String]() // This is from JSON ["Item 1", "Item2", "Item3", "Item4"]
var city = [String]() // This is from JSON ["Item 1", "Item2", "Item3", "Item4"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK - UITableview
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return name.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomOneCell
cell.delegate = self
cell.accessibilityValue = String(id[indexPath.row]) // #1. Initially no values, So I am getting out of range Error
cell.name_Label.text = name[indexPath.row]
cell.city_Label.text = city[indexPath.row]
return cell
}
func cellButtonTapped(cell: CustomOneCell) {
let url = URL(string: "")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print("request failed \(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
for item in json {
let id = item["id"]!
self.id.append(id as! Int) // #2. After table load I am appending some values into id array
}
//Table reload to assign id values
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString!)")
}
}
task.resume()
}
The simplest way forward is to add a range check in tableView:cellForRowAt
if indexPath.row < id.count {
cell.accessibilityValue = String(id[indexPath.row])
}
But if it is possible I would look into creating a struct with all three values and maintaining one instead of three arrays
struct SomeData {
var id: Int
var name: String
var city: String
}
I am building an app whereby you enter ingredients and you return a bunch of recipes based on your input. I'm making the calls to the API using alamofire and these seem to be successful. The problem I'm having is the 6 results in my test call are repeating 1 recipe 6 times rather than returning all the results in separate cells. This is the API call code:
import Alamofire
class RecipeAp: NSObject{
var concoctions = [RecipeDetails]()
func provideRecipeDetailsForName(name: String, completed:#escaping ([RecipeDetails]) -> Void) {
let urlSearchString = URL_FULL + "onion" + "soup"
Alamofire.request(urlSearchString).responseJSON(completionHandler: { response in
let details = RecipeDetails()
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let matches = dict["matches"] as? [[String: Any]] {
for ingredient in matches {
if let name = ingredient["ingredients"] as? [String] {
details.ingredients = name
self.concoctions.append(details)
}
}
for recipeName in matches {
if let name = recipeName["recipeName"] as? String {
details.recipeTitle = name
print("the recipe name = \(name.debugDescription)")
self.concoctions.append(details)
}
}
}
completed(self.concoctions)
}
})
}
}
This is my model:
class RecipeDetails: NSObject {
var recipeID: String?
var recipeImageURL: String?
var recipeTitle: String?
var recipeSourceURL: String?
var recipePublisher: String?
var ingredients: [String]?
}
This is my customCell setup
import UIKit
class RecipeListCustomCell: UITableViewCell {
#IBOutlet weak var recipeTitle: UILabel!
#IBOutlet weak var recipeUrl: UILabel!
var recipe: RecipeDetails? {
didSet {
updateView()
}
}
func updateView() {
recipeTitle.text = recipe?.recipeTitle
recipeUrl.text = recipe?.recipeSourceURL
}
}
And finally this is my viewController
import UIKit
class MainVC: UIViewController {
#IBOutlet weak var tableView: UITableView!
var recipe = RecipeAp()
var results = [RecipeDetails]()
override func viewDidLoad() {
super.viewDidLoad()
loadRecipes()
}
func loadRecipes() {
recipe.provideRecipeDetailsForName(name: "onion" + "soup") { (response) in
self.results = response
self.tableView.reloadData()
}
}
}
extension MainVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return results.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"RecipeListCustomCell", for: indexPath) as! RecipeListCustomCell
let recipe = results[indexPath.row]
cell.recipe = recipe
return cell
}
}
Not sure how to display all the recipes separately in each cell. I have also attached some screen shots on what I am getting back from the API and the display in the simulator.
You create only one instance of RecipeDetails for each response. So, you add exactly the same reference into your self.concoctions repeatedly.
You may need to write something like this:
func provideRecipeDetailsForName(name: String, completed: #escaping ([RecipeDetails]) -> Void) {
let urlSearchString = URL_FULL + "onion" + "soup"
Alamofire.request(urlSearchString).responseJSON(completionHandler: { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let matches = dict["matches"] as? [[String: Any]] {
for match in matches {
//### Create a new instance for each iteration.
let details = RecipeDetails()
if let ingredients = match["ingredients"] as? [String] {
details.ingredients = ingredients
}
if let recipeName = match["recipeName"] as? String {
details.recipeTitle = recipeName
print("the recipe name = \(recipeName.debugDescription)")
}
//### Add the instance once in the iteration
self.concoctions.append(details)
}
}
completed(self.concoctions)
}
})
}
I use a service in a background thread to fetch a post request. Then I use NSJSONSerialization to turn that into an array. I loop thorough the array to create an array of teams. Then i go back to the main queue and call the completion handler.
Team:
class Team
{
private (set) var id: Int
private (set) var city: String
private (set) var name: String
private (set) var abbreviation: String
init(data: JSONDictionary)
{
id = data["team_id"] as? Int ?? 0
city = data["city"] as? String ?? ""
name = data["team_name"] as? String ?? ""
abbreviation = data["abbreviation"] as? String ?? ""
}
}
Service:
func getTeams(urlString: String, completion: [Team] -> Void)
{
let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let session = NSURLSession(configuration: config)
let url = NSURL(string: urlString)!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request) {
(data, response, error) in
if error != nil {
print(error!.localizedDescription)
} else {
print(data)
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? JSONArray {
var teams = [Team]()
for team in json {
let team = Team(data: team as! JSONDictionary)
teams.append(team)
}
let priority = DISPATCH_QUEUE_PRIORITY_HIGH
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(dispatch_get_main_queue()) {
completion(teams)
}
}
}
} catch {
print("error in NSJSONSerialization")
}
}
}
task.resume()
}
I then try to use data to populate a tableView. I also loop through and print out all the team names to the console with success. The problem I am having It populate the tableView but everything is all white. I cant see any txt from my labels until I touch it. While the table cell is selected I can see the contents of the labels which are in black. But if i touch another one only the currently selected label is showing. It seems they should all just show up visible once the data is loaded.
custom cell:
class TeamTableViewCell: UITableViewCell {
var team: Team? {
didSet {
updateCell()
}
}
#IBOutlet weak var title: UILabel!
#IBOutlet weak var abbreviation: UILabel!
func updateCell()
{
title.text = team?.name ?? ""
abbreviation.text = team?.abbreviation ?? ""
}
}
Controller:
var teams = [Team]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Teams"
let service = NBAService()
service.getTeams("https://probasketballapi.com/teams?api_key=\(Constants.API.APIKey)", completion: didLoadTeams )
}
func didLoadTeams(teams: [Team])
{
self.teams = teams
tableView.reloadData()
// This actuall works returns an list of team names to the console.
for team in teams {
print("Team: \(team.name)")
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return teams.count
}
struct Storyboard {
static let TeamCell = "TeamCell"
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.TeamCell, forIndexPath: indexPath) as! TeamTableViewCell
// Configure the cell...
cell.team = self.teams[indexPath.row]
return cell
}
When i print the teams names to the console that prints fine so I know that I have successfully got the data back from the request. And one team at a time is visible when the cell is selected. What am I missing
This is kind of strange:
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(dispatch_get_main_queue()) {
completion(teams)
}
}
I would replace this with:
dispatch_async(dispatch_get_main_queue()) {
completion(teams)
}
I have a problem with reload data in tableView in my simple swift app for iOS.
If I for the first time enter the city name into the cityTextField and press the getDataButton, so the data displays correctly, but If I enter the new city name into cityTextField and press button, so data are still the same like for the first city.
ViewController
import UIKit
class ViewController: UIViewController,UITableViewDelegate {
var arrDict :NSMutableArray=[]
#IBOutlet weak var cityTextField: UITextField!
#IBOutlet weak var weatherTableView: UITableView!
#IBAction func getDataButton(sender: AnyObject) {
weatherDataSource("http://api.openweathermap.org/data/2.5/forecast?q=" + cityTextField.text! + "&appid=<app id>")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func weatherDataSource(urlString: String) {
let urlUTF = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL(string: urlUTF!)
let query = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in dispatch_async(dispatch_get_main_queue(), { ()
self.loadDataWeather(data!)
self.weatherTableView.reloadData()
})
}
query.resume()
}
func loadDataWeather(dataPocasi: NSData){
do {
if let json = try NSJSONSerialization.JSONObjectWithData(dataPocasi, options: []) as? NSDictionary {
print(json)
for var i = 0 ; i < (json.valueForKey("list") as! NSArray).count ; i++
{
arrDict.addObject((json.valueForKey("list") as! NSArray) .objectAtIndex(i))
}
}
} catch {
print(error)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrDict.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell : TableViewCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
if(cell == nil)
{
cell = NSBundle.mainBundle().loadNibNamed("Cell", owner: self, options: nil)[0] as! TableViewCell;
}
let strTitle : NSNumber=arrDict[indexPath.row] .valueForKey("dt") as! NSNumber
let epocTime = NSTimeInterval(strTitle)
let myDate = NSDate(timeIntervalSince1970: epocTime)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm"
let dateString = dateFormatter.stringFromDate(myDate)
cell.dayLabel.text=dateString
let strDescription : NSDictionary=arrDict[indexPath.row] .objectForKey("main") as! NSDictionary
if let bla = strDescription["temp"]{
cell.tempLabel.text=bla.stringValue
}
return cell as TableViewCell
}
}
TableViewCell
import UIKit
class TableViewCell: UITableViewCell{
#IBOutlet weak var dayLabel: UILabel!
#IBOutlet weak var tempLabel: UILabel!
}
You are not instantiating your tableView delegate. Make sure you call self.weatherTableView.delegate = self inside viewDidLoad().
Also, you should create a new arrDict every time you load your data. self.arrDict = [].
In case the above ajustments dont work you should get some time debugging it. Make sure the second request is loading the data and, if so, your self.weatherTableView.reloadData() might not being called. You could try moving it to loadDataWeather().
You can reload tableview in "loadDataWether()" function.
Like,
func loadDataWeather(dataPocasi: NSData){
do {
if let json = try NSJSONSerialization.JSONObjectWithData(dataPocasi, options: []) as? NSDictionary {
print(json)
for var i = 0 ; i < (json.valueForKey("list") as! NSArray).count ; i++
{
arrDict.addObject((json.valueForKey("list") as! NSArray) .objectAtIndex(i))
}
}
} catch {
print(error)
}
self.weatherTableView.reloadData()
}
I am trying to build a object oriented iOS app and I am having problems calling a table reload (ui interaction) from one of my swift class files.
If I am working without objects and write all that stuff in my InterfaceController's viewDidLoad method everything works... but not if I put that into classes.
I am using an asynchronous request in order to load json data from a webservice. After receiving the data I am using this data as data source for my table view.
It seems the tableview is initialized after startup with no data, so it is neccessary to call reload() on the tableview after finishing the async request.
So here are the details:
Main TableController
import UIKit;
class DeviceOverview: UITableViewController {
#IBOutlet var myTableView: UITableView!
var myDevices = Array<String>();
var myDevicesSection = NSMutableDictionary()
var deviceObjects = Array<NSDictionary>();
var mappingSectionIndex = Array<String>();
var sharedUserDefaults = NSUserDefaults(suiteName: "group.barz.fhem.SharingDefaults")
// THIS IS AN ATTEMPT TO give the class itself as PARAMETER
// ALSO TRIED TO USE myTableView (IBOutlet)
var fhem :FHEM = FHEM(tableview : self)
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fhem.sections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var devicesInSection : Array<NSDictionary> = self.fhem.sections[self.fhem.mappingSectionIndex[section]] as! Array<NSDictionary>
return devicesInSection.count;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("device", forIndexPath: indexPath) as! TableViewCell
let sectionName : String = fhem.mappingSectionIndex[indexPath.section]
if let devices : Array<NSDictionary> = self.fhem.sections.objectForKey(sectionName) as? Array<NSDictionary> {
let device = devices[indexPath.row]
var alias : NSString?;
if let attr : NSDictionary = device.objectForKey("ATTR") as? NSDictionary {
alias = attr.objectForKey("alias") as? String
}
if (alias != nil) {
cell.deviceLabel.text = alias as? String
}else{
if let deviceName : String = device.objectForKey("NAME") as? String {
cell.deviceLabel.text = deviceName
}
}
}
return cell
}
FHEM Class
import UIKit
class FHEM: NSObject {
var devices : [NSDictionary]
var sections : NSMutableDictionary
var deviceNames : [String]
var mappingSectionIndex : [String]
var myTableViewController : DeviceOverview
init(tableview : DeviceOverview){
self.devices = Array<NSDictionary>()
self.sections = NSMutableDictionary()
self.deviceNames = Array<String>()
self.mappingSectionIndex = Array<String>()
self.myTableViewController = tableview
super.init()
let url = NSURL(string: "xyz");
var request = NSURLRequest(URL: url!);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response, data, error) in
if let jsonData: NSData? = data {
// do some great stuff
//
// this is an attempt to call the table view to reload
self.myTableViewController.myTableView.reloadData()
}
}
}
}
It throws compile errors if I try to put the self variable into the constructor of my constructor
var fhem :FHEM = FHEM(tableview : self)
It also does not work if I try to put the UITableView directly into the constructor
var fhem :FHEM = FHEM(tableview : myTableView)
Am I walking along complete wrong path using objects and interacting with the ui?
You can just post a Notification when your async task finishes:
NSNotificationCenter.defaultCenter().postNotificationName("refreshMyTableView", object: nil)
Add an observer to that notification to your DeviceOverview class method viewDidLoad:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshList:", name:"refreshMyTableView", object: nil)
and add the method that will be fired at your DeviceOverview class
func refreshList(notification: NSNotification){
myTableView.reloadData()
}
Hi You can use Notification as suggested in Above answers otherwise you can use delegation to resolve this problem
Delegate is doing something like that you done but in easy manner.
Here you pass table view controller in you custom class.this thing you can do with delegate. create custom delegate method in your custom class. set delegate with table view controller object.
here you don't required to take IBOutlet of your table view because your controller inherited from table view controller so it's view is table view
import UIKit
class DeviceOverview: UITableViewController,FHEMDelegate {
#IBOutlet var myTableView: UITableView!
var myDevices = Array<String>();
var myDevicesSection = NSMutableDictionary()
var deviceObjects = Array<NSDictionary>();
var mappingSectionIndex = Array<String>();
var sharedUserDefaults = NSUserDefaults(suiteName: "group.barz.fhem.SharingDefaults")
var fhem :FHEM?
// THIS IS AN ATTEMPT TO give the class itself as PARAMETER
// ALSO TRIED TO USE myTableView (IBOutlet)
override func viewDidLoad() {
super.viewDidLoad()
fhem = FHEM ()
fhem?.delegate = self
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// var devicesInSection : Array<NSDictionary> = self.fhem!.sections[self.fhem!.mappingSectionIndex[section]] as Array<NSDictionary>
return 5;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("device", forIndexPath: indexPath) as UITableViewCell
let sectionName : String = fhem!.mappingSectionIndex[indexPath.section]
if let devices : Array<NSDictionary> = self.fhem!.sections.objectForKey(sectionName) as? Array<NSDictionary> {
let device = devices[indexPath.row]
var alias : NSString?;
if let attr : NSDictionary = device.objectForKey("ATTR") as? NSDictionary {
alias = attr.objectForKey("alias") as? String
}
if (alias != nil) {
// cell.deviceLabel.text = alias as? String
}else{
if let deviceName : String = device.objectForKey("NAME") as? String {
// cell.deviceLabel.text = deviceName
}
}
}
return cell
}
func reloadDataOfTable()
{
self.tableView.reloadData()
}
}
FHEM
import UIKit
protocol FHEMDelegate{
func reloadDataOfTable()
}
class FHEM : NSObject {
var devices : [NSDictionary]
var sections : NSMutableDictionary
var deviceNames : [String]
var mappingSectionIndex : [String]
//var myTableViewController : DeviceOverview
var delegate :FHEMDelegate?
override init(){
self.devices = Array<NSDictionary>()
self.sections = NSMutableDictionary()
self.deviceNames = Array<String>()
self.mappingSectionIndex = Array<String>()
self.delegate = nil
super.init()
let url = NSURL(string: "http://google.com");
var request = NSURLRequest(URL: url!);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response, data, error) in
if let jsonData: NSData? = data {
// do some great stuff
//
// this is an attempt to call the table view to reload
self.delegate?.reloadDataOfTable()
}
}
}
}
Here in FHEM class create one custom delegate method reloadDataOfTable that implement in your viewcontroller class so when got response of code it call that method and this method (reloadDataOfTable) content code for reload table data.
I don't know much Swift, but I've been writing Objective-C for iOS for a while now. (In Objective-C at least) you must call init on super before accessing self, otherwise you're object isn't initialized correctly. You're also not assigning self to the result of super.init(), which is necessary in Objective-C, looks like it isn't in Swift though.
tl;dr -- Move the call to super.init() to the very first line in your FHEM class' init method.