美文网首页
NetworkClient.swift

NetworkClient.swift

作者: 幸运的小强本人 | 来源:发表于2016-03-06 21:28 被阅读9次
    func performRequest<A: JSONDecodable>(request: NSURLRequest, callback:(Result<A>)->()) {
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, urlResponse, error in
            callback(parseResult(data, urlResponse: urlResponse, error:error))
        }
    
        task.resume()
    }
    
    func parseResult<A: JSONDecodable>(data: NSData!, urlResponse: NSURLResponse!, error: NSError!)->Result<A> {
        let responseResult: Result<Response> = Result(error, Response(data: data, urlResponse: urlResponse))
    
         return responseResult >>> parseResponse
                    >>> decodeJSON
                    >>> decodeObject
    }
    
    func parseResponse(response: Response)->Result<NSData> {
        let successRange = 200..<300
        if !successRange.contains(response.statusCode) {
            return .Error(NSError())
        }
        return Result(nil, response.data)
    }
    

    相关文章

      网友评论

          本文标题:NetworkClient.swift

          本文链接:https://www.haomeiwen.com/subject/kbuakttx.html