How can I receive data from URL on iPhone?

2019-03-31 09:01发布

问题:

I'm using the code from Apple's Document to do some HTTP communication. I can connect to the URL successfully, but I failed to receive the data from my server.

// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://..."]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                        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 that will hold
    // the received data
    // receivedData is declared as a method instance elsewhere
    NSMutableData *receivedData=[[NSMutableData data] retain];
} else {
    // inform the user that the download could not be made
}

The reason may be:

  1. I declare receivedData in the Action itself. The annotation says that I should declare it elsewhere. Where should I declare it? Should I declare it as controller's property?

  2. How can [[NSMutableData data] retain] find the URL as it is outside of the if{}?

回答1:

When you use NSURLConnection's initWithRequest:delegate: method, the data (along with other stuff) is sent to the delegate object in a sequence of method calls. The methods are all optional, so if your delegate object doesn't implement them, the connection object just skips them.

There are a bunch of methods, so I won't list them all here, but they're all described in detail in the NSURLConnection documentation. To get the received data you'll want to implement -connection:didReceiveData: on the delegate object. This method will be called, potentially more than once, with an NSData object representing newly-received data. You can then append that to your existing NSMutableData object, or do whatever else makes sense with it. You'll know that you've received all of the data when -connectionDidFinishLoading: is called on the delegate object.

To answer your two specific questions:

  1. Yes, you should declare it as a property of the controller object. You should also make sure to allocate the object BEFORE calling NSURLConnection's initWithRequest:delegate:, because the connection will start loading data asynchronously as soon as the connection object is created. Alternately you could implement -connection:didReceiveResponse: on the delegate, check the HTTP status, and create the data object then.

  2. The mutable data object can't find the URL, the connection, or its data as you've got it set up, but if you follow the steps I've described then you can add data to it as it comes in, and use it when the connection finishes.