Parse XML without Table View

Discussion in 'iOS Programming' started by djbrooks111, Sep 2, 2010.

  1. djbrooks111 macrumors newbie

    Joined:
    Jun 7, 2010
    #1
    Hi all,

    Is there anyway to parse an xml straight to a detail view without having to first go to a table view and select the cell you want?

    I'm trying to parse this xml (feed://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Aries) straight into a detail view. This feed is only ever one post, so I don't need the table view and just want the detail view.

    How can I parse and code this correctly?

    I want this view: [​IMG] instead of this view: [​IMG].

    The items that I would like from the feed are the Date and body of the post.

    Thanks!
    David
     
  2. ulbador macrumors 68000

    ulbador

    Joined:
    Feb 11, 2010
    #2
    Look at the XML reader example that you can download, the one that uses Animals.

    All you do is read your XML file into a NSDictionary. Once it's into a NSDictionary, you can do anything you want with it, including reading it into table or loading it straight into the detail view.

    Heck, since it's only ever one feed and all you ever want is a couple of fields, don't even bother with XML parsing and just use an NSURL to fetch the data and then do some string manipulation to pull out the data you want.
     
  3. djbrooks111 thread starter macrumors newbie

    Joined:
    Jun 7, 2010
    #3
    That is interesting that you say that I don't even need to parse it. This is my first app, and I'm kind of new to the ask, so how might I use an NSURL and manipulate the strings? Also, would I need a separate file to do this NSURL stuff besides the view file that I want the information to be presented on?

    Thanks!
    David
     
  4. ranguvar macrumors 6502

    Joined:
    Sep 18, 2009
    #4
    You'll have to read up on object orientation and Cocoa design principles. One thing you should never ever do is store or parse data in a UIView subclass.
     
  5. ulbador macrumors 68000

    ulbador

    Joined:
    Feb 11, 2010
    #5
    You'd do in the controller for the view that you want to display the data on, not on the view.

    Read the documentation for NSURL.

    The short and simple way is:

    NSString *text = [NSString stringWithContentsOfURL:[NSURL URLWithString:mad:"http://www.google.com"]];


    That would retrieve and store the data from Google in the string. Of course this makes NO allowances for no/slow network and any dozen other possible error conditions. At the very least you would want to check to make sure the text variable isn't nil or empty before trying tear it apart.

    Then you would just manipulate the text string with standard string manipulation (substring, rangeofstring,etc)
     
  6. djbrooks111 thread starter macrumors newbie

    Joined:
    Jun 7, 2010
    #6
    This makes things a little clearer, thanks. But could you explain the string manipulation that you are describing? Or, point me in the direction of a website that details how to do it?

    Thanks,
    David
     
  7. ulbador macrumors 68000

    ulbador

    Joined:
    Feb 11, 2010
  8. djbrooks111 thread starter macrumors newbie

    Joined:
    Jun 7, 2010
    #8
    When I enter this into Xcode, I get a warning saying "stringWithContentsOfURL: is deprecated".

    How can I fix this warning? Is there an updated way to get the contents of url?
     
  9. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #9
    Don't take this the wrong way but are you so lazy you can't spend the 20 seconds to find out? Here's how (in general for all deprecation warnings):

    1) Open the documentation
    2) Go to the entry for the object and method you are using
    3) Read the method Apple say to use instead
     
  10. djbrooks111 thread starter macrumors newbie

    Joined:
    Jun 7, 2010
    #10
    In the documentation, it says to use this "+ (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error" but what are the encoding and error variables if I just want all the content?
     
  11. ulbador macrumors 68000

    ulbador

    Joined:
    Feb 11, 2010
    #11
    Like the poster above said, go back to Objective C 101 and learn to read the docs.


    Code:
    stringWithContentsOfURL:encoding:error:
    
    Returns a string created by reading data from a given URL interpreted using a given encoding.
    
    + (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error
    
    Parameters
    
    url
    
        The URL to read.
    enc
    
        The encoding of the data at url.
    error
    
        If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
    
    Return Value
    
    A string created by reading data from URL using the encoding, enc. If the URL can’t be opened or there is an encoding error, returns nil.
    
    That tells you exactly what you need to know to use the method

    Myself and many others on this board could write the program for you, but then it would be ours and we could sue you for copyright :p
     
  12. djbrooks111 thread starter macrumors newbie

    Joined:
    Jun 7, 2010
    #12
    So, I switched over to TFHpple to help me get the data I want. Here is my code below:

    Code:
    - (void)viewDidLoad {
        [super viewDidLoad];
    	
    	NSString *Data = [NSString stringWithContentsOfURL:[NSURL URLWithString: @"feed://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Aries"] encoding:NSUTF8StringEncoding error:NULL];
    
            NSData *htmlData = [data dataUsingEncoding:NSUTF8StringEncoding];
    	
    	TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
    	NSArray *elements = [xpathParser search:@""];
    	TFHppleElement *element = [elements objectAtIndex:0];
    	NSString *paragraph = [element content];
    	summary.text = paragraph;
    	[xpathParser release];
    	[htmlData release];
    }

    I am trying to figure out what should go between the quotes in [xpathParser search:mad:""];

    This is the attribute that I am trying to locate and then retrieve the information from:

    HTML:
    <div class="apple-rss-summary" >Those of you appearing for competitive examinations do extremely well, winning recognition for your study. Business people find new opportunities knocking on their doors today. Those working from home get prestigious and lucrative work assignments during the latter half of the day. Sweetheart is very caring and tender.</div>
     
  13. ulbador macrumors 68000

    ulbador

    Joined:
    Feb 11, 2010
    #13
    That's HTML from your RSS reader, not the xml from the feed.

    This is what the XML from the feed should look like:

    Code:
    <?xml version="1.0" encoding="iso-8859-1" ?><rss version="2.0"><channel><title> Free Daily Horoscope</title><description> Free Daily Horoscope by findyourfate.com</description><link>http://www.findyourfate.com</link><item><title>Aries Horoscope for Saturday, September 04, 2010</title><description>Those of you appearing for competitive examinations do extremely well, winning recognition for your study. Business people find new opportunities knocking on their doors today. Those working from home get prestigious and lucrative work assignments during the latter half of the day. Sweetheart is very caring and tender.</description><link>http://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Aries</link></item></channel>
    </rss>
    
    You need to NSLog your output so you can see what you actually have, not what you think you have
     
  14. djbrooks111 thread starter macrumors newbie

    Joined:
    Jun 7, 2010
    #14
    Well I figured most of my problems out, but now, I'm left with an error in the Debug screen when I click on the button that takes you to the second view. The second view is where the problem is I believe.

    Code:
    //
    //  AriesView.m
    //  Horoscopes
    //
    //  Created by DJB on 9/2/10.
    //  Copyright 2010 __MyCompanyName__. All rights reserved.
    //
    
    #import "AriesView.h"
    
    
    
    @implementation AriesView
    
    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad {
        [super viewDidLoad];
    	
    	NSString *data = [NSString stringWithContentsOfURL:[NSURL URLWithString: @"feed://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Aries"] encoding:NSUTF8StringEncoding error:NULL];
    	
    	NSData *htmlData = [data dataUsingEncoding:NSUTF8StringEncoding];
    	
    	TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
    	NSArray *elements = [xpathParser search:@"/item/description"];
    	NSLog( @"%@", elements);
    	TFHppleElement *element = [elements objectAtIndex:0];
    	NSString *paragraph = [element content];
    	NSLog(@"%@", paragraph);
    	summary.text = paragraph;
    	[xpathParser release];
    	[htmlData release];
    }
    
    When I run the program and click on the button that bring me to this view, the app crashes. When looking at the Debug log, this is what it says:

    Code:
    [Session started at 2010-09-04 14:16:32 -0400.]
    2010-09-04 14:16:38.758 Horoscopes[19390:207] Unable to parse.
    2010-09-04 14:16:38.760 Horoscopes[19390:207] (
    )
    2010-09-04 14:16:38.762 Horoscopes[19390:207] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
    *** Call stack at first throw:
    (
    	0   CoreFoundation                      0x024bf919 __exceptionPreprocess + 185
    	1   libobjc.A.dylib                     0x0260d5de objc_exception_throw + 47
    	2   CoreFoundation                      0x024b5465 -[__NSArrayM objectAtIndex:] + 261
    	3   Horoscopes                          0x000029ba -[AriesView viewDidLoad] + 333
    	4   UIKit                               0x0048bc26 -[UIViewController view] + 179
    	5   UIKit                               0x0048d43f -[UIViewController viewControllerForRotation] + 36
    	6   UIKit                               0x00489682 -[UIViewController _visibleView] + 90
    	7   UIKit                               0x0074affd -[UIClientRotationContext initWithClient:toOrientation:duration:andWindow:] + 269
    	8   UIKit                               0x0040a0a0 -[UIWindow _setRotatableClient:toOrientation:duration:force:] + 921
    	9   UIKit                               0x00677543 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:] + 768
    	10  UIKit                               0x0048f769 -[UIViewController presentModalViewController:withTransition:] + 2937
    	11  Horoscopes                          0x00002219 -[HoroscopesViewController next:] + 139
    	12  UIKit                               0x003e3e14 -[UIApplication sendAction:to:from:forEvent:] + 119
    	13  UIKit                               0x0046d6c8 -[UIControl sendAction:to:forEvent:] + 67
    	14  UIKit                               0x0046fb4a -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
    	15  UIKit                               0x0046e6f7 -[UIControl touchesEnded:withEvent:] + 458
    	16  UIKit                               0x004072ff -[UIWindow _sendTouchesForEvent:] + 567
    	17  UIKit                               0x003e91ec -[UIApplication sendEvent:] + 447
    	18  UIKit                               0x003edac4 _UIApplicationHandleEvent + 7495
    	19  GraphicsServices                    0x02c01afa PurpleEventCallback + 1578
    	20  CoreFoundation                      0x024a0dc4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
    	21  CoreFoundation                      0x02401737 __CFRunLoopDoSource1 + 215
    	22  CoreFoundation                      0x023fe9c3 __CFRunLoopRun + 979
    	23  CoreFoundation                      0x023fe280 CFRunLoopRunSpecific + 208
    	24  CoreFoundation                      0x023fe1a1 CFRunLoopRunInMode + 97
    	25  GraphicsServices                    0x02c002c8 GSEventRunModal + 217
    	26  GraphicsServices                    0x02c0038d GSEventRun + 115
    	27  UIKit                               0x003f1b58 UIApplicationMain + 1160
    	28  Horoscopes                          0x00001f44 main + 102
    	29  Horoscopes                          0x00001ed5 start + 53
    )
    terminate called after throwing an instance of 'NSException'
    
    What am I doing wrong? How can I fix the problem?
     
  15. ulbador macrumors 68000

    ulbador

    Joined:
    Feb 11, 2010
    #15
    It tells you right there:

    2010-09-04 14:16:38.762 Horoscopes[19390:207] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'

    The elements array is empty. Which means the assignment isn't working right and you are probably using that TFHpple library wrong.

    http://www.amazon.com/gp/product/04...&pf_rd_t=101&pf_rd_p=470938631&pf_rd_i=507846

    I'm just sayin...
     

Share This Page