Hello every one,Today i will give demonstration for call web-service into swift using custom delegate methods.
Here is the description how this source code usable.
In this project I created two different file call as APIConsumer and Rest_API, In that file create custom delegate class I give proper request and response handle.
Following code for the APIConsumer.swift for Get method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
func doRequestGet(url:String){ showNetworkActivity() let session = NSURLSession.sharedSession() let urlPath = NSURL(string: url) let request = NSMutableURLRequest(URL: urlPath!) request.timeoutInterval = 60 request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "GET" let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in self.hideNetworkActivity() if((error) != nil) { print(error!.localizedDescription) [self.delegate .APIResponseArrived([])] }else { _ = NSString(data: data!, encoding:NSUTF8StringEncoding) let _: NSError? let jsonResult: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) self.delegate.APIResponseArrived(jsonResult) } } dataTask.resume() } |
Following code for the APIConsumer.swift for POST method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
func doRequestPost(url:String,data:[String: NSObject]){ showNetworkActivity() requestDic = data let theJSONData = try? NSJSONSerialization.dataWithJSONObject( data , options: NSJSONWritingOptions(rawValue: 0)) let jsonString = NSString(data: theJSONData!, encoding: NSASCIIStringEncoding) print("Request Object:\(data)") print("Request string = \(jsonString!)") let session = NSURLSession.sharedSession() let urlPath = NSURL(string: url) let request = NSMutableURLRequest(URL: urlPath!) request.timeoutInterval = 60 request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "POST" let postLength = NSString(format:"%lu", jsonString!.length) as String request.setValue(postLength, forHTTPHeaderField:"Content-Length") request.HTTPBody = jsonString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:true) let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in self.hideNetworkActivity() if((error) != nil) { print(error!.localizedDescription) [self.delegate .APIResponseArrived([])] }else { print("Succes:") _ = NSString(data: data!, encoding:NSUTF8StringEncoding) let _: NSError? let jsonResult: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) self.delegate.APIResponseArrived(jsonResult) } } dataTask.resume() } |
While when you call those function and class just create the object of Rest_API and add the token name because of in this example i refer the response validate thru the token.
1 2 3 4 |
let rest : Rest_API = Rest_API() rest.initWithToken("firstCall")//Don't forgot to set token name rest.restDelegate = self rest.postLoginDemo(201, user_name: "nimit", password: "nimit") |
Then just implement delegate method into your class like below.
1 2 3 4 5 6 |
func Rest_APIResponseArrived(Response:AnyObject,Token:String){ if(Token == "firstCall"){ print("Token is \(Token) And Response is \(Response)") } //Here code goes for after successfully receive JSON response } |
For more detail you can found the sample code Web-service Demo – Swift.
Leave a Reply