objective-ciphoneinitwithcontentsofurl

Objective-C: initWithContentsOfURL returning null


I'm working on an app that would display a remote html and use local images, so what I'm trying to do is download the HTML of the website and display it as a "local" page, that would have access to images in my bundle.

For some reason I can't get initWithContentsOfURL to work. I checked all manuals and examples I could find and it seems that I'm doing it correctly, but the thing just won't work, returns null all the time. The same page loaded with NSURLRequest requestWithURL works fine.

Here is the code:

- (void)awakeFromNib 
{
    appURL = @"http://dragontest.fantasy-fan.org";
    notConnectedHTML = @"Could not connect.";

    NSString *seedString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/seed.php", appURL]]];

    NSString *HTMLdata = @"";

    if (seedString = @"(null)") {
        NSLog(@"Can't connect on awakeFromNib.");
        HTMLdata = notConnectedHTML;
    }else {
        HTMLdata = [NSString stringWithFormat:@"<body style='padding:0px;margin:0px;'>%@%@</body>", seedString, @"<br><img src='images/Default.png'>"];
    }   
    [homeView loadHTMLString:HTMLdata baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];
}

Solution

  • Firstly, why aren't appURL and notConnectedHTML declared as NSString *? Are they declared this way elsewhere?

    Secondly, you might be better off using NSURL's -urlWithString:relativeToURL: to create the actual request URL.

    Thirdly (and this is your actual problem here I suspect), to compare two C primitives, you use ==. = is the assignment operator (it makes the thing on the left equal to the thing on the right). To compare two Objective-C objects, use a comparison method, like -isEqual: or -isEqualToString: (which is specifically for NSStrings).

    So instead of:

    if (seedString = @"(null)")
    

    You should use

    if ([seedString isEqualToString:@"(null)"])
    

    However I suspect the reason you're trying to compare to "(null)" is because that's what NSLog spits out when an object is equal to nil. When an object is nil, the object reference itself is equal to the nil constant, so you should use this to see if an object is nil:

    if (seedString == nil)
    

    Just for good measure, some people like to use this syntax which does exactly the same thing:

    if (!seedString)