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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
PODS:
- Alamofire (3.4.1)
- Alamofire (3.4.2)
- 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

@ -54,7 +54,7 @@ Carthage/Build
# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md

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

@ -9,7 +9,7 @@ import Foundation
public class PetstoreClientAPI {
public static var basePath = "http://petstore.swagger.io/v2"
public static var credential: NSURLCredential?
public static var customHeaders: [String:String] = [:]
public static var customHeaders: [String:String] = [:]
static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
}
@ -36,7 +36,7 @@ public class RequestBuilder<T> {
let isBody: Bool
let method: String
let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((NSProgress) -> ())?
@ -45,16 +45,16 @@ public class RequestBuilder<T> {
self.URLString = URLString
self.parameters = parameters
self.isBody = isBody
addHeaders(PetstoreClientAPI.customHeaders)
}
public func addHeaders(aHeaders:[String:String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
public func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) { }
public func addHeader(name name: String, value: String) -> Self {
@ -63,7 +63,7 @@ public class RequestBuilder<T> {
}
return self
}
public func addCredential() -> Self {
self.credential = PetstoreClientAPI.credential
return self
@ -73,3 +73,4 @@ public class RequestBuilder<T> {
protocol RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type
}

View File

@ -13,7 +13,7 @@ import RxSwift
public class PetAPI: APIBase {
/**
Add a new pet to the store
- parameter body: (body) Pet object that needs to be added to the store (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
@ -25,7 +25,7 @@ public class PetAPI: APIBase {
/**
Add a new pet to the store
- parameter body: (body) Pet object that needs to be added to the store (optional)
- returns: Observable<Void>
*/
@ -46,22 +46,22 @@ public class PetAPI: APIBase {
/**
Add a new pet to the store
- POST /pet
-
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter body: (body) Pet object that needs to be added to the store (optional)
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func addPetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder<Void> {
let path = "/pet"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -69,8 +69,8 @@ public class PetAPI: APIBase {
/**
Deletes a pet
- parameter petId: (path) Pet id to delete
- parameter petId: (path) Pet id to delete
- parameter completion: completion handler to receive the data and the error objects
*/
public class func deletePet(petId petId: Int64, completion: ((error: ErrorType?) -> Void)) {
@ -81,8 +81,8 @@ public class PetAPI: APIBase {
/**
Deletes a pet
- parameter petId: (path) Pet id to delete
- parameter petId: (path) Pet id to delete
- returns: Observable<Void>
*/
public class func deletePet(petId petId: Int64) -> Observable<Void> {
@ -102,14 +102,14 @@ public class PetAPI: APIBase {
/**
Deletes a pet
- DELETE /pet/{petId}
-
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) Pet id to delete
- parameter petId: (path) Pet id to delete
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func deletePetWithRequestBuilder(petId petId: Int64) -> RequestBuilder<Void> {
var path = "/pet/{petId}"
@ -117,11 +117,11 @@ public class PetAPI: APIBase {
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -129,7 +129,7 @@ public class PetAPI: APIBase {
/**
Finds Pets by status
- parameter status: (query) Status values that need to be considered for filter (optional, default to available)
- parameter completion: completion handler to receive the data and the error objects
*/
@ -141,7 +141,7 @@ public class PetAPI: APIBase {
/**
Finds Pets by status
- parameter status: (query) Status values that need to be considered for filter (optional, default to available)
- returns: Observable<[Pet]>
*/
@ -173,10 +173,10 @@ public class PetAPI: APIBase {
"gender" : "Female",
"breed" : "Mixed"
}, contentType=application/json}]
- parameter status: (query) Status values that need to be considered for filter (optional, default to available)
- returns: RequestBuilder<[Pet]>
- returns: RequestBuilder<[Pet]>
*/
public class func findPetsByStatusWithRequestBuilder(status status: [String]? = nil) -> RequestBuilder<[Pet]> {
let path = "/pet/findByStatus"
@ -185,11 +185,11 @@ public class PetAPI: APIBase {
let nillableParameters: [String:AnyObject?] = [
"status": status
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
@ -197,7 +197,7 @@ public class PetAPI: APIBase {
/**
Finds Pets by tags
- parameter tags: (query) Tags to filter by (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
@ -209,7 +209,7 @@ public class PetAPI: APIBase {
/**
Finds Pets by tags
- parameter tags: (query) Tags to filter by (optional)
- returns: Observable<[Pet]>
*/
@ -280,10 +280,10 @@ public class PetAPI: APIBase {
</tags>
<status>string</status>
</Pet>, contentType=application/xml}]
- parameter tags: (query) Tags to filter by (optional)
- returns: RequestBuilder<[Pet]>
- returns: RequestBuilder<[Pet]>
*/
public class func findPetsByTagsWithRequestBuilder(tags tags: [String]? = nil) -> RequestBuilder<[Pet]> {
let path = "/pet/findByTags"
@ -292,11 +292,11 @@ public class PetAPI: APIBase {
let nillableParameters: [String:AnyObject?] = [
"tags": tags
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
@ -304,8 +304,8 @@ public class PetAPI: APIBase {
/**
Find pet by ID
- parameter petId: (path) ID of pet that needs to be fetched
- parameter petId: (path) ID of pet that needs to be fetched
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getPetById(petId petId: Int64, completion: ((data: Pet?, error: ErrorType?) -> Void)) {
@ -316,8 +316,8 @@ public class PetAPI: APIBase {
/**
Find pet by ID
- parameter petId: (path) ID of pet that needs to be fetched
- parameter petId: (path) ID of pet that needs to be fetched
- returns: Observable<Pet>
*/
public class func getPetById(petId petId: Int64) -> Observable<Pet> {
@ -339,7 +339,7 @@ public class PetAPI: APIBase {
- GET /pet/{petId}
- Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
- API Key:
- type: apiKey api_key
- type: apiKey api_key
- name: api_key
- OAuth:
- type: oauth2
@ -390,10 +390,10 @@ public class PetAPI: APIBase {
</tags>
<status>string</status>
</Pet>, contentType=application/xml}]
- parameter petId: (path) ID of pet that needs to be fetched
- parameter petId: (path) ID of pet that needs to be fetched
- returns: RequestBuilder<Pet>
- returns: RequestBuilder<Pet>
*/
public class func getPetByIdWithRequestBuilder(petId petId: Int64) -> RequestBuilder<Pet> {
var path = "/pet/{petId}"
@ -401,11 +401,11 @@ public class PetAPI: APIBase {
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Pet>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -413,7 +413,7 @@ public class PetAPI: APIBase {
/**
Update an existing pet
- parameter body: (body) Pet object that needs to be added to the store (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
@ -425,7 +425,7 @@ public class PetAPI: APIBase {
/**
Update an existing pet
- parameter body: (body) Pet object that needs to be added to the store (optional)
- returns: Observable<Void>
*/
@ -446,22 +446,22 @@ public class PetAPI: APIBase {
/**
Update an existing pet
- PUT /pet
-
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter body: (body) Pet object that needs to be added to the store (optional)
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func updatePetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder<Void> {
let path = "/pet"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -469,8 +469,8 @@ public class PetAPI: APIBase {
/**
Updates a pet in the store with form data
- parameter petId: (path) ID of pet that needs to be updated
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- parameter completion: completion handler to receive the data and the error objects
@ -483,8 +483,8 @@ public class PetAPI: APIBase {
/**
Updates a pet in the store with form data
- parameter petId: (path) ID of pet that needs to be updated
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- returns: Observable<Void>
@ -506,16 +506,16 @@ public class PetAPI: APIBase {
/**
Updates a pet in the store with form data
- POST /pet/{petId}
-
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet that needs to be updated
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func updatePetWithFormWithRequestBuilder(petId petId: String, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> {
var path = "/pet/{petId}"
@ -526,11 +526,11 @@ public class PetAPI: APIBase {
"name": name,
"status": status
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)
@ -538,8 +538,8 @@ public class PetAPI: APIBase {
/**
uploads an image
- parameter petId: (path) ID of pet to update
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- parameter completion: completion handler to receive the data and the error objects
@ -552,8 +552,8 @@ public class PetAPI: APIBase {
/**
uploads an image
- parameter petId: (path) ID of pet to update
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- returns: Observable<Void>
@ -575,16 +575,16 @@ public class PetAPI: APIBase {
/**
uploads an image
- POST /pet/{petId}/uploadImage
-
-
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet to update
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func uploadFileWithRequestBuilder(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> RequestBuilder<Void> {
var path = "/pet/{petId}/uploadImage"
@ -595,11 +595,11 @@ public class PetAPI: APIBase {
"additionalMetadata": additionalMetadata,
"file": file
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)

View File

@ -13,8 +13,8 @@ import RxSwift
public class StoreAPI: APIBase {
/**
Delete purchase order by ID
- parameter orderId: (path) ID of the order that needs to be deleted
- parameter orderId: (path) ID of the order that needs to be deleted
- parameter completion: completion handler to receive the data and the error objects
*/
public class func deleteOrder(orderId orderId: String, completion: ((error: ErrorType?) -> Void)) {
@ -25,8 +25,8 @@ public class StoreAPI: APIBase {
/**
Delete purchase order by ID
- parameter orderId: (path) ID of the order that needs to be deleted
- parameter orderId: (path) ID of the order that needs to be deleted
- returns: Observable<Void>
*/
public class func deleteOrder(orderId orderId: String) -> Observable<Void> {
@ -47,10 +47,10 @@ public class StoreAPI: APIBase {
Delete purchase order by ID
- DELETE /store/order/{orderId}
- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
- parameter orderId: (path) ID of the order that needs to be deleted
- parameter orderId: (path) ID of the order that needs to be deleted
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func deleteOrderWithRequestBuilder(orderId orderId: String) -> RequestBuilder<Void> {
var path = "/store/order/{orderId}"
@ -58,11 +58,11 @@ public class StoreAPI: APIBase {
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -70,7 +70,7 @@ public class StoreAPI: APIBase {
/**
Returns pet inventories by status
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getInventory(completion: ((data: [String:Int32]?, error: ErrorType?) -> Void)) {
@ -81,7 +81,7 @@ public class StoreAPI: APIBase {
/**
Returns pet inventories by status
- returns: Observable<[String:Int32]>
*/
public class func getInventory() -> Observable<[String:Int32]> {
@ -103,7 +103,7 @@ public class StoreAPI: APIBase {
- GET /store/inventory
- Returns a map of status codes to quantities
- API Key:
- type: apiKey api_key
- type: apiKey api_key
- name: api_key
- examples: [{example={
"key" : 123
@ -112,18 +112,18 @@ public class StoreAPI: APIBase {
"key" : 123
}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
- returns: RequestBuilder<[String:Int32]>
- returns: RequestBuilder<[String:Int32]>
*/
public class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> {
let path = "/store/inventory"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -131,8 +131,8 @@ public class StoreAPI: APIBase {
/**
Find purchase order by ID
- parameter orderId: (path) ID of pet that needs to be fetched
- parameter orderId: (path) ID of pet that needs to be fetched
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getOrderById(orderId orderId: String, completion: ((data: Order?, error: ErrorType?) -> Void)) {
@ -143,8 +143,8 @@ public class StoreAPI: APIBase {
/**
Find purchase order by ID
- parameter orderId: (path) ID of pet that needs to be fetched
- parameter orderId: (path) ID of pet that needs to be fetched
- returns: Observable<Order>
*/
public class func getOrderById(orderId orderId: String) -> Observable<Order> {
@ -195,10 +195,10 @@ public class StoreAPI: APIBase {
<status>string</status>
<complete>true</complete>
</Order>, contentType=application/xml}]
- parameter orderId: (path) ID of pet that needs to be fetched
- parameter orderId: (path) ID of pet that needs to be fetched
- returns: RequestBuilder<Order>
- returns: RequestBuilder<Order>
*/
public class func getOrderByIdWithRequestBuilder(orderId orderId: String) -> RequestBuilder<Order> {
var path = "/store/order/{orderId}"
@ -206,11 +206,11 @@ public class StoreAPI: APIBase {
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -218,7 +218,7 @@ public class StoreAPI: APIBase {
/**
Place an order for a pet
- parameter body: (body) order placed for purchasing the pet (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
@ -230,7 +230,7 @@ public class StoreAPI: APIBase {
/**
Place an order for a pet
- parameter body: (body) order placed for purchasing the pet (optional)
- returns: Observable<Order>
*/
@ -251,7 +251,7 @@ public class StoreAPI: APIBase {
/**
Place an order for a pet
- POST /store/order
-
-
- examples: [{example={
"id" : 123456789,
"petId" : 123456789,
@ -282,18 +282,18 @@ public class StoreAPI: APIBase {
<status>string</status>
<complete>true</complete>
</Order>, contentType=application/xml}]
- parameter body: (body) order placed for purchasing the pet (optional)
- returns: RequestBuilder<Order>
- returns: RequestBuilder<Order>
*/
public class func placeOrderWithRequestBuilder(body body: Order? = nil) -> RequestBuilder<Order> {
let path = "/store/order"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)

View File

@ -13,7 +13,7 @@ import RxSwift
public class UserAPI: APIBase {
/**
Create user
- parameter body: (body) Created user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
@ -25,7 +25,7 @@ public class UserAPI: APIBase {
/**
Create user
- parameter body: (body) Created user object (optional)
- returns: Observable<Void>
*/
@ -47,18 +47,18 @@ public class UserAPI: APIBase {
Create user
- POST /user
- This can only be done by the logged in user.
- parameter body: (body) Created user object (optional)
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func createUserWithRequestBuilder(body body: User? = nil) -> RequestBuilder<Void> {
let path = "/user"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -66,7 +66,7 @@ public class UserAPI: APIBase {
/**
Creates list of users with given input array
- parameter body: (body) List of user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
@ -78,7 +78,7 @@ public class UserAPI: APIBase {
/**
Creates list of users with given input array
- parameter body: (body) List of user object (optional)
- returns: Observable<Void>
*/
@ -99,19 +99,19 @@ public class UserAPI: APIBase {
/**
Creates list of users with given input array
- POST /user/createWithArray
-
-
- parameter body: (body) List of user object (optional)
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func createUsersWithArrayInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder<Void> {
let path = "/user/createWithArray"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -119,7 +119,7 @@ public class UserAPI: APIBase {
/**
Creates list of users with given input array
- parameter body: (body) List of user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
@ -131,7 +131,7 @@ public class UserAPI: APIBase {
/**
Creates list of users with given input array
- parameter body: (body) List of user object (optional)
- returns: Observable<Void>
*/
@ -152,19 +152,19 @@ public class UserAPI: APIBase {
/**
Creates list of users with given input array
- POST /user/createWithList
-
-
- parameter body: (body) List of user object (optional)
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func createUsersWithListInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder<Void> {
let path = "/user/createWithList"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -172,8 +172,8 @@ public class UserAPI: APIBase {
/**
Delete user
- parameter username: (path) The name that needs to be deleted
- parameter username: (path) The name that needs to be deleted
- parameter completion: completion handler to receive the data and the error objects
*/
public class func deleteUser(username username: String, completion: ((error: ErrorType?) -> Void)) {
@ -184,8 +184,8 @@ public class UserAPI: APIBase {
/**
Delete user
- parameter username: (path) The name that needs to be deleted
- parameter username: (path) The name that needs to be deleted
- returns: Observable<Void>
*/
public class func deleteUser(username username: String) -> Observable<Void> {
@ -206,10 +206,10 @@ public class UserAPI: APIBase {
Delete user
- DELETE /user/{username}
- This can only be done by the logged in user.
- parameter username: (path) The name that needs to be deleted
- parameter username: (path) The name that needs to be deleted
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func deleteUserWithRequestBuilder(username username: String) -> RequestBuilder<Void> {
var path = "/user/{username}"
@ -217,11 +217,11 @@ public class UserAPI: APIBase {
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -229,8 +229,8 @@ public class UserAPI: APIBase {
/**
Get user by user name
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getUserByName(username username: String, completion: ((data: User?, error: ErrorType?) -> Void)) {
@ -241,8 +241,8 @@ public class UserAPI: APIBase {
/**
Get user by user name
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- returns: Observable<User>
*/
public class func getUserByName(username username: String) -> Observable<User> {
@ -262,7 +262,7 @@ public class UserAPI: APIBase {
/**
Get user by user name
- GET /user/{username}
-
-
- examples: [{example={
"id" : 123456789,
"lastName" : "aeiou",
@ -301,10 +301,10 @@ public class UserAPI: APIBase {
<phone>string</phone>
<userStatus>0</userStatus>
</User>, contentType=application/xml}]
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- parameter username: (path) The name that needs to be fetched. Use user1 for testing.
- returns: RequestBuilder<User>
- returns: RequestBuilder<User>
*/
public class func getUserByNameWithRequestBuilder(username username: String) -> RequestBuilder<User> {
var path = "/user/{username}"
@ -312,11 +312,11 @@ public class UserAPI: APIBase {
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -324,7 +324,7 @@ public class UserAPI: APIBase {
/**
Logs user into the system
- parameter username: (query) The user name for login (optional)
- parameter password: (query) The password for login in clear text (optional)
- parameter completion: completion handler to receive the data and the error objects
@ -337,7 +337,7 @@ public class UserAPI: APIBase {
/**
Logs user into the system
- parameter username: (query) The user name for login (optional)
- parameter password: (query) The password for login in clear text (optional)
- returns: Observable<String>
@ -359,14 +359,14 @@ public class UserAPI: APIBase {
/**
Logs user into the system
- GET /user/login
-
-
- 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)
- returns: RequestBuilder<String>
- returns: RequestBuilder<String>
*/
public class func loginUserWithRequestBuilder(username username: String? = nil, password: String? = nil) -> RequestBuilder<String> {
let path = "/user/login"
@ -376,11 +376,11 @@ public class UserAPI: APIBase {
"username": username,
"password": password
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
@ -388,7 +388,7 @@ public class UserAPI: APIBase {
/**
Logs out current logged in user session
- parameter completion: completion handler to receive the data and the error objects
*/
public class func logoutUser(completion: ((error: ErrorType?) -> Void)) {
@ -399,7 +399,7 @@ public class UserAPI: APIBase {
/**
Logs out current logged in user session
- returns: Observable<Void>
*/
public class func logoutUser() -> Observable<Void> {
@ -419,20 +419,20 @@ public class UserAPI: APIBase {
/**
Logs out current logged in user session
- GET /user/logout
-
-
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> {
let path = "/user/logout"
let URLString = PetstoreClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
@ -440,8 +440,8 @@ public class UserAPI: APIBase {
/**
Updated user
- parameter username: (path) name that need to be deleted
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
@ -453,8 +453,8 @@ public class UserAPI: APIBase {
/**
Updated user
- parameter username: (path) name that need to be deleted
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object (optional)
- returns: Observable<Void>
*/
@ -476,20 +476,20 @@ public class UserAPI: APIBase {
Updated user
- PUT /user/{username}
- This can only be done by the logged in user.
- parameter username: (path) name that need to be deleted
- parameter username: (path) name that need to be deleted
- parameter body: (body) Updated user object (optional)
- returns: RequestBuilder<Void>
- returns: RequestBuilder<Void>
*/
public class func updateUserWithRequestBuilder(username username: String, body: User? = nil) -> RequestBuilder<Void> {
var path = "/user/{username}"
path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters = body?.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true)

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 {
@ -135,7 +139,7 @@ class Decoders {
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
}
}
// Decoder for [Category]
Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in
@ -163,7 +167,7 @@ class Decoders {
instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"])
instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"])
instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"])
instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"])
return instance
}
@ -182,7 +186,7 @@ class Decoders {
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"])
instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"])
instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
return instance
}

View File

@ -9,7 +9,7 @@ import Foundation
public class Order: JSONEncodable {
public enum Status: String {
public enum Status: String {
case Placed = "placed"
case Approved = "approved"
case Delivered = "delivered"

View File

@ -9,7 +9,7 @@ import Foundation
public class Pet: JSONEncodable {
public enum Status: String {
public enum Status: String {
case Available = "available"
case Pending = "pending"
case Sold = "sold"

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.
@ -119,8 +128,8 @@ $ git submodule add https://github.com/Alamofire/Alamofire.git
- Click on the `+` button under the "Embedded Binaries" section.
- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder.
> It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`.
> It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`.
- Select the top `Alamofire.framework` for iOS and the bottom one for OS X.
> You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS` or `Alamofire OSX`.
@ -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`.
@ -1015,7 +1127,7 @@ let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
There are many different cases of server trust evaluation giving you complete control over the validation process:
* `PerformDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge.
* `PerformDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge.
* `PinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates.
* `PinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys.
* `DisableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid.
@ -1023,7 +1135,7 @@ There are many different cases of server trust evaluation giving you complete co
#### Server Trust Policy Manager
The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy.
The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy.
```swift
let serverTrustPolicies: [String: 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

@ -28,7 +28,7 @@ git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
@ -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;