当然有可能 Will,它与 AFNetworking 关系不大,但更多地与常见的编程模式有关。
您需要将AFURLConnectionOperation 对象存储在视图控制器之外,以便它们都可以访问它。这里的最佳实践是创建一个singleton class,它封装了 AFNetworking 属性和方法来处理上传您的图像。每当您需要有关该上传的信息或与之交互时,您都可以通过类方法(如 sharedInstance)简单地访问该单例。
+ (id)sharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
如果您正在与 Web 服务(而不是原始 FTP 服务器)交互,那么子类化 AFHTTPClient 可能是“上传管理器”类型的类解决方案的最佳选择。
无论您选择什么,一旦您将一个简单的类放在一起,您就可以在 ViewController 的 viewWillAppear 中注册 KVO 通知并在 viewWillDisappear 中取消注册以干净地处理您的 UI 更新(例如进度条)。如果您不了解 Key-Value Observing,请阅读 Introduction to Key-Value Observing Programming Guide。掌握了这些知识后,您将能够更好地应对 iOS。
因此,在视图 A 的上传代码中,使用您的神奇新类使用 URL 创建和排队上传(可以使用多种方法来使用内存中的图像、NSFileURL 或 NSString,如此处所示)
[[MyImageUploadManager sharedInstance] uploadImageFromPath:@"/wherever/1.png" toURL:[NSURL URLWithString:@"ftp://someserver.com/images/"]];
…在视图 C 的控制器的 viewWillAppear 中
- (void) viewWillAppear:(BOOL)animated
{
...
[[MyImageUploadManager sharedInstance] addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew context:nil];
...
}
…在视图 C 的 viewWillDisappear 中
- (void)viewWillDisappear:(BOOL)animated
{
...
[[MyImageUploadManager sharedInstance] removeObserver:self forKeyPath:@"progress" context:nil];
...
}
只要上传管理器类中的“进度”属性发生变化,iOS 就会调用函数observerValueForKeyPath:ofObject:change:context:。这是一个非常简单的版本:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ( [keyPath isEqualToString:@"progress"] )
{
// since you only upload a single file, and you've only added yourself as
// an observer to your upload, there's no mystery as to who has sent you progress
float progress=[change valueForKey:NSKeyValueChangeNewKey];
NSLog(@"operation:%@ progress:%0.2f", object, progress );
// now you'd update the progress control via a property bound in the nib viewer
[[_view progressIndicator] setProgress:progress];
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
这应该会让您顺利进行,希望对您有所帮助。