我正在尝试使用AFNetworking在后台模式上传多张照片,并设法使其正常工作
我现在面临的主要问题是内存,在上传10张以上的照片时,会终止我的应用程序
我正在做的只是同时触发所有上传,因为我已经在StackOverflow上阅读了一些答案
既然出现了这个问题,我想知道我是否对内存管理做错了,或者更好的策略是序列化上传,启动第一个,当它终止时,在handleEventsForBackgroundURLSession方法中开始上传下一个。
在完全更改上传设计之前,我想听听某人是否是一个很好的替代方案,因为我看到的关于这个问题的大多数答案表明应该将所有请求一起解雇。
谢谢
答案 0 :(得分:0)
创建NSOperationQueue并将所有上传图像操作添加到该队列。此队列将管理您的系统内存。请参考以下示例代码。
NSOperationQueue *myQueue = [[NSOperationQueue alloc]init];
NSURLRequest *request = [[AFHTTPRequestSerializer serializer]
multipartFormRequestWithMethod:@"POST"
URLString:apiPostPhoto(singleton.userId, @"icon")
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSString *filepath = [[CustomFunctions getFilesPath] stringByAppendingPathComponent:@"icon.png"];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:filepath] name:@"uploadicon" error:nil];
} error:nil
];
AFHTTPRequestOperation *operationUploadOne = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"uploadlogo:%@",operation.responseString);
[[NSUserDefaults standardUserDefaults]setObject:operation.responseString forKey:KEY_LOGO_TIMESTAMP];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"uploadlogo:%@",[error description]);
}];
[operation addObserver:self forKeyPath:@"isFinished" options:NSKeyValueObservingOptionNew context:nil];
[myQueue addOperation:operationUploadOne];
AFHTTPRequestOperation *operationUploadTwo = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[myQueue addOperation: operationUploadTwo];
您可以使用此方法添加更多操作。
[myQueue addOperation:operationUploadTwo];