Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Last active July 16, 2019 13:14
  • Star 101 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save chriseidhof/26bda788f13b3e8a279c to your computer and use it in GitHub Desktop.
A tiny networking library
Copyright 2015 Chris Eidhof
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// See the accompanying blog post: http://chris.eidhof.nl/posts/tiny-networking-in-swift.html
public enum Method: String { // Bluntly stolen from Alamofire
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
public struct Resource<A> {
let path: String
let method : Method
let requestBody: NSData?
let headers : [String:String]
let parse: NSData -> A?
}
public enum Reason {
case CouldNotParseJSON
case NoData
case NoSuccessStatusCode(statusCode: Int)
case Other(NSError)
}
public func apiRequest<A>(modifyRequest: NSMutableURLRequest -> (), baseURL: NSURL, resource: Resource<A>, failure: (Reason, NSData?) -> (), completion: A -> ()) {
let session = NSURLSession.sharedSession()
let url = baseURL.URLByAppendingPathComponent(resource.path)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = resource.method.rawValue
request.HTTPBody = resource.requestBody
modifyRequest(request)
for (key,value) in resource.headers {
request.setValue(value, forHTTPHeaderField: key)
}
let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
if let responseData = data {
if let result = resource.parse(responseData) {
completion(result)
} else {
failure(Reason.CouldNotParseJSON, data)
}
} else {
failure(Reason.NoData, data)
}
} else {
failure(Reason.NoSuccessStatusCode(statusCode: httpResponse.statusCode), data)
}
} else {
failure(Reason.Other(error), data)
}
}
task.resume()
}
// Here are some convenience functions for dealing with JSON APIs
public typealias JSONDictionary = [String:AnyObject]
func decodeJSON(data: NSData) -> JSONDictionary? {
return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? [String:AnyObject]
}
func encodeJSON(dict: JSONDictionary) -> NSData? {
return dict.count > 0 ? NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.allZeros, error: nil) : nil
}
public func jsonResource<A>(path: String, method: Method, requestParameters: JSONDictionary, parse: JSONDictionary -> A?) -> Resource<A> {
let f = { decodeJSON($0) >>= parse }
let jsonBody = encodeJSON(requestParameters)
let headers = ["Content-Type": "application/json"]
return Resource(path: path, method: method, requestBody: jsonBody, headers: headers, parse: f)
}
@basdelfos
Copy link

Never mind. I didn't read the accompanying blog post that well enough. The answer is in the required code from the JSON article. See http://chris.eidhof.nl/posts/json-parsing-in-swift.html
Although I had to change the operator from >>= to >>>=.

Thanks 😄

@Ben-G
Copy link

Ben-G commented Jul 27, 2015

@chriseidhof: Would it be possible to put a license on this? I'd like to use a substantial part of it for a project :)

@sasikiran
Copy link

@chriseidhof
Throws an error in line 77: let f = { decodeJSON($0) >>= parse }
"Left side of mutating operator isn't mutable: 'decodeJSON' returns an immutable value". Tried making it return a mutable value though, then it complained it couldn't apply binary operation between NSData -> JSONDictionary? and JSONDictionary? -> _

@Arvkon
Copy link

Arvkon commented Jun 6, 2016

@chriseidhof I adapted your library to Swift 2.2. Feel free to comment on the adaptation!
https://gist.github.com/Arvkon/9ad7d9e83ac65634f5df8557746f4978/revisions (revision 4)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment