0

I am trying to set up a NSURLRequest to download a simple index.html with its externa style.css sheet but I am not quite sure how to do this.. I have only ever just formatted the URL of the request to the file I want.. but this has to be slightly different and I cannot find a good example of what I am trying to do.

this is my code so far:

#pragma mark - NSURLConnection methods

- (void)htmlRequest
{
    // Create the request.
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mywebsite.com/index.html"]
                                              cachePolicy:NSURLRequestReloadIgnoringCacheData
                                          timeoutInterval:60.0];

    // create the connection with the request
    // and start loading the data
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        receivedData = [NSMutableData data];
    } else {
        // Inform the user that the connection failed.
        NSLog(@"Connection Fail");
    }
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.

    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.

    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // inform the developer of error type

}

// This method uses methodName to determin which Initalizer method to send the response data to in EngineResponses.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//    EngineResponses *engineResponses = [EngineResponses sharedManager];

//        [engineResponses GetManufacturers:receivedData];

    NSString *myString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", myString);

}

as you can see I am just calling index.html directly.. I would like to know how to format my request so i get the index.html as well as style.css

any help would be greatly appreciated.

HurkNburkS
  • 5,492
  • 19
  • 100
  • 183

3 Answers3

1

I always create a new data structure,which has a -connection property and a -request property,like this

@interface connectionWrapper : NSObject
@property(retain) NSURLRequest *request
@property(retain) NSURLConnection *connection

by retaining this data structure in an mutable array, you can distinguish the connections in callback methods by iterate the array and compare each connectionWrapper instance's -connection property with the connection parameter the of the callback method, if they match(points to a same object), then you can retrieve the -request property of the connectionWrapper instance, then -url property of NSURLRequest instance.

as I'm not an native English speaker, I think code is a better tutor.

-(NSURLRequest*)getRequestByConnection:(NSURLConnection*)connection
{
    for(connectionWrapper *w in theArrayContainingAllConnectionWrappers)
    {
        if(w == connection)
            return w.request;
    }
}

In callback method:

-(void)connection:(NSURLConnection*)connection didReceiveResponse(NSURLResponse*)response
{
    NSURLRequest *request = [self getRequestByConnection:connection];
    NSURL *url = [request url];
    /*apply different approach to different url/*
}

PS:it's very sad that NSURLConnection don't have a -request property so that we can retrieve the request associated with the connection easily.

CarmeloS
  • 7,868
  • 8
  • 56
  • 103
  • forgive my ignorance, but what callback methods? – HurkNburkS Jun 25 '12 at 01:40
  • those methods whose names begin with connection: – CarmeloS Jun 25 '12 at 01:46
  • okay cool.. I need to learn more about them then.. and like you say just distinguidh them in the callbacks.. is there a way of say doing a request then halfway through the request going back and automatically getting a new file depending on the data you have parsed? – HurkNburkS Jun 25 '12 at 01:49
  • 1
    damn, I got a mistake, I'll update the post latter with the way I apply to such problem, this answer is WRONT! – CarmeloS Jun 25 '12 at 01:50
  • oh okay.. not a problem take your time.. thanks for letting me know :) – HurkNburkS Jun 25 '12 at 01:50
  • okay thanks very much for taking the time to help me out :) I am about to test this now.. where you say **apply different approach to different url** would I then put this into different if statements or something. – HurkNburkS Jun 25 '12 at 02:31
1

One way or another, you will have to make 2 requests. Even if you open a web page directly in a web browser, the browser will make a separate request for the CSS file referenced in the HTML it downloads. If your application needs both the HTML and the CSS file, then you want it to make 2 separate URL requests, first to get the HTML and then to get the CSS file.

Now, just because 2 requests need to be made, that doesn't mean you will always need to write the code that makes those 2 requests. It may be that libraries like the ones recommended by @Slee automatically take the results of a first request, parse them out, and make requests for any referenced CSS files. I have not worked with them so I am not sure what they support, or if any libraries will do this for you.

One thing you may want to consider is loading the HTML and CSS through a UIWebView rather than handling it all manually. UIWebView will attempt to load, parse, and render an HTML file into a UI component. In the process it will load referenced CSS and JavaScript files and apply them to its rendering. If you want to do anything special like intercept the calls it makes to load the CSS file(s), you can implement the UIWebViewDelegate protocol and set the delegate of the the UIWebView. Within that delegate you can implement the -webView:shouldStartLoadWithRequest:navigationType: method to be notified when the web view is loading the CSS file. You can use the call to that method to look at the request that is being issued for the CSS and do something else interesting with the request.

Tim Dean
  • 8,253
  • 2
  • 32
  • 59
  • okay awesome! thanks very much for this it makes alot of sense as it relates to the currently problems I am facing :) now I just need to read up and figure out how to attempt this.. but thankyou this is sometimes half the battle figuring out what I need to do and not do, now its just a matter of checking out a few functions in ios library and looking at some example code.. cheers for taking the time to provide a indepth response. – HurkNburkS Jun 25 '12 at 02:54
  • I mean I was planning to just download the data put it into a string then add it to a UIWebView.. but now that you ay you can load it directly through a UIWebView.. I am going to look into doing that! – HurkNburkS Jun 25 '12 at 02:55
0

do you know the name of the .css file?

If so I would just make 2 requests otherwise you will have to write a parser to look for the link to the css and make a second request anyways.

I'd also suggest looking into a library to handle the downlading of stuff - lot's of great libraries that can do the heavy lifting for you with advanced features.

Here's 3 I have used:

http://blog.mugunthkumar.com/coding/ios-tutorial-advanced-networking-with-mknetworkkit/

https://github.com/tonymillion/TMHTTPRequest

https://github.com/pokeb/asi-http-request

Slee
  • 27,498
  • 52
  • 145
  • 243
  • I used asihttprequest before, however it has been discontinued so not I have moved over to NSURLRequest.. which I find okay just means a little extra work I have done alot of my own parser methods.. however I just wasnt sure if there was some snazzy shortcut to get the css file etc.. normally im just calling php scripts that grab data from sql.. this html/css/javascript stuff I havent tried getting before so woundered if i had to go about it differently. – HurkNburkS Jun 25 '12 at 01:42