Reputation: 3071
I have single view for both uploading and downloading images and audio files. Here what I am doing
To start downloading i am using this :
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
and this trigger its delagate methods
connection:didReceiveResponse:
connection:didReceiveData:
connectionDidFinishLoading:
and in these methods I am calculating file size, showing downloading progress through progress bar and saving files in my device.
For uploading I am doing this
[NSURLConnection connectionWithRequest:request delegate:self];
and using this connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
this delegate methods works fine upload file and also tells about bytesWritten, totalBytesWritten, totalBytesExpectedToWrite but it also calls
connection:didReceiveResponse:
connection:didReceiveData:
connectionDidFinishLoading:
and its valid because all are delegate methods.
But problem is I am using these three to handle downloading.
What is the correct way to work with NSURLConection regarding uploading and downloading data?
Reference Apple Doc
Upvotes: 0
Views: 111
Reputation: 50129
Save the pointers to the NSURLConnections and inside the delegates determine which one is used.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if(connection==downloaderConn) {
//handle download
}
else {
//handle upoad
}
}
Upvotes: 1
Reputation: 2007
The best way for me would be to implement the delegates in dedicated classes (e.g DownloadingDelegate and UploadingDelegate) and instantiate different delegates for each connection. The download and upload process could then be handled totally independently.
Or, if the download and upload are not concurrent, it can be simpler to use a boolean as a flag and test it in your delegates functions.
For example, let say you use a boolean instance variable called downloading
.
You will have for the download:
downloading = true;
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
And the upload:
downloading = false;
[NSURLConnection connectionWithRequest:request delegate:self];
Then in your delegate:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if( downloading )
{
// handle the response when downloading ...
}
else
{
// when uploading
}
}
Upvotes: 2
Reputation: 4789
You can Use AFNetworking
for your task.
AFNetworking
is a delightful networking library for iOS
and Mac OS X
. It's built on top of NSURLConnection
, NSOperation
, and other familiar Foundation technologies
. It has a modular architecture
with well-designed, feature-rich APIs that are a joy to use.
Find the SDK here
Upvotes: -1