sapatos
sapatos

Reputation: 1304

afnetworking async background task handle response when viewcontroller changes

My application allows a user to create an item for listing on an eCommerce site. The user goes through a number of screens adding images and information until they need to create the item on the store.

The final upload screen has an UIViewController using AFNetworking has two services to call that:

1) Calls an image upload webservice and returns some ID's. On success it calls (2).

2) Calls another service using these returned ID's as part of the request.

This process is started when the user hits the Submit button.

What I would like to happen is the following:

The users clicks Submit and the process starts in the background The current storyboard scene returns to the start screen to allow the user to create another item whilst the previous is still running.

As the code for the service calls and handling the responses from them are in the UIViewController once the scene changes the UIViewController will no longer be running on the stack so what will happen to the service response etc?

If I create a separate class to do the work I'll loose the object reference when the scene changes. If the method is still processing would it be garbage collected?

Should I be sticking this on a background thread using Grand Central Dispatch?

Upvotes: 1

Views: 156

Answers (1)

Ryan
Ryan

Reputation: 4884

For more detail, here's an example.

I usually have a class named NetWrapper which manages whole network related thing.

.h

@interface NetWrapper : NSObject
+ (instancetype)shared;

#pragma mark - APIs
- (void)requestVersion;
@end

.m

static NetWrapper *_netWrapper;
@implementation NetWrapper

+ (instancetype)shared
{
    if(_netWrapper == nil)
    {
        _netWrapper = [[NetWrapper alloc] init];
    }
    return _netWrapper;
}

#pragma mark - APIs
- (void)requestVersion
{
    // do something
}

If you have a singleton class like this, you can alway have the same instance with

[NetWrapper shared]

and invoke instance method like below.

[[NetWrapper shared] requestVersion];

Upvotes: 1

Related Questions