NSURLConnection is a fundamental class in Objective-C for handling network operations. It provides a simple and efficient way to send and receive data over HTTP and HTTPS protocols.
NSURLConnection serves as a bridge between your application and web services. It allows you to:
To use NSURLConnection, you typically follow these steps:
NSURL *url = [NSURL URLWithString:@"https://api.example.com/data"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
// Delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// Handle the response
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Process received data
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Request completed
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Handle error
}
NSURLConnection supports both asynchronous and synchronous requests. Asynchronous requests are preferred for better performance and user experience.
Asynchronous requests don't block the main thread, allowing your app to remain responsive while waiting for the network operation to complete.
Synchronous requests block the thread until the operation is complete. They should be used sparingly and only on background threads.
NSURLConnection also supports:
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
// Handle server trust (e.g., for self-signed certificates)
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
} else {
// Handle username/password authentication
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
}
}
While NSURLConnection has been a staple in Objective-C networking, modern iOS development often favors NSURLSession for its more flexible and powerful API. However, understanding NSURLConnection remains valuable, especially when working with legacy codebases.