Merge pull request #3850 from wing328/fix_swift_pod_file

[Swift] add default value to swift podspec
This commit is contained in:
wing328 2016-09-22 19:26:24 +08:00 committed by GitHub
commit e3b891a924
72 changed files with 2153 additions and 1578 deletions

View File

@ -1,21 +1,36 @@
Pod::Spec.new do |s| Pod::Spec.new do |s|
s.name = '{{projectName}}'{{#projectDescription}} s.name = '{{projectName}}'
s.summary = '{{projectDescription}}'{{/projectDescription}}
s.ios.deployment_target = '8.0' s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9' s.osx.deployment_target = '10.9'
s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}' s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}'
s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}} s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}
s.authors = '{{podAuthors}}'{{/podAuthors}}{{#podSocialMediaURL}} {{#podAuthors}}
s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}} s.authors = '{{podAuthors}}'
s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}} {{/podAuthors}}
s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}{{#podHomepage}} {{#podSocialMediaURL}}
s.homepage = '{{podHomepage}}'{{/podHomepage}}{{#podSummary}} s.social_media_url = '{{podSocialMediaURL}}'
s.summary = '{{podSummary}}'{{/podSummary}}{{#podDescription}} {{/podSocialMediaURL}}
s.description = '{{podDescription}}'{{/podDescription}}{{#podScreenshots}} {{#podDocsetURL}}
s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}} s.docset_url = '{{podDocsetURL}}'
s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} {{/podDocsetURL}}
s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}
s.dependency 'PromiseKit', '~> 3.1.1'{{/usePromiseKit}}{{#useRxSwift}} s.homepage = '{{podHomepage}}{{^podHomepage}}https://github.com/swagger-api/swagger-codegen{{/podHomepage}}'
s.dependency 'RxSwift', '~> 2.0'{{/useRxSwift}} s.summary = '{{podSummary}}{{^podSummary}}{{projectName}} Swift SDK{{/podSummary}}'
{{#podDescription}}
s.description = '{{podDescription}}'
{{/podDescription}}
{{#podScreenshots}}
s.screenshots = {{& podScreenshots}}
{{/podScreenshots}}
{{#podDocumentationURL}}
s.documentation_url = '{{podDocumentationURL}}'
{{/podDocumentationURL}}
s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'
{{#usePromiseKit}}
s.dependency 'PromiseKit', '~> 3.1.1'
{{/usePromiseKit}}
{{#useRxSwift}}
s.dependency 'RxSwift', '~> 2.0'
{{/useRxSwift}}
s.dependency 'Alamofire', '~> 3.4.1' s.dependency 'Alamofire', '~> 3.4.1'
end end

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: 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 ```swift
enum BackendError: ErrorType { public enum BackendError: ErrorType {
case Network(error: NSError) case Network(error: NSError)
case DataSerialization(reason: String) case DataSerialization(reason: String)
case JSONSerialization(error: NSError) 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 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 * 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> <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

@ -44,27 +44,19 @@ public protocol URLStringConvertible {
} }
extension String: URLStringConvertible { extension String: URLStringConvertible {
public var URLString: String { public var URLString: String { return self }
return self
}
} }
extension NSURL: URLStringConvertible { extension NSURL: URLStringConvertible {
public var URLString: String { public var URLString: String { return absoluteString }
return absoluteString
}
} }
extension NSURLComponents: URLStringConvertible { extension NSURLComponents: URLStringConvertible {
public var URLString: String { public var URLString: String { return URL!.URLString }
return URL!.URLString
}
} }
extension NSURLRequest: URLStringConvertible { extension NSURLRequest: URLStringConvertible {
public var URLString: String { public var URLString: String { return URL!.URLString }
return URL!.URLString
}
} }
// MARK: - URLRequestConvertible // MARK: - URLRequestConvertible
@ -78,9 +70,7 @@ public protocol URLRequestConvertible {
} }
extension NSURLRequest: URLRequestConvertible { extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSMutableURLRequest { public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest }
return self.mutableCopy() as! NSMutableURLRequest
}
} }
// MARK: - Convenience // MARK: - Convenience
@ -91,7 +81,16 @@ func URLRequest(
headers: [String: String]? = nil) headers: [String: String]? = nil)
-> NSMutableURLRequest -> 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 mutableURLRequest.HTTPMethod = method.rawValue
if let headers = headers { if let headers = headers {

View File

@ -60,7 +60,8 @@ public class Manager {
if let info = NSBundle.mainBundle().infoDictionary { if let info = NSBundle.mainBundle().infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey 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 osNameVersion: String = {
let versionString: String let versionString: String
@ -91,7 +92,7 @@ public class Manager {
return "\(osName) \(versionString)" return "\(osName) \(versionString)"
}() }()
return "\(executable)/\(bundle) (\(version); \(osNameVersion))" return "\(executable)/\(bundle) (\(appVersion)/\(appBuild)); \(osNameVersion))"
} }
return "Alamofire" return "Alamofire"

View File

@ -64,7 +64,7 @@ extension Manager {
- parameter hostName: The hostname of the server to connect to. - parameter hostName: The hostname of the server to connect to.
- parameter port: The port 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 { public func stream(hostName hostName: String, port: Int) -> Request {
return stream(.Stream(hostName, port)) return stream(.Stream(hostName, port))

View File

@ -140,7 +140,7 @@ extension Request {
- returns: The 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 return validate { _, response in
guard let validData = self.delegate.data where validData.length > 0 else { return .Success } guard let validData = self.delegate.data where validData.length > 0 else { return .Success }

View File

@ -1,5 +1,5 @@
PODS: PODS:
- Alamofire (3.4.1) - Alamofire (3.4.2)
- PetstoreClient (0.0.1): - PetstoreClient (0.0.1):
- Alamofire (~> 3.4.1) - Alamofire (~> 3.4.1)
@ -11,9 +11,9 @@ EXTERNAL SOURCES:
:path: "../" :path: "../"
SPEC CHECKSUMS: SPEC CHECKSUMS:
Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c Alamofire: 6aa33201d20d069e1598891cf928883ff1888c7a
PetstoreClient: 7489b461499be1b2c4e0ed6624ca76c8db506297 PetstoreClient: 7489b461499be1b2c4e0ed6624ca76c8db506297
PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94
COCOAPODS: 1.0.1 COCOAPODS: 1.0.0

View File

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

View File

@ -48,8 +48,8 @@ EOM
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;; ;;
*.xib) *.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}"
;; ;;
*.framework) *.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

View File

@ -48,8 +48,8 @@ EOM
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;; ;;
*.xib) *.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}"
;; ;;
*.framework) *.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

View File

@ -143,6 +143,7 @@
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */;
buildPhases = ( buildPhases = (
A16DAFA9EF474E5065B5B1C2 /* 📦 Check Pods Manifest.lock */,
CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */, CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */,
1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */,
6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8D1C692C6300B96B06 /* Sources */,
@ -166,6 +167,7 @@
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */;
buildPhases = ( buildPhases = (
FE27E864CEDDA2D12F7972B1 /* 📦 Check Pods Manifest.lock */,
B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */, B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */,
79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */,
6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA11C692C6300B96B06 /* Sources */,
@ -365,6 +367,21 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
A16DAFA9EF474E5065B5B1C2 /* 📦 Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Check Pods Manifest.lock";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */ = { B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
@ -425,6 +442,21 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
FE27E864CEDDA2D12F7972B1 /* 📦 Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Check Pods Manifest.lock";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */ /* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */

View File

@ -160,13 +160,13 @@ public class PetAPI: APIBase {
- OAuth: - OAuth:
- type: oauth2 - type: oauth2
- name: petstore_auth - name: petstore_auth
- examples: [{contentType=application/json, example={ - examples: [{example={
"name" : "Puma", "name" : "Puma",
"type" : "Dog", "type" : "Dog",
"color" : "Black", "color" : "Black",
"gender" : "Female", "gender" : "Female",
"breed" : "Mixed" "breed" : "Mixed"
}}] }, contentType=application/json}]
- parameter status: (query) Status values that need to be considered for filter (optional, default to available) - parameter status: (query) Status values that need to be considered for filter (optional, default to available)
@ -226,20 +226,20 @@ public class PetAPI: APIBase {
- OAuth: - OAuth:
- type: oauth2 - type: oauth2
- name: petstore_auth - name: petstore_auth
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], } ], contentType=application/json}, {example=<Pet>
"status" : "aeiou"
} ]}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -248,21 +248,21 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], } ], contentType=application/json}, {example=<Pet>
"status" : "aeiou"
} ]}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -271,7 +271,7 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- parameter tags: (query) Tags to filter by (optional) - parameter tags: (query) Tags to filter by (optional)
@ -328,26 +328,26 @@ public class PetAPI: APIBase {
Find pet by ID Find pet by ID
- GET /pet/{petId} - GET /pet/{petId}
- Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
- OAuth:
- type: oauth2
- name: petstore_auth
- API Key: - API Key:
- type: apiKey api_key - type: apiKey api_key
- name: api_key - name: api_key
- examples: [{contentType=application/json, example={ - OAuth:
"photoUrls" : [ "aeiou" ], - type: oauth2
"name" : "doggie", - name: petstore_auth
- examples: [{example={
"tags" : [ {
"id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], }, contentType=application/json}, {example=<Pet>
"status" : "aeiou"
}}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -356,21 +356,21 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], }, contentType=application/json}, {example=<Pet>
"status" : "aeiou"
}}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -379,7 +379,7 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- parameter petId: (path) ID of pet that needs to be fetched - parameter petId: (path) ID of pet that needs to be fetched

View File

@ -101,12 +101,12 @@ public class StoreAPI: APIBase {
- API Key: - API Key:
- type: apiKey api_key - type: apiKey api_key
- name: api_key - name: api_key
- examples: [{contentType=application/json, example={ - examples: [{example={
"key" : 123 "key" : 123
}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] }, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"key" : 123 "key" : 123
}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] }, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
- returns: RequestBuilder<[String:Int32]> - returns: RequestBuilder<[String:Int32]>
*/ */
@ -159,36 +159,36 @@ public class StoreAPI: APIBase {
Find purchase order by ID Find purchase order by ID
- GET /store/order/{orderId} - GET /store/order/{orderId}
- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- parameter orderId: (path) ID of pet that needs to be fetched - parameter orderId: (path) ID of pet that needs to be fetched
@ -244,36 +244,36 @@ public class StoreAPI: APIBase {
Place an order for a pet Place an order for a pet
- POST /store/order - POST /store/order
- -
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- parameter body: (body) order placed for purchasing the pet (optional) - parameter body: (body) order placed for purchasing the pet (optional)

View File

@ -253,16 +253,16 @@ public class UserAPI: APIBase {
Get user by user name Get user by user name
- GET /user/{username} - GET /user/{username}
- -
- examples: [{contentType=application/json, example={ - examples: [{example={
"firstName" : "aeiou",
"lastName" : "aeiou",
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
"id" : 123456789, "id" : 123456789,
"lastName" : "aeiou",
"phone" : "aeiou",
"username" : "aeiou",
"email" : "aeiou", "email" : "aeiou",
"username" : "aeiou" "userStatus" : 123,
}}, {contentType=application/xml, example=<User> "firstName" : "aeiou",
"password" : "aeiou"
}, contentType=application/json}, {example=<User>
<id>123456</id> <id>123456</id>
<username>string</username> <username>string</username>
<firstName>string</firstName> <firstName>string</firstName>
@ -271,17 +271,17 @@ public class UserAPI: APIBase {
<password>string</password> <password>string</password>
<phone>string</phone> <phone>string</phone>
<userStatus>0</userStatus> <userStatus>0</userStatus>
</User>}] </User>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"firstName" : "aeiou",
"lastName" : "aeiou",
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
"id" : 123456789, "id" : 123456789,
"lastName" : "aeiou",
"phone" : "aeiou",
"username" : "aeiou",
"email" : "aeiou", "email" : "aeiou",
"username" : "aeiou" "userStatus" : 123,
}}, {contentType=application/xml, example=<User> "firstName" : "aeiou",
"password" : "aeiou"
}, contentType=application/json}, {example=<User>
<id>123456</id> <id>123456</id>
<username>string</username> <username>string</username>
<firstName>string</firstName> <firstName>string</firstName>
@ -290,7 +290,7 @@ public class UserAPI: APIBase {
<password>string</password> <password>string</password>
<phone>string</phone> <phone>string</phone>
<userStatus>0</userStatus> <userStatus>0</userStatus>
</User>}] </User>, contentType=application/xml}]
- parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter username: (path) The name that needs to be fetched. Use user1 for testing.
@ -348,8 +348,8 @@ public class UserAPI: APIBase {
Logs user into the system Logs user into the system
- GET /user/login - GET /user/login
- -
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
- parameter username: (query) The user name for login (optional) - parameter username: (query) The user name for login (optional)
- parameter password: (query) The password for login in clear text (optional) - parameter password: (query) The password for login in clear text (optional)

View File

@ -10,5 +10,5 @@ Pod::Spec.new do |s|
s.summary = 'PetstoreClient' s.summary = 'PetstoreClient'
s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift'
s.dependency 'RxSwift', '~> 2.0' s.dependency 'RxSwift', '~> 2.0'
s.dependency 'Alamofire', '~> 3.1.5' s.dependency 'Alamofire', '~> 3.4.1'
end end

View File

@ -73,3 +73,4 @@ public class RequestBuilder<T> {
protocol RequestBuilderFactory { protocol RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type func getBuilder<T>() -> RequestBuilder<T>.Type
} }

View File

@ -63,7 +63,7 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
} }
self.processRequest(uploadRequest, managerId, completion) self.processRequest(uploadRequest, managerId, completion)
case .Failure(let encodingError): case .Failure(let encodingError):
completion(response: nil, error: encodingError) completion(response: nil, error: ErrorResponse.Error(415, nil, encodingError))
} }
} }
) )
@ -89,14 +89,54 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
let validatedRequest = request.validate() let validatedRequest = request.validate()
switch T.self { switch T.self {
case is String.Type:
validatedRequest.responseString(completionHandler: { (stringResponse) in
cleanupRequest()
if stringResponse.result.isFailure {
completion(
response: nil,
error: ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!)
)
return
}
completion(
response: Response(
response: stringResponse.response!,
body: (stringResponse.result.value ?? "") as! T
),
error: nil
)
})
case is Void.Type:
validatedRequest.responseData(completionHandler: { (voidResponse) in
cleanupRequest()
if voidResponse.result.isFailure {
completion(
response: nil,
error: ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!)
)
return
}
completion(
response: Response(
response: voidResponse.response!,
body: nil
),
error: nil
)
})
case is NSData.Type: case is NSData.Type:
validatedRequest.responseData({ (dataResponse) in validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest() cleanupRequest()
if (dataResponse.result.isFailure) { if (dataResponse.result.isFailure) {
completion( completion(
response: nil, response: nil,
error: dataResponse.result.error error: ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)
) )
return return
} }
@ -114,7 +154,7 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
cleanupRequest() cleanupRequest()
if response.result.isFailure { if response.result.isFailure {
completion(response: nil, error: response.result.error) completion(response: nil, error: ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!))
return return
} }
@ -133,7 +173,7 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
return return
} }
completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) completion(response: nil, error: ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])))
} }
} }
} }

View File

@ -82,3 +82,5 @@ extension NSUUID: JSONEncodable {
return self.UUIDString return self.UUIDString
} }
} }

View File

@ -10,18 +10,22 @@ protocol JSONEncodable {
func encodeToJSON() -> AnyObject func encodeToJSON() -> AnyObject
} }
public enum ErrorResponse : ErrorType {
case Error(Int, NSData?, ErrorType)
}
public class Response<T> { public class Response<T> {
public let statusCode: Int public let statusCode: Int
public let header: [String: String] public let header: [String: String]
public let body: T public let body: T?
public init(statusCode: Int, header: [String: String], body: T) { public init(statusCode: Int, header: [String: String], body: T?) {
self.statusCode = statusCode self.statusCode = statusCode
self.header = header self.header = header
self.body = body self.body = body
} }
public convenience init(response: NSHTTPURLResponse, body: T) { public convenience init(response: NSHTTPURLResponse, body: T?) {
let rawHeader = response.allHeaderFields let rawHeader = response.allHeaderFields
var header = [String:String]() var header = [String:String]()
for (key, value) in rawHeader { for (key, value) in rawHeader {

View File

@ -1,4 +1,4 @@
Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,7 +1,7 @@
![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png)
[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire)
[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) [![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire)
[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF)
@ -22,10 +22,17 @@ Alamofire is an HTTP networking library written in Swift.
- [x] Comprehensive Unit Test Coverage - [x] Comprehensive Unit Test Coverage
- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire)
## Component Libraries
In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem.
* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system.
* [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `NSURLSession` instances not managed by Alamofire.
## Requirements ## Requirements
- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ - iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 7.2+ - Xcode 7.3+
## Migration Guides ## Migration Guides
@ -60,10 +67,12 @@ To integrate Alamofire into your Xcode project using CocoaPods, specify it in yo
```ruby ```ruby
source 'https://github.com/CocoaPods/Specs.git' source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0' platform :ios, '9.0'
use_frameworks! use_frameworks!
pod 'Alamofire', '~> 3.0' target '<Your Target Name>' do
pod 'Alamofire', '~> 3.4'
end
``` ```
Then, run the following command: Then, run the following command:
@ -86,7 +95,7 @@ $ brew install carthage
To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl ```ogdl
github "Alamofire/Alamofire" ~> 3.0 github "Alamofire/Alamofire" ~> 3.4
``` ```
Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project.
@ -161,6 +170,38 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
> Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. > Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler.
### Validation
By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.
#### Manual Validation
```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { response in
print(response)
}
```
#### Automatic Validation
Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided.
```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
print("Validation Successful")
case .Failure(let error):
print(error)
}
}
```
### Response Serialization ### Response Serialization
**Built-in Response Methods** **Built-in Response Methods**
@ -175,6 +216,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.response { request, response, data, error in .response { request, response, data, error in
print(request) print(request)
print(response) print(response)
@ -183,12 +225,13 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
} }
``` ```
> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other responser serializers taking advantage of `Response` and `Result` types. > The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types.
#### Response Data Handler #### Response Data Handler
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseData { response in .responseData { response in
print(response.request) print(response.request)
print(response.response) print(response.response)
@ -200,6 +243,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get") Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseString { response in .responseString { response in
print("Success: \(response.result.isSuccess)") print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)") print("Response String: \(response.result.value)")
@ -210,6 +254,7 @@ Alamofire.request(.GET, "https://httpbin.org/get")
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get") Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseJSON { response in .responseJSON { response in
debugPrint(response) debugPrint(response)
} }
@ -221,6 +266,7 @@ Response handlers can even be chained:
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get") Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseString { response in .responseString { response in
print("Response String: \(response.result.value)") print("Response String: \(response.result.value)")
} }
@ -332,7 +378,7 @@ Adding a custom HTTP header to a `Request` is supported directly in the global `
```swift ```swift
let headers = [ let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Content-Type": "application/x-www-form-urlencoded" "Accept": "application/json"
] ]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
@ -374,6 +420,7 @@ Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
print("Total bytes written on main queue: \(totalBytesWritten)") print("Total bytes written on main queue: \(totalBytesWritten)")
} }
} }
.validate()
.responseJSON { response in .responseJSON { response in
debugPrint(response) debugPrint(response)
} }
@ -540,38 +587,25 @@ Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
} }
``` ```
### Validation ### Timeline
By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`.
#### Manual Validation
```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { response in
print(response)
}
```
#### Automatic Validation
Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided.
```swift ```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate() .validate()
.responseJSON { response in .responseJSON { response in
switch response.result { print(response.timeline)
case .Success:
print("Validation Successful")
case .Failure(let error):
print(error)
}
} }
``` ```
The above reports the following `Timeline` info:
- `Latency`: 0.428 seconds
- `Request Duration`: 0.428 seconds
- `Serialization Duration`: 0.001 seconds
- `Total Duration`: 0.429 seconds
### Printable ### Printable
```swift ```swift
@ -679,6 +713,20 @@ Requests can be suspended, resumed, and cancelled:
### Response Serialization ### Response Serialization
#### Handling Errors
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
public enum BackendError: ErrorType {
case Network(error: NSError)
case DataSerialization(reason: String)
case JSONSerialization(error: NSError)
case ObjectSerialization(reason: String)
case XMLSerialization(error: NSError)
}
```
#### Creating a Custom Response Serializer #### Creating a Custom Response Serializer
Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`.
@ -687,26 +735,24 @@ For example, here's how a response handler using [Ono](https://github.com/mattt/
```swift ```swift
extension Request { extension Request {
public static func XMLResponseSerializer() -> ResponseSerializer<ONOXMLDocument, NSError> { public static func XMLResponseSerializer() -> ResponseSerializer<ONOXMLDocument, BackendError> {
return ResponseSerializer { request, response, data, error in return ResponseSerializer { request, response, data, error in
guard error == nil else { return .Failure(error!) } guard error == nil else { return .Failure(.Network(error: error!)) }
guard let validData = data else { guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil." return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil."))
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
} }
do { do {
let XML = try ONOXMLDocument(data: validData) let XML = try ONOXMLDocument(data: validData)
return .Success(XML) return .Success(XML)
} catch { } catch {
return .Failure(error as NSError) return .Failure(.XMLSerialization(error: error as NSError))
} }
} }
} }
public func responseXMLDocument(completionHandler: Response<ONOXMLDocument, NSError> -> Void) -> Self { public func responseXMLDocument(completionHandler: Response<ONOXMLDocument, BackendError> -> Void) -> Self {
return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler)
} }
} }
@ -722,9 +768,9 @@ public protocol ResponseObjectSerializable {
} }
extension Request { extension Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self { public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, BackendError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in let responseSerializer = ResponseSerializer<T, BackendError> { request, response, data, error in
guard error == nil else { return .Failure(error!) } guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error) let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
@ -737,12 +783,10 @@ extension Request {
{ {
return .Success(responseObject) return .Success(responseObject)
} else { } else {
let failureReason = "JSON could not be serialized into response object: \(value)" return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)"))
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
} }
case .Failure(let error): case .Failure(let error):
return .Failure(error) return .Failure(.JSONSerialization(error: error))
} }
} }
@ -765,7 +809,7 @@ final class User: ResponseObjectSerializable {
```swift ```swift
Alamofire.request(.GET, "https://example.com/users/mattt") Alamofire.request(.GET, "https://example.com/users/mattt")
.responseObject { (response: Response<User, NSError>) in .responseObject { (response: Response<User, BackendError>) in
debugPrint(response) debugPrint(response)
} }
``` ```
@ -777,10 +821,26 @@ public protocol ResponseCollectionSerializable {
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
} }
extension ResponseCollectionSerializable where Self: ResponseObjectSerializable {
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] {
var collection = [Self]()
if let representation = representation as? [[String: AnyObject]] {
for itemRepresentation in representation {
if let item = Self(response: response, representation: itemRepresentation) {
collection.append(item)
}
}
}
return collection
}
}
extension Alamofire.Request { extension Alamofire.Request {
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self { public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], BackendError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in
guard error == nil else { return .Failure(error!) } guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONSerializer.serializeResponse(request, response, data, error) let result = JSONSerializer.serializeResponse(request, response, data, error)
@ -790,12 +850,10 @@ extension Alamofire.Request {
if let response = response { if let response = response {
return .Success(T.collection(response: response, representation: value)) return .Success(T.collection(response: response, representation: value))
} else { } else {
let failureReason = "Response collection could not be serialized due to nil response" return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response"))
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
} }
case .Failure(let error): case .Failure(let error):
return .Failure(error) return .Failure(.JSONSerialization(error: error))
} }
} }
@ -813,26 +871,12 @@ final class User: ResponseObjectSerializable, ResponseCollectionSerializable {
self.username = response.URL!.lastPathComponent! self.username = response.URL!.lastPathComponent!
self.name = representation.valueForKeyPath("name") as! String self.name = representation.valueForKeyPath("name") as! String
} }
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] {
var users: [User] = []
if let representation = representation as? [[String: AnyObject]] {
for userRepresentation in representation {
if let user = User(response: response, representation: userRepresentation) {
users.append(user)
}
}
}
return users
}
} }
``` ```
```swift ```swift
Alamofire.request(.GET, "http://example.com/users") Alamofire.request(.GET, "http://example.com/users")
.responseCollection { (response: Response<[User], NSError>) in .responseCollection { (response: Response<[User], BackendError>) in
debugPrint(response) debugPrint(response)
} }
``` ```
@ -912,7 +956,7 @@ enum Router: URLRequestConvertible {
var URLRequest: NSMutableURLRequest { var URLRequest: NSMutableURLRequest {
let result: (path: String, parameters: [String: AnyObject]) = { let result: (path: String, parameters: [String: AnyObject]) = {
switch self { switch self {
case .Search(let query, let page) where page > 1: case .Search(let query, let page) where page > 0:
return ("/search", ["q": query, "offset": Router.perPage * page]) return ("/search", ["q": query, "offset": Router.perPage * page])
case .Search(let query, _): case .Search(let query, _):
return ("/search", ["q": query]) return ("/search", ["q": query])
@ -997,6 +1041,74 @@ enum Router: URLRequestConvertible {
Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt
``` ```
### SessionDelegate
By default, an Alamofire `Manager` instance creates an internal `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `NSURLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons.
#### Override Closures
The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available:
```swift
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
```
The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains.
```swift
let delegate: Alamofire.Manager.SessionDelegate = manager.delegate
delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
var finalRequest = request
if let originalRequest = task.originalRequest where originalRequest.URLString.containsString("apple.com") {
finalRequest = originalRequest
}
return finalRequest
}
```
#### Subclassing
Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs.
```swift
class LoggingSessionDelegate: Manager.SessionDelegate {
override func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: NSURLRequest? -> Void)
{
print("URLSession will perform HTTP redirection to request: \(request)")
super.URLSession(
session,
task: task,
willPerformHTTPRedirection: response,
newRequest: request,
completionHandler: completionHandler
)
}
}
```
Generally, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort.
> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks.
### Security ### Security
Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`.
@ -1075,7 +1187,7 @@ The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server
#### Validating the Certificate Chain #### Validating the Certificate Chain
Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check.
There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server.
@ -1114,19 +1226,41 @@ Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends
> It is recommended to always use valid certificates in production environments. > It is recommended to always use valid certificates in production environments.
### Network Reachability
The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces.
```swift
let manager = NetworkReachabilityManager(host: "www.apple.com")
manager?.listener = { status in
print("Network Status Changed: \(status)")
}
manager?.startListening()
```
> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported.
There are some important things to remember when using network reachability to determine what to do next.
* **Do NOT** use Reachability to determine if a network request should be sent.
* You should **ALWAYS** send it.
* When Reachability is restored, use the event to retry failed network requests.
* Even though the network requests may still fail, this is a good moment to retry them.
* The network reachability status can be useful for determining why a network request may have failed.
* If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out."
> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info.
--- ---
## Component Libraries
In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem.
* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system.
## Open Rdars ## Open Rdars
The following rdars have some affect on the current implementation of Alamofire. The following rdars have some affect on the current implementation of Alamofire.
* [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case * [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case
* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage
## FAQ ## FAQ
@ -1144,6 +1278,20 @@ Alamofire is owned and maintained by the [Alamofire Software Foundation](http://
If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
## Donations
The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to:
* Pay our legal fees to register as a federal non-profit organization
* Pay our yearly legal fees to keep the non-profit in good status
* Pay for our mail servers to help us stay on top of all questions and security issues
* 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 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>
## License ## License
Alamofire is released under the MIT license. See LICENSE for details. Alamofire is released under the MIT license. See LICENSE for details.

View File

@ -1,6 +1,7 @@
//
// Alamofire.swift // Alamofire.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -42,27 +44,19 @@ public protocol URLStringConvertible {
} }
extension String: URLStringConvertible { extension String: URLStringConvertible {
public var URLString: String { public var URLString: String { return self }
return self
}
} }
extension NSURL: URLStringConvertible { extension NSURL: URLStringConvertible {
public var URLString: String { public var URLString: String { return absoluteString }
return absoluteString
}
} }
extension NSURLComponents: URLStringConvertible { extension NSURLComponents: URLStringConvertible {
public var URLString: String { public var URLString: String { return URL!.URLString }
return URL!.URLString
}
} }
extension NSURLRequest: URLStringConvertible { extension NSURLRequest: URLStringConvertible {
public var URLString: String { public var URLString: String { return URL!.URLString }
return URL!.URLString
}
} }
// MARK: - URLRequestConvertible // MARK: - URLRequestConvertible
@ -76,9 +70,7 @@ public protocol URLRequestConvertible {
} }
extension NSURLRequest: URLRequestConvertible { extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSMutableURLRequest { public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest }
return self.mutableCopy() as! NSMutableURLRequest
}
} }
// MARK: - Convenience // MARK: - Convenience
@ -89,7 +81,16 @@ func URLRequest(
headers: [String: String]? = nil) headers: [String: String]? = nil)
-> NSMutableURLRequest -> 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 mutableURLRequest.HTTPMethod = method.rawValue
if let headers = headers { if let headers = headers {

View File

@ -1,6 +1,7 @@
//
// Download.swift // Download.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -211,6 +213,8 @@ extension Request {
totalBytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) totalBytesExpectedToWrite: Int64)
{ {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData { if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData( downloadTaskDidWriteData(
session, session,

View File

@ -1,6 +1,7 @@
//
// Error.swift // Error.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -39,6 +41,15 @@ public struct Error {
case PropertyListSerializationFailed = -6007 case PropertyListSerializationFailed = -6007
} }
/// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire.
public struct UserInfoKeys {
/// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value.
public static let ContentType = "ContentType"
/// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value.
public static let StatusCode = "StatusCode"
}
/** /**
Creates an `NSError` with the given error code and failure reason. Creates an `NSError` with the given error code and failure reason.
@ -47,6 +58,7 @@ public struct Error {
- returns: An `NSError` with the given error code and failure reason. - returns: An `NSError` with the given error code and failure reason.
*/ */
@available(*, deprecated=3.4.0)
public static func errorWithCode(code: Code, failureReason: String) -> NSError { public static func errorWithCode(code: Code, failureReason: String) -> NSError {
return errorWithCode(code.rawValue, failureReason: failureReason) return errorWithCode(code.rawValue, failureReason: failureReason)
} }
@ -59,8 +71,18 @@ public struct Error {
- returns: An `NSError` with the given error code and failure reason. - returns: An `NSError` with the given error code and failure reason.
*/ */
@available(*, deprecated=3.4.0)
public static func errorWithCode(code: Int, failureReason: String) -> NSError { public static func errorWithCode(code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: Domain, code: code, userInfo: userInfo) return NSError(domain: Domain, code: code, userInfo: userInfo)
} }
static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError {
return error(domain: domain, code: code.rawValue, failureReason: failureReason)
}
static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: domain, code: code, userInfo: userInfo)
}
} }

View File

@ -1,6 +1,7 @@
//
// Manager.swift // Manager.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -56,17 +58,41 @@ public class Manager {
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = { let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary { if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString let osNameVersion: String = {
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString let versionString: String
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) { if #available(OSX 10.10, *) {
return mutableUserAgent as String let version = NSProcessInfo.processInfo().operatingSystemVersion
versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
} else {
versionString = "10.9"
} }
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(OSX)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
return "\(executable)/\(bundle) (\(appVersion)/\(appBuild)); \(osNameVersion))"
} }
return "Alamofire" return "Alamofire"
@ -143,11 +169,11 @@ public class Manager {
delegate: SessionDelegate, delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil) serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{ {
guard delegate === session.delegate else { return nil }
self.delegate = delegate self.delegate = delegate
self.session = session self.session = session
guard delegate === session.delegate else { return nil }
commonInit(serverTrustPolicyManager: serverTrustPolicyManager) commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
} }
@ -218,18 +244,18 @@ public class Manager {
/** /**
Responsible for handling all delegate callbacks for the underlying session. Responsible for handling all delegate callbacks for the underlying session.
*/ */
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:] private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { /// Access the task delegate for the specified task in a thread-safe manner.
public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get { get {
var subdelegate: Request.TaskDelegate? var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate return subdelegate
} }
set { set {
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
} }
@ -254,6 +280,9 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
@ -281,6 +310,11 @@ public class Manager {
didReceiveChallenge challenge: NSURLAuthenticationChallenge, didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{ {
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential? var credential: NSURLCredential?
@ -321,11 +355,23 @@ public class Manager {
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// 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:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
/// 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)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
@ -351,8 +397,13 @@ public class Manager {
task: NSURLSessionTask, task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse, willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest, newRequest request: NSURLRequest,
completionHandler: ((NSURLRequest?) -> Void)) completionHandler: NSURLRequest? -> Void)
{ {
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: NSURLRequest? = request var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
@ -374,10 +425,16 @@ public class Manager {
session: NSURLSession, session: NSURLSession,
task: NSURLSessionTask, task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge, didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
{ {
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge { if let taskDidReceiveChallenge = taskDidReceiveChallenge {
completionHandler(taskDidReceiveChallenge(session, task, challenge)) let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task] { } else if let delegate = self[task] {
delegate.URLSession( delegate.URLSession(
session, session,
@ -400,8 +457,13 @@ public class Manager {
public func URLSession( public func URLSession(
session: NSURLSession, session: NSURLSession,
task: NSURLSessionTask, task: NSURLSessionTask,
needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) needNewBodyStream completionHandler: NSInputStream? -> Void)
{ {
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream { if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task)) completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] { } else if let delegate = self[task] {
@ -452,6 +514,8 @@ public class Manager {
delegate.URLSession(session, task: task, didCompleteWithError: error) delegate.URLSession(session, task: task, didCompleteWithError: error)
} }
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
self[task] = nil self[task] = nil
} }
@ -462,6 +526,10 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// 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)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
@ -469,7 +537,11 @@ public class Manager {
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
/// 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)?
// MARK: Delegate Methods // MARK: Delegate Methods
@ -487,8 +559,13 @@ public class Manager {
session: NSURLSession, session: NSURLSession,
dataTask: NSURLSessionDataTask, dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse, didReceiveResponse response: NSURLResponse,
completionHandler: ((NSURLSessionResponseDisposition) -> Void)) completionHandler: NSURLSessionResponseDisposition -> Void)
{ {
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: NSURLSessionResponseDisposition = .Allow var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
@ -550,8 +627,13 @@ public class Manager {
session: NSURLSession, session: NSURLSession,
dataTask: NSURLSessionDataTask, dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse, willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: ((NSCachedURLResponse?) -> Void)) completionHandler: NSCachedURLResponse? -> Void)
{ {
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate { } else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
@ -674,17 +756,21 @@ public class Manager {
// MARK: - NSObject // MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool { public override func respondsToSelector(selector: Selector) -> Bool {
switch selector { #if !os(OSX)
case "URLSession:didBecomeInvalidWithError:": if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
return sessionDidBecomeInvalidWithError != nil
case "URLSession:didReceiveChallenge:completionHandler:":
return sessionDidReceiveChallenge != nil
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return sessionDidFinishEventsForBackgroundURLSession != nil return sessionDidFinishEventsForBackgroundURLSession != nil
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": }
return taskWillPerformHTTPRedirection != nil #endif
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return dataTaskDidReceiveResponse != nil switch selector {
case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default: default:
return self.dynamicType.instancesRespondToSelector(selector) return self.dynamicType.instancesRespondToSelector(selector)
} }

View File

@ -1,6 +1,7 @@
//
// MultipartFormData.swift // MultipartFormData.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -217,7 +219,7 @@ public class MultipartFormData {
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else { } else {
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
} }
} }
@ -245,8 +247,7 @@ public class MultipartFormData {
guard fileURL.fileURL else { guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)" let failureReason = "The file URL does not point to a file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -261,8 +262,7 @@ public class MultipartFormData {
} }
guard isReachable else { guard isReachable else {
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
setBodyPartError(error)
return return
} }
@ -277,8 +277,7 @@ public class MultipartFormData {
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
{ {
let failureReason = "The file URL is a directory, not a file: \(fileURL)" let failureReason = "The file URL is a directory, not a file: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -301,8 +300,7 @@ public class MultipartFormData {
guard let length = bodyContentLength else { guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -312,8 +310,7 @@ public class MultipartFormData {
guard let stream = NSInputStream(URL: fileURL) else { guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
setBodyPartError(error)
return return
} }
@ -413,10 +410,10 @@ public class MultipartFormData {
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)" let failureReason = "A file already exists at the given file URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL { } else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)" let failureReason = "The URL does not point to a valid file: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} }
let outputStream: NSOutputStream let outputStream: NSOutputStream
@ -425,10 +422,9 @@ public class MultipartFormData {
outputStream = possibleOutputStream outputStream = possibleOutputStream
} else { } else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason)
} }
outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream.open() outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.first?.hasInitialBoundary = true
@ -439,7 +435,6 @@ public class MultipartFormData {
} }
outputStream.close() outputStream.close()
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
} }
// MARK: - Private - Body Part Encoding // MARK: - Private - Body Part Encoding
@ -476,7 +471,6 @@ public class MultipartFormData {
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open() inputStream.open()
var error: NSError? var error: NSError?
@ -495,7 +489,7 @@ public class MultipartFormData {
encoded.appendBytes(buffer, length: bytesRead) encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 { } else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)" let failureReason = "Failed to read from input stream: \(inputStream)"
error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
break break
} else { } else {
break break
@ -503,7 +497,6 @@ public class MultipartFormData {
} }
inputStream.close() inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
if let error = error { if let error = error {
throw error throw error
@ -537,7 +530,6 @@ public class MultipartFormData {
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open() inputStream.open()
while inputStream.hasBytesAvailable { while inputStream.hasBytesAvailable {
@ -556,14 +548,13 @@ public class MultipartFormData {
try writeBuffer(&buffer, toOutputStream: outputStream) try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 { } else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)" let failureReason = "Failed to read from input stream: \(inputStream)"
throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
} else { } else {
break break
} }
} }
inputStream.close() inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
} }
private func writeFinalBoundaryDataForBodyPart( private func writeFinalBoundaryDataForBodyPart(
@ -598,7 +589,7 @@ public class MultipartFormData {
if bytesWritten < 0 { if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)" let failureReason = "Failed to write to output stream: \(outputStream)"
throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason)
} }
bytesToWrite -= bytesWritten bytesToWrite -= bytesWritten
@ -661,9 +652,8 @@ public class MultipartFormData {
// MARK: - Private - Errors // MARK: - Private - Errors
private func setBodyPartError(error: NSError) { private func setBodyPartError(code code: Int, failureReason: String) {
if bodyPartError == nil { guard bodyPartError == nil else { return }
bodyPartError = error bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
}
} }
} }

View File

@ -1,6 +1,7 @@
//
// ParameterEncoding.swift // ParameterEncoding.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -69,8 +71,8 @@ public enum ParameterEncoding {
/** /**
Creates a URL request by encoding parameters and applying them onto an existing request. Creates a URL request by encoding parameters and applying them onto an existing request.
- parameter URLRequest: The request to have parameters applied - parameter URLRequest: The request to have parameters applied.
- parameter parameters: The parameters to apply - 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. if any.
@ -82,9 +84,7 @@ public enum ParameterEncoding {
{ {
var mutableURLRequest = URLRequest.URLRequest var mutableURLRequest = URLRequest.URLRequest
guard let parameters = parameters where !parameters.isEmpty else { guard let parameters = parameters else { return (mutableURLRequest, nil) }
return (mutableURLRequest, nil)
}
var encodingError: NSError? = nil var encodingError: NSError? = nil
@ -118,7 +118,10 @@ public enum ParameterEncoding {
} }
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { if let
URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false)
where !parameters.isEmpty
{
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
URLComponents.percentEncodedQuery = percentEncodedQuery URLComponents.percentEncodedQuery = percentEncodedQuery
mutableURLRequest.URL = URLComponents.URL mutableURLRequest.URL = URLComponents.URL
@ -141,7 +144,10 @@ public enum ParameterEncoding {
let options = NSJSONWritingOptions() let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = data mutableURLRequest.HTTPBody = data
} catch { } catch {
encodingError = error as NSError encodingError = error as NSError
@ -153,7 +159,11 @@ public enum ParameterEncoding {
format: format, format: format,
options: options options: options
) )
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = data mutableURLRequest.HTTPBody = data
} catch { } catch {
encodingError = error as NSError encodingError = error as NSError
@ -219,7 +229,7 @@ public enum ParameterEncoding {
//========================================================================================================== //==========================================================================================================
// //
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to: // info, please refer to:
// //
@ -236,7 +246,7 @@ public enum ParameterEncoding {
while index != string.endIndex { while index != string.endIndex {
let startIndex = index let startIndex = index
let endIndex = index.advancedBy(batchSize, limit: string.endIndex) let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
let range = Range(start: startIndex, end: endIndex) let range = startIndex..<endIndex
let substring = string.substringWithRange(range) let substring = string.substringWithRange(range)

View File

@ -1,6 +1,7 @@
//
// Request.swift // Request.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -48,6 +50,9 @@ public class Request {
/// The progress of the request lifecycle. /// The progress of the request lifecycle.
public var progress: NSProgress { return delegate.progress } public var progress: NSProgress { return delegate.progress }
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
// MARK: - Lifecycle // MARK: - Lifecycle
init(session: NSURLSession, task: NSURLSessionTask) { init(session: NSURLSession, task: NSURLSessionTask) {
@ -55,14 +60,16 @@ public class Request {
switch task { switch task {
case is NSURLSessionUploadTask: case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task) delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask: case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task) delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask: case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task) delegate = DownloadTaskDelegate(task: task)
default: default:
self.delegate = TaskDelegate(task: task) delegate = TaskDelegate(task: task)
} }
delegate.queue.addOperationWithBlock { self.endTime = CFAbsoluteTimeGetCurrent() }
} }
// MARK: - Authentication // MARK: - Authentication
@ -100,6 +107,22 @@ public class Request {
return self return self
} }
/**
Returns a base64 encoded basic authentication credential as an authorization header dictionary.
- parameter user: The user.
- parameter password: The password.
- returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails.
*/
public static func authorizationHeader(user user: String, password: String) -> [String: String] {
guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] }
let credential = data.base64EncodedStringWithOptions([])
return ["Authorization": "Basic \(credential)"]
}
// MARK: - Progress // MARK: - Progress
/** /**
@ -148,18 +171,22 @@ public class Request {
// MARK: - State // MARK: - State
/**
Resumes the request.
*/
public func resume() {
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task)
}
/** /**
Suspends the request. Suspends the request.
*/ */
public func suspend() { public func suspend() {
task.suspend() task.suspend()
} NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task)
/**
Resumes the request.
*/
public func resume() {
task.resume()
} }
/** /**
@ -176,6 +203,8 @@ public class Request {
} else { } else {
task.cancel() task.cancel()
} }
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task)
} }
// MARK: - TaskDelegate // MARK: - TaskDelegate
@ -195,6 +224,7 @@ public class Request {
var data: NSData? { return nil } var data: NSData? { return nil }
var error: NSError? var error: NSError?
var initialResponseTime: CFAbsoluteTime?
var credential: NSURLCredential? var credential: NSURLCredential?
init(task: NSURLSessionTask) { init(task: NSURLSessionTask) {
@ -272,7 +302,7 @@ public class Request {
} }
} else { } else {
if challenge.previousFailureCount > 0 { if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge disposition = .RejectProtectionSpace
} else { } else {
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
@ -381,6 +411,8 @@ public class Request {
} }
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData { if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data) dataTaskDidReceiveData(session, dataTask, data)
} else { } else {
@ -470,7 +502,7 @@ extension Request: CustomDebugStringConvertible {
let protectionSpace = NSURLProtectionSpace( let protectionSpace = NSURLProtectionSpace(
host: host, host: host,
port: URL.port?.integerValue ?? 0, port: URL.port?.integerValue ?? 0,
`protocol`: URL.scheme, protocol: URL.scheme,
realm: host, realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic authenticationMethod: NSURLAuthenticationMethodHTTPBasic
) )
@ -496,33 +528,31 @@ extension Request: CustomDebugStringConvertible {
} }
} }
if let headerFields = request.allHTTPHeaderFields { var headers: [NSObject: AnyObject] = [:]
for (field, value) in headerFields {
switch field { if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
case "Cookie": for (field, value) in additionalHeaders where field != "Cookie" {
continue headers[field] = value
default:
components.append("-H \"\(field): \(value)\"")
}
} }
} }
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { if let headerFields = request.allHTTPHeaderFields {
for (field, value) in additionalHeaders { for (field, value) in headerFields where field != "Cookie" {
switch field { headers[field] = value
case "Cookie": }
continue }
default:
for (field, value) in headers {
components.append("-H \"\(field): \(value)\"") components.append("-H \"\(field): \(value)\"")
} }
}
}
if let if let
HTTPBodyData = request.HTTPBody, HTTPBodyData = request.HTTPBody,
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
{ {
let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"")
escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
components.append("-d \"\(escapedBody)\"") components.append("-d \"\(escapedBody)\"")
} }

View File

@ -1,6 +1,7 @@
//
// Response.swift // Response.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -36,6 +38,9 @@ public struct Response<Value, Error: ErrorType> {
/// The result of response serialization. /// The result of response serialization.
public let result: Result<Value, Error> public let result: Result<Value, Error>
/// The timeline of the complete lifecycle of the `Request`.
public let timeline: Timeline
/** /**
Initializes the `Response` instance with the specified URL request, URL response, server data and response Initializes the `Response` instance with the specified URL request, URL response, server data and response
serialization result. serialization result.
@ -44,14 +49,22 @@ public struct Response<Value, Error: ErrorType> {
- parameter response: The server's response to the URL request. - parameter response: The server's response to the URL request.
- parameter data: The data returned by the server. - parameter data: The data returned by the server.
- parameter result: The result of response serialization. - parameter result: The result of response serialization.
- parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
- returns: the new `Response` instance. - returns: the new `Response` instance.
*/ */
public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>) { public init(
request: NSURLRequest?,
response: NSHTTPURLResponse?,
data: NSData?,
result: Result<Value, Error>,
timeline: Timeline = Timeline())
{
self.request = request self.request = request
self.response = response self.response = response
self.data = data self.data = data
self.result = result self.result = result
self.timeline = timeline
} }
} }
@ -77,6 +90,7 @@ extension Response: CustomDebugStringConvertible {
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[Data]: \(data?.length ?? 0) bytes") output.append("[Data]: \(data?.length ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)") output.append("[Result]: \(result.debugDescription)")
output.append("[Timeline]: \(timeline.debugDescription)")
return output.joinWithSeparator("\n") return output.joinWithSeparator("\n")
} }

View File

@ -1,6 +1,7 @@
//
// ResponseSerialization.swift // ResponseSerialization.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -29,10 +31,10 @@ import Foundation
*/ */
public protocol ResponseSerializerType { public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`. /// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject associatedtype SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails. /// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType associatedtype ErrorObject: ErrorType
/** /**
A closure used by response handlers that takes a request, response, data and error and returns a result. A closure used by response handlers that takes a request, response, data and error and returns a result.
@ -119,16 +121,25 @@ extension Request {
self.delegate.error self.delegate.error
) )
dispatch_async(queue ?? dispatch_get_main_queue()) { let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
let timeline = Timeline(
requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
initialResponseTime: initialResponseTime,
requestCompletedTime: requestCompletedTime,
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
)
let response = Response<T.SerializedObject, T.ErrorObject>( let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request, request: self.request,
response: self.response, response: self.response,
data: self.delegate.data, data: self.delegate.data,
result: result result: result,
timeline: timeline
) )
completionHandler(response) dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) }
}
} }
return self return self
@ -152,7 +163,7 @@ extension Request {
guard let validData = data else { guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil." let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
@ -167,8 +178,12 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self { public func responseData(
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) queue queue: dispatch_queue_t? = nil,
completionHandler: Response<NSData, NSError> -> Void)
-> Self
{
return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
} }
} }
@ -186,7 +201,7 @@ extension Request {
- returns: A string response serializer. - returns: A string response serializer.
*/ */
public static func stringResponseSerializer( public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil) encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError> -> ResponseSerializer<String, NSError>
{ {
return ResponseSerializer { _, response, data, error in return ResponseSerializer { _, response, data, error in
@ -196,23 +211,25 @@ extension Request {
guard let validData = data else { guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil." let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
if let encodingName = response?.textEncodingName where encoding == nil { var convertedEncoding = encoding
encoding = CFStringConvertEncodingToNSStringEncoding(
if let encodingName = response?.textEncodingName where convertedEncoding == nil {
convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName) CFStringConvertIANACharSetNameToEncoding(encodingName)
) )
} }
let actualEncoding = encoding ?? NSISOLatin1StringEncoding let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) { if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string) return .Success(string)
} else { } else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)" let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
} }
@ -229,11 +246,13 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responseString( public func responseString(
encoding encoding: NSStringEncoding? = nil, queue queue: dispatch_queue_t? = nil,
encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void) completionHandler: Response<String, NSError> -> Void)
-> Self -> Self
{ {
return response( return response(
queue: queue,
responseSerializer: Request.stringResponseSerializer(encoding: encoding), responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler completionHandler: completionHandler
) )
@ -263,7 +282,7 @@ extension Request {
guard let validData = data where validData.length > 0 else { guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length." let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
@ -285,11 +304,13 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responseJSON( public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments, queue queue: dispatch_queue_t? = nil,
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void) completionHandler: Response<AnyObject, NSError> -> Void)
-> Self -> Self
{ {
return response( return response(
queue: queue,
responseSerializer: Request.JSONResponseSerializer(options: options), responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler completionHandler: completionHandler
) )
@ -319,7 +340,7 @@ extension Request {
guard let validData = data where validData.length > 0 else { guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length." let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error) return .Failure(error)
} }
@ -343,11 +364,13 @@ extension Request {
- returns: The request. - returns: The request.
*/ */
public func responsePropertyList( public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), queue queue: dispatch_queue_t? = nil,
options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void) completionHandler: Response<AnyObject, NSError> -> Void)
-> Self -> Self
{ {
return response( return response(
queue: queue,
responseSerializer: Request.propertyListResponseSerializer(options: options), responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler completionHandler: completionHandler
) )

View File

@ -1,6 +1,7 @@
//
// Result.swift // Result.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation

View File

@ -1,6 +1,7 @@
//
// ServerTrustPolicy.swift // ServerTrustPolicy.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation

View File

@ -1,6 +1,7 @@
//
// Stream.swift // Stream.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,12 +20,13 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
#if !os(watchOS) #if !os(watchOS)
@available(iOS 9.0, OSX 10.11, *) @available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager { extension Manager {
private enum Streamable { private enum Streamable {
case Stream(String, Int) case Stream(String, Int)
@ -62,7 +64,7 @@ extension Manager {
- parameter hostName: The hostname of the server to connect to. - parameter hostName: The hostname of the server to connect to.
- parameter port: The port 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 { public func stream(hostName hostName: String, port: Int) -> Request {
return stream(.Stream(hostName, port)) return stream(.Stream(hostName, port))
@ -82,7 +84,7 @@ extension Manager {
// MARK: - // MARK: -
@available(iOS 9.0, OSX 10.11, *) @available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager.SessionDelegate: NSURLSessionStreamDelegate { extension Manager.SessionDelegate: NSURLSessionStreamDelegate {
// MARK: Override Closures // MARK: Override Closures

View File

@ -1,6 +1,7 @@
//
// Upload.swift // Upload.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -359,6 +361,8 @@ extension Request {
totalBytesSent: Int64, totalBytesSent: Int64,
totalBytesExpectedToSend: Int64) totalBytesExpectedToSend: Int64)
{ {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData { if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else { } else {

View File

@ -1,6 +1,7 @@
//
// Validation.swift // Validation.swift
// //
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -19,6 +20,7 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
//
import Foundation import Foundation
@ -80,7 +82,17 @@ extension Request {
return .Success return .Success
} else { } else {
let failureReason = "Response status code was unacceptable: \(response.statusCode)" let failureReason = "Response status code was unacceptable: \(response.statusCode)"
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
let error = NSError(
domain: Error.Domain,
code: Error.Code.StatusCodeValidationFailed.rawValue,
userInfo: [
NSLocalizedFailureReasonErrorKey: failureReason,
Error.UserInfoKeys.StatusCode: response.statusCode
]
)
return .Failure(error)
} }
} }
} }
@ -128,7 +140,7 @@ extension Request {
- returns: The 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 return validate { _, response in
guard let validData = self.delegate.data where validData.length > 0 else { return .Success } guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
@ -149,18 +161,31 @@ extension Request {
} }
} }
let contentType: String
let failureReason: String let failureReason: String
if let responseContentType = response.MIMEType { if let responseContentType = response.MIMEType {
contentType = responseContentType
failureReason = ( failureReason = (
"Response content type \"\(responseContentType)\" does not match any acceptable " + "Response content type \"\(responseContentType)\" does not match any acceptable " +
"content types: \(acceptableContentTypes)" "content types: \(acceptableContentTypes)"
) )
} else { } else {
contentType = ""
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
} }
return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) let error = NSError(
domain: Error.Domain,
code: Error.Code.ContentTypeValidationFailed.rawValue,
userInfo: [
NSLocalizedFailureReasonErrorKey: failureReason,
Error.UserInfoKeys.ContentType: contentType
]
)
return .Failure(error)
} }
} }

View File

@ -19,7 +19,7 @@
"~> 2.0" "~> 2.0"
], ],
"Alamofire": [ "Alamofire": [
"~> 3.1.5" "~> 3.4.1"
] ]
} }
} }

View File

@ -1,7 +1,7 @@
PODS: PODS:
- Alamofire (3.1.5) - Alamofire (3.4.2)
- PetstoreClient (0.0.1): - PetstoreClient (0.0.1):
- Alamofire (~> 3.1.5) - Alamofire (~> 3.4.1)
- RxSwift (~> 2.0) - RxSwift (~> 2.0)
- RxSwift (2.6.0) - RxSwift (2.6.0)
@ -13,10 +13,10 @@ EXTERNAL SOURCES:
:path: "../" :path: "../"
SPEC CHECKSUMS: SPEC CHECKSUMS:
Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 Alamofire: 6aa33201d20d069e1598891cf928883ff1888c7a
PetstoreClient: 0baad893079f270b6bcf2e868ba68d8b9ce36812 PetstoreClient: 1090d122e1fe799cb172d74af3445a6945370a59
RxSwift: 77f3a0b15324baa7a1c9bfa9f199648a82424e26 RxSwift: 77f3a0b15324baa7a1c9bfa9f199648a82424e26
PODFILE CHECKSUM: cedb3058b02f4776d7c31f6d92ae2f674fdf424d PODFILE CHECKSUM: cedb3058b02f4776d7c31f6d92ae2f674fdf424d
COCOAPODS: 1.0.1 COCOAPODS: 1.0.0

View File

@ -1,3 +1,4 @@
#ifdef __OBJC__ #ifdef __OBJC__
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#endif #endif

View File

@ -3,3 +3,4 @@
FOUNDATION_EXPORT double AlamofireVersionNumber; FOUNDATION_EXPORT double AlamofireVersionNumber;
FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; FOUNDATION_EXPORT const unsigned char AlamofireVersionString[];

View File

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

View File

@ -1,3 +1,4 @@
#ifdef __OBJC__ #ifdef __OBJC__
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#endif #endif

View File

@ -3,3 +3,4 @@
FOUNDATION_EXPORT double PetstoreClientVersionNumber; FOUNDATION_EXPORT double PetstoreClientVersionNumber;
FOUNDATION_EXPORT const unsigned char PetstoreClientVersionString[]; FOUNDATION_EXPORT const unsigned char PetstoreClientVersionString[];

View File

@ -3,7 +3,7 @@ This application makes use of the following third party libraries:
## Alamofire ## Alamofire
Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/) Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -14,7 +14,7 @@
</dict> </dict>
<dict> <dict>
<key>FooterText</key> <key>FooterText</key>
<string>Copyright (c) 2014&#8211;2016 Alamofire Software Foundation (http://alamofire.org/) <string>Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -48,8 +48,8 @@ EOM
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;; ;;
*.xib) *.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}"
;; ;;
*.framework) *.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

View File

@ -3,3 +3,4 @@
FOUNDATION_EXPORT double Pods_SwaggerClientVersionNumber; FOUNDATION_EXPORT double Pods_SwaggerClientVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientVersionString[]; FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientVersionString[];

View File

@ -81,3 +81,4 @@ strip_invalid_archs() {
echo "Stripped $binary of architectures:$stripped" echo "Stripped $binary of architectures:$stripped"
fi fi
} }

View File

@ -48,8 +48,8 @@ EOM
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;; ;;
*.xib) *.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}"
;; ;;
*.framework) *.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

View File

@ -3,3 +3,4 @@
FOUNDATION_EXPORT double Pods_SwaggerClientTestsVersionNumber; FOUNDATION_EXPORT double Pods_SwaggerClientTestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientTestsVersionString[]; FOUNDATION_EXPORT const unsigned char Pods_SwaggerClientTestsVersionString[];

View File

@ -1,3 +1,4 @@
#ifdef __OBJC__ #ifdef __OBJC__
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#endif #endif

View File

@ -3,3 +3,4 @@
FOUNDATION_EXPORT double RxSwiftVersionNumber; FOUNDATION_EXPORT double RxSwiftVersionNumber;
FOUNDATION_EXPORT const unsigned char RxSwiftVersionString[]; FOUNDATION_EXPORT const unsigned char RxSwiftVersionString[];

View File

@ -141,12 +141,15 @@
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = EAEC0BDB1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildConfigurationList = EAEC0BDB1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClient" */;
buildPhases = ( buildPhases = (
C70A8FFDB7B0A20D2C3436C9 /* 📦 Check Pods Manifest.lock */,
898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */, 898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */,
EAEC0BBA1D4E30CE00C908A3 /* Sources */, EAEC0BBA1D4E30CE00C908A3 /* Sources */,
EAEC0BBB1D4E30CE00C908A3 /* Frameworks */, EAEC0BBB1D4E30CE00C908A3 /* Frameworks */,
EAEC0BBC1D4E30CE00C908A3 /* Resources */, EAEC0BBC1D4E30CE00C908A3 /* Resources */,
8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */, 8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */,
E008DDC7FA2126F111F972F5 /* [CP] Copy Pods Resources */, E008DDC7FA2126F111F972F5 /* [CP] Copy Pods Resources */,
374C38046621787C3C859B01 /* 📦 Embed Pods Frameworks */,
73DCA4494CB87F25D3D5F63E /* 📦 Copy Pods Resources */,
); );
buildRules = ( buildRules = (
); );
@ -161,12 +164,15 @@
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = EAEC0BDE1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildConfigurationList = EAEC0BDE1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */;
buildPhases = ( buildPhases = (
48EADFABBF79C1D5C79CE9A6 /* 📦 Check Pods Manifest.lock */,
82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */, 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */,
EAEC0BCE1D4E30CE00C908A3 /* Sources */, EAEC0BCE1D4E30CE00C908A3 /* Sources */,
EAEC0BCF1D4E30CE00C908A3 /* Frameworks */, EAEC0BCF1D4E30CE00C908A3 /* Frameworks */,
EAEC0BD01D4E30CE00C908A3 /* Resources */, EAEC0BD01D4E30CE00C908A3 /* Resources */,
3920D9C143B997879E5A5B9C /* [CP] Embed Pods Frameworks */, 3920D9C143B997879E5A5B9C /* [CP] Embed Pods Frameworks */,
60E7B02FBDEB028CCE7CCCC5 /* [CP] Copy Pods Resources */, 60E7B02FBDEB028CCE7CCCC5 /* [CP] Copy Pods Resources */,
5879911F238B959C753C7FC4 /* 📦 Embed Pods Frameworks */,
AA1A263EEA3CDAE83EC2DFB9 /* 📦 Copy Pods Resources */,
); );
buildRules = ( buildRules = (
); );
@ -237,6 +243,21 @@
/* End PBXResourcesBuildPhase section */ /* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */
374C38046621787C3C859B01 /* 📦 Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
3920D9C143B997879E5A5B9C /* [CP] Embed Pods Frameworks */ = { 3920D9C143B997879E5A5B9C /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
@ -252,6 +273,36 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
48EADFABBF79C1D5C79CE9A6 /* 📦 Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Check Pods Manifest.lock";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
5879911F238B959C753C7FC4 /* 📦 Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
60E7B02FBDEB028CCE7CCCC5 /* [CP] Copy Pods Resources */ = { 60E7B02FBDEB028CCE7CCCC5 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
@ -267,6 +318,21 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
73DCA4494CB87F25D3D5F63E /* 📦 Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Copy Pods Resources";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n";
showEnvVarsInLog = 0;
};
82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */ = { 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
@ -312,6 +378,36 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
AA1A263EEA3CDAE83EC2DFB9 /* 📦 Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Copy Pods Resources";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n";
showEnvVarsInLog = 0;
};
C70A8FFDB7B0A20D2C3436C9 /* 📦 Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Check Pods Manifest.lock";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
E008DDC7FA2126F111F972F5 /* [CP] Copy Pods Resources */ = { E008DDC7FA2126F111F972F5 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;

View File

@ -49,3 +49,4 @@ git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository # Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https' git push origin master 2>&1 | grep -v 'To https'