我正在开发一个应用程序,用户可以通过它共享图像。使用 php 文件,我在服务器上上传文件并使用 php 文件下载。当我下载文件时,需要很长时间。我如何让它快一点.
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *data1 = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSArray *arrImg = [data1 componentsSeparatedByString:@"@@@"];
int i;
NSMutableArray *receivedUrlArr = [[NSMutableArray alloc]init];
NSString *str,*strNew,*path;
NSData *imageData;
ImagesClass *obj;
int count;
for ( i=0; i<[arrImg count]-1; i++) {
[receivedUrlArr addObject:[arrImg objectAtIndex:i]];
str = [NSString stringWithFormat:@"http:////receive_images/%@",[receivedUrlArr objectAtIndex:i]];
strNew = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
UIImage *myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strNew]]];
obj = [[ImagesClass alloc]init];
obj.imageId = i+1;
obj.imageName = [[arrImg objectAtIndex:i] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
obj.thumbImage = myImage;
[[DBModel database]inserttoReceivedList:obj receiverMobNo:mobileno];
path = [RECEIVEDIMAGE_DIR stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",obj.imageName]];
imageData = UIImagePNGRepresentation(obj.thumbImage);
[imageData writeToFile:path atomically:YES];
}
}
提前致谢。
最佳答案
无论您存储图像的方法有多有效,您始终会受到连接速度的瓶颈。
但是,您似乎采取了错误的方式。 -connection:didReceiveData 用于增量接收数据。似乎您假设一旦收到数据,就已经完成图像加载,然后进行一些复杂的处理来保存部分下载的图像。相反,您的 NSURLConnection 委托(delegate)应该实现 -connectionDidFinishLoading。在此方法中,您将连接的数据转换为图像并保存。
这是我的设置方法: 假设您有一个正在显示图像/需要下载更多图像的 Controller 类。 现在,创建一个名为“ImageDownloader”的类,它实现 NSURLConnection Delegate。初始化此类时,您将为它提供图像名称和需要下载的图像的 URL。在 ImageDownloader 中,您将需要一个 NSMutableData 属性。最后,您将需要一个诸如 -startDownload 之类的方法来使事情顺利进行。
-startDownload 应首先确保您的 NSMutableData 属性为空并已初始化。完成后,您可以开始 NSURLConnection 的下载。请务必将委托(delegate)设置为您的 ImageDownloader 实例。在 -connection:didReceiveData 中,将收到的数据附加到 NSMutableData 属性中。在 -connectionDidFinishLoading 中,将该 NSMutableData 属性转换为图像,并使用 Controller 提供的图像名称保存它。从那里,让 Controller 实例知道图像是通过委托(delegate)方法调用或通知保存的。
希望这对您有所帮助。
编辑:IIRC,Apple 提供了一些名为“ImageDownloader”的示例代码,如果这个解释令人困惑的话,它非常相似。
关于iphone - 通过didReceive数据导入图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15877966/