Created
September 15, 2015 12:20
-
-
Save gabovanlugo/c1c0588ab929df81b3a7 to your computer and use it in GitHub Desktop.
Alamofire-SwiftyJSON Swift 2.0
This file contains 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
// | |
// AlamofireSwiftyJSON.swift | |
// AlamofireSwiftyJSON | |
// | |
// Created by Pinglin Tang on 14-9-22. | |
// Copyright (c) 2014 SwiftyJSON. All rights reserved. | |
// | |
import Foundation | |
import Alamofire | |
import SwiftyJSON | |
// MARK: - Request for Swift JSON | |
extension Request { | |
/** | |
Adds a handler to be called once the request has finished. | |
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the SwiftyJSON enum, if one could be created from the URL response and data, and any error produced while creating the SwiftyJSON enum. | |
:returns: The request. | |
*/ | |
public func responseSwiftyJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, SwiftyJSON.JSON, NSError?) -> Void) -> Self { | |
return responseSwiftyJSON(nil, options:NSJSONReadingOptions.AllowFragments, completionHandler:completionHandler) | |
} | |
/** | |
Adds a handler to be called once the request has finished. | |
:param: queue The queue on which the completion handler is dispatched. | |
:param: options The JSON serialization reading options. `.AllowFragments` by default. | |
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the SwiftyJSON enum, if one could be created from the URL response and data, and any error produced while creating the SwiftyJSON enum. | |
:returns: The request. | |
*/ | |
public func responseSwiftyJSON(queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, JSON, NSError?) -> Void) -> Self { | |
return response(queue: queue, responseSerializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, result) -> Void in | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { | |
var responseJSON: JSON | |
if result.isFailure | |
{ | |
responseJSON = JSON.null | |
} else { | |
responseJSON = SwiftyJSON.JSON(result.value!) | |
} | |
dispatch_async(queue ?? dispatch_get_main_queue(), { | |
completionHandler(self.request!, self.response, responseJSON, result.error as NSError?) | |
}) | |
}) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment