I just need help I building Instagram-clone with firebase and I have an issue whit post feed I can't Retrieve image from firebase storage to show on tableView cell can you help me, please :(
import UIKit
import FirebaseAuth
import FirebaseDatabase
class HomeViewController: UIViewController ,UITableViewDelegate {
#IBOutlet weak var tableview: UITableView!
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
tableview.dataSource = self
loadposts()
// var post = Post(captiontxt: "test", photoUrlString: "urll")
// print(post.caption)
// print(post.photoUrl)
}
func loadposts() {
Database.database().reference().child("posts").observe(.childAdded){ (snapshot: DataSnapshot)in
print(Thread.isMainThread)
if let dict = snapshot.value as? [String: Any]{
let captiontxt = dict["caption"] as! String
let photoUrlString = dict["photoUrl"] as! String
let post = Post(captiontxt: captiontxt, photoUrlString: photoUrlString )
self.posts.append(post)
print(self.posts)
self.tableview.reloadData()
}
}
}
#IBAction func logout(_ sender: Any) {
do {
try Auth.auth().signOut()
}catch let logoutErrorr{
print(logoutErrorr)
}
let storyboard = UIStoryboard(name: "Start", bundle: nil)
let signinVC = storyboard.instantiateViewController(withIdentifier: "SigninViewController")
self.present(signinVC, animated: true, completion: nil)
}
}
extension HomeViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "imagecell", for: indexPath) as! PostCellTableViewCell
cell.captionLabel.text = posts[indexPath.row].caption
cell.postimage.image = posts[indexPath.row].photoUrl
// print(cell.captionLabel.text)
// print(cell.daysLabel.text)
return cell
}
}
enter code here
import Foundation
class Post {
var caption: String
var photoUrl: String
init(captiontxt: String, photoUrlString: String) {
caption = captiontxt
photoUrl = photoUrlString
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "imagecell", for: indexPath) as! PostCellTableViewCell
cell.postimage.image = nil
cell.tag += 1
let tag = cell.tag
cell.captionLabel.text = posts[indexPath.row].caption
let photoUrl = posts[indexPath.row].photoUrl
getImage(url: photoUrl) { photo in
if photo != nil {
if cell.tag == tag {
DispatchQueue.main.async {
cell.postimage.image = photo
}
}
}
}
return cell
}
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()
}
Related
I have home collectionView, here if i click one item using didSelectItemAtindexPathin in home that item values array need to show in AllMakePaymentViewController tableview.
but here i am getting all home items values in AllMakePaymentViewController... but how to show only clicked item values in AllMakePaymentViewController tableview.
for that same typename have in both home and AllMakePaymentViewController json..
Please help me in the code.
here is my code for homeVC:
import UIKit
import SDWebImage
struct JsonData {
var iconHome: String?
var typeName: String?
var id: String?
init(icon: String, tpe: String, id: String) {
self.iconHome = icon
self.typeName = tpe
self.id = id
}
}
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {
#IBOutlet weak var collectionView: UICollectionView!
var itemsArray = [JsonData]()
var typeName: String?
var saveTypenameKey: String?
override func viewDidLoad() {
super.viewDidLoad()
homeServiceCall()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell
let aData = itemsArray[indexPath.row]
cell.paymentLabel.text = aData.typeName
cell.paymentImage.sd_setImage(with: URL(string:aData.iconHome ?? ""), placeholderImage: UIImage(named: "varun finance5_icon"))
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if itemsArray[indexPath.item].typeName == "WATER"{
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
self.navigationController?.pushViewController(nextViewController!, animated: true)
}
else if itemsArray[indexPath.item].typeName == "ELECTRICITY"{
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
self.navigationController?.pushViewController(nextViewController!, animated: true)
}
else if itemsArray[indexPath.item].typeName == "CASH POINT"{
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
self.navigationController?.pushViewController(nextViewController!, animated: true)
}
else if itemsArray[indexPath.item].typeName == "DTH"{
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
self.navigationController?.pushViewController(nextViewController!, animated: true)
}
else{
AlertFun.ShowAlert(title: "", message: "will update soon..", in: self)
}
}
//MARK:- Service-call
func homeServiceCall(){
let urlStr = "https://dev.com/webservices/getfinancer"
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: respData, options: .allowFragments) as! [String: Any]
//print("the home json is \(jsonObj)")
let financerArray = jsonObj["financer"] as! [[String: Any]]
for financer in financerArray {
let id = financer["id"] as? String
let pic = financer["icon"] as? String
self.typeName = financer["tpe"] as! String
KeychainWrapper.standard.set(self.typeName!, forKey: "typeName")
print("keychain typename \(KeychainWrapper.standard.set(self.typeName!, forKey: "typeName"))")
self.itemsArray.append(JsonData(icon: pic ?? "", tpe: self.typeName ?? "", id: id ?? ""))
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
}
This is my AllMakePaymentViewController code:
class PaymentTableViewCell: UITableViewCell{
#IBOutlet weak var pamntTypeLabel: UILabel!
}
class AllMakePaymentViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var categoryName: String?
var iteamsArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
allPaymentService()
}
func allPaymentService(){
let urlStr = "https://dev.com/webservices/api.php?rquest=billermdm"
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: respData, options: .allowFragments) as! [String: Any]
//print("the all make payment json is \(jsonObj)")
let billerdetailsArray = jsonObj["billerdetails"] as! [[String: Any]]
for billerdetail in billerdetailsArray {
self.categoryName = billerdetail["bcategoryname"] as? String
if self.categoryName == "Water"{
let bName = billerdetail["bname"] as? String
self.iteamsArray.append(bName ?? "")
}
if self.categoryName == "Electricity"{
let bName = billerdetail["bname"] as? String
self.iteamsArray.append(bName ?? "")
}
if self.categoryName == "CashPoin"{
let bName = billerdetail["bname"] as? String
self.iteamsArray.append(bName ?? "")
}
if self.categoryName == "DTH"{
let bName = billerdetail["bname"] as? String
self.iteamsArray.append(bName ?? "")
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
}
extension AllMakePaymentViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if categoryName == "Water"{
return iteamsArray.count
}
if categoryName == "Landline Postpaid"{
return iteamsArray.count
}
if categoryName == "DTH"{
return iteamsArray.count
}
if categoryName == "Electricity"{
return iteamsArray.count
}
return iteamsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PaymentTableViewCell
cell.pamntTypeLabel.text = iteamsArray[indexPath.row]
self.tableView.separatorStyle = .none
return cell
}
}
here only one itemsArray is enough or shall i take diierent array fro different category like electrictyArray, waterArray... because here i am getting all values in tabelview... i need only clicked home item valuesarray..
Please help me in the code
You need to set the var in nextViewController before pushing it onto the stack (and you should use if let to avoid potential crashes):
if let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController {
// set the var in the new view controller
nextViewController.categoryName = "WATER"
// now push it onto the stack
self.navigationController?.pushViewController(nextViewController, animated: true)
}
I tried to make ViewController with two TableView but meet the problem.
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableTN: UITableView!
#IBOutlet weak var tableMainNews: UITableView!
var topnews: [TopNews]? = []
var mainnews: [Mainnewsfeed]? = []
override func viewDidLoad() {
super.viewDidLoad()
TopNewsJSON()
MainNewsJSON()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell?
if tableView == self.tableTN {
cell = tableView.dequeueReusableCell(withIdentifier: "topnewsCell", for:indexPath) as! TopNewsCell
cell!.imgTN!.downloadImage(from: (self.topnews?[indexPath.item].image!)!)
cell!.titleTN!.text = self.topnews?[indexPath.item].headline
}
if tableView == self.tableMainNews {
cell = tableView.dequeueReusableCell(withIdentifier: "mainnewsCell", for:indexPath) as! MainNewsCell
cell!.mainnews_title!.text = self.mainnews?[indexPath.item].headline
}
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count:Int?
if tableView == self.tableTN {
count = self.topnews!.count
}
if tableView == self.tableMainNews {
count = self.mainnews!.count
}
return count!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//print(indexPath)
}
func TopNewsJSON () {
let urlRequest = URLRequest(url: URL(string: "https://sportarena.com/wp-api/topnews2018/top/")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error as Any)
return
}
self.topnews = [TopNews]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
//print(json)
let TN = TopNews()
let jarray = json["top-news"] as! NSArray
let jarray1 = jarray[0] as? [String: AnyObject]
if let ID = jarray1!["ID"] as? String,
let title = jarray1!["title"] as? String,
let img = jarray1!["img"] as? String {
TN.headline = title
TN.image = img
TN.id = ID
}
self.topnews?.append(TN)
DispatchQueue.main.async {
self.tableTN.reloadData()
}
} catch let error {
print(error)
}
}
task.resume()
}
func MainNewsJSON () {
let urlRequest = URLRequest(url: URL(string: "anyurl")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error as Any)
return
}
//self.mainnews = [MainNews]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
let jarray = json["general-news"] as! NSArray
let jarray1 = jarray[0]
for jarray1 in jarray1 as! [[String: Any]] {
let MNF = Mainnewsfeed()
if let ID = jarray1["id"],
let title = jarray1["title"],
let time = jarray1["datetime"] {
MNF.headline = title as? String
MNF.id = ID as? String
MNF.time = time as? String
}
self.mainnews?.append(MNF)
DispatchQueue.main.async {
self.tableMainNews.reloadData()
}
}
} catch let error {
print(error)
}
}
task.resume()
}
}
}
After three lines as cell!.titleTN!.text = self.topnews?[indexPath.item].headline and others display error: "Value of type 'UITableViewCell' has no member 'titleTN'" (or also 'imgTN' and 'mainnews_title')
Where the error? What I need to change in my code?
Please help me.
You can try
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.tableTN {
let cell = tableView.dequeueReusableCell(withIdentifier: "topnewsCell", for:indexPath) as! TopNewsCell
cell.imgTN!.downloadImage(from: (self.topnews?[indexPath.item].image!)!)
cell.titleTN!.text = self.topnews?[indexPath.item].headline
return cell
}
else
{
let cell = tableView.dequeueReusableCell(withIdentifier: "mainnewsCell", for:indexPath) as! MainNewsCell
cell.mainnews_title!.text = self.mainnews?[indexPath.item].headline
return cell
}
}
Here is my project on github:
https://github.com/alshfu86/Recipes
I have one problem. If I remove something from my Firebase database I get this error:
Could not cast value of type ‘NSNull’ (0×106a4f520) to ‘NSDictionary’ (0×106a4ef58).
in method:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for:indexPath) as! CategoryTableViewCell
let rowData = self.data[indexPath.row] as! NSDictionary
let title = rowData["title"] as! String
cell.recipeLabel.text = title.uppercased()
let imageUrl = rowData["youtubeID"] as! String
let imageQuality = rowData["imageQuality"] as! String
let urlPath = youtubeBaseImageURL + imageUrl + "/" + imageQuality + ".jpg"
let url = URL(string: urlPath)
cell.recipeImageView.kf.setImage(with: url)
print("uString(describing: rl )path = \(String(describing: url))")
return cell
}
here is all class:
import UIKit
import Kingfisher
class CategoryViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var data = [Any]()
var categoryTitle = ""
let youtubeBaseImageURL = "http://img.youtube.com/vi/"
#IBOutlet weak var tableView: UITableView!
//is the device landscape or portrait
var isPortraid = true
override func viewDidLoad() {
super.viewDidLoad()
let backButton = UIBarButtonItem(image: UIImage(named:"chevron"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(back))
self.navigationItem.leftBarButtonItem = backButton
self.tableView.delegate = self
self.title = categoryTitle
print("data: \(self.data)")
// loadAdmobBanner()
NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.orientationChanged), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
if UIDevice.current.orientation.isLandscape {
isPortraid = false
}
}
func orientationChanged(){
if UIDevice.current.orientation.isLandscape {
isPortraid = false
} else {
isPortraid = true
}
tableView.reloadData()
}
#objc func back(){
self.navigationController?.popViewController(animated: true)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for:indexPath) as! CategoryTableViewCell
let rowData = self.data[indexPath.row] as! NSDictionary
let title = rowData["title"] as! String
cell.recipeLabel.text = title.uppercased()
let imageUrl = rowData["youtubeID"] as! String
let imageQuality = rowData["imageQuality"] as! String
let urlPath = youtubeBaseImageURL + imageUrl + "/" + imageQuality + ".jpg"
let url = URL(string: urlPath)
cell.recipeImageView.kf.setImage(with: url)
print("uString(describing: rl )path = \(String(describing: url))")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let playerViewController = storyboard.instantiateViewController(withIdentifier: "PlayerViewController") as! PlayerViewController
let rowData = self.data[indexPath.row] as! NSDictionary
let youtubeUrl = rowData["youtubeID"] as! String
playerViewController.urlPath = youtubeUrl
let ingredients = rowData["ingredients"] as! String
playerViewController.about = ingredients
self.navigationController?.pushViewController(playerViewController, animated: true)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if isPortraid {return UIScreen.main.bounds.height/5
} else {
return UIScreen.main.bounds.height/5.2
}
}
#IBAction func unwindToCategory(sender: UIStoryboardSegue){
}
The error must be on this line:
let rowData = self.data[indexPath.row] as! NSDictionary
The error is that the array contains some null values (represented as NSNull). You should probably do a conditional cast, i.e.:
if let rowData = self.data[indexPath.row] as? NSDictionary {
// do stuff here
}
Or alternatively, declare data as an array of dictionaries:
var data = [NSDictionary]()
then filter out the null values before assigning them to data:
self.data = yourdatasource.filter { $0 is NSDictionary }
Then later simply retrieve the element:
let rowData = self.data[indexPath.row] // do stuff here
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
}
}
I want to pull to refresh for my RSS feed news app. I using navigation controller and table view controller. How should I do on Table View Controller? What should we add? My code is here.
class TableviewController: UITableViewController {
var items : Array<Item> = []
var entries : Array<Entry> = []
override func viewDidLoad() {
super.viewDidLoad()
loadRSS()
loadAtom()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
let item:Item = self.items[indexPath.row]
cell.textLabel?.text = item.title
cell.detailTextLabel?.text = self.pubDateStringFromDate(item.pubDate! as Date)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.items[indexPath.row]
let url:URL = URL(string: item.link!)!
let safariViewController = SFSafariViewController(url: url, entersReaderIfAvailable: true)
present(safariViewController, animated: true, completion: nil)
}
func loadRSS() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseRSS(xmlData: data as NSData, completionHandler: {(isSuccess, channel, error) -> Void in
if (isSuccess) {
self.items = channel!.items!
self.tableView.reloadData()
}
if (response.error != nil) {
print((response.error?.localizedDescription)! as String)
}
})
}
}
}
func loadAtom() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseAtom(xmlData: data as NSData, completionHandler: {(isSuccess, feed, error) -> Void in
if (isSuccess) {
self.entries = feed!.entries!
self.tableView.reloadData()
}
if (error != nil) {
print((error?.localizedDescription)! as String)
}
})
}
}
}
func pubDateStringFromDate(_ pubDate:Date)->String {
let format = DateFormatter()
format.dateFormat = "yyyy/M/d HH:mm"
let pubDateString = format.string(from: pubDate)
return pubDateString
}
}
1) Declare an property of type UIRefreshControl as:
var refreshControl = UIRefreshControl()
2) In viewDidLoad()method add this refreshControl to your table view as:
self.refreshControl.addTarget(self, action: #selector(loadRSS), for: .valueChanged)
if #available(iOS 10, *){
self.tableView.refreshControl = self.refreshControl
}else{
self.tableView.addSubview(self.refreshControl)
}
Declare a property refreshControl in your TableViewController as
var refreshControl:UIRefreshControl?
The in viewDidLoad() function add the following code
refreshControl?.addTarget(self, action: #selector(loadRSS), for: .valueChanged)
self.tableView.addSubview(refreshControl!)
Update your loadRSS() function as
func loadRSS() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
self.refreshControl?.endRefreshing(
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseRSS(xmlData: data as NSData, completionHandler: {(isSuccess, channel, error) -> Void in
if (isSuccess) {
self.items = channel!.items!
self.tableView.reloadData()
}
if (response.error != nil) {
print((response.error?.localizedDescription)! as String)
}
})
}
}
}
Please refer following code , as i have added pull to refresh control on your code.
class TableviewController: UITableViewController {
var items : Array<Item> = []
var entries : Array<Entry> = []
var pullToFrefreshNews:UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
loadRSS()
loadAtom()
self.addPulltoRefrehs()
}
func addPulltoRefrehs() {
self.pullToFrefreshNews = UIRefreshControl()
self.pullToFrefreshNews.addTarget(self, action: #selector(TableviewController.loadRSS), for: UIControlEvents.valueChanged)
self.newsTableVU.addSubview(pullToFrefreshNews)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
let item:Item = self.items[indexPath.row]
cell.textLabel?.text = item.title
cell.detailTextLabel?.text = self.pubDateStringFromDate(item.pubDate! as Date)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.items[indexPath.row]
let url:URL = URL(string: item.link!)!
let safariViewController = SFSafariViewController(url: url, entersReaderIfAvailable: true)
present(safariViewController, animated: true, completion: nil)
}
func loadRSS() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseRSS(xmlData: data as NSData, completionHandler: {(isSuccess, channel, error) -> Void in
if (isSuccess) {
self.items = channel!.items!
self.tableView.reloadData()
}
if (response.error != nil) {
print((response.error?.localizedDescription)! as String)
}
})
}
}
}
func loadAtom() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseAtom(xmlData: data as NSData, completionHandler: {(isSuccess, feed, error) -> Void in
if (isSuccess) {
self.entries = feed!.entries!
self.tableView.reloadData()
}
if (error != nil) {
print((error?.localizedDescription)! as String)
}
})
}
}
}
func pubDateStringFromDate(_ pubDate:Date)->String {
let format = DateFormatter()
format.dateFormat = "yyyy/M/d HH:mm"
let pubDateString = format.string(from: pubDate)
return pubDateString
}
}