i want to delete the line of text in the list file given under the if editMode == delete function which ever one was swiped on to delete i want it to delete that line of text in the file.
i read the file and parse it into the table view then when the user swipes to delete i want to delete the certain line of text in the file that cell.labelText?.text is if that makes sense. I cant seem to find anywhere that explains my particualr case. so please help me!!!
import UIKit
import Firebase
class ManageVC: UIViewController, UITabBarDelegate, UITableViewDataSource {
#IBOutlet var table: UITableView!
//parse sources text file
var sourcesList = [String:String]()
var sourcesArray = NSMutableArray()
var editMode = false
var refresher: UIRefreshControl!
var idgen = ""
func generateRandomDigits(_ digitNumber: Int) -> String {
var number = ""
for i in 0..<digitNumber {
var randomNumber = arc4random_uniform(10)
while randomNumber == 0 && i == 0 {
randomNumber = arc4random_uniform(10)
}
number += "\(randomNumber)"
}
return number
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sourcesArray.count
}
func tableSetup(){
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let source = sourcesArray[indexPath.row]
cell.textLabel?.text = "\((source as AnyObject).value(forKey: "sourcename")!)"
//cell.detailTextLabel?.text = "\((source as AnyObject).value(forKey: "sourceurl")!)"
return cell
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let source = sourcesArray[indexPath.row]
cell.textLabel?.text = "\((source as AnyObject).value(forKey: "sourcename")!)"
//cell.detailTextLabel?.text = "\((source as AnyObject).value(forKey: "sourceurl")!)"
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editMode == true {
if editingStyle == .delete{
sourcesArray.removeObject(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
var sourceUrlText: UITextField?
var ref: DatabaseReference!
#IBOutlet weak var addBtn: UIBarButtonItem!
#IBOutlet weak var editBtn: UIBarButtonItem!
override func viewDidLoad() {
DispatchQueue.main.async{
self.table.reloadData()
}
self.navigationItem.leftBarButtonItem = self.editButtonItem
refresher = UIRefreshControl()
refresher.addTarget(self, action: #selector(ManageVC.sourceRefresh), for: UIControl.Event.valueChanged)
table.addSubview(refresher)
ref = Database.database().reference()
super.viewDidLoad()
table.dataSource = self
let dir:NSURL = FileManager.default.urls(for: .documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last! as NSURL
let fileurl = dir.appendingPathComponent("sources.list")
let mgr = FileManager.default
if mgr.fileExists(atPath: fileurl!.path) {
do {
let contents = try String(contentsOfFile: fileurl!.path, encoding: String.Encoding.utf8)
let reading = contents.components(separatedBy: "\n") as [String]
for i in 0..<reading.count {
let data : [String] = reading[i].components(separatedBy: ", ")
sourcesList["sourcename"] = "\(data[0])"
//sourcesList["sourceurl"] = "\(data[1])"
sourcesArray.add(sourcesList)
}
} catch let error as NSError {
print("Error: \(error)")
}
}
}
#IBAction func addBtnClicked(_ sender: Any) {
let addSource = UIAlertController(title: "Add Source:", message: nil, preferredStyle: .alert)
addSource.addTextField(configurationHandler: sourceUrlText)
let okAction = UIAlertAction(title: "Add", style: .default, handler: self.okHandler)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
addSource.addAction(cancelAction)
addSource.addAction(okAction)
self.present(addSource, animated: true)
}
func okHandler(alert: UIAlertAction!){
if idgen == "" {
source()
performSegue(withIdentifier: "refreshingShow", sender: self)
}
}
func sourceUrlText(textField: UITextField!){
sourceUrlText = textField
sourceUrlText?.text = "http://"
}
#IBAction func editBtnClicked(_ sender: Any) {
addBtn.isEnabled = true
editBtn.isEnabled = false
editMode = true
}
override func viewDidAppear(_ animated: Bool) {
addBtn.isEnabled = false
editBtn.isEnabled = true
editMode = false
}
func source(){
let dir:NSURL = FileManager.default.urls(for: .documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last! as NSURL
let fileurl = dir.appendingPathComponent("sources.list")
let string = ((self.sourceUrlText?.text)!) + "\n"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)!
if FileManager.default.fileExists(atPath: fileurl!.path) {
var err:NSError?
if let fileHandle = FileHandle(forWritingAtPath: fileurl!.path) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
do {
self.table.reloadData()
refresher.endRefreshing()
let readSources = try String(contentsOfFile: fileurl!.path, encoding: String.Encoding.utf8)
print(readSources)
} catch {
}
}
else {
print("Can't open fileHandle \(err)")
}
}
else {
}
}
#objc func sourceRefresh() {
DispatchQueue.main.async{
self.tableSetup()
self.table.reloadData()
}
refresher.endRefreshing()
}
}
Related
So, I have been building this project that is a todo app. and when you click on a cell your item should be searched on to ask.com. I now keep getting this fatal error. And it shows up as nil in my "Appurl" part of the code as you can see in my code. When I click on it in the code it shows up as nil which is weird. Moreover, it is causing my app to crash. Source code would be amazing. I have no idea how to fix this. all I know is that the nil shows up in the "Appurl" The fatal error message that comes up is as follows below. I have looked up other answer for this type of fatal error message with no luck.
"thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
import UIKit
class NewTableViewController: UITableViewController, NewCellDelegate, {
var news:[News]!
override func viewDidLoad() {
super.viewDidLoad()
loadData()
func loadData() {
news = [News]()
news = DataManager.loadAll(News.self).sorted(by: {$0.createdAt < $1.createdAt})
self.tableView.reloadData()
}
#IBAction func Save(_ sender: Any) {
let addAlert = UIAlertController(title: "ADD", message: "TODO", preferredStyle: .alert)
addAlert.addTextField { (textfield:UITextField) in
textfield.placeholder = "TODO"
}
addAlert.addAction(UIAlertAction(title: "Save", style: .default, handler: { (action:UIAlertAction) in
guard let title = addAlert.textFields?.first?.text else {return}
let newsave = News(title: title, completed: false, createdAt: Date(), itemIdentifier: UUID())
newsave.saveItem()
self.news.append(newsave)
let indexPath = IndexPath(row: self.tableView.numberOfRows(inSection: 0), section: 0)
self.tableView.insertRows(at: [indexPath], with: .automatic)
}))
addAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(addAlert, animated: true, completion: nil)
}
};
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return news.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NewTableViewCell
cell.delegte = self
let news = self.news[indexPath.row]
cell.label.text = news.title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
//getting the index path of selected row
let indexPath = tableView.indexPathForSelectedRow
//getting the current cell from the index path
let currentCell = tableView.cellForRow(at: indexPath!) as! NewTableViewCell
//getting the text of that cell
let TODO = currentCell.label.text
let appURL = NSURL(string: "https://www.ask.com/web?q=\
(TODO))&o=0&qo=homepageSearchBox)")
if UIApplication.shared.canOpenURL(appURL! as URL) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(appURL! as URL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(appURL! as URL)
}
}
}
You need to handle occurrence of spaces and special characters like + in you url string,
For handling spaces,
/**Handle occurance of space in given url string*/
class func handleSpaces(in urlString: String) -> String {
return urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
}
For handling + symbol,
/**Handle occurance of space in given url string*/
class func handlePlusSign(in urlString: String) -> String {
return urlString.replacingOccurrences(of: "+", with: "%2B")
}
To avoid crashes you need to use proper crash resisting conditions like if let and guard let in your app,
e.g
if let url = appURL {
// Proceed to use this url
}
Your code will become,
let indexPath = tableView.indexPathForSelectedRow
//getting the current cell from the index path
guard let currentCell = tableView.cellForRow(at: indexPath!) as? NewTableViewCell else {
print("Can't get your cell")
return
}
//getting the text of that cell
guard let todo = currentCell.label.text else {
print("Error in getting todo string")
return
}
var urlString = "https://www.ask.com/web?q=\(todo))&o=0&qo=homepageSearchBox)"
urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! // Handle spaces in your `todo` string.
guard let appURL = URL(string: urlString) else {
print("Can't form url")
return
}
if UIApplication.shared.canOpenURL(appURL) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(appURL)
}
}
Thanks.
I'm having a problem regarding a feature where You can delete a cell and so delete and event using an Alamofire JSON request.
When I swipe the cell and click delete, the app crashes, but the event get deleted successfully and with no errors, in facts on Laravel side I get the event deleted.
I tried everything, but I really can't figure out how to fix the crash.
Can someone help me please?
here is my .Swift code:
import UIKit
import Alamofire
class EventViewController: UITableViewController {
#objc var transition = ElasticTransition()
#objc let lgr = UIScreenEdgePanGestureRecognizer()
#objc let rgr = UIScreenEdgePanGestureRecognizer()
let rc = UIRefreshControl()
#IBOutlet weak var myTableView: UITableView!
var myTableViewDataSource = [NewInfo]()
let url = URL(string: "http://ns7records.com/staffapp/api/events/index")
override func viewDidLoad() {
super.viewDidLoad()
loadList()
// Add Refresh Control to Table View
if #available(iOS 10.0, *) {
tableView.refreshControl = rc
} else {
tableView.addSubview(rc)
}
// Configure Refresh Control
rc.addTarget(self, action: #selector(refreshTableData(_:)), for: .valueChanged)
let attributesRefresh = [kCTForegroundColorAttributeName: UIColor.white]
rc.attributedTitle = NSAttributedString(string: "Caricamento ...", attributes: attributesRefresh as [NSAttributedStringKey : Any])
DispatchQueue.main.async {
}
// MENU Core
// customization
transition.sticky = true
transition.showShadow = true
transition.panThreshold = 0.3
transition.transformType = .translateMid
// menu// gesture recognizer
lgr.addTarget(self, action: #selector(MyProfileViewController.handlePan(_:)))
rgr.addTarget(self, action: #selector(MyProfileViewController.handleRightPan(_:)))
lgr.edges = .left
rgr.edges = .right
view.addGestureRecognizer(lgr)
view.addGestureRecognizer(rgr)
}
#objc private func refreshTableData(_ sender: Any) {
// Fetch Table Data
//myTableViewDataSource.removeAll()
tableView.reloadData()
loadList()
}
func loadList(){
var myNews = NewInfo()
// URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
//
// })
let task = URLSession.shared.dataTask(with:url!) {
(data, response, error) in
if error != nil
{
print("ERROR HERE..")
}else
{
do
{
if let content = data
{
let myJson = try JSONSerialization.jsonObject(with: content, options: .mutableContainers)
//print(myJson)
if let jsonData = myJson as? [String : Any]
{
if let myResults = jsonData["data"] as? [[String : Any]]
{
//dump(myResults)
for value in myResults
{
if let myTitle = value["title"] as? String
{
//print(myTitle)
myNews.displayTitle = myTitle
}
if let myLocation = value["local"] as? String
{
myNews.location = myLocation
}
if let myDate = value["date"] as? String
{
myNews.date = myDate
}
if let myDescription = value["description"] as? String
{
myNews.description = myDescription
}
if let myCost = value["cost"] as? String
{
myNews.cost = myCost
}
if let myNumMembers = value["num_members"] as? String
{
myNews.num_members = myNumMembers
}
if let myNumMembers_conf = value["num_members_confirmed"] as? String
{
myNews.num_members_confirmed = myNumMembers_conf
}
if let myStartEvent = value["time_start"] as? String
{
myNews.startEvent = myStartEvent
}
if let myEndEvent = value["time_end"] as? String
{
myNews.endEvent = myEndEvent
}
if let myId = value["id"] as? Int
{
myNews.idEvent = myId
}
//x img
// if let myMultimedia = value["data"] as? [String : Any]
// {
if let mySrc = value["event_photo"] as? String
{
myNews.event_photo = mySrc
print(mySrc)
}
self.myTableViewDataSource.append(myNews)
}//end loop
dump(self.myTableViewDataSource)
DispatchQueue.main.async
{
self.tableView.reloadData()
self.rc.endRefreshing()
}
}
}
}
}
catch{
}
}
}
task.resume()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath)->CGFloat {
return 150
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myTableViewDataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "reuseCell", for: indexPath)
let myImageView = myCell.viewWithTag(11) as! UIImageView
let myTitleLabel = myCell.viewWithTag(12) as! UILabel
let myLocation = myCell.viewWithTag(13) as! UILabel
let DateLabelCell = myCell.viewWithTag(14) as! UILabel
let numMembLabel = myCell.viewWithTag(15) as! UILabel
let numMembConfLabel = myCell.viewWithTag(16) as! UILabel
myTitleLabel.text = myTableViewDataSource[indexPath.row].displayTitle
myLocation.text = myTableViewDataSource[indexPath.row].location
DateLabelCell.text = myTableViewDataSource[indexPath.row].date
numMembLabel.text = myTableViewDataSource[indexPath.row].num_members
numMembConfLabel.text = myTableViewDataSource[indexPath.row].num_members_confirmed
if let imageURLString = myTableViewDataSource[indexPath.row].event_photo,
let imageURL = URL(string: AppConfig.public_server + imageURLString) {
myImageView.af_setImage(withURL: imageURL)
}
return myCell
}
//per passare da un viewcontroller a detailviewcontroller
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? EventDetailViewController {
destination.model = myTableViewDataSource[(tableView.indexPathForSelectedRow?.row)!]
// Effetto onda
let vc = segue.destination
vc.transitioningDelegate = transition
vc.modalPresentationStyle = .custom
}
//menu
if let vc = segue.destination as? MenuViewController{
vc.transitioningDelegate = transition
vc.modalPresentationStyle = .custom
//endmenu
}
}
//menu slide
#objc func handlePan(_ pan:UIPanGestureRecognizer){
if pan.state == .began{
transition.edge = .left
transition.startInteractiveTransition(self, segueIdentifier: "menu", gestureRecognizer: pan)
}else{
_ = transition.updateInteractiveTransition(gestureRecognizer: pan)
}
}
//endmenuslide
////ximg
func loadImage(url: String, to imageView: UIImageView)
{
let url = URL(string: url )
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else
{
return
}
DispatchQueue.main.async
{
imageView.image = UIImage(data: data)
}
}.resume()
}
/// star to: (x eliminare row e x muove row)
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObjTemp = myTableViewDataSource[sourceIndexPath.item]
myTableViewDataSource.remove(at: sourceIndexPath.item)
myTableViewDataSource.insert(movedObjTemp, at: destinationIndexPath.item)
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete){
// print(parameters)
let idEvent = (myTableViewDataSource[indexPath.item].idEvent)
let parameters = [
// "id": UserDefaults.standard.object(forKey: "userid")! ,
"id" : idEvent,
] as [String : Any]
let url = "http://www.ns7records.com/staffapp/public/api/deleteevent"
print(url)
Alamofire.request(url, method:.post, parameters:parameters,encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success:
print(response)
let JSON = response.result.value as? [String : Any]
//self.myTableView.reloadData()
let alert = UIAlertController(title: "Yeah!", message: "Evento modificato con successo!", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
// let data = JSON! ["data"] as! NSDictionary
if let jsonData = JSON as? [String : Any]
{
print(jsonData)
self.myTableViewDataSource.remove(at : indexPath.item)
self.myTableView.deleteRows(at: [indexPath], with: .automatic)
let indexPath = IndexPath(item: 0, section: 0)
//self.myTableView.deleteRows(at: [indexPath], with: .fade)
//self.myTableView.reloadData()
// }
// }
//}
}
case .failure(let error):
print(error)
let alert = UIAlertController(title: "Aia", message: "Non puoi cancellare questo evento!", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
#IBAction func EditButtonTableView(_ sender: UIBarButtonItem) {
self.myTableView.isEditing = !self.myTableView.isEditing
sender.title = (self.myTableView.isEditing) ? "Done" : "Edit"
}
/// end to: (x eliminare row e x muove row)
}
// MARK: -
// MARK: UITableView Delegate
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
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()
}
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
}
}
I have UIImage View (post image), label(post title), UIWebView(post content),
and I have this code to parse wordpress JSON posts to my app
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var maindata = (data[indexPath.row] as! NSDictionary)
theTitle = (maindata["post_title"] as? String)!
theImg = (maindata["image"] as? String)!
theDate = (maindata["post_date_gmt"] as? String)!
theBody = (maindata["post_content"] as? String)!
}
and I have installed JSON Api plugin on my wordpress,
but I don't know how to parse to my app ??
this is my whole code
import UIKit
import Haneke
var theTitle = ""
var theImg = ""
var theDate = ""
var theBody = ""
class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate {
#IBOutlet var myTable: UITableView!
// to refresh with pull down
var ref:UIRefreshControl?
// to refresh with pull down
var data = []
var prog:MBProgressHUD!
override func viewDidLoad()
{
super.viewDidLoad()
// to refresh with pull down
self.ref = UIRefreshControl()
self.ref?.attributedTitle = NSAttributedString(string: "اسحب للأسفل للتحديث")
self.ref?.addTarget(self, action: "ref:", forControlEvents: UIControlEvents.ValueChanged)
// to refresh with pull down
myTable.addSubview(self.ref!)
var heloWorldTimer = NSTimer.scheduledTimerWithTimeInterval(0.0001, target: self, selector: Selector("sayHello"), userInfo: nil, repeats: false)
myTable.backgroundColor = UIColor.clearColor()
myTable.dataSource = self
myTable.delegate = self
}
// to refresh with pull down
func ref (sender:UIRefreshControl)
{
self.myTable.reloadData()
self.ref?.endRefreshing()
}
// to refresh with pull down
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
func dataJsonFromURL(url:String)->NSArray
{
if var data = NSData(contentsOfURL: NSURL(string: url)!) {
return (NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSArray)
}
else {
return data
}
}
}
func dataJsonFromURL(url:String)->NSArray
{
var data = NSData(contentsOfURL: NSURL(string: url)!)
return (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSArray)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if data.count == 0 {
prog = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
prog.labelText = "جاري تحميل البيانات"
prog.detailsLabelText = "الرجاء الإنتظار"
return 0
}
else
{ MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
return data.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = myTable.dequeueReusableCellWithIdentifier("NCell", forIndexPath: indexPath) as!
newsCell
var maindata = (data[indexPath.row] as! NSDictionary)
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.titleNews!.text = maindata["post_title"] as? String
cell.dateNews!.text = maindata["post_date_gmt"] as? String
if var urlImg = NSURL(string: (maindata["image"] as? String)!)
{
cell.imgNews.hnk_setImageFromURL(urlImg, placeholder: nil, format:nil, failure:nil, success:nil)
}
cell.backgroundColor = UIColor.clearColor()
return cell
}
#IBAction func rfreshB(sender: UIBarButtonItem) {
prog = MBProgressHUD.showHUDAddedTo(view, animated: true)
prog.labelText = "جاري تحميل البيانات"
prog.detailsLabelText = "الرجاء الإنتظار"
//data = dataJsonFromURL("http://hhz20.co/newstest/PhpFile/admin/show.php")
data = dataJsonFromURL("http://hhz20.co/testing/PhpFile/admin/show.php")
myTable.reloadData()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var maindata = (data[indexPath.row] as! NSDictionary)
theTitle = (maindata["post_title"] as? String)!
theImg = (maindata["image"] as? String)!
theDate = (maindata["post_date_gmt"] as? String)!
theBody = (maindata["post_content"] as? String)!
}
func sayHello ()
{
data = dataJsonFromURL("http://hhz20.co/testing/PhpFile/admin/show.php")
myTable.reloadData()
}
}