0

I have 2 view controllers. In the parent view, i have a progress view. In the child VC, I am uploading an image with parameters using POST request to the server and then dismissing that VC and hence on returning to parent VC, I want progress View to update as the upload is happening. I tried protocol-delegate method, but looks like it only works once and can't return values dynamically. I tried implementing the following method in both view controllers but no success.

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {

    self.progressView.hidden = false
    self.uploadProgress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
    print(self.uploadProgress)
    self.progressView.setProgress(self.uploadProgress, animated: true)

    if (uploadProgress == 1.0) {
        self.progressView.hidden = true
//            uploadProgress = 0.0
    }
}
Karanveer Singh
  • 961
  • 12
  • 27

1 Answers1

0

Have a look on KVO (Key-Value observing) and observe your self.uploadProgress. Each time the self.uploadProgress is change a function will be called and then you can do whatever you want. Make sure to add the observer (function) on the VC you want to show the progress bar.

For example in ParentVC:

[childVC addObserver:self forKeyPath:@"uploadProgress" options: NSKeyValueObservingOptionNew context:NULL];

and then:

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

    if ([keyPath isEqualToString:@"uploadProgress"]) {
        NSLog(@"Updated Value:%@",[change objectForKey:NSKeyValueChangeNewKey]);
        //Do something
    }
}

observeForValue will be called each time uploadProgress property change.

Don't forget to remove observer when you don't need it or when ChildVC will be destroyed.

-(void)dealloc {

    [self removeObserver:parentVC forKeyPath:@"uploadProgress"];
}
BlackM
  • 3,927
  • 8
  • 39
  • 69