[Swift] Use ISOFullDate for date format

This commit is contained in:
Jason Gavris 2016-09-12 13:44:28 -04:00 committed by wing328
parent 40610373f6
commit f639a312e8
41 changed files with 748 additions and 172 deletions

View File

@ -115,8 +115,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("map", "Dictionary");
typeMapping.put("date", "NSDate");
typeMapping.put("Date", "NSDate");
typeMapping.put("date", "ISOFullDate");
typeMapping.put("Date", "ISOFullDate");
typeMapping.put("DateTime", "NSDate");
typeMapping.put("boolean", "Bool");
typeMapping.put("string", "String");

View File

@ -84,6 +84,99 @@ extension NSUUID: JSONEncodable {
}
}
/// Represents an ISO-8601 full-date (RFC-3339).
/// ex: 12-31-1999
/// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
public final class ISOFullDate: CustomStringConvertible {
public let year: Int
public let month: Int
public let day: Int
public init(year year: Int, month: Int, day: Int) {
self.year = year
self.month = month
self.day = day
}
/**
Converts an NSDate to an ISOFullDate. Only interested in the year, month, day components.
- parameter date: The date to convert.
- returns: An ISOFullDate constructed from the year, month, day of the date.
*/
public static func from(date date: NSDate) -> ISOFullDate? {
guard let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
return nil
}
let components = calendar.components(
[
.Year,
.Month,
.Day,
],
fromDate: date
)
return ISOFullDate(
year: components.year,
month: components.month,
day: components.day
)
}
/**
Converts a ISO-8601 full-date string to an ISOFullDate.
- parameter string: The ISO-8601 full-date format string to convert.
- returns: An ISOFullDate constructed from the string.
*/
public static func from(string string: String) -> ISOFullDate? {
let components = string
.characters
.split("-")
.map(String.init)
.flatMap { Int($0) }
guard components.count == 3 else { return nil }
return ISOFullDate(
year: components[0],
month: components[1],
day: components[2]
)
}
/**
Converts the receiver to an NSDate, in the default time zone.
- returns: An NSDate from the components of the receiver, in the default time zone.
*/
public func toDate() -> NSDate? {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
components.timeZone = NSTimeZone.defaultTimeZone()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
// MARK: CustomStringConvertible
public var description: String {
return "\(year)-\(month)-\(day)"
}
}
extension ISOFullDate: JSONEncodable {
public func encodeToJSON() -> AnyObject {
return "\(year)-\(month)-\(day)"
}
}
{{#usePromiseKit}}extension RequestBuilder {
public func execute() -> Promise<Response<T>> {
let deferred = Promise<Response<T>>.pendingPromise()

View File

@ -139,7 +139,16 @@ class Decoders {
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
} {{#models}}{{#model}}
}
// Decoder for ISOFullDate
Decoders.addDecoder(clazz: ISOFullDate.self, decoder: { (source: AnyObject) -> ISOFullDate in
if let string = source as? String,
let isoDate = ISOFullDate.from(string: string) {
return isoDate
}
fatalError("formatter failed to parse \(source)")
}) {{#models}}{{#model}}
// Decoder for [{{{classname}}}]
Decoders.addDecoder(clazz: [{{{classname}}}].self) { (source: AnyObject) -> [{{{classname}}}] in

View File

@ -63,6 +63,18 @@ public class SwiftCodegenTest {
Assert.assertTrue(op.responses.get(0).isBinary);
}
@Test(description = "returns ISOFullDate when response format is date")
public void dateTest() {
final Swagger model = new SwaggerParser().read("src/test/resources/2_0/datePropertyTest.json");
final DefaultCodegen codegen = new SwiftCodegen();
final String path = "/tests/dateResponse";
final Operation p = model.getPaths().get(path).getPost();
final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions());
Assert.assertEquals(op.returnType, "ISOFullDate");
Assert.assertEquals(op.bodyParam.dataType, "ISOFullDate");
}
@Test
public void testDefaultPodAuthors() throws Exception {
// Given

View File

@ -21,6 +21,7 @@ public class SwiftModelTest {
.property("binary", new BinaryProperty())
.property("byte", new ByteArrayProperty())
.property("uuid", new UUIDProperty())
.property("dateOfBirth", new DateProperty())
.required("id")
.required("name")
.discriminator("test");
@ -30,7 +31,7 @@ public class SwiftModelTest {
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 6);
Assert.assertEquals(cm.vars.size(), 7);
Assert.assertEquals(cm.discriminator,"test");
final CodegenProperty property1 = cm.vars.get(0);
@ -91,9 +92,19 @@ public class SwiftModelTest {
Assert.assertEquals(property6.name, "uuid");
Assert.assertNull(property6.defaultValue);
Assert.assertEquals(property6.baseType, "NSUUID");
Assert.assertNull(property6.hasMore);
Assert.assertTrue(property6.hasMore);
Assert.assertNull(property6.required);
Assert.assertTrue(property6.isNotContainer);
final CodegenProperty property7 = cm.vars.get(6);
Assert.assertEquals(property7.baseName, "dateOfBirth");
Assert.assertEquals(property7.datatype, "ISOFullDate");
Assert.assertEquals(property7.name, "dateOfBirth");
Assert.assertNull(property7.defaultValue);
Assert.assertEquals(property7.baseType, "ISOFullDate");
Assert.assertNull(property7.hasMore);
Assert.assertNull(property7.required);
Assert.assertTrue(property7.isNotContainer);
}
}

View File

@ -0,0 +1,45 @@
{
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters",
"version": "1.0.0",
"title": "Swagger Petstore",
"termsOfService": "http://helloreverb.com/terms/",
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"basePath": "/v2",
"schemes": [
"http"
],
"paths": {
"/tests/dateResponse": {
"post": {
"summary": "Echo test",
"operationId": "echotest",
"parameters": [
{
"name": "InputDate",
"in": "body",
"required": true,
"schema": {
"type": "string",
"format": "date"
}
}
],
"responses": {
"200": {
"description": "OutputDate",
"schema": {
"type": "string",
"format": "date"
}
}
}
}
}
}
}

View File

@ -833,6 +833,10 @@
"username": {
"type": "string"
},
"dateOfBirth": {
"type": "string",
"format": "date"
},
"firstName": {
"type": "string"
},

View File

@ -179,6 +179,7 @@ public class UserAPI: APIBase {
}}, {contentType=application/xml, example=<User>
<id>123456</id>
<username>string</username>
<dateOfBirth>2000-01-23T04:56:07.000Z</dateOfBirth>
<firstName>string</firstName>
<lastName>string</lastName>
<email>string</email>
@ -198,6 +199,7 @@ public class UserAPI: APIBase {
}}, {contentType=application/xml, example=<User>
<id>123456</id>
<username>string</username>
<dateOfBirth>2000-01-23T04:56:07.000Z</dateOfBirth>
<firstName>string</firstName>
<lastName>string</lastName>
<email>string</email>

View File

@ -83,4 +83,97 @@ extension NSUUID: JSONEncodable {
}
}
/// Represents an ISO-8601 full-date (RFC-3339).
/// ex: 12-31-1999
/// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
public final class ISOFullDate: CustomStringConvertible {
public let year: Int
public let month: Int
public let day: Int
public init(year year: Int, month: Int, day: Int) {
self.year = year
self.month = month
self.day = day
}
/**
Converts an NSDate to an ISOFullDate. Only interested in the year, month, day components.
- parameter date: The date to convert.
- returns: An ISOFullDate constructed from the year, month, day of the date.
*/
public static func from(date date: NSDate) -> ISOFullDate? {
guard let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
return nil
}
let components = calendar.components(
[
.Year,
.Month,
.Day,
],
fromDate: date
)
return ISOFullDate(
year: components.year,
month: components.month,
day: components.day
)
}
/**
Converts a ISO-8601 full-date string to an ISOFullDate.
- parameter string: The ISO-8601 full-date format string to convert.
- returns: An ISOFullDate constructed from the string.
*/
public static func from(string string: String) -> ISOFullDate? {
let components = string
.characters
.split("-")
.map(String.init)
.flatMap { Int($0) }
guard components.count == 3 else { return nil }
return ISOFullDate(
year: components[0],
month: components[1],
day: components[2]
)
}
/**
Converts the receiver to an NSDate, in the default time zone.
- returns: An NSDate from the components of the receiver, in the default time zone.
*/
public func toDate() -> NSDate? {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
components.timeZone = NSTimeZone.defaultTimeZone()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
// MARK: CustomStringConvertible
public var description: String {
return "\(year)-\(month)-\(day)"
}
}
extension ISOFullDate: JSONEncodable {
public func encodeToJSON() -> AnyObject {
return "\(year)-\(month)-\(day)"
}
}

View File

@ -139,7 +139,16 @@ class Decoders {
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
}
}
// Decoder for ISOFullDate
Decoders.addDecoder(clazz: ISOFullDate.self, decoder: { (source: AnyObject) -> ISOFullDate in
if let string = source as? String,
let isoDate = ISOFullDate.from(string: string) {
return isoDate
}
fatalError("formatter failed to parse \(source)")
})
// Decoder for [Category]
Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in
@ -215,6 +224,7 @@ class Decoders {
let instance = User()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"])
instance.dateOfBirth = Decoders.decodeOptional(clazz: ISOFullDate.self, source: sourceDictionary["dateOfBirth"])
instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"])
instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"])
instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"])

View File

@ -11,6 +11,7 @@ import Foundation
public class User: JSONEncodable {
public var id: Int64?
public var username: String?
public var dateOfBirth: ISOFullDate?
public var firstName: String?
public var lastName: String?
public var email: String?
@ -26,6 +27,7 @@ public class User: JSONEncodable {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["username"] = self.username
nillableDictionary["dateOfBirth"] = self.dateOfBirth?.encodeToJSON()
nillableDictionary["firstName"] = self.firstName
nillableDictionary["lastName"] = self.lastName
nillableDictionary["email"] = self.email

View File

@ -17,6 +17,7 @@
6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; };
6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; };
751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */; };
C6AAAD211D8718D00016A515 /* ISOFullDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6AAAD201D8718D00016A515 /* ISOFullDateTests.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@ -47,6 +48,7 @@
A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = "<group>"; };
B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = "<group>"; };
C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; };
C6AAAD201D8718D00016A515 /* ISOFullDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ISOFullDateTests.swift; sourceTree = "<group>"; };
F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
@ -129,6 +131,7 @@
isa = PBXGroup;
children = (
6D4EFBAB1C692C6300B96B06 /* Info.plist */,
C6AAAD201D8718D00016A515 /* ISOFullDateTests.swift */,
6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */,
6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */,
6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */,
@ -473,6 +476,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C6AAAD211D8718D00016A515 /* ISOFullDateTests.swift in Sources */,
6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */,
6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */,
6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */,

View File

@ -0,0 +1,83 @@
/// Copyright 2012-2016 (C) Butterfly Network, Inc.
import PetstoreClient
import XCTest
@testable import SwaggerClient
final class ISOFullDateTests: XCTestCase {
var fullDate = ISOFullDate(year: 1999, month: 12, day: 31)
func testValidDate() {
XCTAssertEqual(fullDate.year, 1999)
XCTAssertEqual(fullDate.month, 12)
XCTAssertEqual(fullDate.day, 31)
}
func testFromDate() {
let date = NSDate()
let fullDate = ISOFullDate.from(date: date)
guard let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
XCTFail()
return
}
let components = calendar.components(
[
.Year,
.Month,
.Day,
],
fromDate: date
)
XCTAssertEqual(fullDate?.year, components.year)
XCTAssertEqual(fullDate?.month, components.month)
XCTAssertEqual(fullDate?.day, components.day)
}
func testFromString() {
let string = "1999-12-31"
let fullDate = ISOFullDate.from(string: string)
XCTAssertEqual(fullDate?.year, 1999)
XCTAssertEqual(fullDate?.month, 12)
XCTAssertEqual(fullDate?.day, 31)
}
func testFromInvalidString() {
XCTAssertNil(ISOFullDate.from(string: "1999-12"))
}
func testToDate() {
let fullDate = ISOFullDate(year: 1999, month: 12, day: 31)
guard let date = fullDate.toDate(),
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
XCTFail()
return
}
let components = calendar.components(
[
.Year,
.Month,
.Day,
],
fromDate: date
)
XCTAssertEqual(fullDate.year, components.year)
XCTAssertEqual(fullDate.month, components.month)
XCTAssertEqual(fullDate.day, components.day)
}
func testDescription() {
XCTAssertEqual(fullDate.description, "1999-12-31")
}
func testEncodeToJSON() {
XCTAssertEqual(fullDate.encodeToJSON() as? String, "1999-12-31")
}
}

View File

@ -11,22 +11,12 @@ import XCTest
@testable import SwaggerClient
class UserAPITests: XCTestCase {
let testTimeout = 10.0
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testLogin() {
let expectation = self.expectationWithDescription("testLogin")
UserAPI.loginUser(username: "swiftTester", password: "swift") { (_, error) in
guard error == nil else {
XCTFail("error logging in")
@ -35,13 +25,13 @@ class UserAPITests: XCTestCase {
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func testLogout() {
let expectation = self.expectationWithDescription("testLogout")
UserAPI.logoutUser { (error) in
guard error == nil else {
XCTFail("error logging out")
@ -50,15 +40,16 @@ class UserAPITests: XCTestCase {
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test1CreateUser() {
let expectation = self.expectationWithDescription("testCreateUser")
let newUser = User()
newUser.email = "test@test.com"
newUser.dateOfBirth = ISOFullDate.from(string: "1999-12-31")
newUser.firstName = "Test"
newUser.lastName = "Tester"
newUser.id = 1000
@ -66,7 +57,7 @@ class UserAPITests: XCTestCase {
newUser.phone = "867-5309"
newUser.username = "test@test.com"
newUser.userStatus = 0
UserAPI.createUser(body: newUser) { (error) in
guard error == nil else {
XCTFail("error creating user")
@ -75,19 +66,19 @@ class UserAPITests: XCTestCase {
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test2GetUser() {
let expectation = self.expectationWithDescription("testGetUser")
UserAPI.getUserByName(username: "test@test.com") { (user, error) in
guard error == nil else {
XCTFail("error getting user")
return
}
if let user = user {
XCTAssert(user.userStatus == 0, "invalid userStatus")
XCTAssert(user.email == "test@test.com", "invalid email")
@ -95,17 +86,18 @@ class UserAPITests: XCTestCase {
XCTAssert(user.lastName == "Tester", "invalid lastName")
XCTAssert(user.password == "test!", "invalid password")
XCTAssert(user.phone == "867-5309", "invalid phone")
XCTAssert(user.dateOfBirth?.description == "1999-12-31", "invalid date of birth")
expectation.fulfill()
}
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}
func test3DeleteUser() {
let expectation = self.expectationWithDescription("testDeleteUser")
UserAPI.deleteUser(username: "test@test.com") { (error) in
guard error == nil else {
XCTFail("error deleting user")
@ -114,7 +106,7 @@ class UserAPITests: XCTestCase {
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(testTimeout, handler: nil)
}

View File

@ -259,12 +259,14 @@ public class UserAPI: APIBase {
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
"dateOfBirth" : "2000-01-23T04:56:07.000+00:00",
"id" : 123456789,
"email" : "aeiou",
"username" : "aeiou"
}}, {contentType=application/xml, example=<User>
<id>123456</id>
<username>string</username>
<dateOfBirth>2000-01-23T04:56:07.000Z</dateOfBirth>
<firstName>string</firstName>
<lastName>string</lastName>
<email>string</email>
@ -278,12 +280,14 @@ public class UserAPI: APIBase {
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
"dateOfBirth" : "2000-01-23T04:56:07.000+00:00",
"id" : 123456789,
"email" : "aeiou",
"username" : "aeiou"
}}, {contentType=application/xml, example=<User>
<id>123456</id>
<username>string</username>
<dateOfBirth>2000-01-23T04:56:07.000Z</dateOfBirth>
<firstName>string</firstName>
<lastName>string</lastName>
<email>string</email>

View File

@ -84,6 +84,99 @@ extension NSUUID: JSONEncodable {
}
}
/// Represents an ISO-8601 full-date (RFC-3339).
/// ex: 12-31-1999
/// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
public final class ISOFullDate: CustomStringConvertible {
public let year: Int
public let month: Int
public let day: Int
public init(year year: Int, month: Int, day: Int) {
self.year = year
self.month = month
self.day = day
}
/**
Converts an NSDate to an ISOFullDate. Only interested in the year, month, day components.
- parameter date: The date to convert.
- returns: An ISOFullDate constructed from the year, month, day of the date.
*/
public static func from(date date: NSDate) -> ISOFullDate? {
guard let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
return nil
}
let components = calendar.components(
[
.Year,
.Month,
.Day,
],
fromDate: date
)
return ISOFullDate(
year: components.year,
month: components.month,
day: components.day
)
}
/**
Converts a ISO-8601 full-date string to an ISOFullDate.
- parameter string: The ISO-8601 full-date format string to convert.
- returns: An ISOFullDate constructed from the string.
*/
public static func from(string string: String) -> ISOFullDate? {
let components = string
.characters
.split("-")
.map(String.init)
.flatMap { Int($0) }
guard components.count == 3 else { return nil }
return ISOFullDate(
year: components[0],
month: components[1],
day: components[2]
)
}
/**
Converts the receiver to an NSDate, in the default time zone.
- returns: An NSDate from the components of the receiver, in the default time zone.
*/
public func toDate() -> NSDate? {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
components.timeZone = NSTimeZone.defaultTimeZone()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
// MARK: CustomStringConvertible
public var description: String {
return "\(year)-\(month)-\(day)"
}
}
extension ISOFullDate: JSONEncodable {
public func encodeToJSON() -> AnyObject {
return "\(year)-\(month)-\(day)"
}
}
extension RequestBuilder {
public func execute() -> Promise<Response<T>> {
let deferred = Promise<Response<T>>.pendingPromise()

View File

@ -139,7 +139,16 @@ class Decoders {
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
}
}
// Decoder for ISOFullDate
Decoders.addDecoder(clazz: ISOFullDate.self, decoder: { (source: AnyObject) -> ISOFullDate in
if let string = source as? String,
let isoDate = ISOFullDate.from(string: string) {
return isoDate
}
fatalError("formatter failed to parse \(source)")
})
// Decoder for [Category]
Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in
@ -215,6 +224,7 @@ class Decoders {
let instance = User()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"])
instance.dateOfBirth = Decoders.decodeOptional(clazz: ISOFullDate.self, source: sourceDictionary["dateOfBirth"])
instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"])
instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"])
instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"])

View File

@ -11,6 +11,7 @@ import Foundation
public class User: JSONEncodable {
public var id: Int64?
public var username: String?
public var dateOfBirth: ISOFullDate?
public var firstName: String?
public var lastName: String?
public var email: String?
@ -26,6 +27,7 @@ public class User: JSONEncodable {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["username"] = self.username
nillableDictionary["dateOfBirth"] = self.dateOfBirth?.encodeToJSON()
nillableDictionary["firstName"] = self.firstName
nillableDictionary["lastName"] = self.lastName
nillableDictionary["email"] = self.email

View File

@ -718,7 +718,7 @@ Requests can be suspended, resumed, and cancelled:
Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. Alamofire recommends handling these through the use of either your own `NSError` creation methods, or a simple `enum` that conforms to `ErrorType`. For example, this `BackendError` type, which will be used in later examples:
```swift
enum BackendError: ErrorType {
public enum BackendError: ErrorType {
case Network(error: NSError)
case DataSerialization(reason: String)
case JSONSerialization(error: NSError)
@ -1288,7 +1288,7 @@ The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise m
* Potentially fund test servers to make it easier for us to test the edge cases
* Potentially fund developers to work on one of our projects full-time
The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated.
The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiam around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated.
<a href='https://pledgie.com/campaigns/31474'><img alt='Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com !' src='https://pledgie.com/campaigns/31474.png?skin_name=chrome' border='0' ></a>

View File

@ -27,7 +27,7 @@ import Foundation
// MARK: - URLStringConvertible
/**
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to
construct URL requests.
*/
public protocol URLStringConvertible {
@ -44,27 +44,19 @@ public protocol URLStringConvertible {
}
extension String: URLStringConvertible {
public var URLString: String {
return self
}
public var URLString: String { return self }
}
extension NSURL: URLStringConvertible {
public var URLString: String {
return absoluteString
}
public var URLString: String { return absoluteString }
}
extension NSURLComponents: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
public var URLString: String { return URL!.URLString }
}
extension NSURLRequest: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
public var URLString: String { return URL!.URLString }
}
// MARK: - URLRequestConvertible
@ -78,9 +70,7 @@ public protocol URLRequestConvertible {
}
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSMutableURLRequest {
return self.mutableCopy() as! NSMutableURLRequest
}
public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest }
}
// MARK: - Convenience
@ -91,7 +81,16 @@ func URLRequest(
headers: [String: String]? = nil)
-> NSMutableURLRequest
{
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
let mutableURLRequest: NSMutableURLRequest
if let request = URLString as? NSMutableURLRequest {
mutableURLRequest = request
} else if let request = URLString as? NSURLRequest {
mutableURLRequest = request.URLRequest
} else {
mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
}
mutableURLRequest.HTTPMethod = method.rawValue
if let headers = headers {
@ -355,11 +354,11 @@ public func download(URLRequest: URLRequestConvertible, destination: Request.Dow
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a
Creates a request using the shared manager instance for downloading from the resume data produced from a
previous request cancellation.
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
information.
- parameter destination: The closure used to determine the destination of the downloaded file.

View File

@ -114,8 +114,8 @@ extension Manager {
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for
additional information.
- parameter destination: The closure used to determine the destination of the downloaded file.
@ -130,14 +130,14 @@ extension Manager {
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary
file written to during the download process. The closure takes two arguments: the temporary file URL and the URL
A closure executed once a request has successfully completed in order to determine where to move the temporary
file written to during the download process. The closure takes two arguments: the temporary file URL and the URL
response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a
Creates a download file destination closure which uses the default file manager to move the temporary file to a
file URL in the first available directory with the specified search path directory and search path domain mask.
- parameter directory: The search path directory. `.DocumentDirectory` by default.
@ -220,7 +220,7 @@ extension Request {
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {

View File

@ -32,7 +32,7 @@ public class Manager {
// MARK: - Properties
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
for any ad hoc requests.
*/
public static let sharedInstance: Manager = {
@ -60,7 +60,8 @@ public class Manager {
if let info = NSBundle.mainBundle().infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let versionString: String
@ -91,7 +92,7 @@ public class Manager {
return "\(osName) \(versionString)"
}()
return "\(executable)/\(bundle) (\(version); \(osNameVersion))"
return "\(executable)/\(bundle) (\(appVersion)/\(appBuild)); \(osNameVersion))"
}
return "Alamofire"
@ -116,14 +117,14 @@ public class Manager {
public var startRequestsImmediately: Bool = true
/**
The background completion handler closure provided by the UIApplicationDelegate
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
The background completion handler closure provided by the UIApplicationDelegate
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
will automatically call the handler.
If you need to handle your own events before the handler is called, then you need to override the
If you need to handle your own events before the handler is called, then you need to override the
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
`nil` by default.
*/
public var backgroundCompletionHandler: (() -> Void)?
@ -133,11 +134,11 @@ public class Manager {
/**
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
- parameter configuration: The configuration used to construct the managed session.
- parameter configuration: The configuration used to construct the managed session.
`NSURLSessionConfiguration.defaultSessionConfiguration()` by default.
- parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
default.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance.
@ -361,14 +362,14 @@ public class Manager {
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
/// requires the caller to call the `completionHandler`.
public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)?
@ -387,8 +388,8 @@ public class Manager {
- parameter task: The task whose request resulted in a redirect.
- parameter response: An object containing the servers response to the original request.
- parameter request: A URL request object filled out with the new location.
- parameter completionHandler: A closure that your handler should call with either the value of the request
parameter, a modified URL request object, or NULL to refuse the redirect and
- parameter completionHandler: A closure that your handler should call with either the value of the request
parameter, a modified URL request object, or NULL to refuse the redirect and
return the body of the redirect response.
*/
public func URLSession(
@ -525,7 +526,7 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
@ -538,7 +539,7 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)?
@ -550,8 +551,8 @@ public class Manager {
- parameter session: The session containing the data task that received an initial reply.
- parameter dataTask: The data task that received an initial reply.
- parameter response: A URL response object populated with headers.
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
constant to indicate whether the transfer should continue as a data task or
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
constant to indicate whether the transfer should continue as a data task or
should become a download task.
*/
public func URLSession(
@ -614,12 +615,12 @@ public class Manager {
- parameter session: The session containing the data (or upload) task.
- parameter dataTask: The data (or upload) task.
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
caching policy and the values of certain received headers, such as the Pragma
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
caching policy and the values of certain received headers, such as the Pragma
and Cache-Control headers.
- parameter completionHandler: A block that your handler must call, providing either the original proposed
response, a modified version of that response, or NULL to prevent caching the
response. If your delegate implements this method, it must call this completion
- parameter completionHandler: A block that your handler must call, providing either the original proposed
response, a modified version of that response, or NULL to prevent caching the
response. If your delegate implements this method, it must call this completion
handler; otherwise, your app leaks memory.
*/
public func URLSession(
@ -667,8 +668,8 @@ public class Manager {
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that finished.
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
open the file for reading or move it to a permanent location in your apps sandbox
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
open the file for reading or move it to a permanent location in your apps sandbox
container directory before returning from this delegate method.
*/
public func URLSession(
@ -688,11 +689,11 @@ public class Manager {
- parameter session: The session containing the download task.
- parameter downloadTask: The download task.
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
method was called.
- parameter totalBytesWritten: The total number of bytes transferred so far.
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
header. If this header was not provided, the value is
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
header. If this header was not provided, the value is
`NSURLSessionTransferSizeUnknown`.
*/
public func URLSession(
@ -720,11 +721,11 @@ public class Manager {
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
existing content, then this value is zero. Otherwise, this value is an
integer representing the number of bytes on disk that do not need to be
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
existing content, then this value is zero. Otherwise, this value is an
integer representing the number of bytes on disk that do not need to be
retrieved again.
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
*/
public func URLSession(

View File

@ -31,10 +31,10 @@ import CoreServices
#endif
/**
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
@ -118,7 +118,7 @@ public class MultipartFormData {
self.bodyParts = []
/**
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
* information, please refer to the following article:
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
*/
@ -367,8 +367,8 @@ public class MultipartFormData {
/**
Encodes all the appended body parts into a single `NSData` object.
It is important to note that this method will load all the appended body parts into memory all at the same
time. This method should only be used when the encoded data will have a small memory footprint. For large data
It is important to note that this method will load all the appended body parts into memory all at the same
time. This method should only be used when the encoded data will have a small memory footprint. For large data
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
- throws: An `NSError` if encoding encounters an error.

View File

@ -61,7 +61,7 @@ public class NetworkReachabilityManager {
case WWAN
}
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// network reachability status.
public typealias Listener = NetworkReachabilityStatus -> Void

View File

@ -32,7 +32,7 @@ public struct Notifications {
/// `NSURLSessionTask`.
public static let DidResume = "com.alamofire.notifications.task.didResume"
/// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the
/// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the
/// suspended `NSURLSessionTask`.
public static let DidSuspend = "com.alamofire.notifications.task.didSuspend"

View File

@ -38,8 +38,8 @@ public enum Method: String {
/**
Used to specify the way in which a set of parameters are applied to a URL request.
- `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
and `DELETE` requests, or set as the body for requests with any other HTTP method. The
- `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
and `DELETE` requests, or set as the body for requests with any other HTTP method. The
`Content-Type` HTTP header field of an encoded request with HTTP body is set to
`application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification
for how to encode collection types, the convention of appending `[]` to the key for array
@ -49,8 +49,8 @@ public enum Method: String {
- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same
implementation as the `.URL` case, but always applies the encoded result to the URL.
- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is
set as the body of the request. The `Content-Type` HTTP header field of an encoded request is
- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is
set as the body of the request. The `Content-Type` HTTP header field of an encoded request is
set to `application/json`.
- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
@ -74,7 +74,7 @@ public enum ParameterEncoding {
- parameter URLRequest: The request to have parameters applied.
- parameter parameters: The parameters to apply.
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
if any.
*/
public func encode(

View File

@ -25,7 +25,7 @@
import Foundation
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as
Responsible for sending a request and receiving the response and associated data from the server, as well as
managing its underlying `NSURLSessionTask`.
*/
public class Request {
@ -126,12 +126,12 @@ public class Request {
// MARK: - Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
to write.
- For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
- For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
expected to read.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
@ -153,8 +153,8 @@ public class Request {
/**
Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
This closure returns the bytes most recently received from the server, not including data from previous calls.
If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
This closure returns the bytes most recently received from the server, not including data from previous calls.
If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
also important to note that the `response` closure will be called with nil `responseData`.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
@ -210,7 +210,7 @@ public class Request {
// MARK: - TaskDelegate
/**
The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
executing all operations attached to the serial operation queue upon task completion.
*/
public class TaskDelegate: NSObject {
@ -458,7 +458,7 @@ public class Request {
extension Request: CustomStringConvertible {
/**
The textual representation used when written to an output stream, which includes the HTTP method and URL, as
The textual representation used when written to an output stream, which includes the HTTP method and URL, as
well as the response status code if a response has been received.
*/
public var description: String {

View File

@ -44,7 +44,7 @@ public struct Response<Value, Error: ErrorType> {
/**
Initializes the `Response` instance with the specified URL request, URL response, server data and response
serialization result.
- parameter request: The URL request sent to the server.
- parameter response: The server's response to the URL request.
- parameter data: The data returned by the server.

View File

@ -101,7 +101,7 @@ extension Request {
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
@ -192,10 +192,10 @@ extension Request {
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
@ -214,9 +214,9 @@ extension Request {
let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
var convertedEncoding = encoding
if let encodingName = response?.textEncodingName where convertedEncoding == nil {
convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
@ -238,8 +238,8 @@ extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
@ -264,7 +264,7 @@ extension Request {
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
@ -322,7 +322,7 @@ extension Request {
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
@ -358,7 +358,7 @@ extension Request {
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.

View File

@ -27,9 +27,9 @@ import Foundation
/**
Used to represent whether a request was successful or encountered an error.
- Success: The request and all post processing operations were successful resulting in the serialization of the
- Success: The request and all post processing operations were successful resulting in the serialization of the
provided associated value.
- Failure: The request encountered an error resulting in a failure. The associated values are the original data
- Failure: The request encountered an error resulting in a failure. The associated values are the original data
provided by the server as well as the error that caused the failure.
*/
public enum Result<Value, Error: ErrorType> {
@ -75,7 +75,7 @@ public enum Result<Value, Error: ErrorType> {
// MARK: - CustomStringConvertible
extension Result: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
switch self {

View File

@ -32,9 +32,9 @@ public class ServerTrustPolicyManager {
/**
Initializes the `ServerTrustPolicyManager` instance with the given policies.
Since different servers and web services can have different leaf certificates, intermediate and even root
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
Since different servers and web services can have different leaf certificates, intermediate and even root
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
pinning for host3 and disabling evaluation for host4.
- parameter policies: A dictionary of all policies mapped to a particular host.
@ -80,31 +80,31 @@ extension NSURLSession {
// MARK: - ServerTrustPolicy
/**
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
with a given set of criteria to determine whether the server trust is valid and the connection should be made.
Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
to route all communication over an HTTPS connection with pinning enabled.
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
validate the host provided by the challenge. Applications are encouraged to always
validate the host in production environments to guarantee the validity of the server's
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
validate the host provided by the challenge. Applications are encouraged to always
validate the host in production environments to guarantee the validity of the server's
certificate chain.
- PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
considered valid if one of the pinned certificates match one of the server certificates.
By validating both the certificate chain and host, certificate pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
considered valid if one of the pinned certificates match one of the server certificates.
By validating both the certificate chain and host, certificate pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
valid if one of the pinned public keys match one of the server certificate public keys.
By validating both the certificate chain and host, public key pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
valid if one of the pinned public keys match one of the server certificate public keys.
By validating both the certificate chain and host, public key pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.

View File

@ -64,7 +64,7 @@ extension Manager {
- parameter hostName: The hostname of the server to connect to.
- parameter port: The port of the server to connect to.
:returns: The created stream request.
- returns: The created stream request.
*/
public func stream(hostName hostName: String, port: Int) -> Request {
return stream(.Stream(hostName, port))

View File

@ -54,10 +54,10 @@ public struct Timeline {
Creates a new `Timeline` instance with the specified request times.
- parameter requestStartTime: The time the request was initialized. Defaults to `0.0`.
- parameter initialResponseTime: The time the first bytes were received from or sent to the server.
- parameter initialResponseTime: The time the first bytes were received from or sent to the server.
Defaults to `0.0`.
- parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`.
- parameter serializationCompletedTime: The time when the response serialization was completed. Defaults
- parameter serializationCompletedTime: The time when the response serialization was completed. Defaults
to `0.0`.
- returns: The new `Timeline` instance.
@ -83,7 +83,7 @@ public struct Timeline {
// MARK: - CustomStringConvertible
extension Timeline: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the latency, the request
/// The textual representation used when written to an output stream, which includes the latency, the request
/// duration and the total duration.
public var description: String {
let latency = String(format: "%.3f", self.latency)
@ -107,7 +107,7 @@ extension Timeline: CustomStringConvertible {
// MARK: - CustomDebugStringConvertible
extension Timeline: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes the request start time, the
/// The textual representation used when written to an output stream, which includes the request start time, the
/// initial response time, the request completed time, the serialization completed time, the latency, the request
/// duration and the total duration.
public var debugDescription: String {

View File

@ -194,12 +194,12 @@ extension Manager {
public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024
/**
Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
associated values.
- Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with
- Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with
streaming information.
- Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
- Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
error.
*/
public enum MultipartFormDataEncodingResult {
@ -210,17 +210,17 @@ extension Manager {
/**
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
used for larger payloads such as video content.
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
technique was used.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.

View File

@ -38,7 +38,7 @@ extension Request {
}
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the
A closure used to validate a request that takes a URL request and URL response, and returns whether the
request was valid.
*/
public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult
@ -140,7 +140,7 @@ extension Request {
- returns: The request.
*/
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
public func validate<S: SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
return validate { _, response in
guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
@ -192,7 +192,7 @@ extension Request {
// MARK: - Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content
Validates that the response has a status code in the default acceptable range of 200...299, and that the content
type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.

View File

@ -1,5 +1,5 @@
PODS:
- Alamofire (3.4.1)
- Alamofire (3.4.2)
- OMGHTTPURLRQ (3.1.3):
- OMGHTTPURLRQ/RQ (= 3.1.3)
- OMGHTTPURLRQ/FormURLEncode (3.1.3)
@ -31,7 +31,7 @@ EXTERNAL SOURCES:
:path: "../"
SPEC CHECKSUMS:
Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c
Alamofire: 6aa33201d20d069e1598891cf928883ff1888c7a
OMGHTTPURLRQ: a547be1b9721ddfbf9d08aab56ab72dc4c1cc417
PetstoreClient: 24135348a992f2cbd76bc324719173b52e864cdc
PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb

View File

@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>3.4.1</string>
<string>3.4.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>

View File

@ -275,6 +275,7 @@ public class UserAPI: APIBase {
}}, {contentType=application/xml, example=<User>
<id>123456</id>
<username>string</username>
<dateOfBirth>2000-01-23T04:56:07.000Z</dateOfBirth>
<firstName>string</firstName>
<lastName>string</lastName>
<email>string</email>
@ -294,6 +295,7 @@ public class UserAPI: APIBase {
}}, {contentType=application/xml, example=<User>
<id>123456</id>
<username>string</username>
<dateOfBirth>2000-01-23T04:56:07.000Z</dateOfBirth>
<firstName>string</firstName>
<lastName>string</lastName>
<email>string</email>

View File

@ -83,4 +83,97 @@ extension NSUUID: JSONEncodable {
}
}
/// Represents an ISO-8601 full-date (RFC-3339).
/// ex: 12-31-1999
/// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
public final class ISOFullDate: CustomStringConvertible {
public let year: Int
public let month: Int
public let day: Int
public init(year year: Int, month: Int, day: Int) {
self.year = year
self.month = month
self.day = day
}
/**
Converts an NSDate to an ISOFullDate. Only interested in the year, month, day components.
- parameter date: The date to convert.
- returns: An ISOFullDate constructed from the year, month, day of the date.
*/
public static func from(date date: NSDate) -> ISOFullDate? {
guard let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) else {
return nil
}
let components = calendar.components(
[
.Year,
.Month,
.Day,
],
fromDate: date
)
return ISOFullDate(
year: components.year,
month: components.month,
day: components.day
)
}
/**
Converts a ISO-8601 full-date string to an ISOFullDate.
- parameter string: The ISO-8601 full-date format string to convert.
- returns: An ISOFullDate constructed from the string.
*/
public static func from(string string: String) -> ISOFullDate? {
let components = string
.characters
.split("-")
.map(String.init)
.flatMap { Int($0) }
guard components.count == 3 else { return nil }
return ISOFullDate(
year: components[0],
month: components[1],
day: components[2]
)
}
/**
Converts the receiver to an NSDate, in the default time zone.
- returns: An NSDate from the components of the receiver, in the default time zone.
*/
public func toDate() -> NSDate? {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
components.timeZone = NSTimeZone.defaultTimeZone()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
// MARK: CustomStringConvertible
public var description: String {
return "\(year)-\(month)-\(day)"
}
}
extension ISOFullDate: JSONEncodable {
public func encodeToJSON() -> AnyObject {
return "\(year)-\(month)-\(day)"
}
}

View File

@ -141,6 +141,15 @@ class Decoders {
fatalError("formatter failed to parse \(source)")
}
// Decoder for ISOFullDate
Decoders.addDecoder(clazz: ISOFullDate.self, decoder: { (source: AnyObject) -> ISOFullDate in
if let string = source as? String,
let isoDate = ISOFullDate.from(string: string) {
return isoDate
}
fatalError("formatter failed to parse \(source)")
})
// Decoder for [Category]
Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in
return Decoders.decode(clazz: [Category].self, source: source)
@ -215,6 +224,7 @@ class Decoders {
let instance = User()
instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"])
instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"])
instance.dateOfBirth = Decoders.decodeOptional(clazz: ISOFullDate.self, source: sourceDictionary["dateOfBirth"])
instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"])
instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"])
instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"])

View File

@ -11,6 +11,7 @@ import Foundation
public class User: JSONEncodable {
public var id: Int64?
public var username: String?
public var dateOfBirth: ISOFullDate?
public var firstName: String?
public var lastName: String?
public var email: String?
@ -26,6 +27,7 @@ public class User: JSONEncodable {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["username"] = self.username
nillableDictionary["dateOfBirth"] = self.dateOfBirth?.encodeToJSON()
nillableDictionary["firstName"] = self.firstName
nillableDictionary["lastName"] = self.lastName
nillableDictionary["email"] = self.email