Skip to content

Commit

Permalink
Merge branch 'develop/0.4'
Browse files Browse the repository at this point in the history
  • Loading branch information
ishkawa committed Mar 20, 2015
2 parents e23fe9a + d6d02cf commit 092fd42
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 78 deletions.
97 changes: 43 additions & 54 deletions APIKit/APIKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,13 @@ private extension NSURLSessionDataTask {
}

// use private, global scope variable until we can use stored class var in Swift 1.2
private var instancePairDictionary = [String: (API, NSURLSession)]()
private let instancePairSemaphore = dispatch_semaphore_create(1)
private let internalDefaultURLSession = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: URLSessionDelegate(),
delegateQueue: nil
)

public class API: NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate {
public class API {
// configurations
public class func baseURL() -> NSURL {
fatalError("API.baseURL() must be overrided in subclasses.")
Expand All @@ -72,47 +75,13 @@ public class API: NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate {
public class func responseBodyParser() -> ResponseBodyParser {
return .JSON(readingOptions: nil)
}

public class func URLSessionConfiguration() -> NSURLSessionConfiguration {
return NSURLSessionConfiguration.defaultSessionConfiguration()
}

public class func URLSessionDelegateQueue() -> NSOperationQueue? {
// nil indicates NSURLSession creates its own serial operation queue.
// see doc of NSURLSession.init(configuration:delegate:delegateQueue:) for more details.
return nil
}

// prevent instantiation
override private init() {
super.init()
}

// create session and instance of API for each subclasses
private final class var instancePair: (API, NSURLSession) {
let className = NSStringFromClass(self)

dispatch_semaphore_wait(instancePairSemaphore, DISPATCH_TIME_FOREVER)
let pair: (API, NSURLSession) = instancePairDictionary[className] ?? {
let instance = (self as NSObject.Type)() as API
let configuration = self.URLSessionConfiguration()
let queue = self.URLSessionDelegateQueue()
let session = NSURLSession(configuration: configuration, delegate: instance, delegateQueue: queue)
let pair = (instance, session)
instancePairDictionary[className] = pair
return pair
}()
dispatch_semaphore_signal(instancePairSemaphore)

return pair
}

public final class var instance: API {
return instancePair.0

public class var defaultURLSession: NSURLSession {
return internalDefaultURLSession
}
public final class var URLSession: NSURLSession {
return instancePair.1

public class var acceptableStatusCodes: [Int] {
return [Int](200..<300)
}

// build NSURLRequest
Expand Down Expand Up @@ -146,13 +115,22 @@ public class API: NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate {
}
}

// send request and build response object
// In Swift 1.1, we could not omit `URLSession` argument of `func send(request:URLSession(=default):handler(=default):)`
// with trailing closure, so we provide following 2 methods
// - `func sendRequest(request:handler(=default):)`
// - `func sendRequest(request:URLSession:handler(=default):)`.
// In Swift 1.2, we can omit default arguments with trailing closure, so they should be replaced with
// - `func sendRequest(request:URLSession(=default):handler(=default):)`
public class func sendRequest<T: Request>(request: T, handler: (Result<T.Response, NSError>) -> Void = {r in}) -> NSURLSessionDataTask? {
let session = URLSession
return sendRequest(request, URLSession: defaultURLSession, handler: handler)
}

// send request and build response object
public class func sendRequest<T: Request>(request: T, URLSession: NSURLSession, handler: (Result<T.Response, NSError>) -> Void = {r in}) -> NSURLSessionDataTask? {
let mainQueue = dispatch_get_main_queue()

if let URLRequest = request.URLRequest {
let task = session.dataTaskWithRequest(URLRequest)
let task = URLSession.dataTaskWithRequest(URLRequest)

task.completionHandler = { data, URLResponse, connectionError in
if let error = connectionError {
Expand All @@ -161,10 +139,15 @@ public class API: NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate {
}

let statusCode = (URLResponse as? NSHTTPURLResponse)?.statusCode ?? 0
if !contains(200..<300, statusCode) {
let userInfo = [NSLocalizedDescriptionKey: "received status code that represents error"]
let error = NSError(domain: APIKitErrorDomain, code: statusCode, userInfo: userInfo)
dispatch_async(mainQueue, { handler(.Failure(Box(error))) })
if !contains(self.acceptableStatusCodes, statusCode) {
let error: NSError = {
switch self.responseBodyParser().parseData(data) {
case .Success(let box): return self.responseErrorFromObject(box.unbox)
case .Failure(let box): return box.unbox
}
}()

dispatch_async(mainQueue) { handler(failure(error)) }
return
}

Expand All @@ -176,8 +159,8 @@ public class API: NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate {
let error = NSError(domain: APIKitErrorDomain, code: 0, userInfo: userInfo)
return failure(error)
}

}

dispatch_async(mainQueue, { handler(mappedResponse) })
}

Expand All @@ -193,17 +176,23 @@ public class API: NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate {
}
}

public class func responseErrorFromObject(object: AnyObject) -> NSError {
let userInfo = [NSLocalizedDescriptionKey: "received status code that represents error"]
let error = NSError(domain: APIKitErrorDomain, code: 0, userInfo: userInfo)
return error
}
}

public class URLSessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate {
// MARK: - NSURLSessionTaskDelegate
// TODO: add attributes like NS_REQUIRES_SUPER when it is available in future version of Swift.
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError connectionError: NSError?) {
if let dataTask = task as? NSURLSessionDataTask {
dataTask.completionHandler?(dataTask.responseBuffer, dataTask.response, connectionError)
}
}

// MARK: - NSURLSessionDataDelegate
// TODO: add attributes like NS_REQUIRES_SUPER when it is available in future version of Swift.
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
dataTask.responseBuffer.appendData(data)
}
}
}
26 changes: 8 additions & 18 deletions APIKitTests/APITests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ class APITests: XCTestCase {
override class func responseBodyParser() -> ResponseBodyParser {
return .JSON(readingOptions: nil)
}

override class func responseErrorFromObject(object: AnyObject) -> NSError {
return NSError(domain: "MockAPIErrorDomain", code: 10000, userInfo: nil)
}

class Endpoint {
class Get: Request {
Expand All @@ -41,21 +45,6 @@ class APITests: XCTestCase {
super.tearDown()
}

// MARK: - instance tests
func testDifferentSessionsAreCreatedForEachClasses() {
assert(MockAPI.URLSession, !=, AnotherMockAPI.URLSession)
}

func testSameSessionsAreUsedInSameClasses() {
assertEqual(MockAPI.URLSession, MockAPI.URLSession)
assertEqual(AnotherMockAPI.URLSession, AnotherMockAPI.URLSession)
}

func testDelegateOfSessions() {
assertNotNil(MockAPI.URLSession.delegate as? MockAPI)
assertNotNil(AnotherMockAPI.URLSession.delegate as? AnotherMockAPI)
}

// MARK: - integration tests
func testSuccess() {
let dictionary = ["key": "value"]
Expand Down Expand Up @@ -118,7 +107,8 @@ class APITests: XCTestCase {
OHHTTPStubs.stubRequestsPassingTest({ request in
return true
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(), statusCode: 400, headers: nil)
let data = NSJSONSerialization.dataWithJSONObject([:], options: nil, error: nil)!
return OHHTTPStubsResponse(data: data, statusCode: 400, headers: nil)
})

let expectation = expectationWithDescription("wait for response")
Expand All @@ -131,8 +121,8 @@ class APITests: XCTestCase {

case .Failure(let box):
let error = box.unbox
assertEqual(error.domain, APIKitErrorDomain)
assertEqual(error.code, 400)
assertEqual(error.domain, "MockAPIErrorDomain")
assertEqual(error.code, 10000)
}

expectation.fulfill()
Expand Down
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,19 +183,21 @@ class GitHub: API {

## Advanced usage


### NSURLSessionDelegate

APIKit creates singleton instances for each subclasses of API and set them as delegates of NSURLSession,
so you can add following features by implementing delegate methods.
You can add custom behaviors of `NSURLSession` by following steps:

1. Create a subclass of `URLSessionDelegate` (e.g. `MyAPIURLSessionDelegate`).
2. Implement additional delegate methods in it.
3. Override `defaultURLSession` of `API` and return `NSURLSession` that has `MyURLSessionDelegate` as its delegate.

This can add following features:

- Hook events of NSURLSession
- Handle authentication challenges
- Convert a data task to NSURLSessionDownloadTask

#### Overriding delegate methods implemented by API

API class also uses delegate methods of NSURLSession to implement wrapper of NSURLSession, so you should call super if you override following methods.
NOTE: `URLSessionDelegate` also implements delegate methods of `NSURLSession` to implement wrapper of `NSURLSession`, so you should call super if you override following methods.

- `func URLSession(session:task:didCompleteWithError:)`
- `func URLSession(session:dataTask:didReceiveData:)`
Expand Down

0 comments on commit 092fd42

Please sign in to comment.