如何获得在后台运行的AFNetworking AFURLConnectionOperation的进度?

时间:2012-07-12 19:41:51

标签: iphone ios5 upload progress-bar afnetworking

在我的iOS应用中,我使用AFURLConnectionOperation类(视图A)上传图像,然后我允许用户编辑部分图像(视图B)。稍后,在View C中,我有一个进度条,需要显示从视图A开始的上传进度。

我无法弄清楚如何使用AFNetworking从View C中访问View A中开始的操作进度。据我所知,这可能是不可能的。

提前致谢,

威尔

1 个答案:

答案 0 :(得分:3)

当然,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可能是“上传管理器”类型解决方案的最佳选择。

无论您选择什么,一旦您将简单的课程组合在一起,您就可以在ViewControllers的viewWillAppear&中注册KVO通知。取消注册viewWillDisappear以干净地处理您的UI更新(例如进度条)。如果您不理解键值观察,请阅读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/"]];

...在View C的控制器的viewWillAppear

- (void) viewWillAppear:(BOOL)animated
{
    ...
    [[MyImageUploadManager sharedInstance] addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew context:nil];
    ...
}

...并在View C的viewWillDisappear

- (void)viewWillDisappear:(BOOL)animated
{
    ...
    [[MyImageUploadManager sharedInstance] removeObserver:self forKeyPath:@"progress" context:nil];
    ...
}

每当上传管理器类中的'progress'属性发生变化时,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];
    }
}

这应该让你顺利,希望这很有帮助。

相关问题