Jump to content

[SWIFT] Basic Web API


Swizzbeat

Recommended Posts


// Copyright (c) 2014 Anthony Puppo. All rights reserved.

import Foundation

private var instance:WebAPI!

func getWebAPIInstance() -> WebAPI {

if (instance == nil) {

instance = WebAPI()

}

return instance

}

class WebAPI {

private init() {

//Singleton Design Pattern

}

// Sends a pre-configured asynchronous request

func sendRequest(request:NSMutableURLRequest, callback:(String!, NSError!) -> Void) {

let task:NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request) {

(data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in

if (error == nil) {

dispatch_async(dispatch_get_main_queue(), {

callback(NSString(data: data, encoding: NSUTF8StringEncoding), nil)

})

}

else {

dispatch_async(dispatch_get_main_queue(), {

callback(nil, error)

})

}

}

task.resume()

}

// Retrieves a JSON object and handles it asynchronously with the defined callback

func fetchJSON(json:AnyObject!, httpMethod:String, url:String, cachePolicy:NSURLRequestCachePolicy, timeoutInterval:NSTimeInterval, callback:(Dictionary<String, AnyObject>!, NSError!) -> Void) {

let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: url), cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)

request.HTTPMethod = httpMethod

request.setValue("application/json", forHTTPHeaderField: "Accept")

if (json != nil) {

request.setValue("application/json", forHTTPHeaderField: "Content-Type")

request.HTTPBody = stringifyJSON(json).dataUsingEncoding(NSUTF8StringEncoding)!

}

sendRequest(request, callback: {

(data:String!, error:NSError!) -> Void in

if (error == nil) {

dispatch_async(dispatch_get_main_queue(), {

callback(self.parseJSONString(data), nil)

})

}

else {

dispatch_async(dispatch_get_main_queue(), {

callback(nil, error)

})

}

})

}

// MARK: - Privates

// Converts an object into JSON String form if possible

private func stringifyJSON(json:AnyObject) -> String {

var error:NSError?

let jsonData:NSData = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(0), error: &error)!

return (error == nil) ? NSString(data: jsonData, encoding: NSUTF8StringEncoding) : ""

}

// Converts a JSON string (if possible) into a usable Dictionary

private func parseJSONString(jsonString:String) -> Dictionary<String, AnyObject> {

var error:NSError?

let data:NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!

let jsonObj:Dictionary<String, AnyObject> = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) as Dictionary<String, AnyObject>

return (error == nil) ? jsonObj : Dictionary<String, AnyObject>()

}

}

  • Like 2
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...