A Simple HTTP Client written in Swift 3.
Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
You can install Carthage with Homebrew using the following command:
$ brew update
$ brew install carthage
To integrate SwiftClient
into your Xcode project using Carthage, specify it in your Cartfile
:
github "theadam/SwiftClient" ~> 3.0.4
Run carthage update
to build the framework and drag the built SwiftClient.framework
into your Xcode project.
CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:
$ gem install cocoapods
To integrate SwiftClient
into your Xcode project using CocoaPods, specify it in your Podfile
:
platform :ios, '9.0'
use_frameworks!
pod 'SwiftClient', '~> 3.0.4'
Then, run the following command:
$ pod install
- If you are using git then add SwiftClient as a submodule using
git submodule add https://github.com/theadam/SwiftClient.git
otherwise download the project usinggit clone https://github.com/theadam/SwiftClient.git
in your project folder. - In Xcode, Right click on the blue project icon and select "Add files to..." Select SwiftClient/SwiftClient.xcodeproj and click Add.
- Navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar.
- In the tab bar at the top of that window, open the "Build Phases" panel.
- Expand the "Link Binary with Libraries" group, and add SwiftClient.framework.
- In your project file
import SwiftClient
and you can start using SwiftClient.
var client = Client()
.baseUrl("http://myapi.org")
.onError({e in alertError(e)});
// GET http://myapi.org/get?key=value&key2=value2
client.get("/get")
.query(["key": "value", "key2": "value2"])
.set("header", "headerValue")
.end({(res:Response) -> Void in
if(res.basicStatus == .OK) { // status of 2xx
handleResponseJson(res.body)
}
else {
handleErrorJson(res.body)
}
})
A Client is like a request factory. Client objects use functions to create Request Objects.
client.get(url)
client.post(url)
client.put(url)
client.patch(url)
client.delete(url)
client.head(url)
Middleware can be used as plugins that affect every request created by a client.
Client().use({(req:Request) -> Request in
// perform actions on the request.
})
Sets the base URL for any request which has a URL that starts with a "/"
var client = Client().baseUrl("http://myapi.org");
client.get("/endpoint").end(...);
Adds a function that affects every response retrieved from a clients requests.
Client().transform({(res:Response) -> Response in
// perform actions on the response
})
Adds a default error handler for any request made with a client
Client().onError({(err:NSError) -> Void in
// handle error
})
Headers can be set on the request by passing in a key and value or a dictionary of string to string.
Client().get(url).set(key, value)
Client().get(url).set([key : value, key2: value2])
Middleware can be used as plugins that affect a request.
Client().get(url).use({(req:Request) -> Request in
// perform actions on the request.
})
Adds a function that affects the response retrieved from a request.
Client().get(url).transform({(res:Response) -> Response in
// perform actions on the response
})
The content type can be set using a short hand name (json, html, form, urlencoded, form, form-data, xml), or the full type (application/json for example).
Client().get(url).type("json")
Query parameters can be added to the URL by passing in a key and value or a dictionary of string to string.
Client().get(url).query(key, value)
Client().get(url).query([key : value, key2: value2])
Data can be sent in the request body. If the content type is set to "form" or "json", the request attempts to format the data to the appropriate format and send it. A dictionary passed in defaults the type to JSON.
Client().post(url).type("json").send([1,2,3,4]);
Client().post(url).send([key : value, key2 : value2]);
Client().post(url).type("form").send([key : value, key2 : value2]);
Client().post(url).type("html").send("<html>").send("</html>");
Performs basic HTTP authentication for a request.
Client().get(url).auth("username", "password");
Multipart requests can be made with fields and attaching files. The content-type is set automatically with this type of request. If a path is attached that does not exist, the contents of the attachment will be empty.
These functions are not compatible with other functions that add data to the body of the request.
// Adds a field to the multipart data
Client().post(url).field("key", "value")
// Attaches a file to field fileKey, with data content, and a filename of filename.ext (and an inferred MIMEType).
Client().post(url).attach("fileKey", NSData(contentsOfFile: filePath), "filename.ext")
// Attaches a file to field imageKey, with data content, a filename of image.png, and an explicit MIMEType of image/png
Client().post(url).attach("imageKey", NSData(contentsOfFile: "image.png"), "image.png", withMimeType: "image/png")
// Attaches a file located at /path/to/image.png to the field imageKey.
// The filename in the form is image.png, and the MIMEType is inferred.
Client().post(url).attach("imageKey", "/path/to/image.png")
// Attaches a file located at /path/to/image.png to the field imageKey.
// The filename in the form is formImage.png, and the MIMEType is inferred.
Client().post(url).attach("imageKey", "/path/to/image.png", "formImage.png")
// Attaches a file located at /path/to/image.png to the field imageKey.
// The filename in the form is formImage.png, and the MIMEType is explicitly set to image/png.
Client().post(url).attach("imageKey", "/path/to/image.png", "formImage.png", withMimeType: "image/png")
The MIMEType argument is optional. If it is not provided, SwiftClient attempts to infer it from the file extension.
Sets the request's timeout interval.
Client().get(url).timeout(timeoutInSeconds);
Sets the underlying NSURLSessionDelegate.
Client().get(url).delegate(delegate);
Adds a error handler for a request.
Client().get(url).onError({(err:NSError) -> Void in
// handle error
})
The request is performed and handled by passing in a response handler and an optional error handler.
Client().get(url).end(responseHandler);
Client().get(url).end(responseHandler, onError: errorHandler); // Overrides all other error handlers.
response.status
- The HTTP response status code (Response.ResponseType).
response.text
- An optional string containing the text of the body of the response.
response.data
- An optional NSData object with the raw body data from the respnse.
response.body
- An optional object with the parsed version of the response body (for JSON and form responses).
response.headers
- A dictionary of string to string containing the headers of the response.
ResponseType is a new enumeration brought into the client. Instead of having countless, memory allocated, booleans, we've got an enumeration. As before, you will be able to check all of the previously used HTTP status codes.
Enumeration based on statusType.