Make a GET request with Swift, NSURLSession and NSURLSessionDataTask

Here’s how to Make a simple GET request in Swift using NSURLSession and NSURLSessionDataTask. First, we will create singleton that has access to a ‘network’ struct that has a computed property called session. We’ll also create an instance method called apiRequest(name:String, completionblock:(error:NSError, responseDictionary:NSDictionary)->()) in the singleton instance that has access to the network struct.

API.swift

public struct network {
    public var session:NSURLSession? {
    get {
        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        sessionConfig.HTTPAdditionalHeaders = //Dictionary here
        return NSURLSession(configuration: sessionConfig)
    }
    }
}

class API {
    class var sharedInstance : API {
    struct Static {
        static let instance : API = API()
        }
        return Static.instance
    }

//name argument isn't used in this method, 

    func apiRequest(name:String, completionblock:(error:NSError, responseDictionary:NSDictionary)->()) {
        let session = network().session!;
        let task : NSURLSessionDataTask = session.dataTaskWithURL(NSURL(string:"https://url_here"),completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
            let JSON: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)
            NSLog(JSON!.description)
            return
            })
        task.resume()
    }
}

In your ViewController.swift file or another file that references the API class use this:


API.sharedInstance.apiRequest("name", completionblock: {(error: NSError, responseDictionary: NSDictionary) -> () in
//Set variables and do further processing here
 })

Detecting device shake using iOS 8 and Swift

To respond to a shake gesture in iOS 8 using Swift, you must override three methods in the ViewController that will respond to the shake: viewDidAppear(animated: Bool), canBecomeFirstResponder() -> Bool and motionEnded(motion: UIEventSubtype, withEvent event: UIEvent!)


    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        self.becomeFirstResponder()
    }
    
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    
    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent!) {
        if(event.subtype == UIEventSubtype.MotionShake) {
            var alert = UIAlertController(title: "Shaken",
                message: "Not Stirred",
                preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK",
                style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }

Creating a Singleton in Swift – The Nested Struct Approach


class AppService : BaseService {
    class var sharedInstance : AppService {
        struct Static {
            static let instance : AppService = AppService()
        }
        return Static.instance
    }
}

While refactoring one of my apps recently, I had to figure out how to create a singleton in Swift. This approach seems like the most widely accepted way. The shared instance is a class variable. A closure is used to initialize and return a static instance that is contained in the nested Static struct within the closure. Oodles of joy. This is called the nested struct approach. There are two more which can be seen here:


https://github.com/hpique/SwiftSingleton