rebuilt client

This commit is contained in:
Tony Tam 2015-02-16 17:37:05 -08:00
parent 0563be891c
commit a0ea195ffc
72 changed files with 3119 additions and 6278 deletions

View File

@ -1,43 +0,0 @@
/**
* Copyright 2014 Wordnik, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.wordnik.swagger.codegen.BasicObjcGenerator
object ObjcPetstoreCodegen extends BasicObjcGenerator {
def main(args: Array[String]) = generateClient(args)
// where to write generated code
val outputFolder = "samples/client/petstore/objc/"
override def destinationDir = outputFolder + java.io.File.separator + "client"
override def templateDir = "objc"
additionalParams ++= Map("projectName" -> "PetstoreClient")
// supporting classes
override def supportingFiles =
List(
("SWGObject.h", destinationDir, "SWGObject.h"),
("SWGObject.m", destinationDir, "SWGObject.m"),
("SWGApiClient.h", destinationDir, "SWGApiClient.h"),
("SWGApiClient.m", destinationDir, "SWGApiClient.m"),
("SWGFile.h", destinationDir, "SWGFile.h"),
("SWGFile.m", destinationDir, "SWGFile.m"),
("SWGDate.h", destinationDir, "SWGDate.h"),
("SWGDate.m", destinationDir, "SWGDate.m"),
("Podfile.mustache", outputFolder, "Podfile")
)
}

View File

@ -36,6 +36,8 @@
EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E11811D3AE00F06E69 /* SWGUser.m */; };
EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */; };
EAEA85F11811D8F100F06E69 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = EAEA85F01811D8F100F06E69 /* libPods.a */; };
EAFBEABB1A925B8500A27431 /* test-1.png in Resources */ = {isa = PBXBuildFile; fileRef = EAFBEABA1A925B8500A27431 /* test-1.png */; };
EAFBEABE1A92C42700A27431 /* SWGApiResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = EAFBEABD1A92C42700A27431 /* SWGApiResponse.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@ -50,7 +52,8 @@
/* Begin PBXFileReference section */
73DA4F1067C343C3962F1542 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; };
EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.xcconfig; path = ../Pods/Pods.xcconfig; sourceTree = "<group>"; };
A425648B5C0A4849C7668069 /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = "<group>"; };
E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = "<group>"; };
EA6699961811D2FA00A70D03 /* PetstoreClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PetstoreClient.app; sourceTree = BUILT_PRODUCTS_DIR; };
EA6699991811D2FA00A70D03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
@ -95,7 +98,10 @@
EAEA85E11811D3AE00F06E69 /* SWGUser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGUser.m; sourceTree = "<group>"; };
EAEA85E21811D3AE00F06E69 /* SWGUserApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGUserApi.h; sourceTree = "<group>"; };
EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGUserApi.m; sourceTree = "<group>"; };
EAEA85F01811D8F100F06E69 /* libPods.a */ = {isa = PBXFileReference; lastKnownFileType = file; name = libPods.a; path = "../Pods/build/Debug-iphoneos/libPods.a"; sourceTree = "<group>"; };
EAEA85F01811D8F100F06E69 /* libPods.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libPods.a; path = "../Pods/build/Debug-iphoneos/libPods.a"; sourceTree = "<group>"; };
EAFBEABA1A925B8500A27431 /* test-1.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "test-1.png"; sourceTree = "<group>"; };
EAFBEABC1A92C42700A27431 /* SWGApiResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGApiResponse.h; sourceTree = "<group>"; };
EAFBEABD1A92C42700A27431 /* SWGApiResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiResponse.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@ -124,6 +130,15 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
1A15B3DE4358A178ABAEC251 /* Pods */ = {
isa = PBXGroup;
children = (
E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */,
A425648B5C0A4849C7668069 /* Pods.release.xcconfig */,
);
name = Pods;
sourceTree = "<group>";
};
EA66998D1811D2FA00A70D03 = {
isa = PBXGroup;
children = (
@ -132,7 +147,7 @@
EA6699C11811D2FB00A70D03 /* PetstoreClientTests */,
EA6699981811D2FA00A70D03 /* Frameworks */,
EA6699971811D2FA00A70D03 /* Products */,
EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */,
1A15B3DE4358A178ABAEC251 /* Pods */,
);
sourceTree = "<group>";
};
@ -176,6 +191,7 @@
EA6699A01811D2FA00A70D03 /* Supporting Files */ = {
isa = PBXGroup;
children = (
EAFBEABA1A925B8500A27431 /* test-1.png */,
EA6699A11811D2FA00A70D03 /* PetstoreClient-Info.plist */,
EA6699A21811D2FA00A70D03 /* InfoPlist.strings */,
EA6699A51811D2FA00A70D03 /* main.m */,
@ -205,6 +221,8 @@
EAEA85CB1811D3AE00F06E69 /* client */ = {
isa = PBXGroup;
children = (
EAFBEABC1A92C42700A27431 /* SWGApiResponse.h */,
EAFBEABD1A92C42700A27431 /* SWGApiResponse.m */,
EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */,
EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */,
EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */,
@ -315,6 +333,7 @@
EA6699B01811D2FA00A70D03 /* Main_iPad.storyboard in Resources */,
EA6699B51811D2FA00A70D03 /* Images.xcassets in Resources */,
EA6699AD1811D2FA00A70D03 /* Main_iPhone.storyboard in Resources */,
EAFBEABB1A925B8500A27431 /* test-1.png in Resources */,
EA6699A41811D2FA00A70D03 /* InfoPlist.strings in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
@ -357,7 +376,7 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/../Pods/Pods-resources.sh\"\n";
shellScript = "\"${SRCROOT}/../Pods/Target Support Files/Pods/Pods-resources.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
@ -372,6 +391,7 @@
EA6699B31811D2FA00A70D03 /* ViewController.m in Sources */,
EA6699AA1811D2FA00A70D03 /* AppDelegate.m in Sources */,
EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */,
EAFBEABE1A92C42700A27431 /* SWGApiResponse.m in Sources */,
EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */,
EAEA85EB1811D3AE00F06E69 /* SWGPetApi.m in Sources */,
EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */,
@ -515,7 +535,7 @@
};
EA6699CC1811D2FB00A70D03 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */;
baseConfigurationReference = E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
@ -529,7 +549,7 @@
};
EA6699CD1811D2FB00A70D03 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */;
baseConfigurationReference = A425648B5C0A4849C7668069 /* Pods.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;

View File

@ -15,6 +15,11 @@
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "29x29",

View File

@ -22,13 +22,36 @@
SWGPetApi * api = [[SWGPetApi alloc] init];
[api getPetByIdWithCompletionBlock:@10 completionHandler:^(SWGPet *output, NSError *error) {
NSLog(@"%@", [output asDictionary]);
[output set_id:@101];
[api addPetWithCompletionBlock:output completionHandler:^(NSError *error) {
NSLog(@"Done!");
}];
}];
// [api getPetByIdWithCompletionBlock:@10 completionHandler:^(SWGPet *output, NSError *error) {
// NSLog(@"%@", [output asDictionary]);
// [output set_id:@101];
// [api addPetWithCompletionBlock:output completionHandler:^(NSError *error) {
// NSLog(@"Done!");
// }];
// load data into file
// }];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test-1" ofType:@"png"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
SWGFile *file = [[SWGFile alloc] initWithNameData:@"test-2.png" mimeType:@"image/png" data:myData];
[api uploadFileWithCompletionBlock:@1
additionalMetadata:@"some metadata"
file:file
completionHandler:^(NSError *error) {
if(error) {
NSLog(@"%@", error);
}
}
// completionHandler:^(SWGApiResponse *output, NSError *error) {
// if(error) {
// NSLog(@"%@", error);
// }
// else {
// NSLog(@"%@", [output asDictionary]);
// }
// }
];
}
- (void)didReceiveMemoryWarning

Binary file not shown.

After

Width:  |  Height:  |  Size: 717 KiB

View File

@ -1,10 +1,30 @@
PODS:
- AFNetworking (1.3.3)
- AFNetworking (2.5.1):
- AFNetworking/NSURLConnection (= 2.5.1)
- AFNetworking/NSURLSession (= 2.5.1)
- AFNetworking/Reachability (= 2.5.1)
- AFNetworking/Security (= 2.5.1)
- AFNetworking/Serialization (= 2.5.1)
- AFNetworking/UIKit (= 2.5.1)
- AFNetworking/NSURLConnection (2.5.1):
- AFNetworking/Reachability
- AFNetworking/Security
- AFNetworking/Serialization
- AFNetworking/NSURLSession (2.5.1):
- AFNetworking/Reachability
- AFNetworking/Security
- AFNetworking/Serialization
- AFNetworking/Reachability (2.5.1)
- AFNetworking/Security (2.5.1)
- AFNetworking/Serialization (2.5.1)
- AFNetworking/UIKit (2.5.1):
- AFNetworking/NSURLConnection
- AFNetworking/NSURLSession
DEPENDENCIES:
- AFNetworking (~> 1.0)
- AFNetworking (~> 2.1)
SPEC CHECKSUMS:
AFNetworking: 0700ec7a58c36ad217173e167f6e4df7270df66b
AFNetworking: 8bee59492a6ff15d69130efa4d0dc67e0094a52a
COCOAPODS: 0.25.0
COCOAPODS: 0.35.0

View File

@ -1,641 +0,0 @@
// AFHTTPClient.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import <Foundation/Foundation.h>
#import "AFURLConnectionOperation.h"
#import <Availability.h>
/**
`AFHTTPClient` captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations.
## Automatic Content Parsing
Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`.
## Subclassing Notes
In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.
## Methods to Override
To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`.
To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
## Default Headers
By default, `AFHTTPClient` sets the following HTTP headers:
- `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8`
- `User-Agent: (generated user agent)`
You can override these HTTP headers or define new ones using `setDefaultHeader:value:`.
## URL Construction Using Relative Paths
Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact:
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
[NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
[NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
[NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
Also important to note is that a trailing slash will be added to any `baseURL` without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
## NSCoding / NSCopying Conformance
`AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
- Archives and copies of HTTP clients will be initialized with an empty operation queue.
- NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
*/
#ifdef _SYSTEMCONFIGURATION_H
typedef enum {
AFNetworkReachabilityStatusUnknown = -1,
AFNetworkReachabilityStatusNotReachable = 0,
AFNetworkReachabilityStatusReachableViaWWAN = 1,
AFNetworkReachabilityStatusReachableViaWiFi = 2,
} AFNetworkReachabilityStatus;
#else
#pragma message("SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.")
#endif
#ifndef __UTTYPE__
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#pragma message("MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.")
#else
#pragma message("CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.")
#endif
#endif
typedef enum {
AFFormURLParameterEncoding,
AFJSONParameterEncoding,
AFPropertyListParameterEncoding,
} AFHTTPClientParameterEncoding;
@class AFHTTPRequestOperation;
@protocol AFMultipartFormData;
@interface AFHTTPClient : NSObject <NSCoding, NSCopying>
///---------------------------------------
/// @name Accessing HTTP Client Properties
///---------------------------------------
/**
The url used as the base for paths specified in methods such as `getPath:parameters:success:failure`
*/
@property (readonly, nonatomic, strong) NSURL *baseURL;
/**
The string encoding used in constructing url requests. This is `NSUTF8StringEncoding` by default.
*/
@property (nonatomic, assign) NSStringEncoding stringEncoding;
/**
The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body for request methods other than `GET`, `HEAD` or `DELETE`. This is `AFFormURLParameterEncoding` by default.
@warning Some nested parameter structures, such as a keyed array of hashes containing inconsistent keys (i.e. `@{@"": @[@{@"a" : @(1)}, @{@"b" : @(2)}]}`), cannot be unambiguously represented in query strings. It is strongly recommended that an unambiguous encoding, such as `AFJSONParameterEncoding`, is used when posting complicated or nondeterministic parameter structures.
*/
@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
/**
The operation queue which manages operations enqueued by the HTTP client.
*/
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
/**
The reachability status from the device to the current `baseURL` of the `AFHTTPClient`.
@warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
*/
#ifdef _SYSTEMCONFIGURATION_H
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
#endif
/**
Default SSL pinning mode for each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:`.
*/
@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode defaultSSLPinningMode;
/**
Whether each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:` should accept an invalid SSL certificate.
If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`.
*/
@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate;
///---------------------------------------------
/// @name Creating and Initializing HTTP Clients
///---------------------------------------------
/**
Creates and initializes an `AFHTTPClient` object with the specified base URL.
@param url The base URL for the HTTP client. This argument must not be `nil`.
@return The newly-initialized HTTP client
*/
+ (instancetype)clientWithBaseURL:(NSURL *)url;
/**
Initializes an `AFHTTPClient` object with the specified base URL.
This is the designated initializer.
@param url The base URL for the HTTP client. This argument must not be `nil`.
@return The newly-initialized HTTP client
*/
- (id)initWithBaseURL:(NSURL *)url;
///-----------------------------------
/// @name Managing Reachability Status
///-----------------------------------
/**
Sets a callback to be executed when the network availability of the `baseURL` host changes.
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
@warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
*/
#ifdef _SYSTEMCONFIGURATION_H
- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block;
#endif
///-------------------------------
/// @name Managing HTTP Operations
///-------------------------------
/**
Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list.
@param operationClass The subclass of `AFHTTPRequestOperation` to register
@return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`.
*/
- (BOOL)registerHTTPOperationClass:(Class)operationClass;
/**
Unregisters the specified subclass of `AFHTTPRequestOperation` from the chain of classes consulted when `-requestWithMethod:path:parameters` is called.
@param operationClass The subclass of `AFHTTPRequestOperation` to register
*/
- (void)unregisterHTTPOperationClass:(Class)operationClass;
///----------------------------------
/// @name Managing HTTP Header Values
///----------------------------------
/**
Returns the value for the HTTP headers set in request objects created by the HTTP client.
@param header The HTTP header to return the default value for
@return The default value for the HTTP header, or `nil` if unspecified
*/
- (NSString *)defaultValueForHeader:(NSString *)header;
/**
Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
@param header The HTTP header to set a default value for
@param value The value set as default for the specified header, or `nil
*/
- (void)setDefaultHeader:(NSString *)header
value:(NSString *)value;
/**
Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
@param username The HTTP basic auth username
@param password The HTTP basic auth password
*/
- (void)setAuthorizationHeaderWithUsername:(NSString *)username
password:(NSString *)password;
/**
Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header.
@param token The authentication token
*/
- (void)setAuthorizationHeaderWithToken:(NSString *)token;
/**
Clears any existing value for the "Authorization" HTTP header.
*/
- (void)clearAuthorizationHeader;
///-------------------------------
/// @name Managing URL Credentials
///-------------------------------
/**
Set the default URL credential to be set for request operations.
@param credential The URL credential
*/
- (void)setDefaultCredential:(NSURLCredential *)credential;
///-------------------------------
/// @name Creating Request Objects
///-------------------------------
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and path.
If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
@param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
@param path The path to be appended to the HTTP client's base URL and used as the request URL. If `nil`, no path will be appended to the base URL.
@param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
@return An `NSMutableURLRequest` object
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
path:(NSString *)path
parameters:(NSDictionary *)parameters;
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and path, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
@param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values.
@return An `NSMutableURLRequest` object
*/
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
path:(NSString *)path
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block;
///-------------------------------
/// @name Creating HTTP Operations
///-------------------------------
/**
Creates an `AFHTTPRequestOperation`.
In order to determine what kind of operation is created, each registered subclass conforming to the `AFHTTPClient` protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`.
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
*/
- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
///----------------------------------------
/// @name Managing Enqueued HTTP Operations
///----------------------------------------
/**
Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
@param operation The HTTP request operation to be enqueued.
*/
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
/**
Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path.
This method only cancels `AFHTTPRequestOperations` whose request URL matches the HTTP client base URL with the path appended. For complete control over the lifecycle of enqueued operations, you can access the `operationQueue` property directly, which allows you to, for instance, cancel operations filtered by a predicate, or simply use `-cancelAllRequests`. Note that the operation queue may include non-HTTP operations, so be sure to check the type before attempting to directly introspect an operation's `request` property.
@param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled.
@param path The path appended to the HTTP client base URL to match against the cancelled requests. If `nil`, no path will be appended to the base URL.
*/
- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
///---------------------------------------
/// @name Batching HTTP Request Operations
///---------------------------------------
/**
Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
Operations are created by passing the specified `NSURLRequest` objects in `requests`, using `-HTTPRequestOperationWithRequest:success:failure:`, with `nil` for both the `success` and `failure` parameters.
@param urlRequests The `NSURLRequest` objects used to create and enqueue operations.
@param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
@param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
*/
- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
/**
Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
@param operations The request operations used to be batched and enqueued.
@param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
@param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
*/
- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
///---------------------------
/// @name Making HTTP Requests
///---------------------------
/**
Creates an `AFHTTPRequestOperation` with a `GET` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and appended as the query string for the request URL.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)getPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)postPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)putPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and appended as the query string for the request URL.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)deletePath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)patchPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
@end
///----------------
/// @name Constants
///----------------
/**
## Network Reachability
The following constants are provided by `AFHTTPClient` as possible network reachability statuses.
enum {
AFNetworkReachabilityStatusUnknown,
AFNetworkReachabilityStatusNotReachable,
AFNetworkReachabilityStatusReachableViaWWAN,
AFNetworkReachabilityStatusReachableViaWiFi,
}
`AFNetworkReachabilityStatusUnknown`
The `baseURL` host reachability is not known.
`AFNetworkReachabilityStatusNotReachable`
The `baseURL` host cannot be reached.
`AFNetworkReachabilityStatusReachableViaWWAN`
The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
`AFNetworkReachabilityStatusReachableViaWiFi`
The `baseURL` host can be reached via a Wi-Fi connection.
### Keys for Notification UserInfo Dictionary
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
`AFNetworkingReachabilityNotificationStatusItem`
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
## Parameter Encoding
The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values.
enum {
AFFormURLParameterEncoding,
AFJSONParameterEncoding,
AFPropertyListParameterEncoding,
}
`AFFormURLParameterEncoding`
Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise. Dictionary keys are sorted with the `caseInsensitiveCompare:` selector of their description, in order to mitigate the possibility of ambiguous query strings being generated non-deterministically. See the warning for the `parameterEncoding` property for additional information.
`AFJSONParameterEncoding`
Parameters are encoded into JSON in the message body.
`AFPropertyListParameterEncoding`
Parameters are encoded into a property list in the message body.
*/
///----------------
/// @name Functions
///----------------
/**
Returns a query string constructed by a set of parameters, using the specified encoding.
Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&".
If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component.
@param parameters The parameters used to construct the query string
@param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (`NSUTF8StringEncoding`), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs.
@return A percent-escaped query string
*/
extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
///--------------------
/// @name Notifications
///--------------------
/**
Posted when network reachability changes.
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
*/
#ifdef _SYSTEMCONFIGURATION_H
extern NSString * const AFNetworkingReachabilityDidChangeNotification;
extern NSString * const AFNetworkingReachabilityNotificationStatusItem;
#endif
#pragma mark -
extern NSUInteger const kAFUploadStream3GSuggestedPacketSize;
extern NSTimeInterval const kAFUploadStream3GSuggestedDelay;
/**
The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPClient -multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`.
*/
@protocol AFMultipartFormData
/**
Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
@return `YES` if the file data was successfully appended, otherwise `NO`.
*/
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
error:(NSError * __autoreleasing *)error;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
@param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
@return `YES` if the file data was successfully appended otherwise `NO`.
*/
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType
error:(NSError * __autoreleasing *)error;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
@param inputStream The input stream to be appended to the form data
@param name The name to be associated with the specified input stream. This parameter must not be `nil`.
@param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
@param length The length of the specified input stream in bytes.
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
*/
- (void)appendPartWithInputStream:(NSInputStream *)inputStream
name:(NSString *)name
fileName:(NSString *)fileName
length:(unsigned long long)length
mimeType:(NSString *)mimeType;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
@param data The data to be encoded and appended to the form data.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
*/
- (void)appendPartWithFileData:(NSData *)data
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType;
/**
Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
@param data The data to be encoded and appended to the form data.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
*/
- (void)appendPartWithFormData:(NSData *)data
name:(NSString *)name;
/**
Appends HTTP headers, followed by the encoded data and the multipart form boundary.
@param headers The HTTP headers to be appended to the form data.
@param body The data to be encoded and appended to the form data.
*/
- (void)appendPartWithHeaders:(NSDictionary *)headers
body:(NSData *)body;
/**
Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, as of iOS 6, there is no definite way to distinguish between a 3G, EDGE, or LTE connection. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
@param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 32kb.
@param delay Duration of delay each time a packet is read. By default, no delay is set.
*/
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
delay:(NSTimeInterval)delay;
@end

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
// AFHTTPRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
// Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@ -28,82 +28,26 @@
*/
@interface AFHTTPRequestOperation : AFURLConnectionOperation
///----------------------------------------------
///------------------------------------------------
/// @name Getting HTTP URL Connection Information
///----------------------------------------------
///------------------------------------------------
/**
The last HTTP response received by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSHTTPURLResponse *response;
///----------------------------------------------------------
/// @name Managing And Checking For Acceptable HTTP Responses
///----------------------------------------------------------
/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an AFHTTPResponse serializer, which uses the raw data as its response object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
@warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value
*/
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
/**
A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`.
An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error.
*/
@property (nonatomic, readonly) BOOL hasAcceptableStatusCode;
/**
A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`.
*/
@property (nonatomic, readonly) BOOL hasAcceptableContentType;
/**
The callback dispatch queue on success. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, assign) dispatch_queue_t successCallbackQueue;
/**
The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
///------------------------------------------------------------
/// @name Managing Acceptable HTTP Status Codes & Content Types
///------------------------------------------------------------
/**
Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
By default, this is the range 200 to 299, inclusive.
*/
+ (NSIndexSet *)acceptableStatusCodes;
/**
Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants.
@param statusCodes The status codes to be added to the set of acceptable HTTP status codes
*/
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes;
/**
Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
By default, this is `nil`.
*/
+ (NSSet *)acceptableContentTypes;
/**
Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendants.
@param contentTypes The content types to be added to the set of acceptable MIME types
*/
+ (void)addAcceptableContentTypes:(NSSet *)contentTypes;
///-----------------------------------------------------
/// @name Determining Whether A Request Can Be Processed
///-----------------------------------------------------
/**
A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`.
@param urlRequest The request that is determined to be supported or not supported for this class.
*/
+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
@property (readonly, nonatomic, strong) id responseObject;
///-----------------------------------------------------------
/// @name Setting Completion Block Success / Failure Callbacks
@ -121,13 +65,3 @@
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
@end
///----------------
/// @name Functions
///----------------
/**
Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header.
*/
extern NSSet * AFContentTypesFromHTTPHeader(NSString *string);

View File

@ -1,6 +1,6 @@
// AFHTTPRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
// Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@ -21,247 +21,88 @@
// THE SOFTWARE.
#import "AFHTTPRequestOperation.h"
#import <objc/runtime.h>
// Workaround for change in imp_implementationWithBlock() with Xcode 4.5
#if defined(__IPHONE_6_0) || defined(__MAC_10_8)
#define AF_CAST_TO_BLOCK id
#else
#define AF_CAST_TO_BLOCK __bridge void *
#endif
static dispatch_queue_t http_request_operation_processing_queue() {
static dispatch_queue_t af_http_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wstrict-selector-match"
NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
if (!string) {
return nil;
}
NSArray *mediaRanges = [string componentsSeparatedByString:@","];
NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count];
[mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, __unused NSUInteger idx, __unused BOOL *stop) {
NSRange parametersRange = [mediaRange rangeOfString:@";"];
if (parametersRange.location != NSNotFound) {
mediaRange = [mediaRange substringToIndex:parametersRange.location];
}
mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (mediaRange.length > 0) {
[mutableContentTypes addObject:mediaRange];
}
}];
return [NSSet setWithSet:mutableContentTypes];
return af_http_request_operation_processing_queue;
}
static void AFGetMediaTypeAndSubtypeWithString(NSString *string, NSString **type, NSString **subtype) {
if (!string) {
return;
}
static dispatch_group_t http_request_operation_completion_group() {
static dispatch_group_t af_http_request_operation_completion_group;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_http_request_operation_completion_group = dispatch_group_create();
});
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[scanner scanUpToString:@"/" intoString:type];
[scanner scanString:@"/" intoString:nil];
[scanner scanUpToString:@";" intoString:subtype];
}
static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
NSMutableString *string = [NSMutableString string];
NSRange range = NSMakeRange([indexSet firstIndex], 1);
while (range.location != NSNotFound) {
NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location];
while (nextIndex == range.location + range.length) {
range.length++;
nextIndex = [indexSet indexGreaterThanIndex:nextIndex];
}
if (string.length) {
[string appendString:@","];
}
if (range.length == 1) {
[string appendFormat:@"%lu", (long)range.location];
} else {
NSUInteger firstIndex = range.location;
NSUInteger lastIndex = firstIndex + range.length - 1;
[string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex];
}
range.location = nextIndex;
range.length = 1;
}
return string;
}
static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) {
Method originalMethod = class_getClassMethod(klass, selector);
IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block);
class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod));
return af_http_request_operation_completion_group;
}
#pragma mark -
@interface AFHTTPRequestOperation ()
@interface AFURLConnectionOperation ()
@property (readwrite, nonatomic, strong) NSURLRequest *request;
@property (readwrite, nonatomic, strong) NSURLResponse *response;
@end
@interface AFHTTPRequestOperation ()
@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
@property (readwrite, nonatomic, strong) NSError *HTTPError;
@property (readwrite, nonatomic, strong) id responseObject;
@property (readwrite, nonatomic, strong) NSError *responseSerializationError;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@end
@implementation AFHTTPRequestOperation
@synthesize HTTPError = _HTTPError;
@synthesize successCallbackQueue = _successCallbackQueue;
@synthesize failureCallbackQueue = _failureCallbackQueue;
@dynamic lock;
@dynamic request;
@dynamic response;
- (void)dealloc {
if (_successCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_release(_successCallbackQueue);
#endif
_successCallbackQueue = NULL;
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
if (_failureCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_release(_failureCallbackQueue);
#endif
_failureCallbackQueue = NULL;
}
self.responseSerializer = [AFHTTPResponseSerializer serializer];
return self;
}
- (NSError *)error {
[self.lock lock];
if (!self.HTTPError && self.response) {
if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey];
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
[userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey];
[userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey];
- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
NSParameterAssert(responseSerializer);
if (![self hasAcceptableStatusCode]) {
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
[userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey];
self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo];
} else if (![self hasAcceptableContentType]) {
// Don't invalidate content type if there is no content
if ([self.responseData length] > 0) {
[userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected content type %@, got %@", @"AFNetworking", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
}
[self.lock lock];
_responseSerializer = responseSerializer;
self.responseObject = nil;
self.responseSerializationError = nil;
[self.lock unlock];
}
- (id)responseObject {
[self.lock lock];
if (!_responseObject && [self isFinished] && !self.error) {
NSError *error = nil;
self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error];
if (error) {
self.responseSerializationError = error;
}
}
[self.lock unlock];
if (self.HTTPError) {
return self.HTTPError;
return _responseObject;
}
- (NSError *)error {
if (_responseSerializationError) {
return _responseSerializationError;
} else {
return [super error];
}
}
- (NSStringEncoding)responseStringEncoding {
// When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST be labeled with an appropriate charset value.
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.4.1
if (self.response && !self.response.textEncodingName && self.responseData && [self.response respondsToSelector:@selector(allHeaderFields)]) {
NSString *type = nil;
AFGetMediaTypeAndSubtypeWithString([[self.response allHeaderFields] valueForKey:@"Content-Type"], &type, nil);
if ([type isEqualToString:@"text"]) {
return NSISOLatin1StringEncoding;
}
}
return [super responseStringEncoding];
}
- (void)pause {
unsigned long long offset = 0;
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
} else {
offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
}
NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) {
[mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
}
[mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
self.request = mutableURLRequest;
[super pause];
}
- (BOOL)hasAcceptableStatusCode {
if (!self.response) {
return NO;
}
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode];
}
- (BOOL)hasAcceptableContentType {
if (!self.response) {
return NO;
}
// Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html
NSString *contentType = [self.response MIMEType];
if (!contentType) {
contentType = @"application/octet-stream";
}
return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType];
}
- (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue {
if (successCallbackQueue != _successCallbackQueue) {
if (_successCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_release(_successCallbackQueue);
#endif
_successCallbackQueue = NULL;
}
if (successCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_retain(successCallbackQueue);
#endif
_successCallbackQueue = successCallbackQueue;
}
}
}
- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
if (failureCallbackQueue != _failureCallbackQueue) {
if (_failureCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_release(_failureCallbackQueue);
#endif
_failureCallbackQueue = NULL;
}
if (failureCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_retain(failureCallbackQueue);
#endif
_failureCallbackQueue = failureCallbackQueue;
}
}
}
#pragma mark - AFHTTPRequestOperation
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
@ -271,57 +112,95 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^{
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, self.responseData);
});
}
if (self.completionGroup) {
dispatch_group_enter(self.completionGroup);
}
dispatch_async(http_request_operation_processing_queue(), ^{
if (self.error) {
if (failure) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
id responseObject = self.responseObject;
if (self.error) {
if (failure) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
success(self, responseObject);
});
}
}
}
if (self.completionGroup) {
dispatch_group_leave(self.completionGroup);
}
});
};
#pragma clang diagnostic pop
}
#pragma mark - AFHTTPRequestOperation
#pragma mark - AFURLRequestOperation
+ (NSIndexSet *)acceptableStatusCodes {
return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
}
- (void)pause {
[super pause];
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes {
NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]];
[mutableStatusCodes addIndexes:statusCodes];
AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(__unused id _self) {
return mutableStatusCodes;
});
}
+ (NSSet *)acceptableContentTypes {
return nil;
}
+ (void)addAcceptableContentTypes:(NSSet *)contentTypes {
NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES];
[mutableContentTypes unionSet:contentTypes];
AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(__unused id _self) {
return mutableContentTypes;
});
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
return YES;
u_int64_t offset = 0;
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
} else {
offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
}
return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) {
[mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
}
[mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
self.request = mutableURLRequest;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
AFHTTPRequestOperation *operation = [super copyWithZone:zone];
operation.responseSerializer = [self.responseSerializer copyWithZone:zone];
operation.completionQueue = self.completionQueue;
operation.completionGroup = self.completionGroup;
return operation;
}
@end
#pragma clang diagnostic pop

View File

@ -1,113 +0,0 @@
// AFImageRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
#import <Availability.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
#import <Cocoa/Cocoa.h>
#endif
/**
`AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and processing images.
## Acceptable Content Types
By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
- `image/tiff`
- `image/jpeg`
- `image/gif`
- `image/png`
- `image/ico`
- `image/x-icon`
- `image/bmp`
- `image/x-bmp`
- `image/x-xbitmap`
- `image/x-win-bitmap`
*/
@interface AFImageRequestOperation : AFHTTPRequestOperation
/**
An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error.
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
@property (readonly, nonatomic, strong) UIImage *responseImage;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
@property (readonly, nonatomic, strong) NSImage *responseImage;
#endif
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
/**
The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
*/
@property (nonatomic, assign) CGFloat imageScale;
/**
Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
*/
@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
#endif
/**
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
@param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single argument, the image created from the response data of the request.
@return A new image request operation
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSImage *image))success;
#endif
/**
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
@param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image.
@param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data.
@param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation.
@return A new image request operation
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
#endif
@end

View File

@ -1,321 +0,0 @@
// AFImageRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import "AFImageRequestOperation.h"
static dispatch_queue_t image_request_operation_processing_queue() {
static dispatch_queue_t af_image_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_image_request_operation_processing_queue;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <CoreGraphics/CoreGraphics.h>
static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
UIImage *image = [[UIImage alloc] initWithData:data];
return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
}
static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
if (!data || [data length] == 0) {
return nil;
}
UIImage *image = AFImageWithDataAtScale(data, scale);
if (image.images) {
return image;
}
CGImageRef imageRef = nil;
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
if ([response.MIMEType isEqualToString:@"image/png"]) {
imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
} else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
}
if (!imageRef) {
imageRef = CGImageCreateCopy([image CGImage]);
if (!imageRef) {
CGDataProviderRelease(dataProvider);
return image;
}
}
CGDataProviderRelease(dataProvider);
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate()
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
if (CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
int alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
if (alpha == kCGImageAlphaNone) {
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaNoneSkipFirst;
} else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaPremultipliedFirst;
}
}
CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
CGColorSpaceRelease(colorSpace);
if (!context) {
CGImageRelease(imageRef);
return image;
}
CGRect rect = CGRectMake(0.0f, 0.0f, width, height);
CGContextDrawImage(context, rect, imageRef);
CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
CGImageRelease(inflatedImageRef);
CGImageRelease(imageRef);
return inflatedImage;
}
#endif
@interface AFImageRequestOperation ()
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
@property (readwrite, nonatomic, strong) UIImage *responseImage;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
@property (readwrite, nonatomic, strong) NSImage *responseImage;
#endif
@end
@implementation AFImageRequestOperation
@synthesize responseImage = _responseImage;
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
@synthesize imageScale = _imageScale;
#endif
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success
{
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
if (success) {
success(image);
}
} failure:nil];
}
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSImage *image))success
{
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
if (success) {
success(image);
}
} failure:nil];
}
#endif
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
UIImage *image = responseObject;
if (imageProcessingBlock) {
dispatch_async(image_request_operation_processing_queue(), ^(void) {
UIImage *processedImage = imageProcessingBlock(image);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
success(operation.request, operation.response, processedImage);
});
#pragma clang diagnostic pop
});
} else {
success(operation.request, operation.response, image);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error);
}
}];
return requestOperation;
}
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
NSImage *image = responseObject;
if (imageProcessingBlock) {
dispatch_async(image_request_operation_processing_queue(), ^(void) {
NSImage *processedImage = imageProcessingBlock(image);
dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
success(operation.request, operation.response, processedImage);
});
});
} else {
success(operation.request, operation.response, image);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error);
}
}];
return requestOperation;
}
#endif
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
self.imageScale = [[UIScreen mainScreen] scale];
self.automaticallyInflatesResponseImage = YES;
#endif
return self;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
- (UIImage *)responseImage {
if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
if (self.automaticallyInflatesResponseImage) {
self.responseImage = AFInflatedImageFromResponseWithDataAtScale(self.response, self.responseData, self.imageScale);
} else {
self.responseImage = AFImageWithDataAtScale(self.responseData, self.imageScale);
}
}
return _responseImage;
}
- (void)setImageScale:(CGFloat)imageScale {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wfloat-equal"
if (imageScale == _imageScale) {
return;
}
#pragma clang diagnostic pop
_imageScale = imageScale;
self.responseImage = nil;
}
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
- (NSImage *)responseImage {
if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
// Ensure that the image is set to it's correct pixel width and height
NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData];
self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
[self.responseImage addRepresentation:bitimage];
}
return _responseImage;
}
#endif
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
static NSSet * _acceptablePathExtension = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
});
return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^ {
dispatch_async(image_request_operation_processing_queue(), ^(void) {
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
UIImage *image = nil;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
NSImage *image = nil;
#endif
image = self.responseImage;
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, image);
});
}
}
});
};
#pragma clang diagnostic pop
}
@end

View File

@ -1,71 +0,0 @@
// AFJSONRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
/**
`AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data.
## Acceptable Content Types
By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
- `application/json`
- `text/json`
@warning JSON parsing will use the built-in `NSJSONSerialization` class.
*/
@interface AFJSONRequestOperation : AFHTTPRequestOperation
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
A JSON object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
*/
@property (readonly, nonatomic, strong) id responseJSON;
/**
Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions".
*/
@property (nonatomic, assign) NSJSONReadingOptions JSONReadingOptions;
///----------------------------------
/// @name Creating Request Operations
///----------------------------------
/**
Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the JSON object created from the response data of request.
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as JSON. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new JSON request operation
*/
+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
@end

View File

@ -1,150 +0,0 @@
// AFJSONRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import "AFJSONRequestOperation.h"
static dispatch_queue_t json_request_operation_processing_queue() {
static dispatch_queue_t af_json_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_json_request_operation_processing_queue;
}
@interface AFJSONRequestOperation ()
@property (readwrite, nonatomic, strong) id responseJSON;
@property (readwrite, nonatomic, strong) NSError *JSONError;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@end
@implementation AFJSONRequestOperation
@synthesize responseJSON = _responseJSON;
@synthesize JSONReadingOptions = _JSONReadingOptions;
@synthesize JSONError = _JSONError;
@dynamic lock;
+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
{
AFJSONRequestOperation *requestOperation = [(AFJSONRequestOperation *)[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success(operation.request, operation.response, responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]);
}
}];
return requestOperation;
}
- (id)responseJSON {
[self.lock lock];
if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) {
NSError *error = nil;
// Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
// See https://github.com/rails/rails/issues/1742
if (self.responseString && ![self.responseString isEqualToString:@" "]) {
// Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
// See http://stackoverflow.com/a/12843465/157142
NSData *data = [self.responseString dataUsingEncoding:NSUTF8StringEncoding];
if (data) {
self.responseJSON = [NSJSONSerialization JSONObjectWithData:data options:self.JSONReadingOptions error:&error];
} else {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setValue:@"Operation responseData failed decoding as a UTF-8 string" forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[NSString stringWithFormat:@"Could not decode string: %@", self.responseString] forKey:NSLocalizedFailureReasonErrorKey];
error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
}
self.JSONError = error;
}
[self.lock unlock];
return _responseJSON;
}
- (NSError *)error {
if (_JSONError) {
return _JSONError;
} else {
return [super error];
}
}
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^ {
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
dispatch_async(json_request_operation_processing_queue(), ^{
id JSON = self.responseJSON;
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, JSON);
});
}
}
});
}
};
#pragma clang diagnostic pop
}
@end

View File

@ -1,75 +0,0 @@
// AFNetworkActivityIndicatorManager.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import <Foundation/Foundation.h>
#import <Availability.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
/**
`AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
By setting `isNetworkActivityIndicatorVisible` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself.
See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
*/
@interface AFNetworkActivityIndicatorManager : NSObject
/**
A Boolean value indicating whether the manager is enabled.
If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
*/
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
/**
A Boolean value indicating whether the network activity indicator is currently displayed in the status bar.
*/
@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
/**
Returns the shared network activity indicator manager object for the system.
@return The systemwide network activity indicator manager.
*/
+ (instancetype)sharedManager;
/**
Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
*/
- (void)incrementActivityCount;
/**
Decrements the number of active network requests. If this number becomes zero before decrementing, this will stop animating the status bar network activity indicator.
*/
- (void)decrementActivityCount;
@end
#endif

View File

@ -1,157 +0,0 @@
// AFNetworkActivityIndicatorManager.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import "AFNetworkActivityIndicatorManager.h"
#import "AFHTTPRequestOperation.h"
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
@interface AFNetworkActivityIndicatorManager ()
@property (readwrite, nonatomic, assign) NSInteger activityCount;
@property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer;
@property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
- (void)updateNetworkActivityIndicatorVisibility;
- (void)updateNetworkActivityIndicatorVisibilityDelayed;
@end
@implementation AFNetworkActivityIndicatorManager
@synthesize activityCount = _activityCount;
@synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer;
@synthesize enabled = _enabled;
@dynamic networkActivityIndicatorVisible;
+ (instancetype)sharedManager {
static AFNetworkActivityIndicatorManager *_sharedManager = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedManager = [[self alloc] init];
});
return _sharedManager;
}
+ (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible {
return [NSSet setWithObject:@"activityCount"];
}
- (id)init {
self = [super init];
if (!self) {
return nil;
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidStart:) name:AFNetworkingOperationDidStartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_activityIndicatorVisibilityTimer invalidate];
}
- (void)updateNetworkActivityIndicatorVisibilityDelayed {
if (self.enabled) {
// Delay hiding of activity indicator for a short interval, to avoid flickering
if (![self isNetworkActivityIndicatorVisible]) {
[self.activityIndicatorVisibilityTimer invalidate];
self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes];
} else {
[self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
}
}
- (BOOL)isNetworkActivityIndicatorVisible {
return _activityCount > 0;
}
- (void)updateNetworkActivityIndicatorVisibility {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]];
}
// Not exposed, but used if activityCount is set via KVC.
- (NSInteger)activityCount {
return _activityCount;
}
- (void)setActivityCount:(NSInteger)activityCount {
@synchronized(self) {
_activityCount = activityCount;
}
dispatch_async(dispatch_get_main_queue(), ^{
[self updateNetworkActivityIndicatorVisibilityDelayed];
});
}
- (void)incrementActivityCount {
[self willChangeValueForKey:@"activityCount"];
@synchronized(self) {
_activityCount++;
}
[self didChangeValueForKey:@"activityCount"];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateNetworkActivityIndicatorVisibilityDelayed];
});
}
- (void)decrementActivityCount {
[self willChangeValueForKey:@"activityCount"];
@synchronized(self) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
_activityCount = MAX(_activityCount - 1, 0);
#pragma clang diagnostic pop
}
[self didChangeValueForKey:@"activityCount"];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateNetworkActivityIndicatorVisibilityDelayed];
});
}
- (void)networkingOperationDidStart:(NSNotification *)notification {
AFURLConnectionOperation *connectionOperation = [notification object];
if (connectionOperation.request.URL) {
[self incrementActivityCount];
}
}
- (void)networkingOperationDidFinish:(NSNotification *)notification {
AFURLConnectionOperation *connectionOperation = [notification object];
if (connectionOperation.request.URL) {
[self decrementActivityCount];
}
}
@end
#endif

View File

@ -1,6 +1,6 @@
// AFNetworking.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@ -26,18 +26,19 @@
#ifndef _AFNETWORKING_
#define _AFNETWORKING_
#import "AFURLRequestSerialization.h"
#import "AFURLResponseSerialization.h"
#import "AFSecurityPolicy.h"
#import "AFNetworkReachabilityManager.h"
#import "AFURLConnectionOperation.h"
#import "AFHTTPRequestOperation.h"
#import "AFJSONRequestOperation.h"
#import "AFXMLRequestOperation.h"
#import "AFPropertyListRequestOperation.h"
#import "AFHTTPClient.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFImageRequestOperation.h"
#if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \
( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) )
#import "AFURLSessionManager.h"
#import "AFHTTPSessionManager.h"
#endif
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "AFNetworkActivityIndicatorManager.h"
#import "UIImageView+AFNetworking.h"
#endif
#endif /* _AFNETWORKING_ */

View File

@ -1,68 +0,0 @@
// AFPropertyListRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
/**
`AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data.
## Acceptable Content Types
By default, `AFPropertyListRequestOperation` accepts the following MIME types:
- `application/x-plist`
*/
@interface AFPropertyListRequestOperation : AFHTTPRequestOperation
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
An object deserialized from a plist constructed using the response data.
*/
@property (readonly, nonatomic) id responsePropertyList;
///--------------------------------------
/// @name Managing Property List Behavior
///--------------------------------------
/**
One of the `NSPropertyListMutabilityOptions` options, specifying the mutability of objects deserialized from the property list. By default, this is `NSPropertyListImmutable`.
*/
@property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions;
/**
Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the object deserialized from a plist constructed using the response data.
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new property list request operation
*/
+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure;
@end

View File

@ -1,143 +0,0 @@
// AFPropertyListRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import "AFPropertyListRequestOperation.h"
static dispatch_queue_t property_list_request_operation_processing_queue() {
static dispatch_queue_t af_property_list_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_property_list_request_operation_processing_queue;
}
@interface AFPropertyListRequestOperation ()
@property (readwrite, nonatomic) id responsePropertyList;
@property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat;
@property (readwrite, nonatomic) NSError *propertyListError;
@end
@implementation AFPropertyListRequestOperation
@synthesize responsePropertyList = _responsePropertyList;
@synthesize propertyListReadOptions = _propertyListReadOptions;
@synthesize propertyListFormat = _propertyListFormat;
@synthesize propertyListError = _propertyListError;
+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure
{
AFPropertyListRequestOperation *requestOperation = [(AFPropertyListRequestOperation *)[self alloc] initWithRequest:request];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success(operation.request, operation.response, responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]);
}
}];
return requestOperation;
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.propertyListReadOptions = NSPropertyListImmutable;
return self;
}
- (id)responsePropertyList {
if (!_responsePropertyList && [self.responseData length] > 0 && [self isFinished]) {
NSPropertyListFormat format;
NSError *error = nil;
self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error];
self.propertyListFormat = format;
self.propertyListError = error;
}
return _responsePropertyList;
}
- (NSError *)error {
if (_propertyListError) {
return _propertyListError;
} else {
return [super error];
}
}
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"application/x-plist", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^ {
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
dispatch_async(property_list_request_operation_processing_queue(), ^(void) {
id propertyList = self.responsePropertyList;
if (self.propertyListError) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, propertyList);
});
}
}
});
}
};
#pragma clang diagnostic pop
}
@end

View File

@ -1,6 +1,6 @@
// AFURLConnectionOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
// Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@ -23,6 +23,17 @@
#import <Foundation/Foundation.h>
#import <Availability.h>
#import "AFURLRequestSerialization.h"
#import "AFURLResponseSerialization.h"
#import "AFSecurityPolicy.h"
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
/**
`AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
@ -44,14 +55,11 @@
- `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
- `connection:willCacheResponse:`
- `connectionShouldUseCredentialStorage:`
- `connection:needNewBodyStream:`
- `connection:willSendRequestForAuthenticationChallenge:`
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
## Class Constructors
Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`.
## Callbacks and Completion Blocks
The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
@ -64,7 +72,11 @@
SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice.
When `defaultSSLPinningMode` is defined on `AFHTTPClient` and the Security framework is linked, connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
Connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
## App Extensions
When using AFNetworking in an App Extension, `#define AF_APP_EXTENSIONS` to avoid using unavailable APIs.
## NSCoding & NSCopying Conformance
@ -79,21 +91,10 @@
- `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.
- A copy of an operation will not include the `outputStream` of the original.
- Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
- Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
*/
typedef enum {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
} AFURLConnectionOperationSSLPinningMode;
@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate,
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000) || \
(defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
NSURLConnectionDataDelegate,
#endif
NSCoding, NSCopying>
@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying>
///-------------------------------
/// @name Accessing Run Loop Modes
@ -123,13 +124,6 @@ NSCoding, NSCopying>
*/
@property (readonly, nonatomic, strong) NSError *error;
/**
Whether the connection should accept an invalid SSL certificate.
If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`.
*/
@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate;
///----------------------------
/// @name Getting Response Data
///----------------------------
@ -169,12 +163,14 @@ NSCoding, NSCopying>
*/
@property (nonatomic, strong) NSURLCredential *credential;
/**
The pinning mode which will be used for SSL connections. `AFSSLPinningModePublicKey` by default.
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
SSL Pinning requires that the Security framework is linked with the binary. See the "SSL Pinning" section in the `AFURLConnectionOperation`" header for more information.
/**
The security policy used to evaluate server trust for secure connections.
*/
@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode SSLPinningMode;
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
///------------------------
/// @name Accessing Streams
@ -190,10 +186,24 @@ NSCoding, NSCopying>
/**
The output stream that is used to write data received until the request is finished.
By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request, with the intermediary `outputStream` property set to `nil`. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
*/
@property (nonatomic, strong) NSOutputStream *outputStream;
///---------------------------------
/// @name Managing Callback Queues
///---------------------------------
/**
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, strong) dispatch_queue_t completionQueue;
/**
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
@property (nonatomic, strong) dispatch_group_t completionGroup;
///---------------------------------------------
/// @name Managing Request Operation Information
///---------------------------------------------
@ -214,7 +224,7 @@ NSCoding, NSCopying>
@param urlRequest The request object to be used by the operation connection.
*/
- (id)initWithRequest:(NSURLRequest *)urlRequest;
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest NS_DESIGNATED_INITIALIZER;
///----------------------------------
/// @name Pausing / Resuming Requests
@ -249,8 +259,8 @@ NSCoding, NSCopying>
Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
@param handler A handler to be called shortly before the applications remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the applications suspension momentarily while the application is notified.
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;
#endif
@ -286,12 +296,13 @@ NSCoding, NSCopying>
- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
/**
Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`.
Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDataDelegate` method `connection:willSendRequest:redirectResponse:`.
@param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect.
*/
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
/**
Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
@ -299,61 +310,16 @@ NSCoding, NSCopying>
*/
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
@end
///----------------
/// @name Constants
///----------------
///
/**
## SSL Pinning Options
The following constants are provided by `AFURLConnectionOperation` as possible SSL Pinning options.
enum {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
}
`AFSSLPinningModeNone`
Do not pin SSL connections
`AFSSLPinningModePublicKey`
Pin SSL connections to certificate public key (SPKI).
`AFSSLPinningModeCertificate`
Pin SSL connections to exact certificate. This may cause problems when your certificate expires and needs re-issuance.
## User info dictionary keys
These keys may exist in the user info dictionary, in addition to those defined for NSError.
- `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
### Constants
`AFNetworkingOperationFailingURLRequestErrorKey`
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
`AFNetworkingOperationFailingURLResponseErrorKey`
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
## Error Domains
The following error domain is predefined.
- `NSString * const AFNetworkingErrorDomain`
### Constants
`AFNetworkingErrorDomain`
AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`.
*/
extern NSString * const AFNetworkingErrorDomain;
extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
+ (NSArray *)batchOfRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
@end
///--------------------
/// @name Notifications

View File

@ -1,6 +1,6 @@
// AFURLConnectionOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
// Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@ -31,26 +31,40 @@
// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files.
#endif
typedef enum {
typedef NS_ENUM(NSInteger, AFOperationState) {
AFOperationPausedState = -1,
AFOperationReadyState = 1,
AFOperationExecutingState = 2,
AFOperationFinishedState = 3,
} _AFOperationState;
};
typedef signed short AFOperationState;
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS)
typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier;
#else
typedef id AFBackgroundTaskIdentifier;
#endif
static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock";
static dispatch_group_t url_request_operation_completion_group() {
static dispatch_group_t af_url_request_operation_completion_group;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_request_operation_completion_group = dispatch_group_create();
});
NSString * const AFNetworkingErrorDomain = @"AFNetworkingErrorDomain";
NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"AFNetworkingOperationFailingURLRequestErrorKey";
NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"AFNetworkingOperationFailingURLResponseErrorKey";
return af_url_request_operation_completion_group;
}
static dispatch_queue_t url_request_operation_completion_queue() {
static dispatch_queue_t af_url_request_operation_completion_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_request_operation_completion_queue = dispatch_queue_create("com.alamofire.networking.operation.queue", DISPATCH_QUEUE_CONCURRENT );
});
return af_url_request_operation_completion_queue;
}
static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock";
NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start";
NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
@ -70,8 +84,12 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) {
return @"isFinished";
case AFOperationPausedState:
return @"isPaused";
default:
default: {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
return @"state";
#pragma clang diagnostic pop
}
}
}
@ -99,34 +117,25 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
return NO;
case AFOperationPausedState:
return toState == AFOperationReadyState;
default:
return YES;
default: {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
switch (toState) {
case AFOperationPausedState:
case AFOperationReadyState:
case AFOperationExecutingState:
case AFOperationFinishedState:
return YES;
default:
return NO;
}
}
#pragma clang diagnostic pop
}
}
#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
static NSData *AFSecKeyGetData(SecKeyRef key) {
CFDataRef data = NULL;
OSStatus status = SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data);
NSCAssert(status == errSecSuccess, @"SecItemExport error: %ld", (long int)status);
NSCParameterAssert(data);
return (__bridge_transfer NSData *)data;
}
#endif
static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
return [(__bridge id)key1 isEqual:(__bridge id)key2];
#else
return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
#endif
}
@interface AFURLConnectionOperation ()
@property (readwrite, nonatomic, assign) AFOperationState state;
@property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@property (readwrite, nonatomic, strong) NSURLConnection *connection;
@property (readwrite, nonatomic, strong) NSURLRequest *request;
@ -149,33 +158,9 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
@end
@implementation AFURLConnectionOperation
@synthesize state = _state;
@synthesize cancelled = _cancelled;
@synthesize connection = _connection;
@synthesize runLoopModes = _runLoopModes;
@synthesize request = _request;
@synthesize response = _response;
@synthesize error = _error;
@synthesize allowsInvalidSSLCertificate = _allowsInvalidSSLCertificate;
@synthesize responseData = _responseData;
@synthesize responseString = _responseString;
@synthesize responseStringEncoding = _responseStringEncoding;
@synthesize totalBytesRead = _totalBytesRead;
@dynamic inputStream;
@synthesize outputStream = _outputStream;
@synthesize credential = _credential;
@synthesize SSLPinningMode = _SSLPinningMode;
@synthesize shouldUseCredentialStorage = _shouldUseCredentialStorage;
@synthesize userInfo = _userInfo;
@synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier;
@synthesize uploadProgress = _uploadProgress;
@synthesize downloadProgress = _downloadProgress;
@synthesize authenticationChallenge = _authenticationChallenge;
@synthesize cacheResponse = _cacheResponse;
@synthesize redirectResponse = _redirectResponse;
@synthesize lock = _lock;
+ (void)networkRequestThreadEntryPoint:(id __unused)object {
+ (void)networkRequestThreadEntryPoint:(id)__unused object {
@autoreleasepool {
[[NSThread currentThread] setName:@"AFNetworking"];
@ -196,70 +181,7 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
return _networkRequestThread;
}
+ (NSArray *)pinnedCertificates {
static NSArray *_pinnedCertificates = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSBundle *bundle = [NSBundle mainBundle];
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
_pinnedCertificates = [[NSArray alloc] initWithArray:certificates];
});
return _pinnedCertificates;
}
+ (NSArray *)pinnedPublicKeys {
static NSArray *_pinnedPublicKeys = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSArray *pinnedCertificates = [self pinnedCertificates];
NSMutableArray *publicKeys = [NSMutableArray arrayWithCapacity:[pinnedCertificates count]];
for (NSData *data in pinnedCertificates) {
SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data);
NSParameterAssert(allowedCertificate);
SecCertificateRef allowedCertificates[] = {allowedCertificate};
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef allowedTrust = NULL;
OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &allowedTrust);
NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
if (status == errSecSuccess && allowedTrust) {
SecTrustResultType result = 0;
status = SecTrustEvaluate(allowedTrust, &result);
NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
if (status == errSecSuccess) {
SecKeyRef allowedPublicKey = SecTrustCopyPublicKey(allowedTrust);
NSParameterAssert(allowedPublicKey);
if (allowedPublicKey) {
[publicKeys addObject:(__bridge_transfer id)allowedPublicKey];
}
}
CFRelease(allowedTrust);
}
CFRelease(policy);
CFRelease(certificates);
CFRelease(allowedCertificate);
}
_pinnedPublicKeys = [[NSArray alloc] initWithArray:publicKeys];
});
return _pinnedPublicKeys;
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
NSParameterAssert(urlRequest);
self = [super init];
@ -267,6 +189,8 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
return nil;
}
_state = AFOperationReadyState;
self.lock = [[NSRecursiveLock alloc] init];
self.lock.name = kAFNetworkingLockName;
@ -276,12 +200,7 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
self.shouldUseCredentialStorage = YES;
// #ifdef included for backwards-compatibility
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
self.allowsInvalidSSLCertificate = YES;
#endif
self.state = AFOperationReadyState;
self.securityPolicy = [AFSecurityPolicy defaultPolicy];
return self;
}
@ -292,7 +211,7 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
_outputStream = nil;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS)
if (_backgroundTaskIdentifier) {
[[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
_backgroundTaskIdentifier = UIBackgroundTaskInvalid;
@ -300,121 +219,18 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
#endif
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response];
}
#pragma mark -
- (void)setCompletionBlock:(void (^)(void))block {
- (void)setResponseData:(NSData *)responseData {
[self.lock lock];
if (!block) {
[super setCompletionBlock:nil];
if (!responseData) {
_responseData = nil;
} else {
__weak __typeof(&*self)weakSelf = self;
[super setCompletionBlock:^ {
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
block();
[strongSelf setCompletionBlock:nil];
}];
_responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length];
}
[self.lock unlock];
}
- (NSInputStream *)inputStream {
return self.request.HTTPBodyStream;
}
- (void)setInputStream:(NSInputStream *)inputStream {
[self willChangeValueForKey:@"inputStream"];
NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
mutableRequest.HTTPBodyStream = inputStream;
self.request = mutableRequest;
[self didChangeValueForKey:@"inputStream"];
}
- (NSOutputStream *)outputStream {
if (!_outputStream) {
self.outputStream = [NSOutputStream outputStreamToMemory];
}
return _outputStream;
}
- (void)setOutputStream:(NSOutputStream *)outputStream {
[self.lock lock];
if (outputStream != _outputStream) {
[self willChangeValueForKey:@"outputStream"];
if (_outputStream) {
[_outputStream close];
}
_outputStream = outputStream;
[self didChangeValueForKey:@"outputStream"];
}
[self.lock unlock];
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
[self.lock lock];
if (!self.backgroundTaskIdentifier) {
UIApplication *application = [UIApplication sharedApplication];
__weak __typeof(&*self)weakSelf = self;
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
if (handler) {
handler();
}
if (strongSelf) {
[strongSelf cancel];
[application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
}];
}
[self.lock unlock];
}
#endif
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
self.uploadProgress = block;
}
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block {
self.downloadProgress = block;
}
- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block {
self.authenticationChallenge = block;
}
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block {
self.cacheResponse = block;
}
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block {
self.redirectResponse = block;
}
- (void)setState:(AFOperationState)state {
if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
return;
}
[self.lock lock];
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
NSString *newStateKey = AFKeyPathFromOperationState(state);
[self willChangeValueForKey:newStateKey];
[self willChangeValueForKey:oldStateKey];
_state = state;
[self didChangeValueForKey:oldStateKey];
[self didChangeValueForKey:newStateKey];
[self.lock unlock];
}
- (NSString *)responseString {
[self.lock lock];
if (!_responseString && self.response && self.responseData) {
@ -443,15 +259,88 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
return _responseStringEncoding;
}
- (NSInputStream *)inputStream {
return self.request.HTTPBodyStream;
}
- (void)setInputStream:(NSInputStream *)inputStream {
NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
mutableRequest.HTTPBodyStream = inputStream;
self.request = mutableRequest;
}
- (NSOutputStream *)outputStream {
if (!_outputStream) {
self.outputStream = [NSOutputStream outputStreamToMemory];
}
return _outputStream;
}
- (void)setOutputStream:(NSOutputStream *)outputStream {
[self.lock lock];
if (outputStream != _outputStream) {
if (_outputStream) {
[_outputStream close];
}
_outputStream = outputStream;
}
[self.lock unlock];
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
[self.lock lock];
if (!self.backgroundTaskIdentifier) {
UIApplication *application = [UIApplication sharedApplication];
__weak __typeof(self)weakSelf = self;
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (handler) {
handler();
}
if (strongSelf) {
[strongSelf cancel];
[application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
}];
}
[self.lock unlock];
}
#endif
#pragma mark -
- (void)setState:(AFOperationState)state {
if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
return;
}
[self.lock lock];
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
NSString *newStateKey = AFKeyPathFromOperationState(state);
[self willChangeValueForKey:newStateKey];
[self willChangeValueForKey:oldStateKey];
_state = state;
[self didChangeValueForKey:oldStateKey];
[self didChangeValueForKey:newStateKey];
[self.lock unlock];
}
- (void)pause {
if ([self isPaused] || [self isFinished] || [self isCancelled]) {
return;
}
[self.lock lock];
if ([self isExecuting]) {
[self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
[self performSelector:@selector(operationDidPause) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
dispatch_async(dispatch_get_main_queue(), ^{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
@ -460,7 +349,12 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
}
self.state = AFOperationPausedState;
[self.lock unlock];
}
- (void)operationDidPause {
[self.lock lock];
[self.connection cancel];
[self.lock unlock];
}
@ -480,8 +374,57 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
[self.lock unlock];
}
#pragma mark -
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
self.uploadProgress = block;
}
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block {
self.downloadProgress = block;
}
- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block {
self.authenticationChallenge = block;
}
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block {
self.cacheResponse = block;
}
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block {
self.redirectResponse = block;
}
#pragma mark - NSOperation
- (void)setCompletionBlock:(void (^)(void))block {
[self.lock lock];
if (!block) {
[super setCompletionBlock:nil];
} else {
__weak __typeof(self)weakSelf = self;
[super setCompletionBlock:^ {
__strong __typeof(weakSelf)strongSelf = weakSelf;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group();
dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue();
#pragma clang diagnostic pop
dispatch_group_async(group, queue, ^{
block();
});
dispatch_group_notify(group, url_request_operation_completion_queue(), ^{
[strongSelf setCompletionBlock:nil];
});
}];
}
[self.lock unlock];
}
- (BOOL)isReady {
return self.state == AFOperationReadyState && [super isReady];
}
@ -500,7 +443,9 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
- (void)start {
[self.lock lock];
if ([self isReady]) {
if ([self isCancelled]) {
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
} else if ([self isReady]) {
self.state = AFOperationExecutingState;
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
@ -519,6 +464,7 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
}
[self.outputStream open];
[self.connection start];
}
[self.lock unlock];
@ -526,20 +472,12 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self];
});
if ([self isCancelled]) {
NSDictionary *userInfo = nil;
if ([self.request URL]) {
userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
}
self.error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
[self finish];
}
}
- (void)finish {
[self.lock lock];
self.state = AFOperationFinishedState;
[self.lock unlock];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
@ -549,13 +487,11 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
- (void)cancel {
[self.lock lock];
if (![self isFinished] && ![self isCancelled]) {
[self willChangeValueForKey:@"isCancelled"];
_cancelled = YES;
[super cancel];
[self didChangeValueForKey:@"isCancelled"];
// Cancel the connection on the thread it runs on to prevent race conditions
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
if ([self isExecuting]) {
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
}
}
[self.lock unlock];
}
@ -567,12 +503,86 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
}
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
if (![self isFinished] && self.connection) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error];
if (![self isFinished]) {
if (self.connection) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error];
} else {
// Accomodate race condition where `self.connection` has not yet been set before cancellation
self.error = error;
[self finish];
}
}
}
#pragma mark -
+ (NSArray *)batchOfRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock
{
if (!operations || [operations count] == 0) {
return @[[NSBlockOperation blockOperationWithBlock:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (completionBlock) {
completionBlock(@[]);
}
});
}]];
}
__block dispatch_group_t group = dispatch_group_create();
NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
if (completionBlock) {
completionBlock(operations);
}
});
}];
for (AFURLConnectionOperation *operation in operations) {
operation.completionGroup = group;
void (^originalCompletionBlock)(void) = [operation.completionBlock copy];
__weak __typeof(operation)weakOperation = operation;
operation.completionBlock = ^{
__strong __typeof(weakOperation)strongOperation = weakOperation;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue();
#pragma clang diagnostic pop
dispatch_group_async(group, queue, ^{
if (originalCompletionBlock) {
originalCompletionBlock();
}
NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) {
return [op isFinished];
}] count];
if (progressBlock) {
progressBlock(numberOfFinishedOperations, [operations count]);
}
dispatch_group_leave(group);
});
};
dispatch_group_enter(group);
[batchedOperation addDependency:operation];
}
return [operations arrayByAddingObject:batchedOperation];
}
#pragma mark - NSObject
- (NSString *)description {
[self.lock lock];
NSString *description = [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response];
[self.lock unlock];
return description;
}
#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection
@ -584,89 +594,11 @@ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challe
}
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecPolicyRef policy = SecPolicyCreateBasicX509();
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
if (self.SSLPinningMode == AFSSLPinningModeCertificate) {
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
} else if (self.SSLPinningMode == AFSSLPinningModePublicKey) {
SecCertificateRef someCertificates[] = {certificate};
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
SecTrustRef trust = NULL;
OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
if (status == errSecSuccess && trust) {
SecTrustResultType result;
status = SecTrustEvaluate(trust, &result);
NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
if (status == errSecSuccess) {
[trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
}
CFRelease(trust);
}
CFRelease(certificates);
}
}
CFRelease(policy);
switch (self.SSLPinningMode) {
case AFSSLPinningModePublicKey: {
NSArray *pinnedPublicKeys = [self.class pinnedPublicKeys];
for (id publicKey in trustChain) {
for (id pinnedPublicKey in pinnedPublicKeys) {
if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)publicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
return;
}
}
}
[[challenge sender] cancelAuthenticationChallenge:challenge];
break;
}
case AFSSLPinningModeCertificate: {
for (id serverCertificateData in trustChain) {
if ([[self.class pinnedCertificates] containsObject:serverCertificateData]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
return;
}
}
[[challenge sender] cancelAuthenticationChallenge:challenge];
break;
}
case AFSSLPinningModeNone: {
if (self.allowsInvalidSSLCertificate){
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
SecTrustResultType result = 0;
OSStatus status = SecTrustEvaluate(serverTrust, &result);
NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
if (status == errSecSuccess && (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed)) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
break;
}
if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
} else {
if ([challenge previousFailureCount] == 0) {
@ -701,19 +633,17 @@ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challe
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
if (self.uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.uploadProgress) {
self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
});
}
}
});
}
- (void)connection:(NSURLConnection __unused *)connection
didReceiveResponse:(NSURLResponse *)response
{
self.response = response;
[self.outputStream open];
}
- (void)connection:(NSURLConnection __unused *)connection
@ -721,28 +651,32 @@ didReceiveResponse:(NSURLResponse *)response
{
NSUInteger length = [data length];
while (YES) {
NSUInteger totalNumberOfBytesWritten = 0;
NSInteger totalNumberOfBytesWritten = 0;
if ([self.outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = (uint8_t *)[data bytes];
NSInteger numberOfBytesWritten = 0;
while (totalNumberOfBytesWritten < length) {
numberOfBytesWritten = [self.outputStream write:&dataBuffer[0] maxLength:length];
while (totalNumberOfBytesWritten < (NSInteger)length) {
numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)];
if (numberOfBytesWritten == -1) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError];
return;
} else {
totalNumberOfBytesWritten += numberOfBytesWritten;
break;
}
totalNumberOfBytesWritten += numberOfBytesWritten;
}
break;
}
if (self.outputStream.streamError) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError];
return;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
self.totalBytesRead += length;
self.totalBytesRead += (long long)length;
if (self.downloadProgress) {
self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength);
@ -754,10 +688,13 @@ didReceiveResponse:(NSURLResponse *)response
self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
[self.outputStream close];
[self finish];
if (self.responseData) {
self.outputStream = nil;
}
self.connection = nil;
[self finish];
}
- (void)connection:(NSURLConnection __unused *)connection
@ -766,10 +703,13 @@ didReceiveResponse:(NSURLResponse *)response
self.error = error;
[self.outputStream close];
[self finish];
if (self.responseData) {
self.outputStream = nil;
}
self.connection = nil;
[self finish];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
@ -786,48 +726,48 @@ didReceiveResponse:(NSURLResponse *)response
}
}
#pragma mark - NSCoding
#pragma mark - NSSecureCoding
- (id)initWithCoder:(NSCoder *)aDecoder {
NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"];
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
NSURLRequest *request = [decoder decodeObjectOfClass:[NSURLRequest class] forKey:NSStringFromSelector(@selector(request))];
self = [self initWithRequest:request];
if (!self) {
return nil;
}
self.state = (AFOperationState)[aDecoder decodeIntegerForKey:@"state"];
self.cancelled = [aDecoder decodeBoolForKey:@"isCancelled"];
self.response = [aDecoder decodeObjectForKey:@"response"];
self.error = [aDecoder decodeObjectForKey:@"error"];
self.responseData = [aDecoder decodeObjectForKey:@"responseData"];
self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue];
self.allowsInvalidSSLCertificate = [[aDecoder decodeObjectForKey:@"allowsInvalidSSLCertificate"] boolValue];
self.state = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] integerValue];
self.response = [decoder decodeObjectOfClass:[NSHTTPURLResponse class] forKey:NSStringFromSelector(@selector(response))];
self.error = [decoder decodeObjectOfClass:[NSError class] forKey:NSStringFromSelector(@selector(error))];
self.responseData = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(responseData))];
self.totalBytesRead = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesRead))] longLongValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
- (void)encodeWithCoder:(NSCoder *)coder {
[self pause];
[aCoder encodeObject:self.request forKey:@"request"];
[coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))];
switch (self.state) {
case AFOperationExecutingState:
case AFOperationPausedState:
[aCoder encodeInteger:AFOperationReadyState forKey:@"state"];
[coder encodeInteger:AFOperationReadyState forKey:NSStringFromSelector(@selector(state))];
break;
default:
[aCoder encodeInteger:self.state forKey:@"state"];
[coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))];
break;
}
[aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"];
[aCoder encodeObject:self.response forKey:@"response"];
[aCoder encodeObject:self.error forKey:@"error"];
[aCoder encodeObject:self.responseData forKey:@"responseData"];
[aCoder encodeObject:[NSNumber numberWithLongLong:self.totalBytesRead] forKey:@"totalBytesRead"];
[aCoder encodeObject:[NSNumber numberWithBool:self.allowsInvalidSSLCertificate] forKey:@"allowsInvalidSSLCertificate"];
[coder encodeObject:self.response forKey:NSStringFromSelector(@selector(response))];
[coder encodeObject:self.error forKey:NSStringFromSelector(@selector(error))];
[coder encodeObject:self.responseData forKey:NSStringFromSelector(@selector(responseData))];
[coder encodeInt64:self.totalBytesRead forKey:NSStringFromSelector(@selector(totalBytesRead))];
}
#pragma mark - NSCopying
@ -840,7 +780,8 @@ didReceiveResponse:(NSURLResponse *)response
operation.authenticationChallenge = self.authenticationChallenge;
operation.cacheResponse = self.cacheResponse;
operation.redirectResponse = self.redirectResponse;
operation.allowsInvalidSSLCertificate = self.allowsInvalidSSLCertificate;
operation.completionQueue = self.completionQueue;
operation.completionGroup = self.completionGroup;
return operation;
}

View File

@ -1,89 +0,0 @@
// AFXMLRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
#import <Availability.h>
/**
`AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data.
## Acceptable Content Types
By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
- `application/xml`
- `text/xml`
## Use With AFHTTPClient
When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback.
*/
@interface AFXMLRequestOperation : AFHTTPRequestOperation
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
An `NSXMLParser` object constructed from the response data.
*/
@property (readonly, nonatomic, strong) NSXMLParser *responseXMLParser;
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
/**
An `NSXMLDocument` object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
*/
@property (readonly, nonatomic, strong) NSXMLDocument *responseXMLDocument;
#endif
/**
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML parser constructed with the response data of request.
@param failure A block object to be executed when the operation finishes unsuccessfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network error that occurred.
@return A new XML request operation
*/
+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure;
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
/**
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML document created from the response data of request.
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as XML. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new XML request operation
*/
+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure;
#endif
@end

View File

@ -1,167 +0,0 @@
// AFXMLRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import "AFXMLRequestOperation.h"
#include <Availability.h>
static dispatch_queue_t xml_request_operation_processing_queue() {
static dispatch_queue_t af_xml_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_xml_request_operation_processing_queue;
}
@interface AFXMLRequestOperation ()
@property (readwrite, nonatomic, strong) NSXMLParser *responseXMLParser;
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
@property (readwrite, nonatomic, strong) NSXMLDocument *responseXMLDocument;
#endif
@property (readwrite, nonatomic, strong) NSError *XMLError;
@end
@implementation AFXMLRequestOperation
@synthesize responseXMLParser = _responseXMLParser;
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
@synthesize responseXMLDocument = _responseXMLDocument;
#endif
@synthesize XMLError = _XMLError;
+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure
{
AFXMLRequestOperation *requestOperation = [(AFXMLRequestOperation *)[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success(operation.request, operation.response, responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]);
}
}];
return requestOperation;
}
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure
{
AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) {
if (success) {
NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
success(operation.request, operation.response, XMLDocument);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
failure(operation.request, operation.response, error, XMLDocument);
}
}];
return requestOperation;
}
#endif
- (NSXMLParser *)responseXMLParser {
if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) {
self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData];
}
return _responseXMLParser;
}
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
- (NSXMLDocument *)responseXMLDocument {
if (!_responseXMLDocument && [self.responseData length] > 0 && [self isFinished]) {
NSError *error = nil;
self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error];
self.XMLError = error;
}
return _responseXMLDocument;
}
#endif
- (NSError *)error {
if (_XMLError) {
return _XMLError;
} else {
return [super error];
}
}
#pragma mark - NSOperation
- (void)cancel {
[super cancel];
self.responseXMLParser.delegate = nil;
}
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"application/xml", @"text/xml", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^ {
dispatch_async(xml_request_operation_processing_queue(), ^(void) {
NSXMLParser *XMLParser = self.responseXMLParser;
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, XMLParser);
});
}
}
});
};
#pragma clang diagnostic pop
}
@end

View File

@ -1,78 +0,0 @@
// UIImageView+AFNetworking.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import <Foundation/Foundation.h>
#import "AFImageRequestOperation.h"
#import <Availability.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <UIKit/UIKit.h>
/**
This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL.
*/
@interface UIImageView (AFNetworking)
/**
Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
@param url The URL used for the image request.
*/
- (void)setImageWithURL:(NSURL *)url;
/**
Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
@param url The URL used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
*/
- (void)setImageWithURL:(NSURL *)url
placeholderImage:(UIImage *)placeholderImage;
/**
Creates and enqueues an image request operation, which asynchronously downloads the image with the specified URL request object. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is executed.
@param urlRequest The URL request used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
@param success A block to be executed when the image request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`.
@param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
*/
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
/**
Cancels any executing image request operation for the receiver, if one exists.
*/
- (void)cancelImageRequestOperation;
@end
#endif

View File

@ -1,191 +0,0 @@
// UIImageView+AFNetworking.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// 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.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "UIImageView+AFNetworking.h"
@interface AFImageCache : NSCache
- (UIImage *)cachedImageForRequest:(NSURLRequest *)request;
- (void)cacheImage:(UIImage *)image
forRequest:(NSURLRequest *)request;
@end
#pragma mark -
static char kAFImageRequestOperationObjectKey;
@interface UIImageView (_AFNetworking)
@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation;
@end
@implementation UIImageView (_AFNetworking)
@dynamic af_imageRequestOperation;
@end
#pragma mark -
@implementation UIImageView (AFNetworking)
- (AFHTTPRequestOperation *)af_imageRequestOperation {
return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey);
}
- (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation {
objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
+ (NSOperationQueue *)af_sharedImageRequestOperationQueue {
static NSOperationQueue *_af_imageRequestOperationQueue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_imageRequestOperationQueue = [[NSOperationQueue alloc] init];
[_af_imageRequestOperationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
});
return _af_imageRequestOperationQueue;
}
+ (AFImageCache *)af_sharedImageCache {
static AFImageCache *_af_imageCache = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_af_imageCache = [[AFImageCache alloc] init];
});
return _af_imageCache;
}
#pragma mark -
- (void)setImageWithURL:(NSURL *)url {
[self setImageWithURL:url placeholderImage:nil];
}
- (void)setImageWithURL:(NSURL *)url
placeholderImage:(UIImage *)placeholderImage
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
}
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
[self cancelImageRequestOperation];
UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest];
if (cachedImage) {
self.af_imageRequestOperation = nil;
if (success) {
success(nil, nil, cachedImage);
} else {
self.image = cachedImage;
}
} else {
if (placeholderImage) {
self.image = placeholderImage;
}
AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
requestOperation.allowsInvalidSSLCertificate = YES;
#endif
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) {
if (self.af_imageRequestOperation == operation) {
self.af_imageRequestOperation = nil;
}
if (success) {
success(operation.request, operation.response, responseObject);
} else if (responseObject) {
self.image = responseObject;
}
}
[[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) {
if (self.af_imageRequestOperation == operation) {
self.af_imageRequestOperation = nil;
}
if (failure) {
failure(operation.request, operation.response, error);
}
}
}];
self.af_imageRequestOperation = requestOperation;
[[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
}
}
- (void)cancelImageRequestOperation {
[self.af_imageRequestOperation cancel];
self.af_imageRequestOperation = nil;
}
@end
#pragma mark -
static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) {
return [[request URL] absoluteString];
}
@implementation AFImageCache
- (UIImage *)cachedImageForRequest:(NSURLRequest *)request {
switch ([request cachePolicy]) {
case NSURLRequestReloadIgnoringCacheData:
case NSURLRequestReloadIgnoringLocalAndRemoteCacheData:
return nil;
default:
break;
}
return [self objectForKey:AFImageCacheKeyFromURLRequest(request)];
}
- (void)cacheImage:(UIImage *)image
forRequest:(NSURLRequest *)request
{
if (image && request) {
[self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)];
}
}
@end
#endif

View File

@ -1,4 +1,4 @@
Copyright (c) 2011 Gowalla (http://gowalla.com/)
Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com/)
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

@ -2,18 +2,9 @@
<img src="https://raw.github.com/AFNetworking/AFNetworking/assets/afnetworking-logo.png" alt="AFNetworking" title="AFNetworking">
</p>
[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.png?branch=master)](https://travis-ci.org/AFNetworking/AFNetworking)
[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking)
AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of [NSURLConnection](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html), [NSOperation](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html), and other familiar Foundation technologies. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. For example, here's how easy it is to get JSON from a URL:
```objective-c
NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];
[operation start];
```
AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.
Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
@ -21,171 +12,363 @@ Choose AFNetworking for your next project, or migrate over your existing project
## How To Get Started
- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/zipball/master) and try out the included Mac and iPhone example apps
- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles in the wiki](https://github.com/AFNetworking/AFNetworking/wiki)
- Check out the [complete documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at the APIs available in AFNetworking
- Watch the [NSScreencast episode about AFNetworking](http://nsscreencast.com/episodes/6-afnetworking) for a quick introduction to how to use it in your application
- Questions? [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking) is the best place to find answers
- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps
- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki)
- Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking
- Read the [AFNetworking 2.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-2.0-Migration-Guide) for an overview of the architectural changes from 1.0.
## Overview
## Communication
AFNetworking is architected to be as small and modular as possible, in order to make it simple to use and extend.
- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking')
- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking).
- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue.
- If you **have a feature request**, open an issue.
- If you **want to contribute**, submit a pull request.
<table>
<tr><th colspan="2" style="text-align:center;">Core</th></tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFURLConnectionOperation.html">AFURLConnectionOperation</a></td>
<td>An <tt>NSOperation</tt> that implements the <tt>NSURLConnection</tt> delegate methods.</td>
</tr>
### Installation with CocoaPods
<tr><th colspan="2" style="text-align:center;">HTTP Requests</th></tr>
[CocoaPods](http://cocoapods.org) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like AFNetworking in your projects. See the ["Getting Started" guide for more information](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking).
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFHTTPRequestOperation.html">AFHTTPRequestOperation</a></td>
<td>A subclass of <tt>AFURLConnectionOperation</tt> for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.</td>
</tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFJSONRequestOperation.html">AFJSONRequestOperation</a></td>
<td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and working with JSON response data.</td>
</tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFXMLRequestOperation.html">AFXMLRequestOperation</a></td>
<td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and working with XML response data.</td>
</tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFPropertyListRequestOperation.html">AFPropertyListRequestOperation</a></td>
<td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and deserializing objects with <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/index.html">property list</a> response data.</td>
</tr>
#### Podfile
<tr><th colspan="2" style="text-align:center;">HTTP Client</th></tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFHTTPClient.html">AFHTTPClient</a></td>
<td>
Captures the common patterns of communicating with an web application over HTTP, including:
<ul>
<li>Making requests from relative paths of a base URL</li>
<li>Setting HTTP headers to be added automatically to requests</li>
<li>Authenticating requests with HTTP Basic credentials or an OAuth token</li>
<li>Managing an <tt>NSOperationQueue</tt> for requests made by the client</li>
<li>Generating query strings or HTTP bodies from an <tt>NSDictionary</tt></li>
<li>Constructing multipart form requests</li>
<li>Automatically parsing HTTP response data into its corresponding object representation</li>
<li>Monitoring and responding to changes in network reachability</li>
</ul>
</td>
</tr>
<tr><th colspan="2" style="text-align:center;">Images</th></tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFImageRequestOperation.html">AFImageRequestOperation</a></td>
<td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and processing images.</td>
</tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Categories/UIImageView+AFNetworking.html">UIImageView+AFNetworking</a></td>
<td>Adds methods to <tt>UIImageView</tt> for loading remote images asynchronously from a URL.</td>
</tr>
</table>
## Example Usage
### XML Request
```objective-c
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser parse];
} failure:nil];
[operation start];
```
### Image Request
```objective-c
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
```
### API Client Request
```objective-c
// AFAppDotNetAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates
[[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];
```
### File Upload with Progress Callback
```objective-c
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
```
### Streaming Request
```objective-c
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
operation.outputStream = [NSOutputStream outputStreamToMemory];
[operation start];
```ruby
platform :ios, '7.0'
pod "AFNetworking", "~> 2.0"
```
## Requirements
AFNetworking 1.0 and higher requires either [iOS 5.0](http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html) and above, or [Mac OS 10.7](http://developer.apple.com/library/mac/#releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_6.html#//apple_ref/doc/uid/TP40008898-SW7) ([64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)) and above.
| AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Notes |
|:--------------------:|:---------------------------:|:----------------------------:|:-------------------------------------------------------------------------:|
| 2.x | iOS 6 | OS X 10.8 | Xcode 5 is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. |
| [1.x](https://github.com/AFNetworking/AFNetworking/tree/1.x) | iOS 5 | Mac OS X 10.7 | |
| [0.10.x](https://github.com/AFNetworking/AFNetworking/tree/0.10.x) | iOS 4 | Mac OS X 10.6 | |
For compatibility with iOS 4.3, use the latest 0.10.x release.
(OS X projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)).
### ARC
> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs.
AFNetworking uses ARC as of its 1.0 release.
## Architecture
If you are using AFNetworking 1.0 in your non-arc project, you will need to set a `-fobjc-arc` compiler flag on all of the AFNetworking source files. Conversely, if you are adding a pre-1.0 version of AFNetworking, you will need to set a `-fno-objc-arc` compiler flag.
### NSURLConnection
To set a compiler flag in Xcode, go to your active target and select the "Build Phases" tab. Now select all AFNetworking source files, press Enter, insert `-fobjc-arc` or `-fno-objc-arc` and then "Done" to enable or disable ARC for AFNetworking.
- `AFURLConnectionOperation`
- `AFHTTPRequestOperation`
- `AFHTTPRequestOperationManager`
### NSURLSession _(iOS 7 / Mac OS X 10.9)_
- `AFURLSessionManager`
- `AFHTTPSessionManager`
### Serialization
* `<AFURLRequestSerialization>`
- `AFHTTPRequestSerializer`
- `AFJSONRequestSerializer`
- `AFPropertyListRequestSerializer`
* `<AFURLResponseSerialization>`
- `AFHTTPResponseSerializer`
- `AFJSONResponseSerializer`
- `AFXMLParserResponseSerializer`
- `AFXMLDocumentResponseSerializer` _(Mac OS X)_
- `AFPropertyListResponseSerializer`
- `AFImageResponseSerializer`
- `AFCompoundResponseSerializer`
### Additional Functionality
- `AFSecurityPolicy`
- `AFNetworkReachabilityManager`
## Usage
### HTTP Request Operation Manager
`AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management.
#### `GET` Request
```objective-c
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
```
#### `POST` URL-Form-Encoded Request
```objective-c
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
```
#### `POST` Multi-Part Request
```objective-c
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
```
---
### AFURLSessionManager
`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
#### Creating a Download Task
```objective-c
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
```
#### Creating an Upload Task
```objective-c
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
[uploadTask resume];
```
#### Creating an Upload Task for a Multi-Part Request, with Progress
```objective-c
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
```
#### Creating a Data Task
```objective-c
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[dataTask resume];
```
---
### Request Serialization
Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
```objective-c
NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
```
#### Query String Parameter Encoding
```objective-c
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
```
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
#### URL Form Parameter Encoding
```objective-c
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
```
POST http://example.com/
Content-Type: application/x-www-form-urlencoded
foo=bar&baz[]=1&baz[]=2&baz[]=3
#### JSON Parameter Encoding
```objective-c
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
```
POST http://example.com/
Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
---
### Network Reachability Manager
`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
**Network reachability is a diagnostic tool that can be used to understand why a request might have failed. It should not be used to determine whether or not to make a request.**
#### Shared Network Reachability
```objective-c
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];
```
#### HTTP Manager Reachability
```objective-c
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
case AFNetworkReachabilityStatusReachableViaWiFi:
[operationQueue setSuspended:NO];
break;
case AFNetworkReachabilityStatusNotReachable:
default:
[operationQueue setSuspended:YES];
break;
}
}];
[manager.reachabilityManager startMonitoring];
```
---
### Security Policy
`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
Adding pinned SSL certificates to your app helps prevent man-in-the-middle 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 SSL pinning configured and enabled.
#### Allowing Invalid SSL Certificates
```objective-c
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production
```
---
### AFHTTPRequestOperation
`AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
Although `AFHTTPRequestOperationManager` is usually the best way to go about making requests, `AFHTTPRequestOperation` can be used by itself.
#### `GET` with `AFHTTPRequestOperation`
```objective-c
NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
```
#### Batch of Operations
```objective-c
NSMutableArray *mutableOperations = [NSMutableArray array];
for (NSURL *fileURL in filesToUpload) {
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[mutableOperations addObject:operation];
}
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
NSLog(@"All operations in batch complete");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
```
## Unit Tests
AFNetworking includes a suite of unit tests within the Tests subdirectory. In order to run the unit tests, you must install the testing dependencies via CocoaPods. To do so:
AFNetworking includes a suite of unit tests within the Tests subdirectory. In order to run the unit tests, you must install the testing dependencies via [CocoaPods](http://cocoapods.org/):
$ gem install cocoapods # If necessary
$ cd Tests
$ pod install
Once CocoaPods has finished the installation, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode.
Once testing dependencies are installed, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode.
### Test Logging
### Running Tests from the Command Line
By default, the unit tests do not emit any output during execution. For debugging purposes, it can be useful to enable logging of the requests and responses. Logging support is provided by the [AFHTTPRequestOperationLogger](https://github.com/AFNetworking/AFHTTPRequestOperationLogger) extension, which is installed via CocoaPods into the test targets. To enable logging, edit the test Scheme and add an environment variable named `AFTestsLoggingEnabled` with a value of `YES`.
Tests can also be run from the command line or within a continuous integration environment. The [`xcpretty`](https://github.com/mneorr/xcpretty) utility needs to be installed before running the tests from the command line:
### Using xctool
$ gem install xcpretty
If you wish to execute the tests from the command line or within a continuous integration environment, you will need to install [xctool](https://github.com/facebook/xctool). The recommended installation method is [Homebrew](http://mxcl.github.io/homebrew/).
To install the commandline testing support via Homebrew:
$ brew update
$ brew install xctool --HEAD
Once xctool is installed, you can execute the suite via `rake test`.
Once `xcpretty` is installed, you can execute the suite via `rake test`.
## Credits
AFNetworking was created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla).
AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla).
AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/).
@ -195,13 +378,9 @@ And most of all, thanks to AFNetworking's [growing list of contributors](https:/
Follow AFNetworking on Twitter ([@AFNetworking](https://twitter.com/AFNetworking))
### Creators
### Maintainers
[Mattt Thompson](http://github.com/mattt)
[@mattt](https://twitter.com/mattt)
[Scott Raymond](http://github.com/sco)
[@sco](https://twitter.com/sco)
- [Mattt Thompson](http://github.com/mattt) ([@mattt](https://twitter.com/mattt))
## License

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFHTTPClient.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFHTTPRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFImageRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFJSONRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFNetworking.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFPropertyListRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFURLConnectionOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFXMLRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/UIImageView+AFNetworking.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFHTTPClient.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFHTTPRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFImageRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFJSONRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFNetworking.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFPropertyListRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFURLConnectionOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/AFXMLRequestOperation.h

View File

@ -1 +0,0 @@
../../AFNetworking/AFNetworking/UIImageView+AFNetworking.h

View File

@ -1,10 +1,30 @@
PODS:
- AFNetworking (1.3.3)
- AFNetworking (2.5.1):
- AFNetworking/NSURLConnection (= 2.5.1)
- AFNetworking/NSURLSession (= 2.5.1)
- AFNetworking/Reachability (= 2.5.1)
- AFNetworking/Security (= 2.5.1)
- AFNetworking/Serialization (= 2.5.1)
- AFNetworking/UIKit (= 2.5.1)
- AFNetworking/NSURLConnection (2.5.1):
- AFNetworking/Reachability
- AFNetworking/Security
- AFNetworking/Serialization
- AFNetworking/NSURLSession (2.5.1):
- AFNetworking/Reachability
- AFNetworking/Security
- AFNetworking/Serialization
- AFNetworking/Reachability (2.5.1)
- AFNetworking/Security (2.5.1)
- AFNetworking/Serialization (2.5.1)
- AFNetworking/UIKit (2.5.1):
- AFNetworking/NSURLConnection
- AFNetworking/NSURLSession
DEPENDENCIES:
- AFNetworking (~> 1.0)
- AFNetworking (~> 2.1)
SPEC CHECKSUMS:
AFNetworking: 0700ec7a58c36ad217173e167f6e4df7270df66b
AFNetworking: 8bee59492a6ff15d69130efa4d0dc67e0094a52a
COCOAPODS: 0.25.0
COCOAPODS: 0.35.0

View File

@ -1,5 +0,0 @@
#include "Pods-AFNetworking.xcconfig"
GCC_PREPROCESSOR_DEFINITIONS = COCOAPODS=1
HEADER_SEARCH_PATHS = "${PODS_ROOT}/BuildHeaders" "${PODS_ROOT}/BuildHeaders/AFNetworking" "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/AFNetworking"
OTHER_LDFLAGS = -ObjC ${PODS_AFNETWORKING_OTHER_LDFLAGS}
PODS_ROOT = ${SRCROOT}

View File

@ -1,5 +0,0 @@
#import <Foundation/Foundation.h>
@interface PodsDummy_Pods_AFNetworking : NSObject
@end
@implementation PodsDummy_Pods_AFNetworking
@end

View File

@ -1,19 +0,0 @@
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#endif
#import "Pods-environment.h"
#import <Availability.h>
#define _AFNETWORKING_PIN_SSL_CERTIFICATES_
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <SystemConfiguration/SystemConfiguration.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <Security/Security.h>
#else
#import <SystemConfiguration/SystemConfiguration.h>
#import <CoreServices/CoreServices.h>
#import <Security/Security.h>
#endif

View File

@ -1 +0,0 @@
PODS_AFNETWORKING_OTHER_LDFLAGS = -framework CoreGraphics -framework MobileCoreServices -framework Security -framework SystemConfiguration

View File

@ -1,26 +0,0 @@
# Acknowledgements
This application makes use of the following third party libraries:
## AFNetworking
Copyright (c) 2011 Gowalla (http://gowalla.com/)
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.
Generated by CocoaPods - http://cocoapods.org

View File

@ -1,56 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreferenceSpecifiers</key>
<array>
<dict>
<key>FooterText</key>
<string>This application makes use of the following third party libraries:</string>
<key>Title</key>
<string>Acknowledgements</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>Copyright (c) 2011 Gowalla (http://gowalla.com/)
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.
</string>
<key>Title</key>
<string>AFNetworking</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>Generated by CocoaPods - http://cocoapods.org</string>
<key>Title</key>
<string></string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
</array>
<key>StringsTable</key>
<string>Acknowledgements</string>
<key>Title</key>
<string>Acknowledgements</string>
</dict>
</plist>

View File

@ -1,5 +0,0 @@
#import <Foundation/Foundation.h>
@interface PodsDummy_Pods : NSObject
@end
@implementation PodsDummy_Pods
@end

View File

@ -1,14 +0,0 @@
// To check if a library is compiled with CocoaPods you
// can use the `COCOAPODS` macro definition which is
// defined in the xcconfigs so it is available in
// headers also when they are imported in the client
// project.
// AFNetworking
#define COCOAPODS_POD_AVAILABLE_AFNetworking
#define COCOAPODS_VERSION_MAJOR_AFNetworking 1
#define COCOAPODS_VERSION_MINOR_AFNetworking 3
#define COCOAPODS_VERSION_PATCH_AFNetworking 3

View File

@ -1,47 +0,0 @@
#!/bin/sh
set -e
RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
> "$RESOURCES_TO_COPY"
install_resource()
{
case $1 in
*.storyboard)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}"
;;
*.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}"
;;
*.framework)
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
echo "rsync -av ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
rsync -av "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
;;
*.xcdatamodel)
echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1"`.mom\""
xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodel`.mom"
;;
*.xcdatamodeld)
echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd\""
xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd"
;;
/*)
echo "$1"
echo "$1" >> "$RESOURCES_TO_COPY"
;;
*)
echo "${PODS_ROOT}/$1"
echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY"
;;
esac
}
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
if [[ "${ACTION}" == "install" ]]; then
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
rm -f "$RESOURCES_TO_COPY"

View File

@ -1,4 +0,0 @@
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/AFNetworking"
OTHER_LDFLAGS = -ObjC -framework CoreGraphics -framework MobileCoreServices -framework Security -framework SystemConfiguration
PODS_ROOT = ${SRCROOT}/../Pods

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
LastUpgradeVersion = "0510"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@ -14,7 +14,7 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "FEFF1D6E156342BEA878F340"
BlueprintIdentifier = "5A5132A30033F73A0B09AB23"
BuildableName = "libPods-AFNetworking.a"
BlueprintName = "Pods-AFNetworking"
ReferencedContainer = "container:Pods.xcodeproj">

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
LastUpgradeVersion = "0510"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@ -14,7 +14,7 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "9DF4A09206094F4EB8B7F841"
BlueprintIdentifier = "54F2167647AE5DDA578E3CBC"
BuildableName = "libPods.a"
BlueprintName = "Pods"
ReferencedContainer = "container:Pods.xcodeproj">

View File

@ -6,43 +6,23 @@
<dict>
<key>Pods-AFNetworking.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>3</integer>
<key>isShown</key>
<false/>
</dict>
<key>Pods.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>2</integer>
<key>isShown</key>
<false/>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>0A30FD7007D548689A8CFA96</key>
<key>54F2167647AE5DDA578E3CBC</key>
<dict>
<key>primary</key>
<true/>
</dict>
<key>7934141CDD144029B68BBCCA</key>
<dict>
<key>primary</key>
<true/>
</dict>
<key>9DF4A09206094F4EB8B7F841</key>
<dict>
<key>primary</key>
<true/>
</dict>
<key>ADDE8DBB9F9E475B90FBC797</key>
<dict>
<key>primary</key>
<true/>
</dict>
<key>B044D459E2CB44439DF863F1</key>
<dict>
<key>primary</key>
<true/>
</dict>
<key>FEFF1D6E156342BEA878F340</key>
<key>5A5132A30033F73A0B09AB23</key>
<dict>
<key>primary</key>
<true/>

View File

@ -12,7 +12,7 @@ static bool cacheEnabled = false;
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
static NSOperationQueue* sharedQueue;
static void (^reachabilityChangeBlock)(int);
static bool loggingEnabled = false;
static bool loggingEnabled = true;
+(void)setLoggingEnabled:(bool) state {
loggingEnabled = state;
@ -26,8 +26,8 @@ static bool loggingEnabled = false;
cacheEnabled = enabled;
}
+(void)configureCacheWithMemoryAndDiskCapacity:(unsigned long) memorySize
diskSize:(unsigned long) diskSize {
+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize
diskSize: (unsigned long) diskSize {
NSAssert(memorySize > 0, @"invalid in-memory cache size");
NSAssert(diskSize >= 0, @"invalid disk cache size");
@ -234,32 +234,51 @@ static bool loggingEnabled = false;
NSLog(@"request: %@ response: %@ ", [self descriptionForRequest:request], data );
}
-(NSNumber*) dictionary:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock {
-(NSNumber*) dictionary: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock {
NSMutableURLRequest * request = nil;
if ([body isKindOfClass:[SWGFile class]]){
SWGFile * file = (SWGFile*) body;
if (body != nil && [body isKindOfClass:[NSArray class]]){
SWGFile * file;
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
for(id obj in body) {
if([obj isKindOfClass:[SWGFile class]]) {
file = (SWGFile*) obj;
requestContentType = @"multipart/form-data";
}
else if([obj isKindOfClass:[NSDictionary class]]) {
for(NSString * key in obj) {
params[key] = obj[key];
}
}
}
NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString];
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
URLString:urlString
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:[file data]
name:@"image"
fileName:[file name]
mimeType:[file mimeType]];
}
error:nil];
if(file != nil) {
request = [self.requestSerializer multipartFormRequestWithMethod: @"POST"
URLString: urlString
parameters: nil
constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) {
for(NSString * key in params) {
NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData: data name: key];
}
[formData appendPartWithFileData: [file data]
name: [file paramName]
fileName: [file name]
mimeType: [file mimeType]];
}
error:nil];
}
}
else {
NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
@ -286,9 +305,11 @@ static bool loggingEnabled = false;
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
}
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
if(body != nil) {
if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){
[request setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
[requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
}
else if ([body isKindOfClass:[SWGFile class]]) {}
else {
@ -300,7 +321,7 @@ static bool loggingEnabled = false;
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[request setValue:[headerParams valueForKey:responseContentType] forHTTPHeaderField:@"Accept"];
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];
@ -339,39 +360,59 @@ static bool loggingEnabled = false;
return requestId;
}
-(NSNumber*) stringWithCompletionBlock:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(NSString*, NSError *))completionBlock {
-(NSNumber*) stringWithCompletionBlock: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(NSString*, NSError *))completionBlock {
NSMutableURLRequest * request = nil;
if ([body isKindOfClass:[SWGFile class]]){
SWGFile * file = (SWGFile*) body;
if (body != nil && [body isKindOfClass:[NSArray class]]){
SWGFile * file;
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
for(id obj in body) {
if([obj isKindOfClass:[SWGFile class]]) {
file = (SWGFile*) obj;
requestContentType = @"multipart/form-data";
}
else if([obj isKindOfClass:[NSDictionary class]]) {
for(NSString * key in obj) {
params[key] = obj[key];
}
}
}
NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString];
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
URLString:urlString
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:[file data]
name:@"image"
fileName:[file name]
mimeType:[file mimeType]];
}
error:nil];
if(file != nil) {
request = [self.requestSerializer multipartFormRequestWithMethod: @"POST"
URLString: urlString
parameters: nil
constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) {
for(NSString * key in params) {
NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData: data name: key];
}
[formData appendPartWithFileData: [file data]
name: [file paramName]
fileName: [file name]
mimeType: [file mimeType]];
}
error:nil];
}
}
else {
NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:body
error:nil];
request = [self.requestSerializer requestWithMethod: method
URLString: urlString
parameters: body
error: nil];
}
BOOL hasHeaderParams = false;
if(headerParams != nil && [headerParams count] > 0)
@ -389,9 +430,12 @@ static bool loggingEnabled = false;
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
}
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
if(body != nil) {
if([body isKindOfClass:[NSDictionary class]]){
[request setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){
[requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
}
else if ([body isKindOfClass:[SWGFile class]]){}
else {
@ -403,7 +447,8 @@ static bool loggingEnabled = false;
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[request setValue:[headerParams valueForKey:responseContentType] forHTTPHeaderField:@"Accept"];
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];

View File

@ -0,0 +1,18 @@
#import <Foundation/Foundation.h>
#import "SWGObject.h"
@interface SWGApiResponse : SWGObject
@property(nonatomic) NSNumber* code;
@property(nonatomic) NSString* type;
@property(nonatomic) NSString* message;
- (id) code: (NSNumber*) code
type: (NSString*) type
message: (NSString*) message;
- (id) initWithValues: (NSDictionary*)dict;
- (NSDictionary*) asDictionary;
@end

View File

@ -0,0 +1,54 @@
#import "SWGDate.h"
#import "SWGApiResponse.h"
@implementation SWGApiResponse
-(id)code: (NSNumber*) code
type: (NSString*) type
message: (NSString*) message
{
_code = code;
_type = type;
_message = message;
return self;
}
-(id) initWithValues:(NSDictionary*)dict
{
self = [super init];
if(self) {
_code = dict[@"code"];
_type = dict[@"type"];
_message = dict[@"message"];
}
return self;
}
-(NSDictionary*) asDictionary {
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
if(_code != nil) dict[@"code"] = _code ;
if(_type != nil) dict[@"type"] = _type ;
if(_message != nil) dict[@"message"] = _message ;
NSDictionary* output = [dict copy];
return output;
}
@end

View File

@ -5,9 +5,10 @@
@property(nonatomic, readonly) NSString* name;
@property(nonatomic, readonly) NSString* mimeType;
@property(nonatomic, readonly) NSData* data;
@property(nonatomic) NSString* paramName;
- (id) initWithNameData: (NSString*) filename
mimeType: (NSString*) mimeType
data: (NSData*) data;
@end
@end

View File

@ -38,12 +38,12 @@
@param pet Pet object that needs to be added to the store
@param body Pet object that needs to be added to the store
return type:
*/
-(NSNumber*) addPetWithCompletionBlock :(SWGPet*) pet
-(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock;
@ -155,16 +155,24 @@
/**
Upload an image for a pet
uploads an image
@param petImage image to upload
@param petId ID of pet to update
@param additionalMetadata Additional data to pass to server
@param file file to upload
return type:
*/
-(NSNumber*) uploadImageWithCompletionBlock :(SWGFile*) petImage
-(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId
additionalMetadata:(NSString*) additionalMetadata
file:(SWGFile*) file
completionHandler: (void (^)(NSError* error))completionBlock;

View File

@ -7,7 +7,7 @@
@implementation SWGPetApi
static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
static NSString * basePath = @"http://petstore.swagger.io/v2";
+(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
static SWGPetApi* singletonAPI = nil;
@ -51,7 +51,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) updatePetWithCompletionBlock:(SWGPet*) body
-(NSNumber*) updatePetWithCompletionBlock: (SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock {
@ -96,18 +96,12 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
else if([__body isKindOfClass: [SWGFile class]]) {
requestContentType = @"form-data";
bodyDictionary = __body;
}
else{
NSLog(@"don't know what to do with %@", __body);
}
@ -120,19 +114,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"PUT"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"PUT"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
@ -140,7 +134,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) addPetWithCompletionBlock:(SWGPet*) pet
-(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock {
@ -163,7 +157,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
id __body = pet;
id __body = body;
if(__body != nil && [__body isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] init];
@ -185,18 +179,12 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
else if([__body isKindOfClass: [SWGFile class]]) {
requestContentType = @"form-data";
bodyDictionary = __body;
}
else{
NSLog(@"don't know what to do with %@", __body);
}
@ -209,19 +197,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"POST"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
@ -229,7 +217,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) findPetsByStatusWithCompletionBlock:(NSArray*) status
-(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray*) status
completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock
{
@ -255,6 +243,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -268,32 +264,17 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
if([data isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]];
for (NSDictionary* dict in (NSArray*)data) {
SWGPet* d = [[SWGPet alloc]initWithValues: dict];
[objs addObject:d];
}
completionBlock(objs, nil);
}
if (error) {
completionBlock(nil, error);
return;
}
}];
}
-(NSNumber*) findPetsByTagsWithCompletionBlock:(NSArray*) tags
-(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray*) tags
completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock
{
@ -319,6 +300,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -332,32 +321,17 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
if([data isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]];
for (NSDictionary* dict in (NSArray*)data) {
SWGPet* d = [[SWGPet alloc]initWithValues: dict];
[objs addObject:d];
}
completionBlock(objs, nil);
}
if (error) {
completionBlock(nil, error);
return;
}
}];
}
-(NSNumber*) getPetByIdWithCompletionBlock:(NSNumber*) petId
-(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock
{
@ -382,6 +356,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -391,14 +373,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// comples response type
return [client dictionary:requestUrl
method:@"GET"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType:requestContentType
responseContentType:responseContentType
completionBlock:^(NSDictionary *data, NSError *error) {
return [client dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
@ -416,9 +398,9 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) updatePetWithFormWithCompletionBlock:(NSString*) petId
name:(NSString*) name
status:(NSString*) status
-(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId
name: (NSString*) name
status: (NSString*) status
completionHandler: (void (^)(NSError* error))completionBlock {
@ -443,6 +425,18 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
formParams[@"name"] = name;
formParams[@"status"] = status;
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -453,19 +447,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"POST"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
@ -473,8 +467,8 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) deletePetWithCompletionBlock:(NSString*) api_key
petId:(NSNumber*) petId
-(NSNumber*) deletePetWithCompletionBlock: (NSString*) api_key
petId: (NSNumber*) petId
completionHandler: (void (^)(NSError* error))completionBlock {
@ -501,6 +495,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -511,19 +513,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"DELETE"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
@ -531,17 +533,20 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) uploadImageWithCompletionBlock:(SWGFile*) petImage
-(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId
additionalMetadata: (NSString*) additionalMetadata
file: (SWGFile*) file
completionHandler: (void (^)(NSError* error))completionBlock {
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}/upload", basePath];
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}/uploadImage", basePath];
// remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]];
NSString* requestContentType = @"application/json";
@ -555,6 +560,20 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
formParams[@"additionalMetadata"] = additionalMetadata;
requestContentType = @"multipart/form-data";
[bodyDictionary addObject:file];
file.paramName = @"file";
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -565,19 +584,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"POST"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];

View File

@ -10,6 +10,22 @@
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath;
/**
Returns pet inventories by status
Returns a map of status codes to quantities
return type: NSDictionary*
*/
-(NSNumber*) getInventoryWithCompletionBlock :
(void (^)(NSDictionary* output, NSError* error))completionBlock;
/**
Place an order for a pet

View File

@ -6,7 +6,7 @@
@implementation SWGStoreApi
static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
static NSString * basePath = @"http://petstore.swagger.io/v2";
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
static SWGStoreApi* singletonAPI = nil;
@ -50,7 +50,67 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) placeOrderWithCompletionBlock:(SWGOrder*) body
-(NSNumber*) getInventoryWithCompletionBlock:
(void (^)(NSDictionary* output, NSError* error))completionBlock
{
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath];
// remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
NSString* requestContentType = @"application/json";
NSString* responseContentType = @"application/json";
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init];
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
// map container response type
return [client dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
NSDictionary *result = nil;
if (data) {
result = [[NSDictionary alloc]initWithDictionary: data];
}
completionBlock(data, nil);
}];
}
-(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
{
@ -95,18 +155,12 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
else if([__body isKindOfClass: [SWGFile class]]) {
requestContentType = @"form-data";
bodyDictionary = __body;
}
else{
NSLog(@"don't know what to do with %@", __body);
}
@ -118,14 +172,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// comples response type
return [client dictionary:requestUrl
method:@"POST"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType:requestContentType
responseContentType:responseContentType
completionBlock:^(NSDictionary *data, NSError *error) {
return [client dictionary: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
@ -143,7 +197,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) getOrderByIdWithCompletionBlock:(NSString*) orderId
-(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
{
@ -168,6 +222,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -177,14 +239,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// comples response type
return [client dictionary:requestUrl
method:@"GET"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType:requestContentType
responseContentType:responseContentType
completionBlock:^(NSDictionary *data, NSError *error) {
return [client dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
@ -202,7 +264,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) deleteOrderWithCompletionBlock:(NSString*) orderId
-(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(NSError* error))completionBlock {
@ -227,6 +289,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -237,19 +307,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"DELETE"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];

View File

@ -6,7 +6,7 @@
@implementation SWGUserApi
static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
static NSString * basePath = @"http://petstore.swagger.io/v2";
+(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
static SWGUserApi* singletonAPI = nil;
@ -50,7 +50,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) createUserWithCompletionBlock:(SWGUser*) body
-(NSNumber*) createUserWithCompletionBlock: (SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock {
@ -95,18 +95,12 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
else if([__body isKindOfClass: [SWGFile class]]) {
requestContentType = @"form-data";
bodyDictionary = __body;
}
else{
NSLog(@"don't know what to do with %@", __body);
}
@ -119,19 +113,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"POST"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
@ -139,7 +133,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock:(NSArray*) body
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock: (NSArray*) body
completionHandler: (void (^)(NSError* error))completionBlock {
@ -184,18 +178,12 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
else if([__body isKindOfClass: [SWGFile class]]) {
requestContentType = @"form-data";
bodyDictionary = __body;
}
else{
NSLog(@"don't know what to do with %@", __body);
}
@ -208,19 +196,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"POST"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
@ -228,7 +216,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) createUsersWithListInputWithCompletionBlock:(NSArray*) body
-(NSNumber*) createUsersWithListInputWithCompletionBlock: (NSArray*) body
completionHandler: (void (^)(NSError* error))completionBlock {
@ -273,18 +261,12 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
else if([__body isKindOfClass: [SWGFile class]]) {
requestContentType = @"form-data";
bodyDictionary = __body;
}
else{
NSLog(@"don't know what to do with %@", __body);
}
@ -297,19 +279,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"POST"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
@ -317,8 +299,8 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) loginUserWithCompletionBlock:(NSString*) username
password:(NSString*) password
-(NSNumber*) loginUserWithCompletionBlock: (NSString*) username
password: (NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error))completionBlock
{
@ -346,6 +328,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -353,14 +343,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// primitive response type
return [client stringWithCompletionBlock:requestUrl
method:@"GET"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
return [client stringWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
@ -398,6 +388,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -408,19 +406,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"GET"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
@ -428,7 +426,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) getUserByNameWithCompletionBlock:(NSString*) username
-(NSNumber*) getUserByNameWithCompletionBlock: (NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock
{
@ -453,6 +451,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -462,14 +468,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// comples response type
return [client dictionary:requestUrl
method:@"GET"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType:requestContentType
responseContentType:responseContentType
completionBlock:^(NSDictionary *data, NSError *error) {
return [client dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
@ -487,8 +493,8 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) updateUserWithCompletionBlock:(NSString*) username
body:(SWGUser*) body
-(NSNumber*) updateUserWithCompletionBlock: (NSString*) username
body: (SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock {
@ -534,18 +540,12 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
else if([__body isKindOfClass: [SWGFile class]]) {
requestContentType = @"form-data";
bodyDictionary = __body;
}
else{
NSLog(@"don't know what to do with %@", __body);
}
@ -558,19 +558,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"PUT"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"PUT"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
@ -578,7 +578,7 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
}
-(NSNumber*) deleteUserWithCompletionBlock:(NSString*) username
-(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username
completionHandler: (void (^)(NSError* error))completionBlock {
@ -603,6 +603,14 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
id bodyDictionary = nil;
bodyDictionary = [[NSMutableArray alloc] init];
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
[bodyDictionary addObject:formParams];
SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath];
@ -613,19 +621,19 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/v2";
// no return base type
return [client stringWithCompletionBlock:requestUrl
method:@"DELETE"
queryParams:queryParams
body:bodyDictionary
headerParams:headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock:^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
return [client stringWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];