2012-07-12 38 views
2

在我的iOS应用程序中,我使用AFURLConnectionOperation类(视图A)上传图像,然后允许用户编辑图像的一部分(视图B)。后来,在View C中,我有一个进度条,需要显示在视图A中开始的上传进度。如何获得在后台运行的AFNetworking AFURLConnectionOperation的进度?

我无法弄清楚如何访问在视图A中启动的操作的进度从视图C与AFNetworking。据我所知,这可能是不可能的。

由于提前,

请问

回答

3

当然,这是可能的意志,它有很少做与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很可能是对的一流的解决方案的“上传管理器”类型的你最好的选择。

无论你选择,一旦你有一个简单的类放在一起,那么你可以在viewWillDisappear注册志愿通知您ViewControllers' viewWillAppear中&注销干净地处理你的UI更新(例如进度条)。如果您不了解Key-Value Observing,请阅读Introduction to Key-Value Observing Programming Guide。在你掌握了这些知识之后,你将能够更好地应对iOS。

因此,鉴于A的上传代码,使用你的魔法新类来创建和排队使用网址上传(多种方法可以作出内存,NSFileURLs或一个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]; 
    } 
} 

这应该会让你很好,希望对你有帮助。