Last active
May 11, 2016 10:06
-
-
Save justAnotherDev/bf57110999fe81a5a9b9 to your computer and use it in GitHub Desktop.
First stab at a Swift network requestor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SwiftRequests.swift | |
// | |
import Foundation | |
@objc class SwiftRequests : NSObject { | |
enum SwiftRequestsError { | |
case InvalidURL | |
var errorObject: NSError { | |
let errorString = String(self) | |
let errorCode = errorString.hash | |
return NSError(domain: "SwiftRequestsError", code: errorCode, userInfo: [NSLocalizedDescriptionKey:errorString]) | |
} | |
} | |
static func sendDataFrom(URL:String, headers:[String:String]?=nil, to completionBlock:(data:NSData?, error:NSError?) -> Void) throws { | |
guard let nsURL = NSURL(string: URL) else { | |
throw SwiftRequestsError.InvalidURL.errorObject | |
} | |
// create the request and add the headers | |
let request = NSMutableURLRequest(URL: nsURL) | |
if let headers = headers { | |
for (field, value) in headers { | |
request.addValue(value, forHTTPHeaderField: field) | |
} | |
} | |
// fire the request | |
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler:{ data, response, error in | |
completionBlock(data: data, error: error) | |
}).resume() | |
} | |
static func sendStringFrom(URL:String, headers:[String:String]?=nil, to completionBlock:(string:String?, error:NSError?)->Void) throws { | |
try sendDataFrom(URL, headers: headers, to:{ data, error in | |
guard let data = data else { | |
return completionBlock(string: nil, error: error) | |
} | |
let responseString = String(NSString.init(data: data, encoding: NSUTF8StringEncoding)) | |
completionBlock(string: responseString, error: nil) | |
}) // if error is thrown, will bubble up | |
} | |
static func sendJSONFrom(URL:String, headers:[String:String]?=nil, to completionBlock:(json:AnyObject?, error:NSError?)->Void) throws { | |
try sendDataFrom(URL, headers: headers, to:{ data, error in | |
guard let data = data else { | |
return completionBlock(json: nil, error: error) | |
} | |
var jsonObject: AnyObject? | |
var jsonError: NSError? | |
do { | |
try jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: []) | |
} catch let error as NSError { | |
jsonError = error | |
} | |
completionBlock(json: jsonObject, error: jsonError) | |
}) // if error is thrown, will bubble up | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment