我有上传和下载图片和音频文件的单一视图。这就是我在做什么
开始下载我正在使用:
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
这会触发其解决方法
connection:didReceiveResponse:
connection:didReceiveData:
connectionDidFinishLoading:
在这些方法中,我正在计算文件大小,显示通过进度条下载进度并在我的设备中保存文件。
上传时我正在做这个
[NSURLConnection connectionWithRequest:request delegate:self];
并使用此connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
这个委托方法工作正常上传文件,并讲述bytesWritten,totalBytesWritten,totalBytesExpectedToWrite但它也调用
connection:didReceiveResponse:
connection:didReceiveData:
connectionDidFinishLoading:
并且它有效,因为所有都是委托方法。
但问题是我正在使用这三个来处理下载。
使用NSURLConection处理上传和下载数据的正确方法是什么?
答案 0 :(得分:2)
对我来说,最好的方法是在专用类(例如DownloadingDelegate和UploadingDelegate)中实现委托,并为每个连接实例化不同的委托。然后可以完全独立地处理下载和上传过程。
或者,如果下载和上传不是并发的,则可以更简单地使用布尔值作为标志并在代理函数中对其进行测试。
例如,假设您使用名为downloading
的布尔实例变量。
您需要下载:
downloading = true;
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
上传:
downloading = false;
[NSURLConnection connectionWithRequest:request delegate:self];
然后在你的代表中:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if( downloading )
{
// handle the response when downloading ...
}
else
{
// when uploading
}
}
答案 1 :(得分:1)
将指针保存到NSURLConnections,并在委托内部确定使用哪一个。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if(connection==downloaderConn) {
//handle download
}
else {
//handle upoad
}
}
答案 2 :(得分:-1)
您可以使用AFNetworking
完成任务。
AFNetworking
是iOS
和Mac OS X
的令人愉快的网络库。它建立在NSURLConnection
,NSOperation
和其他熟悉的Foundation technologies
之上。它有一个modular architecture
,设计精良,功能丰富的API非常适合使用。
找到SDK here