iOS

How to Create a Simple RSS Reader App


Editor’s note: we received a number of requests for a tutorial about building a RSS reader app. This week, Rafael Garcia Leiva will show you how to create a simple iPhone app to consume a RSS feed. Rafael is a senior iPhone developer author of more than a dozen applications. Currently he works as freelancer developing iPhone applications and teaching introductory and advanced courses about iPhone programming. When away from a keyboard Rafael spends his time on the mountains with his wife and three children.

Enter the RSS Reader tutorial.

In this tutorial, we are going to learn how to create a simple RSS reader application. The app will be based on a master / detail design, where the master view will display the list of available feeds, and the detail view will show the corresponding web pages.

Simple RSS Reader Tutorial

Simple RSS Reader Tutorial

The core of the application is the NSXMLParser class. NSXMLParser is the XML parser included by default with the iPhone SDK. NSXMLParser is a SAX parser, which means that it adopts an event-driven style of parsing XML files: whenever the parser has finished the processing of a part of the XML file, it calls a method from the parser’s delegate.

Creating a Master Detail Application

Open Xcode and create a new Project, choose the template Master Detail Application as shown below.

Creating a new Xcode Project

Creating a new Xcode Project

In the next screen, enter RSSreader as the product name and set com.appcoda in the company identifier field. Don’t forget to select the “User Storyboard” and “Use Automatic Reference Counting” options. Press next and create.

Xcode Project Identification

Setting the project option

Designing the User Interface

Select the MainStoryboard.storyboard file from Xcode’s Navigator to display the storyboard on the Editor pane.

RSS Reader Storyboard

RSS Reader Storyboard

As you can see, we already have all the elements we need for our reader:

  • A Navigation Bar to go back and forward from the stories.
  • A Table View to display the list of available stories.
  • A Detailed View that will contain a Web View to display the selected story.

However, we still need to make a few changes in the storyboard to have a fully functional user interface.

First select the Master View Controller and change the Navigation Bar title from “Master” to “Stories”, or to any other title you prefer. Then, click on the Assistant Editor button to open the source code associated to our Master View Controller (APPMasterViewController.h), and create an IBOutlet for our Table View (control drag from the UITableView to the source code).

Creating an outlet for table view

Creating an outlet for table view

In the Connection field we have to choose Outlet, as Name use tableView, as Type select UITableView, and finally, as Storage select Strong. That should create the following IBOutlet:

Now select the Detail View Controller and change again the title of the Navigation Bar; instead of “Detail” write “Content”. Then we have to remove the label in the center of the View, since we are not going to use it. Do not forget to remove the IBOutlet property form the APPDetailViewController.h file, and remove the detailItem property as well. Finally, drag and drop an UIWebView from the Object Library to the Detail View Controller View. Make sure that the web view takes all the available space.

Adding a web view

Adding a web view

Again, we have to create an IBOutlet form the UIWebView. Using the same procedure described above, control drag an outlet to the APPDetailViewController.h file, and call it webView. Add also another @property of type NSString, and with copy modifier. The string property will contain the URL address of the current selected story. If you did everything correctly, the APPDetailViewController.h should be something like:

Implementing the Master View Controller

In the APPMasterViewController.m file, replace the @interface declaration by the following:

In this section we have declared several helper variables: parser is the object that will download and parse the RSS XML files; feeds is a mutable array that will contain the list of feeds downloaded; item is a mutable dictionary that will contains the details of a feed, in our case its title and its link; and finally, element will help us to control with element is currently parsing the NSXMLParser object.

In the viewDidLoad function we have to initialize and start the NSXMLParser object. For simplicity, in this example the URL for the feed is hard coded. We simple use the hot news feed from Apple (http://images.apple.com/main/rss/hotnews/hotnews.rss). In a production application, you should allow the user to change this address from the user interface.

Next remove the insertNewObject method, since we will not allow the user to add feeds manually, and replace the methods for managing the table by the following:

The only element that is new is the following line of code, where we set the title of the current cell to the title of the feed:

Remove also the canEditRowAtIndexPath and commitEditingStyle methods, since we do not need them for this application.

Implementing the Parser Delegate

Next we have to implement the parser delegate methods. In order to do that, we have to tell the compiler that the ENTMasterViewController class implements the NSXMLParserDelegate protocol. Open the ENTMasterViewController.h file and replace the class definition by:

@interface ENTMasterViewController : UITableViewController

Whenever the parser finds a new element, it calls the didStartElement method from its delegate. In that method we have to check that the element found is an “item”, and if so, we allocate the variables to store the item.

Then, the parser calls its delegate every time new characters are found. This is why we have to use mutable strings, since we have to add the new characters found to the previous ones. In our case we are interested in the “title” and “link” elements, but we could also store information about the “date” or “summary” of the story.

When the parser encounters the end of an element, it calls the didEndElement method. In that case we simply add the new object to the array of objects.

And when the parser encounters the end of the document, it calls the method parserDidEndDocument. In that case what we have to do is to inform to the UITableView to redisplay itself, since we have all the data to be displayed.

Implementing the Detail View Controller

We need a way to inform to our Detail View Controller about the URL of the feed we want to display. In order to do that we use the prepareForSegue method of the Master View Controller, where we set the url property of the destintionViewController:

The last step is to modify the APPDetailViewController.m file. In our case, the Detail View Controller is very simple, we only need to provide the following viewDidLoad method, and safely remove the rest of the methods:

The method just ask to the webView to display the content of the selected feed. For that, first we create an NSURL with the string we have, but escaping those characters that can create problems in an URK with the option using stringByAddingPercentEscapesUsingEncoding. And then, we create an NSURLRequest to download the web page with the story.

If you make no mistakes, you should be able to compile and run the RSS reader app in the simulator.

Simple RSS Reader App

Simple RSS Reader App

Download the Full Source Code

I hope you enjoy the tutorial. You should now have a basic idea of consuming RSS feed using NSURLRequest and NSXMLParser. For your complete reference, you can download the full source code from here.

We'll explore some more interesting things in the upcoming tutorials. As always, leave us comment and share your thought about the tutorials.

Tutorial
Building a Speech-to-Text App Using Speech Framework in iOS 10
iOS
Working with Core Bluetooth in iOS 11
iOS
iOS Programming 101: How To Get the User Location in iPhone App
  • Osvaldo Cipriano

    Another awesome tutorial.
    How can we use images in the feed “list”


    • iOS Killer

      iOS KilleriOS Killer

      Author Reply

      Yes i was suppose to ask this only… it would be helpfull if get some help on this


  • Anonymous Programmer

    Be careful when writing the code in the MasterViewController’s ‘prepareForSegue’ method. The ‘setURL’ method only accepts NSURL Objects.

    Try this in place of the ‘setURL’ method:

    DetailViewController *dest = segue.destinationViewController;
    dest.url = string;


    • Erik Fisher

      You just have to make sure you write ‘setUrl’ and not ‘setURL’, as you want to reference the *url property declared in DetailViewController.


  • Yamil Urbina

    Thanks for another great tutorial! Any chance to put the code for the tutorials on Github? Would be great to fork it or just browse through the code online 🙂


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      You can download the whole Xcode project using the above download link. But later we may put the code on Github too.


  • Pattyla Patty

    Thanks tutorial~

    Testing several rss feeds but got different messages, someone have any good suggestion? Thank u!

    1. http://rss.chinatimes.com/rss/latestnews-u.rss msg:CGAffineTransformInvert: singular matrix

    2.http://cnyes.feedsportal.com/c/33100/fe.ed/news.cnyes.com/rss1/industry

    : ImageIO: readICCData Embedded profile header length is greater than data length.

    3. http://www.chinatimes.com/realtimenews-stock.rss

    can’t get link (because it includes Chinese words?) msg: Bad Request -Invalid URL

    4. http://www.baidu.com/search/rss.html
    can’t get link msg: Not Found

    5. BBC chinese & UK rss can’t work:

    http://www.bbc.co.uk/zhongwen/trad/institutional/2011/04/111111_rss.shtml

    http://www.bbc.co.uk/news/10628494


  • chris

    chrischris

    Author Reply

    hi! I’ve inserted my wordpress feed link. the table view find my headline. but the detail view can’t find the link. can i fix this?
    thx


    • chris

      chrischris

      Author Reply

      it works when wordpress permalink is set on standard. but i need the permalink “article name”. can anybody help me?


      • Fred R.

        Fred R.Fred R.

        Author Reply

        I have the same problem. I want to use it with customized permalinks. Do you have any idea on how to fix it?


        • Simon Ng

          Simon NgSimon Ng

          Author Reply

          Can you show me the rss feed?


          • FredSocial

            FredSocialFredSocial

            Author

            The following wordpress blog fails: http://gigaom.com/channel/apple/feed

            The news feed shows up, however when you try to open any story, it gives you a “page not found” (401) error.

            Same issue with the apple feed that you mentioned in the example: “http://images.apple.com/main/rss/hotnews/hotnews.rss


          • FredSocial

            FredSocialFredSocial

            Author

            I noticed that when you click on a link. The code add the following characters at the end of the URL: %09%09

            That is why we get the 401 error or page not found error message in the viewdetail controller


          • FredSocial

            FredSocialFredSocial

            Author

            The issue seems to be related to the APPDetailViewController.m file in the following line:

            – (void)viewDidLoad {
            [super viewDidLoad];
            NSURL *myURL = [NSURL URLWithString: [self.url stringByAddingPercentEscapesUsingEncoding:
            NSUTF8StringEncoding]];
            NSURLRequest *request = [NSURLRequest requestWithURL:myURL];
            [self.webView loadRequest:request];
            }

            It seems that the encoding is adding additional characters to the URL. How can we fix it?


          • Dan

            DanDan

            Author

            Looks like you have the same problem as me. Turns out the link passed to APPDetailViewController contains trailing linefeed and spaces. I solved it by trimming the url:

            NSString *urlString = [self.url stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];


          • FredSocial

            FredSocialFredSocial

            Author

            Hi Dan – Can you post your code here (viewDidLoad)?

            I tried and it gave me an error.


          • FredSocial

            FredSocialFredSocial

            Author

            Never mind. I was able to figure it out. Thanks!


          • jasper

            jasperjasper

            Author

            Would be cool if you could share the code with us fred which you used to fix it cause i am having the same problem as you and dan but i cant figure it out.

            I have tryed the code dan has provided but it comes up with an error.

            It would be much appreciated if you could share the code and some info you used to figure the error out


          • Oscar

            OscarOscar

            Author

            This is the code

            – (void)viewDidLoad {
            [super viewDidLoad];

            //NSString *URL = [self.url stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

            NSURL *URL = [NSURL URLWithString: [self.url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];

            NSURLRequest *request = [NSURLRequest requestWithURL:URL];
            [self.webView loadRequest:request];

            }


          • francois53

            francois53francois53

            Author

            Thanks !


          • puranjay

            puranjaypuranjay

            Author

            after i load the project
            i am not able to scroll through in the simulator
            any idea y??


          • Oscar

            OscarOscar

            Author

            Hi, when you put this code NSString *urlString = [self.url stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; ??
            Thanks


  • Roya

    RoyaRoya

    Author Reply

    Thank you! Please post more iOS tutorials.


  • Chris

    ChrisChris

    Author Reply

    Hi great tutorial !!! , but I have one question, how can i add “pull to refresh” to get new rss feed when I in aplication ?


  • Stephen W.

    Stephen W.Stephen W.

    Author Reply

    Great article! This was my first iPhone application. Pretty great start.


  • Christophe

    ChristopheChristophe

    Author Reply

    it seems that with some of the apple feed links the link is broken, for example adding a simple NSLog indicates that the link being passed is:
    “http://www.apple.com/ipad/business/profiles/mayo-clinic/ ?sr=hotnews.rss”

    both:
    “http://www.apple.com/ipad/business/profiles/mayo-clinic/?sr=hotnews.rss”
    “http://www.apple.com/ipad/business/profiles/mayo-clinic/”

    seem to work fine

    by accessing the link directly (http://images.apple.com/main/rss/hotnews/hotnews.rss) it seems that feed itself is corrupt, are there any quick ways one can check the validity of a url ?


    • Josh

      JoshJosh

      Author Reply

      Ah, thats why it wasn’t working. thank you for this update. I was scratching my head and looking at NSlog output.


  • A.Thind

    A.ThindA.Thind

    Author Reply

    How would i go about adding and implementing a search field for this for the uitableview?


  • tigreroux

    tigrerouxtigreroux

    Author Reply

    I use this tutorial and added a tabbar but i don’t know how define a new feed in the second view of the tabbar


  • Hugo

    HugoHugo

    Author Reply

    I think you should tell us that we’re comparing elementName to @”item” and @”title” and @”link” because the NSXMLParser is going through all the words in the XML file and it’s trying to find the tags and and so that it can then extract the text content. It’s not that obvious when you know nothing about XML parsing. At least for me it wasn’t. Good tutorial nonetheless.


  • sivabalan

    sivabalansivabalan

    Author Reply

    I am in need of displaying the “description” alone instead of taking user to the new link , any help with that ?


  • chuy

    chuychuy

    Author Reply

    thanks for sharing!! this is an awesome easy-to-follow tutorial!!! thanks!!!


  • Chris

    ChrisChris

    Author Reply

    You did a great job on this tutorial. I managed to get my parser working but had problems get url attribute of for an image in TableView. Could you tell me how I can do it. Thanks and keep posting this tutorials


  • ran

    ranran

    Author Reply

    Great tutorial! Clear and accurate! 10X!!!


  • Gil Creque

    Gil CrequeGil Creque

    Author Reply

    You mentioned the ENTMasterViewController class when I believe you meant the APPMasterViewController


    • abraham

      abrahamabraham

      Author Reply

      you’re absolutely right 🙂


    • George

      GeorgeGeorge

      Author Reply

      Yeah, it’s this kind of carelessness that makes us beginners pull our hair. He also missed several steps because I’m getting 3 errors a warning after following to a T.


  • ahmed

    ahmedahmed

    Author Reply

    H
    ow to add load more cell for this project


  • RedProgrammer

    Great tutorial thanks! However, I am having some issues loading the UI. I have read the NSXMLParser blocks the the thread and so when I implement this example into my project it appears to the user as if the app is unresponsive while the XML data is parsed and loaded. I am new to obj -C but have found some information about solving this issues with Grand Central Dispatch. Is this the best method to go about solving this issue? Anyone have some example code?


  • Jeff

    JeffJeff

    Author Reply

    Anyone have an idea about Bad Request – Invalid URL?

    I have tried typing setURL. It still the same.


  • DocAsh59

    DocAsh59DocAsh59

    Author Reply

    Just what I was searching for! But how would you show the RSS feed but when you click on the button instead of taking you to another screen to take direct to the link in the RSS feed?
    Thanks


  • samsulfreude

    Since iOS 7 is already here, am just wondering, will this code work with Xcode 5?


  • philippe b

    philippe bphilippe b

    Author Reply

    great tutorrial, my first app really – however although i think i followed instructions, i get a ‘URL not Found’ in the details list – quite frustrating! anyone have the solution? thanks


  • philippe b

    philippe bphilippe b

    Author Reply

  • Dameon Bryant

    great tutorial. when I tested the code in the xcode 5 iPad simulator the uitableview displays fine but the the webuiview doesn’t display anything for the ipad. it works fine in the iphone simulator. Any suggestions?


  • george

    georgegeorge

    Author Reply

    is there anyway that you can create multiply feeds, because i am doing a app for a recruitment business and they have around 5 different feed urls deepening on what kind of job. so is it possible to say 3-5 different master table and master detail with different jobs categories feeding through


    • Nick G.

      Nick G.Nick G.

      Author Reply

      No need, just change the URL parameter depending on the kind of job and call [self.table reloadData];


  • MacTechReviews

    2013-11-15 10:43:07.934 RSS App[25897:70b] *** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key detailDescriptionLabel.’

    Got this error, I also get it when I try and run another app.


  • Nassif Najdat

    Hello there,
    I developing an IOS app, The app is depending on the RSS feeds from my client website, The problem is that my app is very very slow, what to do to make it faster?? it takes too much time to load the home page, and it takes too much time to load the categories news, please I need help if someone can ??


  • SomeDude

    SomeDudeSomeDude

    Author Reply

    Nice tutorial and it even works in xcode 5 with a little tweaking. What I’m wondering about is the best way to take the feed and divide it into categories. It wouldn’t be a multi-feed reader, but the same feed categorized into six or seven different categories of posts from a blog. Ive looked at adding multiple sets of master/detail VCs, one set for each category, but I’ve also wondered about simply adding a bacic VC for an initial view with buttons (one for each category in the feed) and then having those buttons determine the URL that is loaded into the parser. ONly problem is I’m too much of a novice to know not only which method would be best, but how to do either without errors galore. Any advice?


  • Stieger

    StiegerStieger

    Author Reply

    Hello

    When i try to open my Link “http://gipsbachschluderi.ch/blog/files/feed.html” the start page will display bud the link to the feed did not work?

    Can you help me please ?


  • George

    GeorgeGeorge

    Author Reply

    Seems to me like some steps missing. 1 warning and 3 errors after following to a T is not a good tutorial. Also, wasn’t too sure where some of the code went initially. Thanks for taking your time to write all this code, but it would be appreciated if you would test what you wrote so we don’t have to download. Otherwise, just give us the download link and we’ll look into it ourselves.

    Cheers!


  • ©ameron Tarbell

    Hey 2 things. 1. The download link is broken. 2. where do i get the ENTMasterViewController class from? Is it in an apple framework?


  • ©ameron Tarbell

    ok… Followed the tutorial and even downloaded the source code. Everytime I click on a link in the table view, the website says 404- Page not found. When I take the link from the RSS feed and paste it into my browser, it works fine! help please


  • mike

    mikemike

    Author Reply

    the fix described by oscar works, thanks. for some reason all the items in the feed I am testing are not showing up, just 10 of 42 items shown in feed reader. why is that?


    • sKiZZiT

      sKiZZiTsKiZZiT

      Author Reply

      Same here, have the same issue. Anyone?


  • Jeremy

    JeremyJeremy

    Author Reply

    Whoever wrote this really should follow there own process just once before they publish it. Referring to classes by the wrong name half way through a tutorial is careless.


  • Alireza Behraznia

    hi there i have setup everything and i get no errors no issues nothing at all and its successfully build and runs on the simulator but the problem is in the master view i see all the feeds fetched but when i tap on it it the detail view ( the uiwebview ) wont show anything is blank white, if somebody can help me it would be great


  • Gouranga

    GourangaGouranga

    Author Reply

    Great Tutorial


  • Radu Ursache

    thank you, great tutorial!


  • Mohammed Gritli

    how can i add the post image in the table view ?


  • Kenson

    KensonKenson

    Author Reply

    After tried it on Xcode5.1, I got a blank list. No work in 5.1?


  • Mohammed Gritli

    Thank you , a great tutorial , but , is there a way i can add post image to a uiimageview in the cell next to the title ? please help


  • Sheikh

    SheikhSheikh

    Author Reply

    God Bless You it’s very help ful


  • Dimensioner

    Vague, cursory tutorial that should be updated or removed. For a tutorial in a beginner section, it gives hardly any “why” or “how” answers.


  • NewbieProgrammer

    When running the tutorial app on my iPhone…..the latest RSS feed (following) does not load when the app is launched. If I delete the app and re-run the simulator, the latest news feed is always loaded.

    Has anyone else ran into this problem? Would adding “[self.tableview reloadData];” to the viewDidLoad method force the table to always refresh on launching of the app? Tx


  • Soroush

    SoroushSoroush

    Author Reply

    Great! Thank you so much :*
    but I have question and that is how can add notification when new rss arrives?
    Please help me


  • Srinadh

    SrinadhSrinadh

    Author Reply

    Great tutorial, it works perfect, where i come to real Rss Feed my nsxmlparser object giving error like

    new Error Domain=NSCocoaErrorDomain Code=-1 “The operation couldn’t be completed. (Cocoa error -1.)” UserInfo=0x786a9730 {NSXMLParserErrorMessage=Could not open data stream

    Please help me on issue. if i give different RSS Feeds, those are working, but i dont know what is the problem of my Rss Feed url.


  • timbojill

    timbojilltimbojill

    Author Reply

    Love this example. I was wondering how to pull an image into the cell. Here is an example of the feed below kindly email me at [email protected]. I don’t come here often. Just wondering if it is possible how the feed is right now.


    St. Thomas Man Arrested On Three Counts Of Possession Of Unlicensed Firearm http://viconsortium.com/virgin-islands-2/st-thomas-man-arrested-on-three-counts-of-possession-of-unlicensed-firearm/
    http://viconsortium.com/virgin-islands-2/st-thomas-man-arrested-on-three-counts-of-possession-of-unlicensed-firearm/#comments Sun, 28 Jun 2015 14:41:38 +0000




    http://viconsortium.com/?p=24715
    ST. THOMAS — A man who goes by the moniker “Rambo” was arrested and charged with three counts of possession of an unlicensed firearm, VIPD’s Public Information Officer Kevin Jackson announced last Wednesday. According to Jackson, Michael “Rambo” Lewis, 36, was observed in the vicinity of Coki Point with a gun’s magazine visible in his back […]

    The post St. Thomas Man Arrested On Three Counts Of Possession Of Unlicensed Firearm appeared first on .

    ]]>
    ST. THOMAS — A man who goes by the moniker “Rambo” was arrested and charged with three counts of possession of an unlicensed firearm, VIPD’s Public Information Officer Kevin Jackson announced last Wednesday.

    According to Jackson, Michael “Rambo” Lewis, 36, was observed in the vicinity of Coki Point with a gun’s magazine visible in his back pocket. When approached by officers, Lewis attempted to escape but was soon after apprehended in a nearby residence.

    Police then proceeded to read the suspect his Miranda Rights, at which point he directed the officers to areas in the residence where three firearms were located. Unable to make bail of $100,000, Lewis was remanded to the Bureau of Corrections pending his advise-of-rights hearing.

    The post St. Thomas Man Arrested On Three Counts Of Possession Of Unlicensed Firearm appeared first on .

    ]]>

    http://viconsortium.com/virgin-islands-2/st-thomas-man-arrested-on-three-counts-of-possession-of-unlicensed-firearm/feed/
    0


  • Jayson Ong

    Jayson OngJayson Ong

    Author Reply

    Why do I get null in Request url: { URL: (null) } It can’t load the stories after I click them in the list view.


  • Evyn G

    Evyn GEvyn G

    Author Reply

    Hello, the dropbox URL is outdated anyway there is a updated version for me to download?


Leave a Reply to DocAsh59
Cancel Reply

Shares