0

I would like to use AFNetworking to perform periodical JSON requests to my server (updating the user's profile and checking for changes).

What if the background job is running but the user pushed the "Back" button or anything that makes the ViewController to be destroyed? How can I manage this? I mean, in that case I would like to ignore the result and perform it again when the user returns to the View

Thank you

PS: I don't want a full working code. I just would like to know how can I know, from a background download job (ran using AFNetworking) if the ViewController has been destroyed or not.

goodolddays
  • 2,595
  • 4
  • 34
  • 51
  • Try to store those values in the NSUserDefaults and restart the connection when user comes to that view – Tendulkar Oct 21 '13 at 07:52
  • I've never used AFNetworking - but I am going to presume you give it some sort of delegate, which is usually your ViewController. All you need to do (if this is the case) is to set the delegate property to nil when your ViewController is unloaded. – Marc Oct 21 '13 at 09:05

4 Answers4

1

Check out this question: Best architecture for an iOS application that makes many network requests?

A simple way is to create a singleton instance of a custom Network Manager class which will handle all the request and network background jobs. You can access it from anywhere (e.g. view controllers) and it keeps its instance for the whole runtime of the app.

About singleton: http://en.wikipedia.org/wiki/Singleton_pattern

Community
  • 1
  • 1
maros
  • 432
  • 3
  • 17
1

In order to stop the running network request, you can send cancel to the network operation in method viewWillDisappear: of the View Controller.

Likewise, in order to "automatically" start the network request when the view becomes visible, use method viewWillAppear:.

CouchDeveloper
  • 18,174
  • 3
  • 45
  • 67
1

If you just need to achieve your task . mean, trying to get the changes if & only if the particular ViewController appears.

Use the methods

-(void) viewDidappear{
// Initialise Your task here 
}

-(void) viewWillDisappear{
// Destoy(Cancel ) the task 
}
Kumar KL
  • 15,315
  • 9
  • 38
  • 60
1

One solution would be to implement the downloading in a way that uses NSNotification mechanism :

  1. Set up the ViewController as a listener.

  2. Set up the bg download to fire up a notification when the download process has been finished.

  3. If the VC is still around when the notification fires, great - it will handle notification and do whatever you need. If it is not around... nothing happens.

Peter Sarnowski
  • 11,900
  • 5
  • 36
  • 33