Thursday 17 December 2015

Custom Closure in Swift for a Service Class

Hi Welcome all to this basic swift closures example

Now lets begin with the actual closure class

typealias CompletionBlock = ((NSData?) -> Void) //like typedef a completionBlockName or alais

class ServiceClass: AnyObject //The class is of type any object
{
    
   internal func makeServiceCall(urlToCall:String,completionHandler: CompletionBlock)
    {
        let googleURL:NSURL? = NSURL(string: urlToCall) //Can be nil
        
        
        let request:NSURLRequest = NSURLRequest(URL: googleURL!);
        
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
            
            print("response is \(response)");
            print("response is \(error)");
            print("response is \(data)");
            
            if((error) == nil) //Could rather use if let here
            {
               completionHandler(nil);
            }
            else
            {
                if let finaldata = data
                {
                    completionHandler(finaldata);
                }
                else
                {
                    completionHandler(nil);
                }
            }
        }
        
        task.resume();
    }
}


How to invoke there methods are as follows.


    override func viewDidLoad() {
        super.viewDidLoad()
        
        ServiceClass().makeServiceCall("http://google.com") { (ServiceData) -> Void in
            
            if let _ = ServiceData
            {
                print("service data==\(ServiceData)")
            }
            else
            {
                print("service data is nil")
            }
        };

        // Do any additional setup after loading the view, typically from a nib.
    }

No comments:

Post a Comment