How to solve this error in Swift? - ios

I'm getting the following error in console:
fatal error: unexpectedly found nil while unwrapping an Optional value
And showing error in Xcode editor like following:
THREAD 1 EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0*0)
I have this code in Swift 3 for calling API and load it in view:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.nameLabel!.text = nameArray[indexPath.row]
cell.dobLabel!.text = dobArray[indexPath.row]
cell.descLabel!.text = descArray[indexPath.row]
/*
let imgURL = NSURL(string: imgURLArray[indexPath.row])
let data = NSData(contentsOf: (imgURLArray as? URL)!)
cell.imageView!.image = UIImage(data: data as! Data)
*/
return cell
}
And here is my TableViewCell file:
class TableViewCell: UITableViewCell {
#IBOutlet weak var nameLabel: UILabel?
#IBOutlet weak var descLabel: UILabel?
#IBOutlet weak var dobLabel: 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
}
}

try to modify you ApiViewController and check with my code then see what happen
import UIKit
class ApiViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
var nameArray = [String]()
var dobArray = [String]()
var imgURLArray = [String]()
var descArray = [String]()
var actorarray = NSArray()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
// 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 downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!.value(forKey: "actors")!)
actorarray = jsonObj!.value(forKey: "actors") as? NSArray
self.tableView.reloadData()
}
}).resume()
}
func downloadJsonWithTask(){
let url = NSURL(string:urlString)
var downloadTask = URLRequest(url: (url as? URL)!,cachePolicy:URLRequest.CachePolicy.reloadIgnoringCacheData,timeoutInterval:20)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask,completionHandler:{(data,response,error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData!)
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actorarray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
let dic = self.actorarray[indexPath.row] as! NSDictionary
cell.nameLabel!.text = dic.object(forKey: "name") as! String
cell.dobLabel!.text = dic.object(forKey: "dob") as! String
cell.descLabel!.text = dic.object(forKey: "image") as! String
return cell
}
}

Related

(iOS + Firebase) Unable to pass the Image to the next ViewController from a UITableViewCell

I have a UITableView where the data is coming from a Firebase RealtimeDatabase. Once the user selects the row, the data from the row i.e: Title, Description and an Image will be taken to the next ViewController.
I'm able to pass the Title and Description but I'm unable to pass the Image.
Here is my code for the UITableView:
import UIKit
import Firebase
class PostTable: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView:UITableView!
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds, style: .plain)
view.addSubview(tableView)
let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "postCell")
var layoutGuide:UILayoutGuide!
layoutGuide = view.safeAreaLayoutGuide
tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableView.reloadData()
observePosts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func observePosts() {
let postsRef = Database.database().reference().child("Data")
print(postsRef)
postsRef.observe(.value, with: { snapshot in
var tempPosts = [Post]()
for child in snapshot.children{
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String:Any],
let title = dict["title"] as? String,
let logoImage = dict["image"] as? String,
let url = URL(string:logoImage),
let description = dict["description"] as? String{
let userProfile = UserProfile(title: title, photoURL: url)
let post = Post(id: childSnapshot.key, title: userProfile, description: description, image: userProfile)
print(post)
tempPosts.append(post)
}
}
self.posts = tempPosts
self.tableView.reloadData()
})
}
func getImage(url: String, completion: #escaping (UIImage?) -> ()) {
URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
if error == nil {
completion(UIImage(data: data!))
} else {
completion(nil)
}
}.resume()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(posts.count)
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let postsInfo = posts[indexPath.row]
print(postsInfo)
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let DvC = Storyboard.instantiateViewController(withIdentifier: "PostTableDetailed") as! PostTableDetailed
DvC.getName = postsInfo.title.title
DvC.getDesc = postsInfo.description
// DvC.getImg = postsInfo.title.photoURL
self.navigationController?.pushViewController(DvC, animated: true)
}
}
Here is the second ViewControler which has the post details:
import UIKit
class PostTableDetailed: UIViewController {
var getName = String()
var getDesc = String()
#IBOutlet weak var Name: UILabel!
#IBOutlet weak var Description: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
Name.text! = getName
Description.text! = getDesc
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I also have a few Models (Post, UserProfile) and Services (UserService and ImageService), please let me know if that is required to break down this problem.
if you have the imageUrl, all you need is to pass it from PostTable to PostTableDetailed and download the image.
// PostTable
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let postsInfo = posts[indexPath.row]
print(postsInfo)
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let DvC = Storyboard.instantiateViewController(withIdentifier: "PostTableDetailed") as! PostTableDetailed
DvC.getName = postsInfo.title.title
DvC.getDesc = postsInfo.description
DvC.getImg = postsInfo.photoURL
self.navigationController?.pushViewController(DvC, animated: true)
}
// PostTableDetailed
class PostTableDetailed: UIViewController {
var getName = String()
var getDesc = String()
var imageUrl = ""
#IBOutlet weak var Name: UILabel!
#IBOutlet weak var Description: UILabel!
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
Name.text! = getName
Description.text! = getDesc
updayeImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func updateImage() {
URLSession.shared.dataTask(with: URL(string: self.imageUrl)!) { data, response, error in
if error == nil, let data = data {
imageView.image = UIImage(data: data)
}
}.resume()
}
}
The image will be shown when the task will complete.
so I suggest for you to add a spinner to the imageView.
In PostDetail ViewController do like this
import UIKit
class PostTableDetailed: UIViewController {
var getName = String()
var getDesc = String()
var getImg = String()
#IBOutlet weak var Name: UILabel!
#IBOutlet weak var Description: UILabel!
#IBOutlet weak var ImageContainer: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
Name.text! = getName
Description.text! = getDesc
if let image = getImage(url: getImg) { (image)
ImageContainer.image = image
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getImage(url: String, completion: #escaping (UIImage?) -> ()) {
URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
if error == nil {
completion(UIImage(data: data!))
} else {
completion(nil)
}
}.resume()
}
}
First of all, you can use this code to download the image:
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func downloadImageWithUrlString(urlString: String) -> Void {
if urlString.count == 0 {
print("Image Url is not found")
return
}
self.image = nil
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cachedImage
return
}
let request = URLRequest(url: URL(string: urlString)!)
let dataTask = URLSession.shared.dataTask(with: request) {data, response, error in
if error != nil { return }
DispatchQueue.main.async {
let downloadedImage = UIImage(data: data!)
if let image = downloadedImage {
imageCache.setObject(image, forKey: urlString as AnyObject)
self.image = UIImage(data: data!)
}
}
}
dataTask.resume()
}
}
Now, if you are using the model that contains Title, Description, and ImageUrlString, then simply pass the selected model object to the next viewController.
In next ViewController, just simply call the same method to download the image which you are using on first ViewController. You don't need to pass the image from VC1 to VC2 because it might be the possible image is not downloaded yet and you select a row to move on next VC.
So here simple thing that pass the model object and calls the image downloading method.

My Table View is not Reloading When I type in the Search Bar to Retrieve the Google Books Information

This is my controller that I am using to lookup the specific books. When I type in the search bar, no book information is displayed back to me while I type or after I finish typing. I would like to understand why and find a solution that would remedy this problem.
import UIKit
class TextbookSearchViewController: UIViewController, UITableViewDelegate {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
var booksFound = [[String: AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
}
func queryBooks(bookTitle: String) {
let stringURL = "https://www.googleapis.com/books/v1/volumes?q=\(bookTitle)"
guard let url = URL(string: stringURL) else {
print("Problem with URL")
return
}
let urlRequest = URLRequest(url: url as URL)
let urlSession = URLSession.shared
let queryTask = urlSession.dataTask(with: urlRequest) { (data, response, error) in
guard let jsonData = data else {
print("No Information could be Found:")
return
}
do {
let json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: AnyObject]
let tableItems = json["Items"] as! [[String: AnyObject]]
self.booksFound = tableItems
self.tableView.reloadData()
} catch {
print("Error with JSON: ")
}
}
queryTask.resume()
}
}
extension TextbookSearchViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return booksFound.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath)
if let volumeInfo = self.booksFound[indexPath.row]["volumeInfo"] as? [String: AnyObject] {
cell.textLabel?.text = volumeInfo["title"] as? String
cell.detailTextLabel?.text = volumeInfo["subtitle"] as? String
}
return cell
}
}
extension TextbookSearchViewController: UISearchBarDelegate {
func searchBarButtonClicked(searchBar: UISearchBar) {
let bookTitle = searchBar.text?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
self.queryBooks(bookTitle: bookTitle!)
searchBar.resignFirstResponder()
}
}
Probably you forget to set UISearchBar delegate
#IBOutlet weak var searchBar: UISearchBar! {
didSet {
searchBar.delegate = self
}
}
Also, you need below in place of func searchBarButtonClicked(searchBar: UISearchBar)
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
// your code
}
Key in response is items not Items
Use json["items"] in place of json["Items"]
Complete code:
import UIKit
class TextbookSearchViewController: UIViewController, UITableViewDelegate {
#IBOutlet weak var searchBar: UISearchBar! {
didSet {
searchBar.delegate = self
}
}
#IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
}
}
var booksFound = [[String: AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
}
}
extension TextbookSearchViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return booksFound.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath)
if let volumeInfo = self.booksFound[indexPath.row]["volumeInfo"] as? [String: AnyObject] {
cell.textLabel?.text = volumeInfo["title"] as? String
cell.detailTextLabel?.text = volumeInfo["subtitle"] as? String
}
return cell
}
}
extension TextbookSearchViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let bookTitle = searchBar.text?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
queryBooks(bookTitle: bookTitle!)
searchBar.resignFirstResponder()
}
func queryBooks(bookTitle: String) {
let stringURL = "https://www.googleapis.com/books/v1/volumes?q=\(bookTitle)"
guard let url = URL(string: stringURL) else {
print("Problem with URL")
return
}
let urlRequest = URLRequest(url: url as URL)
let urlSession = URLSession.shared
let queryTask = urlSession.dataTask(with: urlRequest) { [weak self] (data, response, error) in
guard let jsonData = data else {
print("No Information could be Found:")
return
}
do {
let json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: AnyObject]
guard let tableItems = json["items"] as? [[String: AnyObject]] else {
self?.booksFound = [[String: AnyObject]]()
return
}
print(tableItems)
self?.booksFound = tableItems
DispatchQueue.main.async {
self?.tableView.reloadData()
}
} catch {
print("Error with JSON: ")
}
}
queryTask.resume()
}
}

TableView Repeating youtube-api result

The problem is---->
The TableView Display the same title and Distribution in all cells
my project ViewController:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableview: UITableView!
var articles: [Article]? = []
override func viewDidLoad() {
super.viewDidLoad()
fetchArticles()
}
func fetchArticles(){
let urlRequest = URLRequest(url: URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=horses&type=video&maxResults=10&key=(apiKey)")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error as Any)
return
}
self.articles = [Article]()
do {
let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String : Any]
let article = Article()
if let articlesFromJson = json?["items"] as? [[String : Any]] {
for item in articlesFromJson {
if let snippet = item["snippet"] as? [String : Any],let title = snippet["title"]as? String,let desc = snippet["description"]as? String {
article.headline = title
article.desc = desc
self.articles?.append(article)
}
}
}
DispatchQueue.main.async {
self.tableview.reloadData()
}
}
}
task.resume()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as? ArticleCell
cell?.title.text = self.articles?[indexPath.row].headline!
cell?.desc.text = self.articles?[indexPath.row].desc!
return cell!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articles?.count ?? 0
}
}
Article.Swift :
import UIKit
class Article: NSObject {
var headline: String?
var desc: String?
}
**ArticleCell :**
import UIKit
class ArticleCell: UITableViewCell {
#IBOutlet weak var title: UILabel!
#IBOutlet weak var desc: 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
}
}
The problem is---->
The TableView Display the same title and Distribution in all cells
just comment this line
DispatchQueue.main.async {
self.tableview.reloadData()
}
/and add it after for loop
insert let article = Article() inside for loop/
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableview: UITableView!
var articles: [Article]? = []
override func viewDidLoad() {
super.viewDidLoad()
fetchArticles()
}
func fetchArticles(){
let urlRequest = URLRequest(url: URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=horses&type=video&maxResults=10&key=(apiKey)")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error as Any)
return
}
self.articles = [Article]()
do {
let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String : Any]
if let articlesFromJson = json?["items"] as? [[String : Any]] {
for item in articlesFromJson {
if let snippet = item["snippet"] as? [String : Any],let title = snippet["title"]as? String,let desc = snippet["description"]as? String {
let article = Article()
article.headline = title
article.desc = desc
self.articles?.append(article)
}
}
self.tableview.reloadData()
}
/*DispatchQueue.main.async {
self.tableview.reloadData()
} */
}
}
task.resume()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as? ArticleCell
cell?.title.text = self.articles?[indexPath.row].headline!
cell?.desc.text = self.articles?[indexPath.row].desc!
return cell!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articles?.count ?? 0
}
}

error with maindata in swift 3

I have this problem (Type any has no subscript members) in this line `
import Foundation
import UIKit
import WebKit
import GoogleMobileAds
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,GADBannerViewDelegate {
#IBOutlet weak var BannerView: GADBannerView!
#IBOutlet var tableView: UITableView!
#IBAction func refresh(_ sender: AnyObject) {
get()
}
var values:NSArray = []
override func viewDidLoad() {
super.viewDidLoad();
let request = GADRequest()
request.testDevices = [kGADSimulatorID]
BannerView.delegate = self
BannerView.adUnitID = ""
BannerView.rootViewController = self
BannerView.load(request)
get();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func get(){
let url = URL(string: "http://www.X.php")
let data = try? Data(contentsOf: url!)
values = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SpecialCell
let maindata = values[(indexPath as NSIndexPath).row]
cell.info!.text = maindata ["Info"] as String?
return cell;
}
}
image
thank you all..
First of all declare the data source array as Swift Array. Foundation NSArray has no type information and doesn't help Swift's strong type system at all.
var values = [[String:Any]]()
Then load the data asynchronously(!) and reload the table view on the main thread
func get() {
let url = URL(string: "http://www.X.php")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
} else {
do {
self.values = try JSONSerialization.jsonObject(with: data!, options: []) as! [[String:Any]]
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}
task.resume()
}
Then in cellForRow assign the value
let maindata = values[indexPath.row]
cell.info!.text = maindata["Info"] as? String
Now the compiler knows all subscripted types and the error goes away.
I believe you have to give mainData a type like this:
let maindata = values[(indexPath as NSIndexPath).row] as? [String:Any]
and then make sure mainData actually contains a value
if let info = mainData?["Info"] as? String {
cell.info!.text = info
}

not showing data in table view swift

i have one table view with two labels. I need to display the data which are coming from json. But now its not showing any data in table view:
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate
{
let yourJsonFormat: String = "JSONFile" // set text JSONFile : json data from file
// set text JSONUrl : json data from web url
var arrDict :NSMutableArray=[]
#IBOutlet weak var tvJSON: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
if yourJsonFormat == "JSONFile" {
jsonParsingFromFile()
} else {
jsonParsingFromURL()
}
}
func jsonParsingFromURL () {
let url = NSURL(string: "url")
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
}
}
func jsonParsingFromFile()
{
let path: NSString = NSBundle.mainBundle().pathForResource("days", ofType: "json")!
let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrDict.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell : TableViewCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
let strTitle : NSString=arrDict[indexPath.row] .valueForKey("name") as! NSString
let strDescription : NSString=arrDict[indexPath.row] .valueForKey("rating") as! NSString
cell.lblTitle.text=strTitle as String
cell.lbDetails.text=strDescription as String
return cell as TableViewCell
}
}
Any thing i missed,please help me out.
I am not able to see any data in my table view...
your code is partially correct, I followed your question
Step-1
Right click on the info.plist file, select open as, Source code. Add the lines of code that allow the http connection to this server.
do like
Step-2
For Server request
sendAsynchronousRequest is deprecated in this place use
func jsonParsingFromURL () {
let url = NSURL(string: "url")
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
print("done, error: \(error)")
let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
arrDict.addObject((dict.valueForKey("xxxx")
tvJSON .reloadData()
}
dataTask.resume()
}
For local Request
func jsonParsingFromFile()
{
let path: NSString = NSBundle.mainBundle().pathForResource("days", ofType: "json")!
let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)
let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
arrDict.addObject((dict.valueForKey("xxxx")
tvJSON .reloadData()
}
Update and Edit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet var showtable: UITableView!
var arrDict :NSMutableArray=[]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.jsonParsingFromURL()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func jsonParsingFromURL () {
let url = NSURL(string: "http://kirisoft.limitscale.com/GetVendor.php?category_id=1")
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
print("done, error: \(error)")
if error == nil
{
self.arrDict=(try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray
print(self.arrDict)
if (self.arrDict.count>0)
{
self.showtable.reloadData()
}
// arrDict.addObject((dict.valueForKey("xxxx")
}
}
dataTask.resume()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrDict.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let CellIdentifier: String = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: CellIdentifier)
}
cell?.textLabel!.text=arrDict[indexPath.row] .valueForKey("name") as? String
cell?.detailTextLabel!.text=arrDict[indexPath.row] .valueForKey("rating") as? String
return cell!
}
}
you can get the output like
For sample Project

Resources