views:

24

answers:

1

Hi there,

I've got a problem which I thought is pretty simple to fix but somehow I can't figure out what to do.

I've got an URL like http://www.myserver.com/myservice.php?param=foobar. When I type that into Safari's address bar I see an result like "Error" or "OK". So, how do I properly call that URL from within my code and get that result as a string? I've tried it with NSURLConnection, NSURLRequest and NSURLResponse but my response object is always nil. Maybe I'm just missing something?

Thanks in advance
–f

+1  A: 

The "response" in those classes refers to the protocol response (HTTP headers, etc.), not the content.

To get the content, you have a few options:

  1. Use NSURLConnection in asynchronous mode: Using NSURLConnection
  2. Use NSURLConnection in synchronous mode:

    // Error checks omitted
    NSURL *URL = [NSURL URLwithString:@"http://www.myserver.com/myservice.php?param=foobar"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:nil
                                                     error:nil];
    
  3. Use [NSString stringWithContentsOfURL:]

    NSURL *URL = [NSURL URLwithString:@"http://www.myserver.com/myservice.php?param=foobar"];
    NSString *content = [NSString stringWithContentsOfURL:URL];
    

Of course, you should use options 2 and 3 only if your content will be really small in size, to maintain responsiveness.

Can Berk Güder
Thank you! Number two did it for me. :)
flohei
you're welcome. =)
Can Berk Güder