I'm subclassing AFHTTPSessionManager
to create a client for Web API. Basic stuff... sharedInstance
as a singleton and methods for fetching specific data etc. So far so good. But there is one tricky part. User needs to login and in response he gets a uniqe token which will be stored in NSUserDefaults
. So if there is token stored inside NSUserDefaults
it's used to identify user on server and enable him to send request without need to login every time. This token has a long TTL but there is possibility that user will reinstall app or create new account so his token will be ereased.
My question is how to connect this AFHTTPSessionManager
subclass and token stored in NSUserDefaults
? Is preferable to create a property in this client which will be checked when shaedInstance
method is called? Or maybe check it manually every time I want to make a HTTP request?
According to the docs, subclassing AFHTTPSessionManager
and making a singleton is the way to go on iOS 7 and up:
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass
AFHTTPSessionManager
, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
Checking NSUserDefaults
when sharedInstance
is requested is probably not the proper way of doing it, because doing so precludes other parts of your code from storing a reference to the instance of singleton, say, in viewDidLoad
, because if they do, the change of the token may go unnoticed.
Checking each request is a better option. You can place the checking code into a calculated token
property on the AFHTTPSessionManager
subclass, and have it check NSUserDefaults
value.
Finally, you could set up an observer on NSUserDefaults
, watch for the change in the property that you need, and make the update automatically. The answer linked above explains how this can be done. In your situation, the code that sets up the observer would go into the constructor of your AFHTTPSessionManager
subclass, and the code that unregisters the observer would go into dealloc
(the linked answer shows them in viewDidLoad
and viewDidUnload
).