Reputation: 31973
I have a UIViewController which is also a NSURLConnectionDelegate. As such, it defines behavior such as:
– connection:didReceiveResponse:
– connection:didReceiveData:
– connectionDidFinishLoading:
However, in this view I have multiple NSURLConnections which assign it as the delegate. I need to achieve custom behavior in connectionDidFinishLoading: depending on which object is calling the delegate (e.g playing audio vs displaying an image vs opening a link)
What is the correct way to achieve this?
Upvotes: 0
Views: 311
Reputation: 23278
If you have a lot of urlconnections which falls under different categories(say 10 connections out of 5 are for audio, 3 for display image, 2 for opening link etc..), better option is to subclass NSURLConnection
and create a custom NSURLConnection
class. You can add your own property like a tag to this class. And define your own custom tags to different type of connections. In your UIViewController
and delegate methods try to use this subclass object and use this tag
property to differentiate between different NSURLConnections
.
For eg:-
Create a CustomNSURLConnection
file and write,
#define kAudioConnectionTag 100
#define kDisplayConnectionTag 200
#define kOpenURLConnectionTag 300
@interface CustomNSURLConnection : NSURLConnection
@property (nonatomic) NSInteger tag;
In UIViewController
class,
CustomNSURLConnection *audioConnection = [CustomNSURLConnection ...];
audioConnection.tag = kAudioConnectionTag;
CustomNSURLConnection *displayConnection = [CustomNSURLConnection ...];
audioConnection.tag = kDisplayConnectionTag;
CustomNSURLConnection *openURLConnection = [CustomNSURLConnection ...];
audioConnection.tag = kOpenURLConnectionTag;
- (void)connectionDidFinishLoading:(CustomNSURLConnection *)connection{
if (connection.tag == kAudioConnectionTag) {
//code
} else if (connection.tag == kDisplayConnectionTag) {
//code
} else {
//code
}
}
Upvotes: 0
Reputation: 54
You could declare each of the connection
@interface YourViewController
@property (retain, nonatomic) NSURLConnection *audioConnection;
@property (retain, nonatomic) NSURLConnection *anotherConnection;
then, on your connectionDidFinishLoading: method call each connection like this:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (connection == audioConnection) {
//doSomething
} else if (connection == anotherConnection) {
//doSomethingElse
}
}
Upvotes: 1
Reputation: 5291
Each of the delegate methods pass in the NSURLConnection as a parameter. Store a reference to your connection in a property and then check the if the connection parameter passed into connectionDidFinishLoading is your audio connection or your image connection etc.
Upvotes: 1