I am making an app that has the need to make HTTP Request in many of its ViewControllers.
I ended up copy and pasting these codes in to each of the ViewControllers and listen to the delegates callback of NSURLConnectionDelegate and NSURLConnectionDataDelegate
func makeRequest()
{
//Base64
var username = "testUsername";
var password = "testPassword";
var loginString = NSString(format: "%@:%@", username, password);
var loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!;
var base64LoginString = loginData.base64EncodedStringWithOptions(nil);
var url: NSURL = NSURL(string: self.HTTP_REQUEST_STRING)!;
var urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: url);
urlRequest.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization");
urlRequest.HTTPMethod = "POST";
urlConnection = NSURLConnection(request: urlRequest, delegate: self)!;
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!)
{
self.resultData.appendData(data);
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
//Do Something
}
func connection(connection: NSURLConnection, didFailWithError error: NSError)
{
//Do Something
}
I am wondering if there is a better approach than this, rather than copy and pasting the codes into every ViewControllers?
Is it possible to put these codes into a class? But then, how do we know if the connection has finished loading?
I am sorry for this question, I lack the knowledge of good Object Oriented design.
Thank you
To be up to date, you should be using NSURLSession
as your request class. You're not necessarily required to listen in for the delegation callbacks as there is a closure callback that will provide you with and error and data according to how you configured your session. Regarding placement, it depends on your code and what you want. You can place this code in the viewController if it makes sense, some people create proxy classes to make all their requests and report statuses back to them. It all depends on flexibility, robustness and structure of your application. If you're making the same network request from 3 different viewControllers, it's likely that your should be placing the network request in a type of proxy class to prevent duplicate code. Look into the proxy and singleton design patterns if you'd like to know more about code design.
Here's a nice tutorial on NSURLSession
to get you started:
Raywenderlich tutorial