如何在AFNetworking 2.0中使用Progress参数

Vig*_*esh 11 objective-c ios afnetworking afnetworking-2

我正在尝试将AFNetworking 2.0与NSURLSession一起使用.我正在使用这种方法

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
                                         fromFile:(NSURL *)fileURL
                                         progress:(NSProgress * __autoreleasing *)progress
                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
Run Code Online (Sandbox Code Playgroud)

我该如何使用progress参数.该方法是一种非阻塞方法.因此,我将不得不听' progress'来获取更新.但参数不会占用属性.只接受局部变量(NSProgress*__autoreleasing*).我无法将KVO添加到本地var.

我不太确定如何使用.

iwa*_*bed 24

任何时候给出一个参数,因为**这意味着你应该将指针传递给指向现有对象的指针,而不是像往常那样传递给实际对象的指针.

在这种情况下,您传入指向NSProgress对象的指针,然后观察该对象中的更改以获取更新.

例:

// Create a progress object and pass it in
NSProgress *progress;
[sessionManager uploadTaskWithRequest:request fromFile:fileURL progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    // Completion code
}];

// Observe fractionCompleted using KVO
[progress addObserver:self
          forKeyPath:@"fractionCompleted"
             options:NSKeyValueObservingOptionNew
             context:NULL];
Run Code Online (Sandbox Code Playgroud)

然后报告:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
        NSProgress *progress = (NSProgress *)object;
        NSLog(@"Progress is %f", progress.fractionCompleted);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果将调用添加到[super observeValueForKeyPath:ofObject:change:context:],则会导致出现"收到消息但未处理"等错误. (3认同)