karumi / bothamnetworking Goto Github PK
View Code? Open in Web Editor NEWNetworking Framework written in Swift.
License: Apache License 2.0
Networking Framework written in Swift.
License: Apache License 2.0
Define a protocol that will allow to return custom headers and react to response to unauthenticated responses.
HTTP Basic Authentication should be provided as an implementation.
HTTP Basic Authentication object should be able to generate the following headers
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
And provide a callback o delegate when receiving
HTTP 401 Unauthorized
Example: Response with Status Code 400
With JSON Body Mapping to domain Error
I have no preference on the naming.
The name Converter come from Retrofit and Formater form Server Implementation of Django having similar behavior. We could also use the word Serializer, but I prefer to keep for serializing specific Object.
They should have a method that take in Input NSData and return a Specific Type.
By Default this lib should Include 3 implementation:
Something similar to the protocol below.
And change HTTPClient protocol to include this kind of mechanism.
protocol Middleware {
/*
* Called on each request, before calling send on HTTPClient.
*/
func processRequest(var httpRequest: HTTPRequest)
/*
* Called on all responses before they’re returned from the HTTPClient.
*/
func processResponse(httpRequest: HTTPRequest, httpResponse: HTTPResponse) -> HTTPResponse
}
We should configure the default HTTPClient
implementation, NSHTTPClient
with a default timeout. The value I suggest is 10 seconds. Another approach should be to add a new feature to the project to be able to configure this and another similar values.
We should add a basic interceptor to log request and responses:
Here you have a possible implementation:
import Foundation
import BothamNetworking
class NSLogInterceptor: BothamRequestInterceptor, BothamResponseInterceptor {
func intercept(request: HTTPRequest) -> HTTPRequest {
NSLog("REQUEST -> \(request)")
return request
}
func intercept(response: HTTPResponse) -> HTTPResponse {
NSLog("RESPONSE <- \(response)")
return response
}
}
To do this we need to change HTTPRequest
and HTTPResponse
to implement CustomStringConvertible
. A possible implementation for HTTPRequest
and HTTPResponse
could be:
public var description: String {
get {
return "URL: \(self.url) - "
+ "PARAMETERS: \(self.parameters)"
+ "HEADERS: \(self.headers)"
+ "HTTP METHOD: \(self.httpMethod)"
+ "BODY: \(self.body)"
}
}
public var description: String {
get {
return "STATUS CODE: \(self.statusCode) - "
+ "HEADERS: \(self.headers)"
+ "BODY: \(self.body)"
}
}
@davideme do you like the format used? If you like this implementation I can send a PR :)
It can be usefull in order to implement
I can imagine various way to implement it, we should discuss them before a PR.
To be able to show how this library should be used we are going to add all the documentation needed to the project README.md
and create a XCode playground
to show it's usage.
We should support at least URL and JSON Encoding(via converter).
We will only support parameters: [String:String]? instead of parameters: [String:String?]?.
For url that don't need value you can use empty string ["key1": "", "key2": "value2"] and it will be encoded by default as key1=&key2=value2
I a future we will implement a configuration that will allow to handle this case as
["key1": "", "key2": "value2"]
key1&key2=value2
We should review this code and maybe unify it inside NSHTTPClient.
We are going to implement a basic BothamAPIClient based on a HTTPClient
and a baseEndpoint
.
This new component will allow us to send HTTPRequest
objects to obtain one HTTPResponse
or a ApiError
instance.
The execution should be performed out of the main thread.
That define the following HTTP Method
The current implementation is not parsing network errors coming from the HTTPClient
implementation. We should detect the error code inside the NSError returned by the HTTPClient
implementation and map it to a BothamAPIClientError
.
By default, Swift creates struct init methods with default visibility. This means that two of our structs, HTTPRequest
and HTTPResponse
can be initialized outside the framework. We have to add a public constructor to these structs.
BothamAPIClient class should also have a public init method.
We should support at least 2 kind of encoding for the Body.
The encoding should go in relationship with the value of the http header "Content-Type"
application/x-www-form-urlencoded format: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
There is no implementation in built-in in Foundation that I can find, you can take a look to the Alamofire one.
https://github.com/Alamofire/Alamofire/blob/b0c6a9bf27940e60cfda629811e84a1f6f1f9ff2/Source/ParameterEncoding.swift#L134
let data = query(value).dataUsingEncoding(
NSUTF8StringEncoding,
allowLossyConversion: false
)
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sort(<) {
let value = parameters[key]!
components += queryComponents(key, value)
}
return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
}
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(value, options: options)
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
sessionConfiguration.HTTPCookieStorage = cookieStorage
sessionConfiguration.HTTPCookieAcceptPolicy = .Always
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.