Can I make an asynchronous NSURL Connection in a b

2019-08-07 09:15发布

问题:

I am working through through the basics of Objective-C, I've graduated past syntax but I'm still not doing any ios specific stuff. Anyway, I'm trying to figure out http requests, and I can't get an asynchronous post to work correctly.

I can go very basic (this works):

NSString *doc = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error];

NSLog(@"%@", doc);

And I can make a synchronous request (also works):

NSData *urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

NSString *doc = [[NSString alloc]initWithData:urlData encoding:NSASCIIStringEncoding];

But when I try this:

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];

I can't seem to get any of the connection methods to fire, such as didReceiveResponse or didReceiveData.

So here are my questions:

Will what I am trying to do work in a command-line obejctive c app?

-Does the delegate need to be "self"? Can I make a custom "delegate" class and add methods like:

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"Data");
}

-If a custom delegate is possible, is it a good idea? Should I attach the above didReceiveData method to whatever class is performing the connection?

-Do I need to have some kind of task running continuously so my program doesn't end before the response comes in?

-Am I barking up the wrong tree entirely? Can you set me straight?

Thanks in advance for your time.

回答1:

NSURLConnection and NSURLRequest are both part of the Foundation framework, so you should be fine using them in your program. However, per the NSURLConnection documentation:

For the connection to work correctly the calling thread’s run loop must be operating in the default run loop mode.

You'll want to read about NSRunLoop. Your command line app probably doesn't have a run loop, which is why your async request isn't doing what you expect.

The delegate doesn't have to be 'self' -- it can be any object you like provided that object implements the appropriate delegate methods.

Obviously, if the program exits before the connection completes its work, your program isn't going to get the data it was looking for.