This commit is contained in:
wing328 2016-09-24 00:17:54 +08:00
commit f47208a75b
87 changed files with 2171 additions and 1595 deletions

View File

@ -777,6 +777,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Kabuku](http://www.kabuku.co.jp/en)
- [Kuroi](http://kuroiwebdesign.com/)
- [Kuary](https://kuary.com/)
- [Mindera](http://mindera.com/)
- [Mporium](http://mporium.com/)
- [nViso](http://www.nviso.ch/)
- [Okiok](https://www.okiok.com)

View File

@ -1 +1 @@
{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}\"") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}}
{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}}

View File

@ -10,7 +10,7 @@ import * as assign from "core-js/library/fn/object/assign";
interface Dictionary<T> { [index: string]: T; }
export interface FetchAPI { (url: string, init?: any): Promise<any>; }
const BASE_PATH = "{{basePath}}";
const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, '');
export interface FetchArgs {
url: string;

View File

@ -46,7 +46,7 @@ mvn package
In your generator project. A single jar file will be produced in `target`. You can now use that with codegen:
```
java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l {{name}} -o ./test
java -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.Codegen -l {{name}} -i /path/to/swagger.yaml -o ./test
```
Now your templates are available to the client generator and you can write output values
@ -67,7 +67,7 @@ the object you have available during client generation:
# -DdebugOperations prints operations passed to the template engine
# -DdebugSupportingFiles prints additional data passed to the template engine
java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l {{name}} -o ./test
java -DdebugOperations -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.Codegen -l {{name}} -i /path/to/swagger.yaml -o ./test
```
Will, for example, output the debug info for operations. You can use this info

View File

@ -33,11 +33,11 @@ utility::string_t ApiClient::parameterToString(utility::string_t value)
}
utility::string_t ApiClient::parameterToString(int64_t value)
{
return std::to_wstring(value);
return utility::conversions::to_string_t(std::to_string(value));
}
utility::string_t ApiClient::parameterToString(int32_t value)
{
return std::to_wstring(value);
return utility::conversions::to_string_t(std::to_string(value));
}
pplx::task<web::http::http_response> ApiClient::callApi(

View File

@ -306,7 +306,7 @@ utility::string_t ModelBase::stringFromHttpContent(std::shared_ptr<HttpContent>
std::string str((std::istreambuf_iterator<char>(*data.get())),
std::istreambuf_iterator<char>());
return utility::conversions::to_utf16string(str);
return utility::conversions::to_string_t(str);
}
utility::datetime ModelBase::dateFromHttpContent(std::shared_ptr<HttpContent> val)
{

View File

@ -11,7 +11,7 @@
"api"
],
"homepage": "http://swagger.io",
"license": "Apache v2",
"license": "Apache-2.0",
"authors": [
{
"name": "Swagger and contributors",

View File

@ -1,21 +1,36 @@
Pod::Spec.new do |s|
s.name = '{{projectName}}'{{#projectDescription}}
s.summary = '{{projectDescription}}'{{/projectDescription}}
s.name = '{{projectName}}'
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
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.authors = '{{podAuthors}}'{{/podAuthors}}{{#podSocialMediaURL}}
s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}}
s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}}
s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}{{#podHomepage}}
s.homepage = '{{podHomepage}}'{{/podHomepage}}{{#podSummary}}
s.summary = '{{podSummary}}'{{/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.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}
{{#podAuthors}}
s.authors = '{{podAuthors}}'
{{/podAuthors}}
{{#podSocialMediaURL}}
s.social_media_url = '{{podSocialMediaURL}}'
{{/podSocialMediaURL}}
{{#podDocsetURL}}
s.docset_url = '{{podDocsetURL}}'
{{/podDocsetURL}}
s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}
s.homepage = '{{podHomepage}}{{^podHomepage}}https://github.com/swagger-api/swagger-codegen{{/podHomepage}}'
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'
end

View File

@ -57,11 +57,11 @@ utility::string_t ApiClient::parameterToString(utility::string_t value)
}
utility::string_t ApiClient::parameterToString(int64_t value)
{
return std::to_wstring(value);
return utility::conversions::to_string_t(std::to_string(value));
}
utility::string_t ApiClient::parameterToString(int32_t value)
{
return std::to_wstring(value);
return utility::conversions::to_string_t(std::to_string(value));
}
pplx::task<web::http::http_response> ApiClient::callApi(

View File

@ -330,7 +330,7 @@ utility::string_t ModelBase::stringFromHttpContent(std::shared_ptr<HttpContent>
std::string str((std::istreambuf_iterator<char>(*data.get())),
std::istreambuf_iterator<char>());
return utility::conversions::to_utf16string(str);
return utility::conversions::to_string_t(str);
}
utility::datetime ModelBase::dateFromHttpContent(std::shared_ptr<HttpContent> val)
{

View File

@ -118,7 +118,7 @@ public interface PetApi {
@Multipart
@POST("pet/{petId}/uploadImage")
Call<ModelApiResponse> uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file") RequestBody file
);
}

View File

@ -118,7 +118,7 @@ public interface PetApi {
@Multipart
@POST("pet/{petId}/uploadImage")
Observable<ModelApiResponse> uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file") RequestBody file
);
}

View File

@ -8,7 +8,7 @@
"api"
],
"homepage": "http://swagger.io",
"license": "Apache v2",
"license": "Apache-2.0",
"authors": [
{
"name": "Swagger and contributors",

View File

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

View File

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

View File

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

View File

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

View File

@ -140,7 +140,7 @@ extension Request {
- returns: The request.
*/
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
public func validate<S: SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
return validate { _, response in
guard let validData = self.delegate.data where validData.length > 0 else { return .Success }

View File

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

View File

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

View File

@ -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}
;;
*.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}"
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}"
;;
*.framework)
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}
;;
*.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}"
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}"
;;
*.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

View File

@ -143,6 +143,7 @@
isa = PBXNativeTarget;
buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */;
buildPhases = (
A16DAFA9EF474E5065B5B1C2 /* 📦 Check Pods Manifest.lock */,
CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */,
1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */,
6D4EFB8D1C692C6300B96B06 /* Sources */,
@ -166,6 +167,7 @@
isa = PBXNativeTarget;
buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */;
buildPhases = (
FE27E864CEDDA2D12F7972B1 /* 📦 Check Pods Manifest.lock */,
B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */,
79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */,
6D4EFBA11C692C6300B96B06 /* Sources */,
@ -365,6 +367,21 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n";
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 */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
@ -425,6 +442,21 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n";
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 */
/* Begin PBXSourcesBuildPhase section */

View File

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

View File

@ -101,12 +101,12 @@ public class StoreAPI: APIBase {
- API Key:
- type: apiKey api_key
- name: api_key
- examples: [{contentType=application/json, example={
- examples: [{example={
"key" : 123
}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}]
- examples: [{contentType=application/json, example={
}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
- examples: [{example={
"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]>
*/
@ -159,36 +159,36 @@ public class StoreAPI: APIBase {
Find purchase order by ID
- GET /store/order/{orderId}
- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
- examples: [{contentType=application/json, example={
"petId" : 123456789,
"quantity" : 123,
- examples: [{example={
"id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"petId" : 123456789,
"complete" : true,
"status" : "aeiou"
}}, {contentType=application/xml, example=<Order>
"status" : "aeiou",
"quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id>
<petId>123456</petId>
<quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status>
<complete>true</complete>
</Order>}]
- examples: [{contentType=application/json, example={
"petId" : 123456789,
"quantity" : 123,
</Order>, contentType=application/xml}]
- examples: [{example={
"id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"petId" : 123456789,
"complete" : true,
"status" : "aeiou"
}}, {contentType=application/xml, example=<Order>
"status" : "aeiou",
"quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id>
<petId>123456</petId>
<quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status>
<complete>true</complete>
</Order>}]
</Order>, contentType=application/xml}]
- 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
- POST /store/order
-
- examples: [{contentType=application/json, example={
"petId" : 123456789,
"quantity" : 123,
- examples: [{example={
"id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"petId" : 123456789,
"complete" : true,
"status" : "aeiou"
}}, {contentType=application/xml, example=<Order>
"status" : "aeiou",
"quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id>
<petId>123456</petId>
<quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status>
<complete>true</complete>
</Order>}]
- examples: [{contentType=application/json, example={
"petId" : 123456789,
"quantity" : 123,
</Order>, contentType=application/xml}]
- examples: [{example={
"id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"petId" : 123456789,
"complete" : true,
"status" : "aeiou"
}}, {contentType=application/xml, example=<Order>
"status" : "aeiou",
"quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+00:00"
}, contentType=application/json}, {example=<Order>
<id>123456</id>
<petId>123456</petId>
<quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status>
<complete>true</complete>
</Order>}]
</Order>, contentType=application/xml}]
- 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/{username}
-
- examples: [{contentType=application/json, example={
"firstName" : "aeiou",
"lastName" : "aeiou",
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
- examples: [{example={
"id" : 123456789,
"lastName" : "aeiou",
"phone" : "aeiou",
"username" : "aeiou",
"email" : "aeiou",
"username" : "aeiou"
}}, {contentType=application/xml, example=<User>
"userStatus" : 123,
"firstName" : "aeiou",
"password" : "aeiou"
}, contentType=application/json}, {example=<User>
<id>123456</id>
<username>string</username>
<firstName>string</firstName>
@ -271,17 +271,17 @@ public class UserAPI: APIBase {
<password>string</password>
<phone>string</phone>
<userStatus>0</userStatus>
</User>}]
- examples: [{contentType=application/json, example={
"firstName" : "aeiou",
"lastName" : "aeiou",
"password" : "aeiou",
"userStatus" : 123,
"phone" : "aeiou",
</User>, contentType=application/xml}]
- examples: [{example={
"id" : 123456789,
"lastName" : "aeiou",
"phone" : "aeiou",
"username" : "aeiou",
"email" : "aeiou",
"username" : "aeiou"
}}, {contentType=application/xml, example=<User>
"userStatus" : 123,
"firstName" : "aeiou",
"password" : "aeiou"
}, contentType=application/json}, {example=<User>
<id>123456</id>
<username>string</username>
<firstName>string</firstName>
@ -290,7 +290,7 @@ public class UserAPI: APIBase {
<password>string</password>
<phone>string</phone>
<userStatus>0</userStatus>
</User>}]
</User>, contentType=application/xml}]
- 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
- GET /user/login
-
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}]
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}]
- examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
- examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
- parameter username: (query) The user name for login (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.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift'
s.dependency 'RxSwift', '~> 2.0'
s.dependency 'Alamofire', '~> 3.1.5'
s.dependency 'Alamofire', '~> 3.4.1'
end

View File

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

View File

@ -63,7 +63,7 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
}
self.processRequest(uploadRequest, managerId, completion)
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()
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:
validatedRequest.responseData({ (dataResponse) in
validatedRequest.responseData(completionHandler: { (dataResponse) in
cleanupRequest()
if (dataResponse.result.isFailure) {
completion(
response: nil,
error: dataResponse.result.error
error: ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!)
)
return
}
@ -114,7 +154,7 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
cleanupRequest()
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
}
@ -133,7 +173,7 @@ class AlamofireRequestBuilder<T>: RequestBuilder<T> {
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
}
}

View File

@ -10,18 +10,22 @@ protocol JSONEncodable {
func encodeToJSON() -> AnyObject
}
public enum ErrorResponse : ErrorType {
case Error(Int, NSData?, ErrorType)
}
public class Response<T> {
public let statusCode: Int
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.header = header
self.body = body
}
public convenience init(response: NSHTTPURLResponse, body: T) {
public convenience init(response: NSHTTPURLResponse, body: T?) {
let rawHeader = response.allHeaderFields
var header = [String:String]()
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
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)
[![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)
[![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)
@ -22,10 +22,17 @@ Alamofire is an HTTP networking library written in Swift.
- [x] Comprehensive Unit Test Coverage
- [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
- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 7.2+
- Xcode 7.3+
## Migration Guides
@ -60,10 +67,12 @@ To integrate Alamofire into your Xcode project using CocoaPods, specify it in yo
```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
platform :ios, '9.0'
use_frameworks!
pod 'Alamofire', '~> 3.0'
target '<Your Target Name>' do
pod 'Alamofire', '~> 3.4'
end
```
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`:
```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.
@ -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.
### 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
**Built-in Response Methods**
@ -175,6 +216,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.response { request, response, data, error in
print(request)
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
```swift
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseData { response in
print(response.request)
print(response.response)
@ -200,6 +243,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
```swift
Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
@ -210,6 +254,7 @@ Alamofire.request(.GET, "https://httpbin.org/get")
```swift
Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseJSON { response in
debugPrint(response)
}
@ -221,6 +266,7 @@ Response handlers can even be chained:
```swift
Alamofire.request(.GET, "https://httpbin.org/get")
.validate()
.responseString { response in
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
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Content-Type": "application/x-www-form-urlencoded"
"Accept": "application/json"
]
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)")
}
}
.validate()
.responseJSON { response in
debugPrint(response)
}
@ -390,14 +437,14 @@ Alamofire.upload(
multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
```
@ -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.
#### 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.
Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`.
```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)
}
print(response.timeline)
}
```
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
```swift
@ -679,6 +713,20 @@ Requests can be suspended, resumed, and cancelled:
### 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
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
extension Request {
public static func XMLResponseSerializer() -> ResponseSerializer<ONOXMLDocument, NSError> {
public static func XMLResponseSerializer() -> ResponseSerializer<ONOXMLDocument, BackendError> {
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 {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil."))
}
do {
let XML = try ONOXMLDocument(data: validData)
return .Success(XML)
} 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)
}
}
@ -722,9 +768,9 @@ public protocol ResponseObjectSerializable {
}
extension Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, BackendError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, BackendError> { request, response, data, error in
guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
@ -737,12 +783,10 @@ extension Request {
{
return .Success(responseObject)
} else {
let failureReason = "JSON could not be serialized into response object: \(value)"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)"))
}
case .Failure(let error):
return .Failure(error)
return .Failure(.JSONSerialization(error: error))
}
}
@ -765,7 +809,7 @@ final class User: ResponseObjectSerializable {
```swift
Alamofire.request(.GET, "https://example.com/users/mattt")
.responseObject { (response: Response<User, NSError>) in
.responseObject { (response: Response<User, BackendError>) in
debugPrint(response)
}
```
@ -777,10 +821,26 @@ public protocol ResponseCollectionSerializable {
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 {
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], BackendError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in
guard error == nil else { return .Failure(.Network(error: error!)) }
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONSerializer.serializeResponse(request, response, data, error)
@ -790,12 +850,10 @@ extension Alamofire.Request {
if let response = response {
return .Success(T.collection(response: response, representation: value))
} else {
let failureReason = "Response collection could not be serialized due to nil response"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response"))
}
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.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
Alamofire.request(.GET, "http://example.com/users")
.responseCollection { (response: Response<[User], NSError>) in
.responseCollection { (response: Response<[User], BackendError>) in
debugPrint(response)
}
```
@ -912,7 +956,7 @@ enum Router: URLRequestConvertible {
var URLRequest: NSMutableURLRequest {
let result: (path: String, parameters: [String: AnyObject]) = {
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])
case .Search(let query, _):
return ("/search", ["q": query])
@ -997,6 +1041,74 @@ enum Router: URLRequestConvertible {
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
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
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.
@ -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.
### 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
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://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage
## 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.
## 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
Alamofire is released under the MIT license. See LICENSE for details.

View File

@ -1,24 +1,26 @@
// Alamofire.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Alamofire.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -42,27 +44,19 @@ public protocol URLStringConvertible {
}
extension String: URLStringConvertible {
public var URLString: String {
return self
}
public var URLString: String { return self }
}
extension NSURL: URLStringConvertible {
public var URLString: String {
return absoluteString
}
public var URLString: String { return absoluteString }
}
extension NSURLComponents: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
public var URLString: String { return URL!.URLString }
}
extension NSURLRequest: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
public var URLString: String { return URL!.URLString }
}
// MARK: - URLRequestConvertible
@ -76,9 +70,7 @@ public protocol URLRequestConvertible {
}
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSMutableURLRequest {
return self.mutableCopy() as! NSMutableURLRequest
}
public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest }
}
// MARK: - Convenience
@ -89,7 +81,16 @@ func URLRequest(
headers: [String: String]? = nil)
-> NSMutableURLRequest
{
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
let mutableURLRequest: NSMutableURLRequest
if let request = URLString as? NSMutableURLRequest {
mutableURLRequest = request
} else if let request = URLString as? NSURLRequest {
mutableURLRequest = request.URLRequest
} else {
mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
}
mutableURLRequest.HTTPMethod = method.rawValue
if let headers = headers {

View File

@ -1,24 +1,26 @@
// Download.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Download.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -211,6 +213,8 @@ extension Request {
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,

View File

@ -1,24 +1,26 @@
// Error.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Error.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -39,6 +41,15 @@ public struct Error {
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.
@ -47,6 +58,7 @@ public struct Error {
- 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 {
return errorWithCode(code.rawValue, failureReason: failureReason)
}
@ -59,8 +71,18 @@ public struct Error {
- 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 {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
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,24 +1,26 @@
// Manager.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Manager.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -56,17 +58,41 @@ public class Manager {
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
let osNameVersion: String = {
let versionString: String
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) {
return mutableUserAgent as String
}
if #available(OSX 10.10, *) {
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"
@ -143,11 +169,11 @@ public class Manager {
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
guard delegate === session.delegate else { return nil }
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
@ -218,18 +244,18 @@ public class Manager {
/**
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 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 {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate
}
set {
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:`.
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:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
@ -281,6 +310,11 @@ public class Manager {
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
@ -321,11 +355,23 @@ public class Manager {
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
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:`.
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:`.
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:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
@ -351,8 +397,13 @@ public class Manager {
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: ((NSURLRequest?) -> Void))
completionHandler: NSURLRequest? -> Void)
{
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
@ -374,10 +425,16 @@ public class Manager {
session: NSURLSession,
task: NSURLSessionTask,
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 {
completionHandler(taskDidReceiveChallenge(session, task, challenge))
let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task] {
delegate.URLSession(
session,
@ -400,8 +457,13 @@ public class Manager {
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
needNewBodyStream completionHandler: NSInputStream? -> Void)
{
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] {
@ -452,6 +514,8 @@ public class Manager {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
self[task] = nil
}
@ -462,6 +526,10 @@ public class Manager {
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
@ -469,7 +537,11 @@ public class Manager {
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// 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
@ -487,8 +559,13 @@ public class Manager {
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: ((NSURLSessionResponseDisposition) -> Void))
completionHandler: NSURLSessionResponseDisposition -> Void)
{
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
@ -550,8 +627,13 @@ public class Manager {
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: ((NSCachedURLResponse?) -> Void))
completionHandler: NSCachedURLResponse? -> Void)
{
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
@ -674,17 +756,21 @@ public class Manager {
// MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool {
#if !os(OSX)
if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
return sessionDidFinishEventsForBackgroundURLSession != nil
}
#endif
switch selector {
case "URLSession:didBecomeInvalidWithError:":
case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case "URLSession:didReceiveChallenge:completionHandler:":
return sessionDidReceiveChallenge != nil
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return sessionDidFinishEventsForBackgroundURLSession != nil
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return taskWillPerformHTTPRedirection != nil
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return dataTaskDidReceiveResponse != 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:
return self.dynamicType.instancesRespondToSelector(selector)
}

View File

@ -1,24 +1,26 @@
// MultipartFormData.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// MultipartFormData.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -217,7 +219,7 @@ public class MultipartFormData {
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else {
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 {
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
@ -261,8 +262,7 @@ public class MultipartFormData {
}
guard isReachable else {
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
setBodyPartError(error)
setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
return
}
@ -277,8 +277,7 @@ public class MultipartFormData {
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
{
let failureReason = "The file URL is a directory, not a file: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
@ -301,8 +300,7 @@ public class MultipartFormData {
guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
@ -312,8 +310,7 @@ public class MultipartFormData {
guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
setBodyPartError(error)
setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
return
}
@ -413,10 +410,10 @@ public class MultipartFormData {
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
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 {
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
@ -425,10 +422,9 @@ public class MultipartFormData {
outputStream = possibleOutputStream
} else {
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()
self.bodyParts.first?.hasInitialBoundary = true
@ -439,7 +435,6 @@ public class MultipartFormData {
}
outputStream.close()
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
}
// MARK: - Private - Body Part Encoding
@ -476,7 +471,6 @@ public class MultipartFormData {
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
var error: NSError?
@ -495,7 +489,7 @@ public class MultipartFormData {
encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 {
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
} else {
break
@ -503,7 +497,6 @@ public class MultipartFormData {
}
inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
if let error = error {
throw error
@ -537,7 +530,6 @@ public class MultipartFormData {
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
while inputStream.hasBytesAvailable {
@ -556,14 +548,13 @@ public class MultipartFormData {
try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 {
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 {
break
}
}
inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
}
private func writeFinalBoundaryDataForBodyPart(
@ -598,7 +589,7 @@ public class MultipartFormData {
if bytesWritten < 0 {
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
@ -661,9 +652,8 @@ public class MultipartFormData {
// MARK: - Private - Errors
private func setBodyPartError(error: NSError) {
if bodyPartError == nil {
bodyPartError = error
}
private func setBodyPartError(code code: Int, failureReason: String) {
guard bodyPartError == nil else { return }
bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
}
}

View File

@ -1,24 +1,26 @@
// ParameterEncoding.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// ParameterEncoding.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -69,8 +71,8 @@ public enum ParameterEncoding {
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
- parameter URLRequest: The request to have parameters applied
- parameter parameters: The parameters to apply
- parameter URLRequest: The request to have parameters applied.
- parameter parameters: The parameters to apply.
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
if any.
@ -82,9 +84,7 @@ public enum ParameterEncoding {
{
var mutableURLRequest = URLRequest.URLRequest
guard let parameters = parameters where !parameters.isEmpty else {
return (mutableURLRequest, nil)
}
guard let parameters = parameters else { return (mutableURLRequest, nil) }
var encodingError: NSError? = nil
@ -118,7 +118,10 @@ public enum ParameterEncoding {
}
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)
URLComponents.percentEncodedQuery = percentEncodedQuery
mutableURLRequest.URL = URLComponents.URL
@ -141,7 +144,10 @@ public enum ParameterEncoding {
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = data
} catch {
encodingError = error as NSError
@ -153,7 +159,11 @@ public enum ParameterEncoding {
format: format,
options: options
)
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = data
} catch {
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
// 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
// info, please refer to:
//
@ -236,7 +246,7 @@ public enum ParameterEncoding {
while index != string.endIndex {
let startIndex = index
let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
let range = Range(start: startIndex, end: endIndex)
let range = startIndex..<endIndex
let substring = string.substringWithRange(range)

View File

@ -1,24 +1,26 @@
// Request.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Request.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -48,6 +50,9 @@ public class Request {
/// The progress of the request lifecycle.
public var progress: NSProgress { return delegate.progress }
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
// MARK: - Lifecycle
init(session: NSURLSession, task: NSURLSessionTask) {
@ -55,14 +60,16 @@ public class Request {
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
delegate = TaskDelegate(task: task)
}
delegate.queue.addOperationWithBlock { self.endTime = CFAbsoluteTimeGetCurrent() }
}
// MARK: - Authentication
@ -100,6 +107,22 @@ public class Request {
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
/**
@ -148,18 +171,22 @@ public class Request {
// 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.
*/
public func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
public func resume() {
task.resume()
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task)
}
/**
@ -176,6 +203,8 @@ public class Request {
} else {
task.cancel()
}
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task)
}
// MARK: - TaskDelegate
@ -195,6 +224,7 @@ public class Request {
var data: NSData? { return nil }
var error: NSError?
var initialResponseTime: CFAbsoluteTime?
var credential: NSURLCredential?
init(task: NSURLSessionTask) {
@ -272,7 +302,7 @@ public class Request {
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
disposition = .RejectProtectionSpace
} else {
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) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
@ -470,7 +502,7 @@ extension Request: CustomDebugStringConvertible {
let protectionSpace = NSURLProtectionSpace(
host: host,
port: URL.port?.integerValue ?? 0,
`protocol`: URL.scheme,
protocol: URL.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
@ -496,33 +528,31 @@ extension Request: CustomDebugStringConvertible {
}
}
if let headerFields = request.allHTTPHeaderFields {
for (field, value) in headerFields {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
var headers: [NSObject: AnyObject] = [:]
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
for (field, value) in additionalHeaders where field != "Cookie" {
headers[field] = value
}
}
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
for (field, value) in additionalHeaders {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
if let headerFields = request.allHTTPHeaderFields {
for (field, value) in headerFields where field != "Cookie" {
headers[field] = value
}
}
for (field, value) in headers {
components.append("-H \"\(field): \(value)\"")
}
if let
HTTPBodyData = request.HTTPBody,
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
{
let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"")
escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
components.append("-d \"\(escapedBody)\"")
}

View File

@ -1,24 +1,26 @@
// Response.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Response.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -36,6 +38,9 @@ public struct Response<Value, Error: ErrorType> {
/// The result of response serialization.
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
serialization result.
@ -44,14 +49,22 @@ public struct Response<Value, Error: ErrorType> {
- parameter response: The server's response to the URL request.
- parameter data: The data returned by the server.
- 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.
*/
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.response = response
self.data = data
self.result = result
self.timeline = timeline
}
}
@ -77,6 +90,7 @@ extension Response: CustomDebugStringConvertible {
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[Data]: \(data?.length ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)")
output.append("[Timeline]: \(timeline.debugDescription)")
return output.joinWithSeparator("\n")
}

View File

@ -1,24 +1,26 @@
// ResponseSerialization.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// ResponseSerialization.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -29,10 +31,10 @@ import Foundation
*/
public protocol 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.
typealias ErrorObject: ErrorType
associatedtype ErrorObject: ErrorType
/**
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
)
dispatch_async(queue ?? dispatch_get_main_queue()) {
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result
)
let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
completionHandler(response)
}
let timeline = Timeline(
requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
initialResponseTime: initialResponseTime,
requestCompletedTime: requestCompletedTime,
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
)
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result,
timeline: timeline
)
dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) }
}
return self
@ -152,7 +163,7 @@ extension Request {
guard let validData = data else {
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)
}
@ -167,8 +178,12 @@ extension Request {
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
public func responseData(
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.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
@ -196,23 +211,25 @@ extension Request {
guard let validData = data else {
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)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
var convertedEncoding = encoding
if let encodingName = response?.textEncodingName where convertedEncoding == nil {
convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
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)
}
}
@ -229,11 +246,13 @@ extension Request {
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
queue queue: dispatch_queue_t? = nil,
encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
@ -263,7 +282,7 @@ extension Request {
guard let validData = data where validData.length > 0 else {
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)
}
@ -285,11 +304,13 @@ extension Request {
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
queue queue: dispatch_queue_t? = nil,
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
@ -319,7 +340,7 @@ extension Request {
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 error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
@ -343,11 +364,13 @@ extension Request {
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
queue queue: dispatch_queue_t? = nil,
options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)

View File

@ -1,24 +1,26 @@
// Result.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Result.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation

View File

@ -1,24 +1,26 @@
// ServerTrustPolicy.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// ServerTrustPolicy.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation

View File

@ -1,30 +1,32 @@
// Stream.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Stream.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
#if !os(watchOS)
@available(iOS 9.0, OSX 10.11, *)
@available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager {
private enum Streamable {
case Stream(String, Int)
@ -62,7 +64,7 @@ extension Manager {
- parameter hostName: The hostname of the server to connect to.
- parameter port: The port of the server to connect to.
:returns: The created stream request.
- returns: The created stream request.
*/
public func stream(hostName hostName: String, port: Int) -> Request {
return stream(.Stream(hostName, port))
@ -82,7 +84,7 @@ extension Manager {
// MARK: -
@available(iOS 9.0, OSX 10.11, *)
@available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager.SessionDelegate: NSURLSessionStreamDelegate {
// MARK: Override Closures

View File

@ -1,24 +1,26 @@
// Upload.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Upload.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -359,6 +361,8 @@ extension Request {
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {

View File

@ -1,24 +1,26 @@
// Validation.swift
//
// Copyright (c) 20142016 Alamofire Software Foundation (http://alamofire.org/)
// Validation.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@ -80,7 +82,17 @@ extension Request {
return .Success
} else {
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.
*/
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
public func validate<S: SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
return validate { _, response in
guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
@ -149,18 +161,31 @@ extension Request {
}
}
let contentType: String
let failureReason: String
if let responseContentType = response.MIMEType {
contentType = responseContentType
failureReason = (
"Response content type \"\(responseContentType)\" does not match any acceptable " +
"content types: \(acceptableContentTypes)"
)
} else {
contentType = ""
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"
],
"Alamofire": [
"~> 3.1.5"
"~> 3.4.1"
]
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -3,7 +3,7 @@ This application makes use of the following third party libraries:
## 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
of this software and associated documentation files (the "Software"), to deal

View File

@ -14,7 +14,7 @@
</dict>
<dict>
<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
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}
;;
*.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}"
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}"
;;
*.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

View File

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

View File

@ -81,3 +81,4 @@ strip_invalid_archs() {
echo "Stripped $binary of architectures:$stripped"
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}
;;
*.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}"
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}"
;;
*.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"

View File

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

View File

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

View File

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

View File

@ -141,12 +141,15 @@
isa = PBXNativeTarget;
buildConfigurationList = EAEC0BDB1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClient" */;
buildPhases = (
C70A8FFDB7B0A20D2C3436C9 /* 📦 Check Pods Manifest.lock */,
898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */,
EAEC0BBA1D4E30CE00C908A3 /* Sources */,
EAEC0BBB1D4E30CE00C908A3 /* Frameworks */,
EAEC0BBC1D4E30CE00C908A3 /* Resources */,
8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */,
E008DDC7FA2126F111F972F5 /* [CP] Copy Pods Resources */,
374C38046621787C3C859B01 /* 📦 Embed Pods Frameworks */,
73DCA4494CB87F25D3D5F63E /* 📦 Copy Pods Resources */,
);
buildRules = (
);
@ -161,12 +164,15 @@
isa = PBXNativeTarget;
buildConfigurationList = EAEC0BDE1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */;
buildPhases = (
48EADFABBF79C1D5C79CE9A6 /* 📦 Check Pods Manifest.lock */,
82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */,
EAEC0BCE1D4E30CE00C908A3 /* Sources */,
EAEC0BCF1D4E30CE00C908A3 /* Frameworks */,
EAEC0BD01D4E30CE00C908A3 /* Resources */,
3920D9C143B997879E5A5B9C /* [CP] Embed Pods Frameworks */,
60E7B02FBDEB028CCE7CCCC5 /* [CP] Copy Pods Resources */,
5879911F238B959C753C7FC4 /* 📦 Embed Pods Frameworks */,
AA1A263EEA3CDAE83EC2DFB9 /* 📦 Copy Pods Resources */,
);
buildRules = (
);
@ -237,6 +243,21 @@
/* End PBXResourcesBuildPhase 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 */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
@ -252,6 +273,36 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n";
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 */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
@ -267,6 +318,21 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n";
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 */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
@ -312,6 +378,36 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n";
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 */ = {
isa = PBXShellScriptBuildPhase;
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
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -31,7 +31,7 @@ import * as assign from "core-js/library/fn/object/assign";
interface Dictionary<T> { [index: string]: T; }
export interface FetchAPI { (url: string, init?: any): Promise<any>; }
const BASE_PATH = "http://petstore.swagger.io/v2";
const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, '');
export interface FetchArgs {
url: string;

View File

@ -30,7 +30,7 @@ import * as isomorphicFetch from "isomorphic-fetch";
interface Dictionary<T> { [index: string]: T; }
export interface FetchAPI { (url: string, init?: any): Promise<any>; }
const BASE_PATH = "http://petstore.swagger.io/v2";
const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, '');
export interface FetchArgs {
url: string;

View File

@ -31,7 +31,7 @@ import * as assign from "core-js/library/fn/object/assign";
interface Dictionary<T> { [index: string]: T; }
export interface FetchAPI { (url: string, init?: any): Promise<any>; }
const BASE_PATH = "http://petstore.swagger.io/v2";
const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, '');
export interface FetchArgs {
url: string;