I'm creating an app that reads news when I press the update button, but how do I read news when I open the app?

Asked 2 years ago, Updated 2 years ago, 47 views

import UIKit

classViewController:UITableViewController {

    variants = NSMutableArray()

    let newsUrlStrings = [
        "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://www3.nhk.or.jp/rss/news/cat0.xml&num=8",
        "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://www3.nhk.or.jp/rss/news/cat6.xml&num=8",
        "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://www3.nhk.or.jp/rss/news/cat7.xml&num=8"
        ]

    let imageNames = [
    "Japan.jpg",
    "world.jpg",
    "sport.jpg",
    ]

    @ IBAction func refresh (sender: AnyObject) {
        entries.removeAllObjects()


        for newsUrlString in newsUrlString {

            varurl = NSURL (string:newsUrlString) !
            var task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {data, response, error in

                variable=NSJSONSERIALIZATION.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error:nil) as!NSDictionary

                if var responseData=dict["responseData"] as ? NSDictionary {
                    if var feed=responseData["feed"]as? NSDictionary {
                        if varentries=feed ["entries"] as ? US>NSArray {

                            var formatter = NSDateFormatter()
                            formatter.locale=NSLocale(localeIdentifier: "en-US")
                            formatter.dateFormat="EEE,ddMMMMMYyyy HH:mm:sszzzz"

                            for vari=0;i<entries.count;i++{
                                variable=entries[i]as!NSMutableDictionary

                                entry ["url"] = newsUrlString

                                vardateStr=entry["publishedDate"] as!String
                                vardate=formatter.dateFromString(dateStr)
                                entry ["date"] = date
                            }

                            self.entries.addObjectsFromArray (entries as [AnyObject])

                            self.entries.sortUsingComparator({object1, object2 in)

                            vardate1 = object1 ["date"] as!NSDate
                            vardate2 = object2 ["date"] as!NSDate

                            var order=date1.compare(date2)

                                if order==NSComparisonResult.OrderedAscending{
                                    returnNSComparisonResult.OrderedAscending
                                }
                                else if order == NSComparisonResult.OrderedAscending {
                                    returnNSComparisonResult.OrderedAscending
                                }

                                return order
                            })
                        }
                    }
                }



                dispatch_async(dispatch_get_main_queue(), {

                    self.tableView.reloadData()

                    })
                })


            task.resume()
        }
    }

    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from anib.
    }

    override funcdidReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override functableView (tableView: UITableView, numberOfRowsInSection
        section: Int) - > Int {
        return entries.count
    }

    override functableView (tableView: UITableView, cellForRowAtIndexPath
        indexPath:NSIndexPath)->UITableViewCell{

        varcell=tableView.dueReusableCellWithIdentifier("news") as!UITableViewCell

        US>var entry=entries [indexPath.row] as!NSDictionary

        variableLabel=cell.viewWithTag(1)as!UILabel
        titleLabel.text=entry["title"] as ? String

        var descriptionLabel=cell.viewWithTag(2)as!UILabel
        descriptionLabel.text=entry["contentSnippet"] as ? String

        var urlString=entry ["url"] as!String
        var index = find(newsUrlStrings, urlString)
        varimageName=imageNames [index!]
        var image = UIImage (named: imageName)

        varimageView=cell.viewWithTag(4)as!UIImageView
        imageView.image=image
        return cell
    }

    override functableView(tableView:UITableView, didSelectRowAtIndexPathindexPath:NSIndexPath){
        performSegueWithIdentifier("detail", sender:entries [indexPath.row])
    }

    override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject?) {
        if segue.identifier == "detail" {
            var detailController=segue.destinationViewController as!DetailController

                    detailController.entry=sender as!NSDictionary
                }
            }
}

It looks like this.
As the title says, what should I do if I want to load a news story the moment I open the app?

ios swift

2022-09-30 20:58

2 Answers

I understand that the intention is to perform the loading process when the app changes from background to foreground.

In that case, you need to get an event that the app has moved to foreground.There are two ways to do this.One is to update the applicationWillResignActive: in AppDelegate at that time.Another way is to use NSNotificationCenter to receive notifications.

http://crunchtimer.jp/blog/technology/ios/700/

Please refer to the following URL for the lifecycle of other apps.
http://d.hatena.ne.jp/glass-_-onion/20100630/1277909762


2022-09-30 20:58

Try adding the viewWillAppear method as follows:
viewWillAppear is the life cycle event that occurs just before the screen appears.

override func viewWillAppear(){
    super.viewWillAppear()
    refresh() // Read Run
}

You must understand the life cycle of View in order to develop mobile apps.
In addition to the viewWillAppear above, the lifecycle varies and will need to be used differently depending on usage and timing.

Here's a link to a great article:Take a look.

View Lifecycle


2022-09-30 20:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.