2017-01-23 3 views
1

GitHub의 Alamofire-SwiftyJSON 프로젝트의 확장 방법을 사용하는 Swift 2.2에서 3.0으로 응용 프로그램을 마이그레이션했습니다. SwimtyJSON 결과를 반환하는 Alamofire의 신속한 확장 방법

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) 
    .responseSwiftyJSON({ (request, response, json, error) in 
     print(json) // json is a SwiftyJSON 'JSON' instance 
     print(error) 
    }) 

Alamofire - SwiftyJSON 프로젝트

이 질문을 작성으로 스위프트 3 업데이트되지 않은 : Alamofire-SwiftyJSON이 같은 SwiftyJSON 인스턴스로 변환 된 Alamofire 네트워크 요청의 응답을 수신 허용한다. Swift 3+ 및 Alamofire 4+와 함께 작동하는 responseSwiftyJSON 확장 메서드의 동일한 구현을 찾고 있습니다.

답변

3

확장 메서드

이 솔루션은 SwiftyJSON readme에서 Alamofire 작업에 대한 제안을 포함한다.

그것은 ResponseSerialization.swift에 Alamofire에 포함 된 유사한 확장을 기반으로합니다

  • DataRequest.responseJSON(queue:options:completionHandler:)
  • DataRequest.jsonResponseSerializer(options:)

이 솔루션은 위의 스위프트 3와 함께 작동합니다. Alamofire 4.2+ 및 SwiftyJSON 3.1.3+에서 테스트되었습니다.

import Alamofire 
import SwiftyJSON 

extension DataRequest { 

    /// Adds a handler to be called once the request has finished. 
    /// 
    /// - parameter options:   The JSON serialization reading options. Defaults to `.allowFragments`. 
    /// - parameter completionHandler: A closure to be executed once the request has finished. 
    /// 
    /// - returns: The request. 
    @discardableResult 
    public func responseSwiftyJSON(
     queue: DispatchQueue? = nil, 
     options: JSONSerialization.ReadingOptions = .allowFragments, 
     completionHandler: @escaping (DataResponse<JSON>) -> Void) -> Self { 
      return response(
       queue: queue, 
       responseSerializer: DataRequest.swiftyJSONResponseSerializer(options: options), 
       completionHandler: completionHandler 
      ) 
    } 

    /// Creates a response serializer that returns a SwiftyJSON instance result type constructed from the response data using 
    /// `JSONSerialization` with the specified reading options. 
    /// 
    /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. 
    /// 
    /// - returns: A SwiftyJSON response serializer. 
    public static func swiftyJSONResponseSerializer(
     options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer<JSON> { 
      return DataResponseSerializer { _, response, data, error in 
       let result = Request.serializeResponseJSON(options: options, response: response, data: data, error: error) 
       switch result { 
        case .success(let value): 
         return .success(JSON(value)) 
        case .failure(let error): 
         return .failure(error) 
       } 
      } 
    } 
} 

사용 예 :

Alamofire.request("https://httpbin.org/get").validate().responseSwiftyJSON { 
     response in 

     print("Response: \(response)") 

     switch response.result { 
      case .success(let json): 
       // Use SwiftyJSON instance 
       print("JSON: \(json)") 

      case .failure(let error): 
       // Handle error 
       print("Error: \(error)") 
     } 
    } 
+1

형편,하지만 우아한 당신이 Alamofire이 무엇을하고 있는지 이해하면. completionHandler는 대기열이 실행중인 스레드에서 호출되거나 대기열이 nil 인 경우 주 스레드에서 호출됩니다. responseSerializer는 Alamofire 내부의 NSOperationQueue에서 호출됩니다. SWiftyJSON readme처럼 validate()에 대한 호출을 추가 할 것입니다. – Heliotropix

+0

피드백 @ user992167 주셔서 감사합니다! 제안한대로 validate() 메서드를 추가했습니다. –

관련 문제