diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..6472be2 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore index c964cd8..08dec93 100644 --- a/.gitignore +++ b/.gitignore @@ -16,7 +16,7 @@ DerivedData *.hmap *.ipa *.xcuserstate - +TalkinToTheNet/.DS_Store # CocoaPods # # We recommend against adding the Pods directory to your .gitignore. However diff --git a/README.md b/README.md index 0c0341f..7a2ba66 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,14 @@ -# unit-2-hw-1 +# Vegan Om Nom Nom -Welcome to the world of places. +###Description +Search for Vegan businesses using the Yelp API. +View location on a mapview. +View posts with the #restaurantName using the Instagram API. + + -### Objective +#### Originated from class assignment, unit-2-hw-1: +#####Objective Using either the **[Foursquare API](https://developer.foursquare.com)** or the **[Yelp API](https://www.yelp.com/developers/documentation/v2/overview)**, fetch a list of places near a specific location. Your application should also provide the ability to view additional data (category, address, avatar, etc) @@ -10,7 +16,6 @@ Your application should also provide the ability to view additional data (catego **The interesting part** On the detail page, your application must provide one additional piece of information provided by another api. For example, fetch the number of Twitter followers based on their twitter handle. Or pull instagram pictures based on the category of the venue. -I'll update this with some screens. ### Ideas > **Twitter** diff --git a/TalkinToTheNet/Podfile b/TalkinToTheNet/Podfile new file mode 100644 index 0000000..619bd7c --- /dev/null +++ b/TalkinToTheNet/Podfile @@ -0,0 +1,3 @@ +pod 'SDWebImage', '~>3.7' +pod 'AFNetworking', '~> 2.5' +pod 'NYAlertViewController' \ No newline at end of file diff --git a/TalkinToTheNet/Podfile.lock b/TalkinToTheNet/Podfile.lock new file mode 100644 index 0000000..cb34362 --- /dev/null +++ b/TalkinToTheNet/Podfile.lock @@ -0,0 +1,38 @@ +PODS: + - AFNetworking (2.6.0): + - AFNetworking/NSURLConnection (= 2.6.0) + - AFNetworking/NSURLSession (= 2.6.0) + - AFNetworking/Reachability (= 2.6.0) + - AFNetworking/Security (= 2.6.0) + - AFNetworking/Serialization (= 2.6.0) + - AFNetworking/UIKit (= 2.6.0) + - AFNetworking/NSURLConnection (2.6.0): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/NSURLSession (2.6.0): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/Reachability (2.6.0) + - AFNetworking/Security (2.6.0) + - AFNetworking/Serialization (2.6.0) + - AFNetworking/UIKit (2.6.0): + - AFNetworking/NSURLConnection + - AFNetworking/NSURLSession + - NYAlertViewController (1.3.0) + - SDWebImage (3.7.3): + - SDWebImage/Core (= 3.7.3) + - SDWebImage/Core (3.7.3) + +DEPENDENCIES: + - AFNetworking (~> 2.5) + - NYAlertViewController + - SDWebImage (~> 3.7) + +SPEC CHECKSUMS: + AFNetworking: 79f7eb1a0fcfa7beb409332b2ca49afe9ce53b05 + NYAlertViewController: b93f82e2c1fc6d5e9485512ddbe7b481f463a074 + SDWebImage: 1d2b1a1efda1ade1b00b6f8498865f8ddedc8a84 + +COCOAPODS: 0.38.2 diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h new file mode 100644 index 0000000..cf6def4 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h @@ -0,0 +1,70 @@ +// AFHTTPRequestOperation.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 +#import "AFURLConnectionOperation.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + `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. + */ +@interface AFHTTPRequestOperation : AFURLConnectionOperation + +///------------------------------------------------ +/// @name Getting HTTP URL Connection Information +///------------------------------------------------ + +/** + The last HTTP response received by the operation's connection. + */ +@property (readonly, nonatomic, strong, nullable) NSHTTPURLResponse *response; + +/** + 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 * responseSerializer; + +/** + 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 (readonly, nonatomic, strong, nullable) id responseObject; + +///----------------------------------------------------------- +/// @name Setting Completion Block Success / Failure Callbacks +///----------------------------------------------------------- + +/** + Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. + + This method should be overridden in subclasses in order to specify the response object passed into the success block. + + @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. + @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. + */ +- (void)setCompletionBlockWithSuccess:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m new file mode 100644 index 0000000..b8deda8 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m @@ -0,0 +1,206 @@ +// AFHTTPRequestOperation.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "AFHTTPRequestOperation.h" + +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); + }); + + return af_http_request_operation_processing_queue; +} + +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(); + }); + + return af_http_request_operation_completion_group; +} + +#pragma mark - + +@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) id responseObject; +@property (readwrite, nonatomic, strong) NSError *responseSerializationError; +@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; +@end + +@implementation AFHTTPRequestOperation +@dynamic response; +@dynamic lock; + +- (instancetype)initWithRequest:(NSURLRequest *)urlRequest { + self = [super initWithRequest:urlRequest]; + if (!self) { + return nil; + } + + self.responseSerializer = [AFHTTPResponseSerializer serializer]; + + return self; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + NSParameterAssert(responseSerializer); + + [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]; + + return _responseObject; +} + +- (NSError *)error { + if (_responseSerializationError) { + return _responseSerializationError; + } else { + return [super error]; + } +} + +#pragma mark - AFHTTPRequestOperation + +- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" +#pragma clang diagnostic ignored "-Wgnu" + self.completionBlock = ^{ + 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 - AFURLRequestOperation + +- (void)pause { + [super pause]; + + 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]; + } + + 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 diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h new file mode 100644 index 0000000..d2385ed --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h @@ -0,0 +1,326 @@ +// AFHTTPRequestOperationManager.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 +#import +#import + +#if __IPHONE_OS_VERSION_MIN_REQUIRED +#import +#else +#import +#endif + +#import "AFHTTPRequestOperation.h" +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" +#import "AFSecurityPolicy.h" +#import "AFNetworkReachabilityManager.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 + +NS_ASSUME_NONNULL_BEGIN + +/** + `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. + + ## Subclassing Notes + + Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. + + For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. + + ## Methods to Override + + To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`. + + ## Serialization + + Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. + + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` + + ## URL Construction Using Relative Paths + + For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. + + 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. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. + + ## Network Reachability Monitoring + + Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. + + ## NSSecureCoding & NSCopying Caveats + + `AFHTTPRequestOperationManager` conforms to the `NSSecureCoding` 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. + - NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set. + */ +@interface AFHTTPRequestOperationManager : NSObject + +/** + The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. + */ +@property (readonly, nonatomic, strong, nullable) NSURL *baseURL; + +/** + Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. + + @warning `requestSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; + +/** + 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 a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data 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`. + */ +@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; + +/** + The operation queue on which request operations are scheduled and run. + */ +@property (nonatomic, strong) NSOperationQueue *operationQueue; + +///------------------------------- +/// @name Managing URL Credentials +///------------------------------- + +/** + Whether request operations should consult the credential storage for authenticating the connection. `YES` by default. + + @see AFURLConnectionOperation -shouldUseCredentialStorage + */ +@property (nonatomic, assign) BOOL shouldUseCredentialStorage; + +/** + The credential used by request operations for authentication challenges. + + @see AFURLConnectionOperation -credential + */ +@property (nonatomic, strong, nullable) NSURLCredential *credential; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +///------------------------------------ +/// @name Managing Network Reachability +///------------------------------------ + +/** + The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default. + */ +@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; + +///------------------------------- +/// @name Managing Callback Queues +///------------------------------- + +/** + The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used. + */ +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; +#else +@property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; +#endif + +/** + The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used. + */ +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; +#else +@property (nonatomic, assign, nullable) dispatch_group_t completionGroup; +#endif + +///--------------------------------------------- +/// @name Creating and Initializing HTTP Clients +///--------------------------------------------- + +/** + Creates and returns an `AFHTTPRequestOperationManager` object. + */ ++ (instancetype)manager; + +/** + Initializes an `AFHTTPRequestOperationManager` object with the specified base URL. + + This is the designated initializer. + + @param url The base URL for the HTTP client. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url NS_DESIGNATED_INITIALIZER; + +///--------------------------------------- +/// @name Managing HTTP Request Operations +///--------------------------------------- + +/** + Creates an `AFHTTPRequestOperation`, and sets the response serializers to that of the HTTP client. + + @param request 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 *)request + success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +///--------------------------- +/// @name Making HTTP Requests +///--------------------------- + +/** + Creates and runs an `AFHTTPRequestOperation` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @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 request operation, and the response object created by the client response serializer. + @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 a two arguments: the request operation and the error describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (nullable AFHTTPRequestOperation *)GET:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates and runs an `AFHTTPRequestOperation` with a `HEAD` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes a single arguments: the request operation. + @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 a two arguments: the request operation and the error describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (nullable AFHTTPRequestOperation *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(AFHTTPRequestOperation *operation))success + failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates and runs an `AFHTTPRequestOperation` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @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 request operation, and the response object created by the client response serializer. + @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 a two arguments: the request operation and the error describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates and runs an `AFHTTPRequestOperation` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @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. + @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 request operation, and the response object created by the client response serializer. + @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 a two arguments: the request operation and the error describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates and runs an `AFHTTPRequestOperation` with a `PUT` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @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 request operation, and the response object created by the client response serializer. + @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 a two arguments: the request operation and the error describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (nullable AFHTTPRequestOperation *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates and runs an `AFHTTPRequestOperation` with a `PATCH` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @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 request operation, and the response object created by the client response serializer. + @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 a two arguments: the request operation and the error describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (nullable AFHTTPRequestOperation *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates and runs an `AFHTTPRequestOperation` with a `DELETE` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @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 request operation, and the response object created by the client response serializer. + @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 a two arguments: the request operation and the error describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (nullable AFHTTPRequestOperation *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m new file mode 100644 index 0000000..60739e5 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m @@ -0,0 +1,284 @@ +// AFHTTPRequestOperationManager.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import "AFHTTPRequestOperationManager.h" +#import "AFHTTPRequestOperation.h" + +#import +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import +#endif + +@interface AFHTTPRequestOperationManager () +@property (readwrite, nonatomic, strong) NSURL *baseURL; +@end + +@implementation AFHTTPRequestOperationManager + ++ (instancetype)manager { + return [[self alloc] initWithBaseURL:nil]; +} + +- (instancetype)init { + return [self initWithBaseURL:nil]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + self = [super init]; + if (!self) { + return nil; + } + + // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected + if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { + url = [url URLByAppendingPathComponent:@""]; + } + + self.baseURL = url; + + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + self.securityPolicy = [AFSecurityPolicy defaultPolicy]; + + self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; + + self.operationQueue = [[NSOperationQueue alloc] init]; + + self.shouldUseCredentialStorage = YES; + + return self; +} + +#pragma mark - + +#ifdef _SYSTEMCONFIGURATION_H +#endif + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + NSParameterAssert(requestSerializer); + + _requestSerializer = requestSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + NSParameterAssert(responseSerializer); + + _responseSerializer = responseSerializer; +} + +#pragma mark - + +- (AFHTTPRequestOperation *)HTTPRequestOperationWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; + if (serializationError) { + if (failure) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); +#pragma clang diagnostic pop + } + + return nil; + } + + return [self HTTPRequestOperationWithRequest:request success:success failure:failure]; +} + +- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; + operation.responseSerializer = self.responseSerializer; + operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage; + operation.credential = self.credential; + operation.securityPolicy = self.securityPolicy; + + [operation setCompletionBlockWithSuccess:success failure:failure]; + operation.completionQueue = self.completionQueue; + operation.completionGroup = self.completionGroup; + + return operation; +} + +#pragma mark - + +- (AFHTTPRequestOperation *)GET:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure]; + + [self.operationQueue addOperation:operation]; + + return operation; +} + +- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(AFHTTPRequestOperation *operation))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) { + if (success) { + success(requestOperation); + } + } failure:failure]; + + [self.operationQueue addOperation:operation]; + + return operation; +} + +- (AFHTTPRequestOperation *)POST:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure]; + + [self.operationQueue addOperation:operation]; + + return operation; +} + +- (AFHTTPRequestOperation *)POST:(NSString *)URLString + parameters:(id)parameters + constructingBodyWithBlock:(void (^)(id formData))block + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; + if (serializationError) { + if (failure) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); +#pragma clang diagnostic pop + } + + return nil; + } + + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; + + [self.operationQueue addOperation:operation]; + + return operation; +} + +- (AFHTTPRequestOperation *)PUT:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure]; + + [self.operationQueue addOperation:operation]; + + return operation; +} + +- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure]; + + [self.operationQueue addOperation:operation]; + + return operation; +} + +- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure]; + + [self.operationQueue addOperation:operation]; + + return operation; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (id)initWithCoder:(NSCoder *)decoder { + NSURL *baseURL = [decoder decodeObjectForKey:NSStringFromSelector(@selector(baseURL))]; + + self = [self initWithBaseURL:baseURL]; + if (!self) { + return nil; + } + + self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; + self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; + [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; + [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL]; + + HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; + HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; + + return HTTPClient; +} + +@end diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h new file mode 100644 index 0000000..e516e6d --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h @@ -0,0 +1,253 @@ +// AFHTTPSessionManager.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 +#if !TARGET_OS_WATCH +#import +#endif +#import + +#if __IPHONE_OS_VERSION_MIN_REQUIRED +#import +#else +#import +#endif + +#import "AFURLSessionManager.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 + +/** + `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. + + ## Subclassing Notes + + Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. + + For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. + + ## Methods to Override + + To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`. + + ## Serialization + + Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. + + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` + + ## URL Construction Using Relative Paths + + For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. + + 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. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_OS_WATCH + +NS_ASSUME_NONNULL_BEGIN + +@interface AFHTTPSessionManager : AFURLSessionManager + +/** + The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. + */ +@property (readonly, nonatomic, strong, nullable) NSURL *baseURL; + +/** + Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. + + @warning `requestSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; + +/** + 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 instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns an `AFHTTPSessionManager` object. + */ ++ (instancetype)manager; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + @param url The base URL for the HTTP client. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + This is the designated initializer. + + @param url The base URL for the HTTP client. + @param configuration The configuration used to create the managed session. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url + sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +///--------------------------- +/// @name Making HTTP Requests +///--------------------------- + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @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. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PUT` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m new file mode 100644 index 0000000..bd9163f --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m @@ -0,0 +1,323 @@ +// AFHTTPSessionManager.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "AFHTTPSessionManager.h" + +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_WATCH_OS + +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" + +#import +#import + +#ifdef _SYSTEMCONFIGURATION_H +#import +#import +#import +#import +#import +#endif + +#if TARGET_OS_IOS +#import +#elif TARGET_OS_WATCH +#import +#endif + +@interface AFHTTPSessionManager () +@property (readwrite, nonatomic, strong) NSURL *baseURL; +@end + +@implementation AFHTTPSessionManager +@dynamic responseSerializer; + ++ (instancetype)manager { + return [[[self class] alloc] initWithBaseURL:nil]; +} + +- (instancetype)init { + return [self initWithBaseURL:nil]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url sessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + return [self initWithBaseURL:nil sessionConfiguration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + sessionConfiguration:(NSURLSessionConfiguration *)configuration +{ + self = [super initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected + if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { + url = [url URLByAppendingPathComponent:@""]; + } + + self.baseURL = url; + + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + return self; +} + +#pragma mark - + +#ifdef _SYSTEMCONFIGURATION_H +#endif + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + NSParameterAssert(requestSerializer); + + _requestSerializer = requestSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + NSParameterAssert(responseSerializer); + + [super setResponseSerializer:responseSerializer]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, __unused id responseObject) { + if (success) { + success(task); + } + } failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + constructingBodyWithBlock:(void (^)(id formData))block + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; + if (serializationError) { + if (failure) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); +#pragma clang diagnostic pop + } + + return nil; + } + + __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(task, error); + } + } else { + if (success) { + success(task, responseObject); + } + } + }]; + + [task resume]; + + return task; +} + +- (NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *, id))success + failure:(void (^)(NSURLSessionDataTask *, NSError *))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; + if (serializationError) { + if (failure) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); +#pragma clang diagnostic pop + } + + return nil; + } + + __block NSURLSessionDataTask *dataTask = nil; + dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(dataTask, error); + } + } else { + if (success) { + success(dataTask, responseObject); + } + } + }]; + + return dataTask; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (id)initWithCoder:(NSCoder *)decoder { + NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + if (!configuration) { + NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; + if (configurationIdentifier) { +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100) + configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; +#else + configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier]; +#endif + } + } + + self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; + if (!self) { + return nil; + } + + self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; + self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; + if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; + } else { + [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; + } + [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; + [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; + + HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; + HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; + + return HTTPClient; +} + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h new file mode 100644 index 0000000..5a44507 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h @@ -0,0 +1,207 @@ +// AFNetworkReachabilityManager.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#if !TARGET_OS_WATCH +#import + +#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 + +typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { + AFNetworkReachabilityStatusUnknown = -1, + AFNetworkReachabilityStatusNotReachable = 0, + AFNetworkReachabilityStatusReachableViaWWAN = 1, + AFNetworkReachabilityStatusReachableViaWiFi = 2, +}; + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. + + See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/) + + @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. + */ +@interface AFNetworkReachabilityManager : NSObject + +/** + The current network reachability status. + */ +@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; + +/** + Whether or not the network is currently reachable. + */ +@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; + +/** + Whether or not the network is currently reachable via WWAN. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; + +/** + Whether or not the network is currently reachable via WiFi. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Returns the shared network reachability manager. + */ ++ (instancetype)sharedManager; + +/** + Creates and returns a network reachability manager for the specified domain. + + @param domain The domain used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified domain. + */ ++ (instancetype)managerForDomain:(NSString *)domain; + +/** + Creates and returns a network reachability manager for the socket address. + + @param address The socket address (`sockaddr_in`) used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified socket address. + */ ++ (instancetype)managerForAddress:(const void *)address; + +/** + Initializes an instance of a network reachability manager from the specified reachability object. + + @param reachability The reachability object to monitor. + + @return An initialized network reachability manager, actively monitoring the specified reachability. + */ +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; + +///-------------------------------------------------- +/// @name Starting & Stopping Reachability Monitoring +///-------------------------------------------------- + +/** + Starts monitoring for changes in network reachability status. + */ +- (void)startMonitoring; + +/** + Stops monitoring for changes in network reachability status. + */ +- (void)stopMonitoring; + +///------------------------------------------------- +/// @name Getting Localized Reachability Description +///------------------------------------------------- + +/** + Returns a localized string representation of the current network reachability status. + */ +- (NSString *)localizedNetworkReachabilityStatusString; + +///--------------------------------------------------- +/// @name Setting Network Reachability Change Callback +///--------------------------------------------------- + +/** + 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`. + */ +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Network Reachability + + The following constants are provided by `AFNetworkReachabilityManager` 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. + */ + +///-------------------- +/// @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 ` to the header prefix of the project (`Prefix.pch`). + */ +extern NSString * const AFNetworkingReachabilityDidChangeNotification; +extern NSString * const AFNetworkingReachabilityNotificationStatusItem; + +///-------------------- +/// @name Functions +///-------------------- + +/** + Returns a localized string representation of an `AFNetworkReachabilityStatus` value. + */ +extern NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); + +NS_ASSUME_NONNULL_END +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m new file mode 100644 index 0000000..2e5e2ed --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m @@ -0,0 +1,262 @@ +// AFNetworkReachabilityManager.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "AFNetworkReachabilityManager.h" +#if !TARGET_OS_WATCH + +#import +#import +#import +#import +#import + +NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; +NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; + +typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); + +typedef NS_ENUM(NSUInteger, AFNetworkReachabilityAssociation) { + AFNetworkReachabilityForAddress = 1, + AFNetworkReachabilityForAddressPair = 2, + AFNetworkReachabilityForName = 3, +}; + +NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { + switch (status) { + case AFNetworkReachabilityStatusNotReachable: + return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWWAN: + return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWiFi: + return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); + case AFNetworkReachabilityStatusUnknown: + default: + return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); + } +} + +static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { + BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); + BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); + BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); + BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); + BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); + + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; + if (isNetworkReachable == NO) { + status = AFNetworkReachabilityStatusNotReachable; + } +#if TARGET_OS_IPHONE + else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { + status = AFNetworkReachabilityStatusReachableViaWWAN; + } +#endif + else { + status = AFNetworkReachabilityStatusReachableViaWiFi; + } + + return status; +} + +static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); + AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info; + if (block) { + block(status); + } + + + dispatch_async(dispatch_get_main_queue(), ^{ + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; + }); + +} + +static const void * AFNetworkReachabilityRetainCallback(const void *info) { + return Block_copy(info); +} + +static void AFNetworkReachabilityReleaseCallback(const void *info) { + if (info) { + Block_release(info); + } +} + +@interface AFNetworkReachabilityManager () +@property (readwrite, nonatomic, strong) id networkReachability; +@property (readwrite, nonatomic, assign) AFNetworkReachabilityAssociation networkReachabilityAssociation; +@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; +@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; +@end + +@implementation AFNetworkReachabilityManager + ++ (instancetype)sharedManager { + static AFNetworkReachabilityManager *_sharedManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + struct sockaddr_in address; + bzero(&address, sizeof(address)); + address.sin_len = sizeof(address); + address.sin_family = AF_INET; + + _sharedManager = [self managerForAddress:&address]; + }); + + return _sharedManager; +} + ++ (instancetype)managerForDomain:(NSString *)domain { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); + + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + manager.networkReachabilityAssociation = AFNetworkReachabilityForName; + + return manager; +} + ++ (instancetype)managerForAddress:(const void *)address { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); + + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + manager.networkReachabilityAssociation = AFNetworkReachabilityForAddress; + + return manager; +} + +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { + self = [super init]; + if (!self) { + return nil; + } + + self.networkReachability = CFBridgingRelease(reachability); + self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; + + return self; +} + +- (instancetype)init NS_UNAVAILABLE +{ + return nil; +} + +- (void)dealloc { + [self stopMonitoring]; +} + +#pragma mark - + +- (BOOL)isReachable { + return [self isReachableViaWWAN] || [self isReachableViaWiFi]; +} + +- (BOOL)isReachableViaWWAN { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; +} + +- (BOOL)isReachableViaWiFi { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; +} + +#pragma mark - + +- (void)startMonitoring { + [self stopMonitoring]; + + if (!self.networkReachability) { + return; + } + + __weak __typeof(self)weakSelf = self; + AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + + strongSelf.networkReachabilityStatus = status; + if (strongSelf.networkReachabilityStatusBlock) { + strongSelf.networkReachabilityStatusBlock(status); + } + + }; + + id networkReachability = self.networkReachability; + SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; + SCNetworkReachabilitySetCallback((__bridge SCNetworkReachabilityRef)networkReachability, AFNetworkReachabilityCallback, &context); + SCNetworkReachabilityScheduleWithRunLoop((__bridge SCNetworkReachabilityRef)networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); + + switch (self.networkReachabilityAssociation) { + case AFNetworkReachabilityForName: + break; + case AFNetworkReachabilityForAddress: + case AFNetworkReachabilityForAddressPair: + default: { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ + SCNetworkReachabilityFlags flags; + SCNetworkReachabilityGetFlags((__bridge SCNetworkReachabilityRef)networkReachability, &flags); + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); + dispatch_async(dispatch_get_main_queue(), ^{ + callback(status); + + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }]; + + + }); + }); + } + break; + } +} + +- (void)stopMonitoring { + if (!self.networkReachability) { + return; + } + + SCNetworkReachabilityUnscheduleFromRunLoop((__bridge SCNetworkReachabilityRef)self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); +} + +#pragma mark - + +- (NSString *)localizedNetworkReachabilityStatusString { + return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); +} + +#pragma mark - + +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { + self.networkReachabilityStatusBlock = block; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { + if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { + return [NSSet setWithObject:@"networkReachabilityStatus"]; + } + + return [super keyPathsForValuesAffectingValueForKey:key]; +} + +@end +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFNetworking.h new file mode 100644 index 0000000..6d442bb --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFNetworking.h @@ -0,0 +1,46 @@ +// AFNetworking.h +// +// 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 +// 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 +#import + +#ifndef _AFNETWORKING_ + #define _AFNETWORKING_ + + #import "AFURLRequestSerialization.h" + #import "AFURLResponseSerialization.h" + #import "AFSecurityPolicy.h" +#if !TARGET_OS_WATCH + #import "AFNetworkReachabilityManager.h" + #import "AFURLConnectionOperation.h" + #import "AFHTTPRequestOperation.h" + #import "AFHTTPRequestOperationManager.h" +#endif + +#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 ) || \ + TARGET_OS_WATCH ) + #import "AFURLSessionManager.h" + #import "AFHTTPSessionManager.h" +#endif + +#endif /* _AFNETWORKING_ */ diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h new file mode 100644 index 0000000..3c38da8 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h @@ -0,0 +1,142 @@ +// AFSecurityPolicy.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 +#import + +typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, +}; + +/** + `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. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFSecurityPolicy : NSObject + +/** + The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. + */ +@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; + +/** + The certificates used to evaluate server trust according to the SSL pinning mode. By default, this property is set to any (`.cer`) certificates included in the app bundle. Note that if you create an array with duplicate certificates, the duplicate certificates will be removed. Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. + */ +@property (nonatomic, strong, nullable) NSArray *pinnedCertificates; + +/** + Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL allowInvalidCertificates; + +/** + Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. + */ +@property (nonatomic, assign) BOOL validatesDomainName; + +///----------------------------------------- +/// @name Getting Specific Security Policies +///----------------------------------------- + +/** + Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. + + @return The default security policy. + */ ++ (instancetype)defaultPolicy; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + + @return A new security policy. + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; + +///------------------------------ +/// @name Evaluating Server Trust +///------------------------------ + +/** + Whether or not the specified server trust should be accepted, based on the security policy. + + This method should be used when responding to an authentication challenge from a server. + + @param serverTrust The X.509 certificate trust of the server. + + @return Whether or not to trust the server. + + @warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`. + */ +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE; + +/** + Whether or not the specified server trust should be accepted, based on the security policy. + + This method should be used when responding to an authentication challenge from a server. + + @param serverTrust The X.509 certificate trust of the server. + @param domain The domain of serverTrust. If `nil`, the domain will not be validated. + + @return Whether or not to trust the server. + */ +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(nullable NSString *)domain; + +@end + +NS_ASSUME_NONNULL_END + +///---------------- +/// @name Constants +///---------------- + +/** + ## SSL Pinning Modes + + The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. + + enum { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, + } + + `AFSSLPinningModeNone` + Do not used pinned certificates to validate servers. + + `AFSSLPinningModePublicKey` + Validate host certificates against public keys of pinned certificates. + + `AFSSLPinningModeCertificate` + Validate host certificates against pinned certificates. +*/ diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m new file mode 100644 index 0000000..e8eaa65 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m @@ -0,0 +1,311 @@ +// AFSecurityPolicy.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "AFSecurityPolicy.h" + +#import + +#if !TARGET_OS_IOS && !TARGET_OS_WATCH +static NSData * AFSecKeyGetData(SecKeyRef key) { + CFDataRef data = NULL; + + __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); + + return (__bridge_transfer NSData *)data; + +_out: + if (data) { + CFRelease(data); + } + + return nil; +} +#endif + +static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { +#if TARGET_OS_IOS || TARGET_OS_WATCH + return [(__bridge id)key1 isEqual:(__bridge id)key2]; +#else + return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; +#endif +} + +static id AFPublicKeyForCertificate(NSData *certificate) { + id allowedPublicKey = nil; + SecCertificateRef allowedCertificate; + SecCertificateRef allowedCertificates[1]; + CFArrayRef tempCertificates = nil; + SecPolicyRef policy = nil; + SecTrustRef allowedTrust = nil; + SecTrustResultType result; + + allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); + __Require_Quiet(allowedCertificate != NULL, _out); + + allowedCertificates[0] = allowedCertificate; + tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); + + policy = SecPolicyCreateBasicX509(); + __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); + __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); + + allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); + +_out: + if (allowedTrust) { + CFRelease(allowedTrust); + } + + if (policy) { + CFRelease(policy); + } + + if (tempCertificates) { + CFRelease(tempCertificates); + } + + if (allowedCertificate) { + CFRelease(allowedCertificate); + } + + return allowedPublicKey; +} + +static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { + BOOL isValid = NO; + SecTrustResultType result; + __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); + + isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); + +_out: + return isValid; +} + +static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; + } + + return [NSArray arrayWithArray:trustChain]; +} + +static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { + SecPolicyRef policy = SecPolicyCreateBasicX509(); + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + + SecCertificateRef someCertificates[] = {certificate}; + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); + + SecTrustRef trust; + __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); + + SecTrustResultType result; + __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); + + [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; + + _out: + if (trust) { + CFRelease(trust); + } + + if (certificates) { + CFRelease(certificates); + } + + continue; + } + CFRelease(policy); + + return [NSArray arrayWithArray:trustChain]; +} + +#pragma mark - + +@interface AFSecurityPolicy() +@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; +@property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys; +@end + +@implementation AFSecurityPolicy + ++ (NSArray *)defaultPinnedCertificates { + static NSArray *_defaultPinnedCertificates = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + 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]; + } + + _defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates]; + }); + + return _defaultPinnedCertificates; +} + ++ (instancetype)defaultPolicy { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = AFSSLPinningModeNone; + + return securityPolicy; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = pinningMode; + + [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]]; + + return securityPolicy; +} + +- (id)init { + self = [super init]; + if (!self) { + return nil; + } + + self.validatesDomainName = YES; + + return self; +} + +- (void)setPinnedCertificates:(NSArray *)pinnedCertificates { + _pinnedCertificates = [[NSOrderedSet orderedSetWithArray:pinnedCertificates] array]; + + if (self.pinnedCertificates) { + NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]]; + for (NSData *certificate in self.pinnedCertificates) { + id publicKey = AFPublicKeyForCertificate(certificate); + if (!publicKey) { + continue; + } + [mutablePinnedPublicKeys addObject:publicKey]; + } + self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys]; + } else { + self.pinnedPublicKeys = nil; + } +} + +#pragma mark - + +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust { + return [self evaluateServerTrust:serverTrust forDomain:nil]; +} + +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(NSString *)domain +{ + if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { + // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html + // According to the docs, you should only trust your provided certs for evaluation. + // Pinned certificates are added to the trust. Without pinned certificates, + // there is nothing to evaluate against. + // + // From Apple Docs: + // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). + // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." + NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); + return NO; + } + + NSMutableArray *policies = [NSMutableArray array]; + if (self.validatesDomainName) { + [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; + } else { + [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; + } + + SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); + + if (self.SSLPinningMode == AFSSLPinningModeNone) { + if (self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust)){ + return YES; + } else { + return NO; + } + } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { + return NO; + } + + NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); + switch (self.SSLPinningMode) { + case AFSSLPinningModeNone: + default: + return NO; + case AFSSLPinningModeCertificate: { + NSMutableArray *pinnedCertificates = [NSMutableArray array]; + for (NSData *certificateData in self.pinnedCertificates) { + [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; + } + SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); + + if (!AFServerTrustIsValid(serverTrust)) { + return NO; + } + + NSUInteger trustedCertificateCount = 0; + for (NSData *trustChainCertificate in serverCertificates) { + if ([self.pinnedCertificates containsObject:trustChainCertificate]) { + trustedCertificateCount++; + } + } + return trustedCertificateCount > 0; + } + case AFSSLPinningModePublicKey: { + NSUInteger trustedPublicKeyCount = 0; + NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); + + for (id trustChainPublicKey in publicKeys) { + for (id pinnedPublicKey in self.pinnedPublicKeys) { + if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { + trustedPublicKeyCount += 1; + } + } + } + return trustedPublicKeyCount > 0; + } + } + + return NO; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { + return [NSSet setWithObject:@"pinnedCertificates"]; +} + +@end diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h new file mode 100644 index 0000000..3ea87fe --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h @@ -0,0 +1,344 @@ +// AFURLConnectionOperation.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import +#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. + + ## Subclassing Notes + + This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors. + + If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. + + ## NSURLConnection Delegate Methods + + `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: + + - `connection:didReceiveResponse:` + - `connection:didReceiveData:` + - `connectionDidFinishLoading:` + - `connection:didFailWithError:` + - `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. + + ## 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. + + Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). + + ## SSL Pinning + + Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle. + + SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice. + + Connections will be validated on all matching certificates with a `.cer` extension in the bundle root. + + ## NSCoding & NSCopying Conformance + + `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: + + ### NSCoding Caveats + + - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. + - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. + + ### NSCopying Caveats + + - `-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`, 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. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFURLConnectionOperation : NSOperation + +///------------------------------- +/// @name Accessing Run Loop Modes +///------------------------------- + +/** + The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. + */ +@property (nonatomic, strong) NSSet *runLoopModes; + +///----------------------------------------- +/// @name Getting URL Connection Information +///----------------------------------------- + +/** + The request used by the operation's connection. + */ +@property (readonly, nonatomic, strong) NSURLRequest *request; + +/** + The last response received by the operation's connection. + */ +@property (readonly, nonatomic, strong, nullable) NSURLResponse *response; + +/** + The error, if any, that occurred in the lifecycle of the request. + */ +@property (readonly, nonatomic, strong, nullable) NSError *error; + +///---------------------------- +/// @name Getting Response Data +///---------------------------- + +/** + The data received during the request. + */ +@property (readonly, nonatomic, strong, nullable) NSData *responseData; + +/** + The string representation of the response data. + */ +@property (readonly, nonatomic, copy, nullable) NSString *responseString; + +/** + The string encoding of the response. + + If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`. + */ +@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding; + +///------------------------------- +/// @name Managing URL Credentials +///------------------------------- + +/** + Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. + + This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. + */ +@property (nonatomic, assign) BOOL shouldUseCredentialStorage; + +/** + The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. + + This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. + */ +@property (nonatomic, strong, nullable) NSURLCredential *credential; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used to evaluate server trust for secure connections. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +///------------------------ +/// @name Accessing Streams +///------------------------ + +/** + The input stream used to read data to be sent during the request. + + This property acts as a proxy to the `HTTPBodyStream` property of `request`. + */ +@property (nonatomic, strong) NSInputStream *inputStream; + +/** + 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, 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, nullable) NSOutputStream *outputStream; + +///--------------------------------- +/// @name Managing Callback Queues +///--------------------------------- + +/** + The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. + */ +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; +#else +@property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; +#endif + +/** + The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. + */ +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; +#else +@property (nonatomic, assign, nullable) dispatch_group_t completionGroup; +#endif + +///--------------------------------------------- +/// @name Managing Request Operation Information +///--------------------------------------------- + +/** + The user info dictionary for the receiver. + */ +@property (nonatomic, strong) NSDictionary *userInfo; +// FIXME: It doesn't seem that this userInfo is used anywhere in the implementation. + +///------------------------------------------------------ +/// @name Initializing an AFURLConnectionOperation Object +///------------------------------------------------------ + +/** + Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. + + This is the designated initializer. + + @param urlRequest The request object to be used by the operation connection. + */ +- (instancetype)initWithRequest:(NSURLRequest *)urlRequest NS_DESIGNATED_INITIALIZER; + +///---------------------------------- +/// @name Pausing / Resuming Requests +///---------------------------------- + +/** + Pauses the execution of the request operation. + + A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. + */ +- (void)pause; + +/** + Whether the request operation is currently paused. + + @return `YES` if the operation is currently paused, otherwise `NO`. + */ +- (BOOL)isPaused; + +/** + Resumes the execution of the paused request operation. + + Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. + */ +- (void)resume; + +///---------------------------------------------- +/// @name Configuring Backgrounding Task Behavior +///---------------------------------------------- + +/** + 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 application’s 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 application’s suspension momentarily while the application is notified. + */ +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(nullable void (^)(void))handler NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); +#endif + +///--------------------------------- +/// @name Setting Progress Callbacks +///--------------------------------- + +/** + Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. + + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setUploadProgressBlock:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; + +/** + Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setDownloadProgressBlock:(nullable void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; + +///------------------------------------------------- +/// @name Setting NSURLConnection Delegate Callbacks +///------------------------------------------------- + +/** + Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`. + + @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol). + + If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. + */ +- (void)setWillSendRequestForAuthenticationChallengeBlock:(nullable 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 `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:(nullable 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:`. + + @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. + */ +- (void)setCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; + +/// + +/** + + */ ++ (NSArray *)batchOfRequestOperations:(nullable NSArray *)operations + progressBlock:(nullable void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock + completionBlock:(nullable void (^)(NSArray *operations))completionBlock; + +@end + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when an operation begins executing. + */ +extern NSString * const AFNetworkingOperationDidStartNotification; + +/** + Posted when an operation finishes. + */ +extern NSString * const AFNetworkingOperationDidFinishNotification; + +NS_ASSUME_NONNULL_END diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m new file mode 100644 index 0000000..d28d69a --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m @@ -0,0 +1,792 @@ +// AFURLConnectionOperation.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "AFURLConnectionOperation.h" + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import +#endif + +#if !__has_feature(objc_arc) +#error AFNetworking must be built with ARC. +// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files. +#endif + +typedef NS_ENUM(NSInteger, AFOperationState) { + AFOperationPausedState = -1, + AFOperationReadyState = 1, + AFOperationExecutingState = 2, + AFOperationFinishedState = 3, +}; + +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(); + }); + + 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"; + +typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); +typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge); +typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse); +typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse); +typedef void (^AFURLConnectionOperationBackgroundTaskCleanupBlock)(); + +static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { + switch (state) { + case AFOperationReadyState: + return @"isReady"; + case AFOperationExecutingState: + return @"isExecuting"; + case AFOperationFinishedState: + return @"isFinished"; + case AFOperationPausedState: + return @"isPaused"; + default: { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunreachable-code" + return @"state"; +#pragma clang diagnostic pop + } + } +} + +static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) { + switch (fromState) { + case AFOperationReadyState: + switch (toState) { + case AFOperationPausedState: + case AFOperationExecutingState: + return YES; + case AFOperationFinishedState: + return isCancelled; + default: + return NO; + } + case AFOperationExecutingState: + switch (toState) { + case AFOperationPausedState: + case AFOperationFinishedState: + return YES; + default: + return NO; + } + case AFOperationFinishedState: + return NO; + case AFOperationPausedState: + return toState == AFOperationReadyState; + 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 + } +} + +@interface AFURLConnectionOperation () +@property (readwrite, nonatomic, assign) AFOperationState state; +@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; +@property (readwrite, nonatomic, strong) NSURLConnection *connection; +@property (readwrite, nonatomic, strong) NSURLRequest *request; +@property (readwrite, nonatomic, strong) NSURLResponse *response; +@property (readwrite, nonatomic, strong) NSError *error; +@property (readwrite, nonatomic, strong) NSData *responseData; +@property (readwrite, nonatomic, copy) NSString *responseString; +@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding; +@property (readwrite, nonatomic, assign) long long totalBytesRead; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationBackgroundTaskCleanupBlock backgroundTaskCleanup; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse; + +- (void)operationDidStart; +- (void)finish; +- (void)cancelConnection; +@end + +@implementation AFURLConnectionOperation +@synthesize outputStream = _outputStream; + ++ (void)networkRequestThreadEntryPoint:(id)__unused object { + @autoreleasepool { + [[NSThread currentThread] setName:@"AFNetworking"]; + + NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; + [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; + [runLoop run]; + } +} + ++ (NSThread *)networkRequestThread { + static NSThread *_networkRequestThread = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; + [_networkRequestThread start]; + }); + + return _networkRequestThread; +} + +- (instancetype)initWithRequest:(NSURLRequest *)urlRequest { + NSParameterAssert(urlRequest); + + self = [super init]; + if (!self) { + return nil; + } + + _state = AFOperationReadyState; + + self.lock = [[NSRecursiveLock alloc] init]; + self.lock.name = kAFNetworkingLockName; + + self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; + + self.request = urlRequest; + + self.shouldUseCredentialStorage = YES; + + self.securityPolicy = [AFSecurityPolicy defaultPolicy]; + + return self; +} + +- (instancetype)init NS_UNAVAILABLE +{ + return nil; +} + +- (void)dealloc { + if (_outputStream) { + [_outputStream close]; + _outputStream = nil; + } + + if (_backgroundTaskCleanup) { + _backgroundTaskCleanup(); + } +} + +#pragma mark - + +- (void)setResponseData:(NSData *)responseData { + [self.lock lock]; + if (!responseData) { + _responseData = nil; + } else { + _responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length]; + } + [self.lock unlock]; +} + +- (NSString *)responseString { + [self.lock lock]; + if (!_responseString && self.response && self.responseData) { + self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding]; + } + [self.lock unlock]; + + return _responseString; +} + +- (NSStringEncoding)responseStringEncoding { + [self.lock lock]; + if (!_responseStringEncoding && self.response) { + NSStringEncoding stringEncoding = NSUTF8StringEncoding; + if (self.response.textEncodingName) { + CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName); + if (IANAEncoding != kCFStringEncodingInvalidId) { + stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding); + } + } + + self.responseStringEncoding = stringEncoding; + } + [self.lock unlock]; + + 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) +- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { + [self.lock lock]; + if (!self.backgroundTaskCleanup) { + UIApplication *application = [UIApplication sharedApplication]; + UIBackgroundTaskIdentifier __block backgroundTaskIdentifier = UIBackgroundTaskInvalid; + __weak __typeof(self)weakSelf = self; + + self.backgroundTaskCleanup = ^(){ + if (backgroundTaskIdentifier != UIBackgroundTaskInvalid) { + [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier]; + backgroundTaskIdentifier = UIBackgroundTaskInvalid; + } + }; + + backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ + __strong __typeof(weakSelf)strongSelf = weakSelf; + + if (handler) { + handler(); + } + + if (strongSelf) { + [strongSelf cancel]; + strongSelf.backgroundTaskCleanup(); + } + }]; + } + [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 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]; + [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; + }); + } + + self.state = AFOperationPausedState; + [self.lock unlock]; +} + +- (void)operationDidPause { + [self.lock lock]; + [self.connection cancel]; + [self.lock unlock]; +} + +- (BOOL)isPaused { + return self.state == AFOperationPausedState; +} + +- (void)resume { + if (![self isPaused]) { + return; + } + + [self.lock lock]; + self.state = AFOperationReadyState; + + [self start]; + [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]; +} + +- (BOOL)isExecuting { + return self.state == AFOperationExecutingState; +} + +- (BOOL)isFinished { + return self.state == AFOperationFinishedState; +} + +- (BOOL)isConcurrent { + return YES; +} + +- (void)start { + [self.lock lock]; + 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]]; + } + [self.lock unlock]; +} + +- (void)operationDidStart { + [self.lock lock]; + if (![self isCancelled]) { + self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; + + NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; + for (NSString *runLoopMode in self.runLoopModes) { + [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; + [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; + } + + [self.outputStream open]; + [self.connection start]; + } + [self.lock unlock]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self]; + }); +} + +- (void)finish { + [self.lock lock]; + self.state = AFOperationFinishedState; + [self.lock unlock]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; + }); +} + +- (void)cancel { + [self.lock lock]; + if (![self isFinished] && ![self isCancelled]) { + [super cancel]; + + if ([self isExecuting]) { + [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; + } + } + [self.lock unlock]; +} + +- (void)cancelConnection { + NSDictionary *userInfo = nil; + if ([self.request URL]) { + userInfo = @{NSURLErrorFailingURLErrorKey : [self.request URL]}; + } + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; + + if (![self isFinished]) { + if (self.connection) { + [self.connection cancel]; + [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error]; + } else { + // Accommodate 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 +willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge +{ + if (self.authenticationChallenge) { + self.authenticationChallenge(connection, challenge); + return; + } + + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + 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) { + if (self.credential) { + [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; + } else { + [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; + } + } else { + [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; + } + } +} + +- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { + return self.shouldUseCredentialStorage; +} + +- (NSURLRequest *)connection:(NSURLConnection *)connection + willSendRequest:(NSURLRequest *)request + redirectResponse:(NSURLResponse *)redirectResponse +{ + if (self.redirectResponse) { + return self.redirectResponse(connection, request, redirectResponse); + } else { + return request; + } +} + +- (void)connection:(NSURLConnection __unused *)connection + didSendBodyData:(NSInteger)bytesWritten + totalBytesWritten:(NSInteger)totalBytesWritten +totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite +{ + 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; +} + +- (void)connection:(NSURLConnection __unused *)connection + didReceiveData:(NSData *)data +{ + NSUInteger length = [data length]; + while (YES) { + NSInteger totalNumberOfBytesWritten = 0; + if ([self.outputStream hasSpaceAvailable]) { + const uint8_t *dataBuffer = (uint8_t *)[data bytes]; + + NSInteger numberOfBytesWritten = 0; + while (totalNumberOfBytesWritten < (NSInteger)length) { + numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)]; + if (numberOfBytesWritten == -1) { + 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 += (long long)length; + + if (self.downloadProgress) { + self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength); + } + }); +} + +- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection { + self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + + [self.outputStream close]; + if (self.responseData) { + self.outputStream = nil; + } + + self.connection = nil; + + [self finish]; +} + +- (void)connection:(NSURLConnection __unused *)connection + didFailWithError:(NSError *)error +{ + self.error = error; + + [self.outputStream close]; + if (self.responseData) { + self.outputStream = nil; + } + + self.connection = nil; + + [self finish]; +} + +- (NSCachedURLResponse *)connection:(NSURLConnection *)connection + willCacheResponse:(NSCachedURLResponse *)cachedResponse +{ + if (self.cacheResponse) { + return self.cacheResponse(connection, cachedResponse); + } else { + if ([self isCancelled]) { + return nil; + } + + return cachedResponse; + } +} + +#pragma mark - NSSecureCoding + ++ (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 = [[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 *)coder { + [self pause]; + + [coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))]; + + switch (self.state) { + case AFOperationExecutingState: + case AFOperationPausedState: + [coder encodeInteger:AFOperationReadyState forKey:NSStringFromSelector(@selector(state))]; + break; + default: + [coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))]; + break; + } + + [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 + +- (id)copyWithZone:(NSZone *)zone { + AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request]; + + operation.uploadProgress = self.uploadProgress; + operation.downloadProgress = self.downloadProgress; + operation.authenticationChallenge = self.authenticationChallenge; + operation.cacheResponse = self.cacheResponse; + operation.redirectResponse = self.redirectResponse; + operation.completionQueue = self.completionQueue; + operation.completionGroup = self.completionGroup; + + return operation; +} + +@end diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h new file mode 100644 index 0000000..d747496 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h @@ -0,0 +1,473 @@ +// AFURLRequestSerialization.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 +#if TARGET_OS_IOS +#import +#elif TARGET_OS_WATCH +#import +#endif + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary. + + For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`. + */ +@protocol AFURLRequestSerialization + +/** + Returns a request with the specified parameters encoded into a copy of the original request. + + @param request The original request. + @param parameters The parameters to be encoded. + @param error The error that occurred while attempting to encode the request parameters. + + @return A serialized request. + */ +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(nullable id)parameters + error:(NSError * __nullable __autoreleasing *)error; + +@end + +#pragma mark - + +/** + + */ +typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { + AFHTTPRequestQueryStringDefaultStyle = 0, +}; + +@protocol AFMultipartFormData; + +/** + `AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPRequestSerializer : NSObject + +/** + The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default. + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/** + Whether created requests can use the device’s cellular radio (if present). `YES` by default. + + @see NSMutableURLRequest -setAllowsCellularAccess: + */ +@property (nonatomic, assign) BOOL allowsCellularAccess; + +/** + The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default. + + @see NSMutableURLRequest -setCachePolicy: + */ +@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; + +/** + Whether created requests should use the default cookie handling. `YES` by default. + + @see NSMutableURLRequest -setHTTPShouldHandleCookies: + */ +@property (nonatomic, assign) BOOL HTTPShouldHandleCookies; + +/** + Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default + + @see NSMutableURLRequest -setHTTPShouldUsePipelining: + */ +@property (nonatomic, assign) BOOL HTTPShouldUsePipelining; + +/** + The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default. + + @see NSMutableURLRequest -setNetworkServiceType: + */ +@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType; + +/** + The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds. + + @see NSMutableURLRequest -setTimeoutInterval: + */ +@property (nonatomic, assign) NSTimeInterval timeoutInterval; + +///--------------------------------------- +/// @name Configuring HTTP Request Headers +///--------------------------------------- + +/** + Default HTTP header field values to be applied to serialized requests. By default, these include the following: + + - `Accept-Language` with the contents of `NSLocale +preferredLanguages` + - `User-Agent` with the contents of various bundle identifiers and OS designations + + @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +/** + 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 field The HTTP header to set a default value for + @param value The value set as default for the specified header, or `nil` + */ +- (void)setValue:(nullable NSString *)value +forHTTPHeaderField:(NSString *)field; + +/** + Returns the value for the HTTP headers set in the request serializer. + + @param field The HTTP header to retrieve the default value for + + @return The value set as default for the specified header, or `nil` + */ +- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; + +/** + 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)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password; + +/** + @deprecated This method has been deprecated. Use -setValue:forHTTPHeaderField: instead. + */ +- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token DEPRECATED_ATTRIBUTE; + + +/** + Clears any existing value for the "Authorization" HTTP header. + */ +- (void)clearAuthorizationHeader; + +///------------------------------------------------------- +/// @name Configuring Query String Parameter Serialization +///------------------------------------------------------- + +/** + HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. + */ +@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; + +/** + Set the method of query string serialization according to one of the pre-defined styles. + + @param style The serialization style. + + @see AFHTTPRequestQueryStringSerializationStyle + */ +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style; + +/** + Set the a custom method of query string serialization according to the specified block. + + @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request. + */ +- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; + +///------------------------------- +/// @name Creating Request Objects +///------------------------------- + +/** + @deprecated This method has been deprecated. Use -requestWithMethod:URLString:parameters:error: instead. + */ +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters DEPRECATED_ATTRIBUTE; + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. + + 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 URLString The URL string used to create the request URL. + @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object. + */ +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + error:(NSError * __nullable __autoreleasing *)error; + +/** + @deprecated This method has been deprecated. Use -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error: instead. + */ +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(NSDictionary *)parameters + constructingBodyWithBlock:(void (^)(id formData))block DEPRECATED_ATTRIBUTE; + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, 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 URLString The URL string used to create 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. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object + */ +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable NSDictionary *)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + error:(NSError * __nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished. + + @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`. + @param fileURL The file URL to write multipart form contents to. + @param handler A handler block to execute. + + @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request. + + @see https://github.com/AFNetworking/AFNetworking/issues/1398 + */ +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(nullable void (^)(NSError *error))handler; + +@end + +#pragma mark - + +/** + The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString: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 * __nullable __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 * __nullable __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:(nullable NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)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. This parameter must not be `nil`. + */ +- (void)appendPartWithHeaders:(nullable 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, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. 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 16kb. + @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 + +#pragma mark - + +/** + `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`. + */ +@interface AFJSONRequestSerializer : AFHTTPRequestSerializer + +/** + Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONWritingOptions writingOptions; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param writingOptions The specified JSON writing options. + */ ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions; + +@end + +#pragma mark - + +/** + `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`. + */ +@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + @warning The `writeOptions` property is currently unused. + */ +@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param writeOptions The property list write options. + + @warning The `writeOptions` property is currently unused. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions; + +@end + +#pragma mark - + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLRequestSerializationErrorDomain` + + ### Constants + + `AFURLRequestSerializationErrorDomain` + AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +extern NSString * const AFURLRequestSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` + + ### 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 `AFURLRequestSerializationErrorDomain`. + */ +extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; + +/** + ## Throttling Bandwidth for HTTP Request Input Streams + + @see -throttleBandwidthWithPacketSize:delay: + + ### Constants + + `kAFUploadStream3GSuggestedPacketSize` + Maximum packet size, in number of bytes. Equal to 16kb. + + `kAFUploadStream3GSuggestedDelay` + Duration of delay each time a packet is read. Equal to 0.2 seconds. + */ +extern NSUInteger const kAFUploadStream3GSuggestedPacketSize; +extern NSTimeInterval const kAFUploadStream3GSuggestedDelay; + +NS_ASSUME_NONNULL_END diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m new file mode 100644 index 0000000..8431761 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m @@ -0,0 +1,1397 @@ +// AFURLRequestSerialization.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "AFURLRequestSerialization.h" + +#if __IPHONE_OS_VERSION_MIN_REQUIRED +#import +#else +#import +#endif + +NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; +NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; + +typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); + +static NSString * AFBase64EncodedStringFromString(NSString *string) { + NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; + NSUInteger length = [data length]; + NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; + + uint8_t *input = (uint8_t *)[data bytes]; + uint8_t *output = (uint8_t *)[mutableData mutableBytes]; + + for (NSUInteger i = 0; i < length; i += 3) { + NSUInteger value = 0; + for (NSUInteger j = i; j < (i + 3); j++) { + value <<= 8; + if (j < length) { + value |= (0xFF & input[j]); + } + } + + static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + NSUInteger idx = (i / 3) * 4; + output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F]; + output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F]; + output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '='; + output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '='; + } + + return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding]; +} + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + - parameter string: The string to be percent-escaped. + - returns: The percent-escaped string. + */ +static NSString * AFPercentEscapedStringFromString(NSString *string) { + static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 + static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]]; + + return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; +} + +#pragma mark - + +@interface AFQueryStringPair : NSObject +@property (readwrite, nonatomic, strong) id field; +@property (readwrite, nonatomic, strong) id value; + +- (id)initWithField:(id)field value:(id)value; + +- (NSString *)URLEncodedStringValue; +@end + +@implementation AFQueryStringPair + +- (id)initWithField:(id)field value:(id)value { + self = [super init]; + if (!self) { + return nil; + } + + self.field = field; + self.value = value; + + return self; +} + +- (NSString *)URLEncodedStringValue { + if (!self.value || [self.value isEqual:[NSNull null]]) { + return AFPercentEscapedStringFromString([self.field description]); + } else { + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])]; + } +} + +@end + +#pragma mark - + +extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); +extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); + +static NSString * AFQueryStringFromParameters(NSDictionary *parameters) { + NSMutableArray *mutablePairs = [NSMutableArray array]; + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + [mutablePairs addObject:[pair URLEncodedStringValue]]; + } + + return [mutablePairs componentsJoinedByString:@"&"]; +} + +NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { + return AFQueryStringPairsFromKeyAndValue(nil, dictionary); +} + +NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { + NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; + + NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]; + + if ([value isKindOfClass:[NSDictionary class]]) { + NSDictionary *dictionary = value; + // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries + for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + id nestedValue = dictionary[nestedKey]; + if (nestedValue) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; + } + } + } else if ([value isKindOfClass:[NSArray class]]) { + NSArray *array = value; + for (id nestedValue in array) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; + } + } else if ([value isKindOfClass:[NSSet class]]) { + NSSet *set = value; + for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; + } + } else { + [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; + } + + return mutableQueryStringComponents; +} + +#pragma mark - + +@interface AFStreamingMultipartFormData : NSObject +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding; + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData; +@end + +#pragma mark - + +static NSArray * AFHTTPRequestSerializerObservedKeyPaths() { + static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))]; + }); + + return _AFHTTPRequestSerializerObservedKeyPaths; +} + +static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext; + +@interface AFHTTPRequestSerializer () +@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders; +@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle; +@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization; +@end + +@implementation AFHTTPRequestSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = NSUTF8StringEncoding; + + self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary]; + + // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 + NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; + [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + float q = 1.0f - (idx * 0.1f); + [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; + *stop = q <= 0.5f; + }]; + [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"]; + + NSString *userAgent = nil; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" +#if TARGET_OS_IOS + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; +#elif TARGET_OS_WATCH + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]]; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) + userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; +#endif +#pragma clang diagnostic pop + if (userAgent) { + if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { + NSMutableString *mutableUserAgent = [userAgent mutableCopy]; + if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) { + userAgent = mutableUserAgent; + } + } + [self setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + + // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil]; + + self.mutableObservedChangedKeyPaths = [NSMutableSet set]; + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; + } + } + + return self; +} + +- (void)dealloc { + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; + } + } +} + +#pragma mark - + +// Workarounds for crashing behavior using Key-Value Observing with XCTest +// See https://github.com/AFNetworking/AFNetworking/issues/2523 + +- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess { + [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; + _allowsCellularAccess = allowsCellularAccess; + [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; +} + +- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy { + [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; + _cachePolicy = cachePolicy; + [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; +} + +- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; + _HTTPShouldHandleCookies = HTTPShouldHandleCookies; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; +} + +- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; + _HTTPShouldUsePipelining = HTTPShouldUsePipelining; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; +} + +- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType { + [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; + _networkServiceType = networkServiceType; + [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; +} + +- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval { + [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; + _timeoutInterval = timeoutInterval; + [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; +} + +#pragma mark - + +- (NSDictionary *)HTTPRequestHeaders { + return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; +} + +- (void)setValue:(NSString *)value +forHTTPHeaderField:(NSString *)field +{ + [self.mutableHTTPRequestHeaders setValue:value forKey:field]; +} + +- (NSString *)valueForHTTPHeaderField:(NSString *)field { + return [self.mutableHTTPRequestHeaders valueForKey:field]; +} + +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password +{ + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; + [self setValue:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField:@"Authorization"]; +} + +- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token { + [self setValue:[NSString stringWithFormat:@"Token token=\"%@\"", token] forHTTPHeaderField:@"Authorization"]; +} + +- (void)clearAuthorizationHeader { + [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"]; +} + +#pragma mark - + +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style { + self.queryStringSerializationStyle = style; + self.queryStringSerialization = nil; +} + +- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block { + self.queryStringSerialization = block; +} + +#pragma mark - + +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters +{ + return [self requestWithMethod:method URLString:URLString parameters:parameters error:nil]; +} + +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(URLString); + + NSURL *url = [NSURL URLWithString:URLString]; + + NSParameterAssert(url); + + NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; + mutableRequest.HTTPMethod = method; + + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) { + [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath]; + } + } + + mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy]; + + return mutableRequest; +} + +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(NSDictionary *)parameters + constructingBodyWithBlock:(void (^)(id formData))block +{ + return [self multipartFormRequestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:block error:nil]; +} + +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(NSDictionary *)parameters + constructingBodyWithBlock:(void (^)(id formData))block + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); + + NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error]; + + __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding]; + + if (parameters) { + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + NSData *data = nil; + if ([pair.value isKindOfClass:[NSData class]]) { + data = pair.value; + } else if ([pair.value isEqual:[NSNull null]]) { + data = [NSData data]; + } else { + data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; + } + + if (data) { + [formData appendPartWithFormData:data name:[pair.field description]]; + } + } + } + + if (block) { + block(formData); + } + + return [formData requestByFinalizingMultipartFormData]; +} + +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(void (^)(NSError *error))handler +{ + NSParameterAssert(request.HTTPBodyStream); + NSParameterAssert([fileURL isFileURL]); + + NSInputStream *inputStream = request.HTTPBodyStream; + NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO]; + __block NSError *error = nil; + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + + [inputStream open]; + [outputStream open]; + + while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) { + uint8_t buffer[1024]; + + NSInteger bytesRead = [inputStream read:buffer maxLength:1024]; + if (inputStream.streamError || bytesRead < 0) { + error = inputStream.streamError; + break; + } + + NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead]; + if (outputStream.streamError || bytesWritten < 0) { + error = outputStream.streamError; + break; + } + + if (bytesRead == 0 && bytesWritten == 0) { + break; + } + } + + [outputStream close]; + [inputStream close]; + + if (handler) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler(error); + }); + } + }); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + mutableRequest.HTTPBodyStream = nil; + + return mutableRequest; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + NSString *query = nil; + if (self.queryStringSerialization) { + NSError *serializationError; + query = self.queryStringSerialization(request, parameters, &serializationError); + + if (serializationError) { + if (error) { + *error = serializationError; + } + + return nil; + } + } else { + switch (self.queryStringSerializationStyle) { + case AFHTTPRequestQueryStringDefaultStyle: + query = AFQueryStringFromParameters(parameters); + break; + } + } + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; + } else { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + } + [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; + } + } + + return mutableRequest; +} + +#pragma mark - NSKeyValueObserving + ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { + if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) { + return NO; + } + + return [super automaticallyNotifiesObserversForKey:key]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(__unused id)object + change:(NSDictionary *)change + context:(void *)context +{ + if (context == AFHTTPRequestSerializerObserverContext) { + if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) { + [self.mutableObservedChangedKeyPaths removeObject:keyPath]; + } else { + [self.mutableObservedChangedKeyPaths addObject:keyPath]; + } + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (id)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; + self.queryStringSerializationStyle = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))]; + [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone]; + serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; + serializer.queryStringSerialization = self.queryStringSerialization; + + return serializer; +} + +@end + +#pragma mark - + +static NSString * AFCreateMultipartFormBoundary() { + return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()]; +} + +static NSString * const kAFMultipartFormCRLF = @"\r\n"; + +static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFContentTypeForPathExtension(NSString *extension) { +#ifdef __UTTYPE__ + NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); + NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); + if (!contentType) { + return @"application/octet-stream"; + } else { + return contentType; + } +#else +#pragma unused (extension) + return @"application/octet-stream"; +#endif +} + +NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; +NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; + +@interface AFHTTPBodyPart : NSObject +@property (nonatomic, assign) NSStringEncoding stringEncoding; +@property (nonatomic, strong) NSDictionary *headers; +@property (nonatomic, copy) NSString *boundary; +@property (nonatomic, strong) id body; +@property (nonatomic, assign) unsigned long long bodyContentLength; +@property (nonatomic, strong) NSInputStream *inputStream; + +@property (nonatomic, assign) BOOL hasInitialBoundary; +@property (nonatomic, assign) BOOL hasFinalBoundary; + +@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; +@property (readonly, nonatomic, assign) unsigned long long contentLength; + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@interface AFMultipartBodyStream : NSInputStream +@property (nonatomic, assign) NSUInteger numberOfBytesInPacket; +@property (nonatomic, assign) NSTimeInterval delay; +@property (nonatomic, strong) NSInputStream *inputStream; +@property (readonly, nonatomic, assign) unsigned long long contentLength; +@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; + +- (id)initWithStringEncoding:(NSStringEncoding)encoding; +- (void)setInitialAndFinalBoundaries; +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; +@end + +#pragma mark - + +@interface AFStreamingMultipartFormData () +@property (readwrite, nonatomic, copy) NSMutableURLRequest *request; +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, copy) NSString *boundary; +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; +@end + +@implementation AFStreamingMultipartFormData + +- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding +{ + self = [super init]; + if (!self) { + return nil; + } + + self.request = urlRequest; + self.stringEncoding = encoding; + self.boundary = AFCreateMultipartFormBoundary(); + self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; + + return self; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + + NSString *fileName = [fileURL lastPathComponent]; + NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); + + return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + if (![fileURL isFileURL]) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } + + NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error]; + if (!fileAttributes) { + return NO; + } + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = fileURL; + bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue]; + [self.bodyStream appendHTTPBodyPart:bodyPart]; + + return YES; +} + +- (void)appendPartWithInputStream:(NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = inputStream; + + bodyPart.bodyContentLength = (unsigned long long)length; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name +{ + NSParameterAssert(name); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithHeaders:(NSDictionary *)headers + body:(NSData *)body +{ + NSParameterAssert(body); + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = headers; + bodyPart.boundary = self.boundary; + bodyPart.bodyContentLength = [body length]; + bodyPart.body = body; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay +{ + self.bodyStream.numberOfBytesInPacket = numberOfBytes; + self.bodyStream.delay = delay; +} + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData { + if ([self.bodyStream isEmpty]) { + return self.request; + } + + // Reset the initial and final boundaries to ensure correct Content-Length + [self.bodyStream setInitialAndFinalBoundaries]; + [self.request setHTTPBodyStream:self.bodyStream]; + + [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"]; + [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; + + return self.request; +} + +@end + +#pragma mark - + +@interface NSStream () +@property (readwrite) NSStreamStatus streamStatus; +@property (readwrite, copy) NSError *streamError; +@end + +@interface AFMultipartBodyStream () +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; +@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; +@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; +@property (readwrite, nonatomic, strong) NSOutputStream *outputStream; +@property (readwrite, nonatomic, strong) NSMutableData *buffer; +@end + +@implementation AFMultipartBodyStream +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wimplicit-atomic-properties" +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100) +@synthesize delegate; +#endif +@synthesize streamStatus; +@synthesize streamError; +#pragma clang diagnostic pop + +- (id)initWithStringEncoding:(NSStringEncoding)encoding { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = encoding; + self.HTTPBodyParts = [NSMutableArray array]; + self.numberOfBytesInPacket = NSIntegerMax; + + return self; +} + +- (void)setInitialAndFinalBoundaries { + if ([self.HTTPBodyParts count] > 0) { + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + bodyPart.hasInitialBoundary = NO; + bodyPart.hasFinalBoundary = NO; + } + + [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES]; + [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; + } +} + +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { + [self.HTTPBodyParts addObject:bodyPart]; +} + +- (BOOL)isEmpty { + return [self.HTTPBodyParts count] == 0; +} + +#pragma mark - NSInputStream + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + if ([self streamStatus] == NSStreamStatusClosed) { + return 0; + } + + NSInteger totalNumberOfBytesRead = 0; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { + if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { + if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { + break; + } + } else { + NSUInteger maxLength = length - (NSUInteger)totalNumberOfBytesRead; + NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; + if (numberOfBytesRead == -1) { + self.streamError = self.currentHTTPBodyPart.inputStream.streamError; + break; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if (self.delay > 0.0f) { + [NSThread sleepForTimeInterval:self.delay]; + } + } + } + } +#pragma clang diagnostic pop + + return totalNumberOfBytesRead; +} + +- (BOOL)getBuffer:(__unused uint8_t **)buffer + length:(__unused NSUInteger *)len +{ + return NO; +} + +- (BOOL)hasBytesAvailable { + return [self streamStatus] == NSStreamStatusOpen; +} + +#pragma mark - NSStream + +- (void)open { + if (self.streamStatus == NSStreamStatusOpen) { + return; + } + + self.streamStatus = NSStreamStatusOpen; + + [self setInitialAndFinalBoundaries]; + self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; +} + +- (void)close { + self.streamStatus = NSStreamStatusClosed; +} + +- (id)propertyForKey:(__unused NSString *)key { + return nil; +} + +- (BOOL)setProperty:(__unused id)property + forKey:(__unused NSString *)key +{ + return NO; +} + +- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + length += [bodyPart contentLength]; + } + + return length; +} + +#pragma mark - Undocumented CFReadStream Bridged Methods + +- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags + callback:(__unused CFReadStreamClientCallBack)inCallback + context:(__unused CFStreamClientContext *)inContext { + return NO; +} + +#pragma mark - NSCopying + +-(id)copyWithZone:(NSZone *)zone { + AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; + + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; + } + + [bodyStreamCopy setInitialAndFinalBoundaries]; + + return bodyStreamCopy; +} + +@end + +#pragma mark - + +typedef enum { + AFEncapsulationBoundaryPhase = 1, + AFHeaderPhase = 2, + AFBodyPhase = 3, + AFFinalBoundaryPhase = 4, +} AFHTTPBodyPartReadPhase; + +@interface AFHTTPBodyPart () { + AFHTTPBodyPartReadPhase _phase; + NSInputStream *_inputStream; + unsigned long long _phaseReadOffset; +} + +- (BOOL)transitionToNextPhase; +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@implementation AFHTTPBodyPart + +- (id)init { + self = [super init]; + if (!self) { + return nil; + } + + [self transitionToNextPhase]; + + return self; +} + +- (void)dealloc { + if (_inputStream) { + [_inputStream close]; + _inputStream = nil; + } +} + +- (NSInputStream *)inputStream { + if (!_inputStream) { + if ([self.body isKindOfClass:[NSData class]]) { + _inputStream = [NSInputStream inputStreamWithData:self.body]; + } else if ([self.body isKindOfClass:[NSURL class]]) { + _inputStream = [NSInputStream inputStreamWithURL:self.body]; + } else if ([self.body isKindOfClass:[NSInputStream class]]) { + _inputStream = self.body; + } else { + _inputStream = [NSInputStream inputStreamWithData:[NSData data]]; + } + } + + return _inputStream; +} + +- (NSString *)stringForHeaders { + NSMutableString *headerString = [NSMutableString string]; + for (NSString *field in [self.headers allKeys]) { + [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; + } + [headerString appendString:kAFMultipartFormCRLF]; + + return [NSString stringWithString:headerString]; +} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + length += [encapsulationBoundaryData length]; + + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + length += [headersData length]; + + length += _bodyContentLength; + + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + length += [closingBoundaryData length]; + + return length; +} + +- (BOOL)hasBytesAvailable { + // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer + if (_phase == AFFinalBoundaryPhase) { + return YES; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcovered-switch-default" + switch (self.inputStream.streamStatus) { + case NSStreamStatusNotOpen: + case NSStreamStatusOpening: + case NSStreamStatusOpen: + case NSStreamStatusReading: + case NSStreamStatusWriting: + return YES; + case NSStreamStatusAtEnd: + case NSStreamStatusClosed: + case NSStreamStatusError: + default: + return NO; + } +#pragma clang diagnostic pop +} + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + NSInteger totalNumberOfBytesRead = 0; + + if (_phase == AFEncapsulationBoundaryPhase) { + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFHeaderPhase) { + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFBodyPhase) { + NSInteger numberOfBytesRead = 0; + + numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + if (numberOfBytesRead == -1) { + return -1; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { + [self transitionToNextPhase]; + } + } + } + + if (_phase == AFFinalBoundaryPhase) { + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + return totalNumberOfBytesRead; +} + +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); + [data getBytes:buffer range:range]; +#pragma clang diagnostic pop + + _phaseReadOffset += range.length; + + if (((NSUInteger)_phaseReadOffset) >= [data length]) { + [self transitionToNextPhase]; + } + + return (NSInteger)range.length; +} + +- (BOOL)transitionToNextPhase { + if (![[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + [self transitionToNextPhase]; + }); + return YES; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcovered-switch-default" + switch (_phase) { + case AFEncapsulationBoundaryPhase: + _phase = AFHeaderPhase; + break; + case AFHeaderPhase: + [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + [self.inputStream open]; + _phase = AFBodyPhase; + break; + case AFBodyPhase: + [self.inputStream close]; + _phase = AFFinalBoundaryPhase; + break; + case AFFinalBoundaryPhase: + default: + _phase = AFEncapsulationBoundaryPhase; + break; + } + _phaseReadOffset = 0; +#pragma clang diagnostic pop + + return YES; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; + + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = self.headers; + bodyPart.bodyContentLength = self.bodyContentLength; + bodyPart.body = self.body; + bodyPart.boundary = self.boundary; + + return bodyPart; +} + +@end + +#pragma mark - + +@implementation AFJSONRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithWritingOptions:(NSJSONWritingOptions)0]; +} + ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions +{ + AFJSONRequestSerializer *serializer = [[self alloc] init]; + serializer.writingOptions = writingOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + } + + [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (id)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.writingOptions = self.writingOptions; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFPropertyListRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions +{ + AFPropertyListRequestSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.writeOptions = writeOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerializer + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"]; + } + + [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (id)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.format = self.format; + serializer.writeOptions = self.writeOptions; + + return serializer; +} + +@end diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h new file mode 100644 index 0000000..e14dc8a --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h @@ -0,0 +1,311 @@ +// AFURLResponseSerialization.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. + + For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. + */ +@protocol AFURLResponseSerialization + +/** + The response object decoded from the data associated with a specified response. + + @param response The response to be processed. + @param data The response data to be decoded. + @param error The error that occurred while attempting to decode the response data. + + @return The object decoded from the specified response data. + */ +- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response + data:(nullable NSData *)data + error:(NSError * __nullable __autoreleasing *)error; + +@end + +#pragma mark - + +/** + `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPResponseSerializer : NSObject + +- (instancetype)init; + +/** + The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default. + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +///----------------------------------------- +/// @name Configuring Response Serialization +///----------------------------------------- + +/** + The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. + + See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + */ +@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; + +/** + The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. + */ +@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; + +/** + Validates the specified response and data. + + In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. + + @param response The response to be validated. + @param data The data associated with the response. + @param error The error that occurred while attempting to validate the response. + + @return `YES` if the response is valid, otherwise `NO`. + */ +- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response + data:(nullable NSData *)data + error:(NSError * __nullable __autoreleasing *)error; + +@end + +#pragma mark - + + +/** + `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. + + By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: + + - `application/json` + - `text/json` + - `text/javascript` + */ +@interface AFJSONResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONReadingOptions readingOptions; + +/** + Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL removesKeysWithNullValues; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param readingOptions The specified JSON reading options. + */ ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; + +@end + +#pragma mark - + +/** + `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. + + By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +/** + `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. + */ +@property (nonatomic, assign) NSUInteger options; + +/** + Creates and returns an XML document serializer with the specified options. + + @param mask The XML document options. + */ ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; + +@end + +#endif + +#pragma mark - + +/** + `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFPropertyListResponseSerializer` accepts the following MIME types: + + - `application/x-plist` + */ +@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." + */ +@property (nonatomic, assign) NSPropertyListReadOptions readOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param readOptions The property list reading options. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions; + +@end + +#pragma mark - + +/** + `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. + + By default, `AFImageResponseSerializer` 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 AFImageResponseSerializer : AFHTTPResponseSerializer + +#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 + +@end + +#pragma mark - + +/** + `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. + */ +@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer + +/** + The component response serializers. + */ +@property (readonly, nonatomic, copy) NSArray *responseSerializers; + +/** + Creates and returns a compound serializer comprised of the specified response serializers. + + @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. + */ ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLResponseSerializationErrorDomain` + + ### Constants + + `AFURLResponseSerializationErrorDomain` + AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +extern NSString * const AFURLResponseSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` + - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLResponseErrorKey` + The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + + `AFNetworkingOperationFailingURLResponseDataErrorKey` + The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + */ +extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey; + +extern NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m new file mode 100644 index 0000000..f95834f --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m @@ -0,0 +1,825 @@ +// AFURLResponseSerialization.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "AFURLResponseSerialization.h" + +#if TARGET_OS_IOS +#import +#elif TARGET_OS_WATCH +#import +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#import +#endif + +NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response"; +NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response"; +NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data"; + +static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { + if (!error) { + return underlyingError; + } + + if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) { + return error; + } + + NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy]; + mutableUserInfo[NSUnderlyingErrorKey] = underlyingError; + + return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo]; +} + +static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) { + if ([error.domain isEqualToString:domain] && error.code == code) { + return YES; + } else if (error.userInfo[NSUnderlyingErrorKey]) { + return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain); + } + + return NO; +} + +static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { + if ([JSONObject isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; + for (id value in (NSArray *)JSONObject) { + [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; + } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; + for (id key in [(NSDictionary *)JSONObject allKeys]) { + id value = (NSDictionary *)JSONObject[key]; + if (!value || [value isEqual:[NSNull null]]) { + [mutableDictionary removeObjectForKey:key]; + } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); + } + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; + } + + return JSONObject; +} + +@implementation AFHTTPResponseSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = NSUTF8StringEncoding; + + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + self.acceptableContentTypes = nil; + + return self; +} + +#pragma mark - + +- (BOOL)validateResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError * __autoreleasing *)error +{ + BOOL responseIsValid = YES; + NSError *validationError = nil; + + if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) { + if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) { + if ([data length] > 0 && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); + } + + responseIsValid = NO; + } + + if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError); + + responseIsValid = NO; + } + } + + if (error && !responseIsValid) { + *error = validationError; + } + + return responseIsValid; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + [self validateResponse:(NSHTTPURLResponse *)response data:data error:error]; + + return data; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (id)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; + serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFJSONResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:(NSJSONReadingOptions)0]; +} + ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions { + AFJSONResponseSerializer *serializer = [[self alloc] init]; + serializer.readingOptions = readingOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return 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 + NSStringEncoding stringEncoding = self.stringEncoding; + if (response.textEncodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); + if (encoding != kCFStringEncodingInvalidId) { + stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); + } + } + + id responseObject = nil; + NSError *serializationError = nil; + @autoreleasepool { + NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding]; + if (responseString && ![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 + data = [responseString dataUsingEncoding:NSUTF8StringEncoding]; + + if (data) { + if ([data length] > 0) { + responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; + } else { + return nil; + } + } else { + NSDictionary *userInfo = @{ + NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", @"AFNetworking", nil), + NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", @"AFNetworking", nil), responseString] + }; + + serializationError = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; + } + } + } + + if (self.removesKeysWithNullValues && responseObject) { + responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); + } + + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + +- (id)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue]; + self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))]; + [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.readingOptions = self.readingOptions; + serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFXMLParserResponseSerializer + ++ (instancetype)serializer { + AFXMLParserResponseSerializer *serializer = [[self alloc] init]; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + return [[NSXMLParser alloc] initWithData:data]; +} + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +@implementation AFXMLDocumentResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithXMLDocumentOptions:0]; +} + ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask { + AFXMLDocumentResponseSerializer *serializer = [[self alloc] init]; + serializer.options = mask; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + NSError *serializationError = nil; + NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; + + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + + return document; +} + +#pragma mark - NSSecureCoding + +- (id)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.options = self.options; + + return serializer; +} + +@end + +#endif + +#pragma mark - + +@implementation AFPropertyListResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions +{ + AFPropertyListResponseSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.readOptions = readOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + id responseObject; + NSError *serializationError = nil; + + if (data) { + responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; + } + + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + +- (id)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.format = self.format; + serializer.readOptions = self.readOptions; + + return serializer; +} + +@end + +#pragma mark - + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import + +@interface UIImage (AFNetworkingSafeImageLoading) ++ (UIImage *)af_safeImageWithData:(NSData *)data; +@end + +static NSLock* imageLock = nil; + +@implementation UIImage (AFNetworkingSafeImageLoading) + ++ (UIImage *)af_safeImageWithData:(NSData *)data { + UIImage* image = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + imageLock = [[NSLock alloc] init]; + }); + + [imageLock lock]; + image = [UIImage imageWithData:data]; + [imageLock unlock]; + return image; +} + +@end + +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { + UIImage *image = [UIImage af_safeImageWithData:data]; + if (image.images) { + return image; + } + + 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; + } + + CGImageRef imageRef = NULL; + 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) { + CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); + CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); + + // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale + if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { + CGImageRelease(imageRef); + imageRef = NULL; + } + } + } + + CGDataProviderRelease(dataProvider); + + UIImage *image = AFImageWithDataAtScale(data, scale); + if (!imageRef) { + if (image.images || !image) { + return image; + } + + imageRef = CGImageCreateCopy([image CGImage]); + if (!imageRef) { + return nil; + } + } + + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); + + if (width * height > 1024 * 1024 || bitsPerComponent > 8) { + CGImageRelease(imageRef); + + return image; + } + + // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate + size_t bytesPerRow = 0; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + if (colorSpaceModel == kCGColorSpaceModelRGB) { + uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wassign-enum" + if (alpha == kCGImageAlphaNone) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } +#pragma clang diagnostic pop + } + + CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); + + CGColorSpaceRelease(colorSpace); + + if (!context) { + CGImageRelease(imageRef); + + return image; + } + + CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), 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 + + +@implementation AFImageResponseSerializer + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"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]; + +#if TARGET_OS_IOS + self.imageScale = [[UIScreen mainScreen] scale]; + self.automaticallyInflatesResponseImage = YES; +#elif TARGET_OS_WATCH + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; + self.automaticallyInflatesResponseImage = YES; +#endif + + return self; +} + +#pragma mark - AFURLResponseSerializer + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + if (self.automaticallyInflatesResponseImage) { + return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); + } else { + return AFImageWithDataAtScale(data, self.imageScale); + } +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) + // Ensure that the image is set to it's correct pixel width and height + NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; + NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; + [image addRepresentation:bitimage]; + + return image; +#endif + + return nil; +} + +#pragma mark - NSSecureCoding + +- (id)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; +#if CGFLOAT_IS_DOUBLE + self.imageScale = [imageScale doubleValue]; +#else + self.imageScale = [imageScale floatValue]; +#endif + + self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; + [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + serializer.imageScale = self.imageScale; + serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; +#endif + + return serializer; +} + +@end + +#pragma mark - + +@interface AFCompoundResponseSerializer () +@property (readwrite, nonatomic, copy) NSArray *responseSerializers; +@end + +@implementation AFCompoundResponseSerializer + ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers { + AFCompoundResponseSerializer *serializer = [[self alloc] init]; + serializer.responseSerializers = responseSerializers; + + return serializer; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + for (id serializer in self.responseSerializers) { + if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) { + continue; + } + + NSError *serializerError = nil; + id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError]; + if (responseObject) { + if (error) { + *error = AFErrorWithUnderlyingError(serializerError, *error); + } + + return responseObject; + } + } + + return [super responseObjectForResponse:response data:data error:error]; +} + +#pragma mark - NSSecureCoding + +- (id)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.responseSerializers = self.responseSerializers; + + return serializer; +} + +@end diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h new file mode 100644 index 0000000..1cdb516 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h @@ -0,0 +1,554 @@ +// AFURLSessionManager.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" +#import "AFSecurityPolicy.h" +#if !TARGET_OS_WATCH +#import "AFNetworkReachabilityManager.h" +#endif + +#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 + +/** + `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + + ## Subclassing Notes + + This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead. + + ## NSURLSession & NSURLSessionTask Delegate Methods + + `AFURLSessionManager` implements the following delegate methods: + + ### `NSURLSessionDelegate` + + - `URLSession:didBecomeInvalidWithError:` + - `URLSession:didReceiveChallenge:completionHandler:` + - `URLSessionDidFinishEventsForBackgroundURLSession:` + + ### `NSURLSessionTaskDelegate` + + - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` + - `URLSession:task:didReceiveChallenge:completionHandler:` + - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` + - `URLSession:task:didCompleteWithError:` + + ### `NSURLSessionDataDelegate` + + - `URLSession:dataTask:didReceiveResponse:completionHandler:` + - `URLSession:dataTask:didBecomeDownloadTask:` + - `URLSession:dataTask:didReceiveData:` + - `URLSession:dataTask:willCacheResponse:completionHandler:` + + ### `NSURLSessionDownloadDelegate` + + - `URLSession:downloadTask:didFinishDownloadingToURL:` + - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:` + - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` + + If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. + + ## Network Reachability Monitoring + + Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. + + ## NSCoding Caveats + + - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. + + ## NSCopying Caveats + + - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. + - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_OS_WATCH + +@interface AFURLSessionManager : NSObject + +/** + The managed session. + */ +@property (readonly, nonatomic, strong) NSURLSession *session; + +/** + The operation queue on which delegate callbacks are run. + */ +@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; + +/** + 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 instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) id responseSerializer; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created request operations to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +#if !TARGET_OS_WATCH +///-------------------------------------- +/// @name Monitoring Network Reachability +///-------------------------------------- + +/** + The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. + */ +@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; +#endif + +///---------------------------- +/// @name Getting Session Tasks +///---------------------------- + +/** + The data, upload, and download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *tasks; + +/** + The data tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *dataTasks; + +/** + The upload tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *uploadTasks; + +/** + The download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *downloadTasks; + +///------------------------------- +/// @name Managing Callback Queues +///------------------------------- + +/** + The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. + */ +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; +#else +@property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; +#endif + +/** + The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. + */ +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; +#else +@property (nonatomic, assign, nullable) dispatch_group_t completionGroup; +#endif + +///--------------------------------- +/// @name Working Around System Bugs +///--------------------------------- + +/** + Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default. + + @bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again. + + @see https://github.com/AFNetworking/AFNetworking/issues/1675 + */ +@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. + + @param configuration The configuration used to create the managed session. + + @return A manager for a newly-created session. + */ +- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +/** + Invalidates the managed session, optionally canceling pending tasks. + + @param cancelPendingTasks Whether or not to cancel pending tasks. + */ +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; + +///------------------------- +/// @name Running Data Tasks +///------------------------- + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + completionHandler:(nullable void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + +///--------------------------- +/// @name Running Upload Tasks +///--------------------------- + +/** + Creates an `NSURLSessionUploadTask` with the specified request for a local file. + + @param request The HTTP request for the request. + @param fileURL A URL to the local file to be uploaded. + @param progress A progress object monitoring the current upload progress. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + + @see `attemptsToRecreateUploadTasksForBackgroundSessions` + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(NSProgress * __nullable __autoreleasing * __nullable)progress + completionHandler:(nullable void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. + + @param request The HTTP request for the request. + @param bodyData A data object containing the HTTP body to be uploaded. + @param progress A progress object monitoring the current upload progress. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(nullable NSData *)bodyData + progress:(NSProgress * __nullable __autoreleasing * __nullable)progress + completionHandler:(nullable void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified streaming request. + + @param request The HTTP request for the request. + @param progress A progress object monitoring the current upload progress. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(NSProgress * __nullable __autoreleasing * __nullable)progress + completionHandler:(nullable void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + +///----------------------------- +/// @name Running Download Tasks +///----------------------------- + +/** + Creates an `NSURLSessionDownloadTask` with the specified request. + + @param request The HTTP request for the request. + @param progress A progress object monitoring the current download progress. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + + @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(NSProgress * __nullable __autoreleasing * __nullable)progress + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; + +/** + Creates an `NSURLSessionDownloadTask` with the specified resume data. + + @param resumeData The data used to resume downloading. + @param progress A progress object monitoring the current download progress. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(NSProgress * __nullable __autoreleasing * __nullable)progress + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; + +///--------------------------------- +/// @name Getting Progress for Tasks +///--------------------------------- + +/** + Returns the upload progress of the specified task. + + @param uploadTask The session upload task. Must not be `nil`. + + @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask; + +/** + Returns the download progress of the specified task. + + @param downloadTask The session download task. Must not be `nil`. + + @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask; + +///----------------------------------------- +/// @name Setting Session Delegate Callbacks +///----------------------------------------- + +/** + Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. + + @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. + */ +- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; + +/** + Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + */ +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __nullable __autoreleasing * __nullable credential))block; + +///-------------------------------------- +/// @name Setting Task Delegate Callbacks +///-------------------------------------- + +/** + Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`. + + @param block A block object to be executed when a task requires a new request body stream. + */ +- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; + +/** + Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`. + + @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. + */ +- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; + +/** + Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + */ +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __nullable __autoreleasing * __nullable credential))block; + +/** + Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; + +/** + Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. + + @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. + */ +- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block; + +///------------------------------------------- +/// @name Setting Data Task Delegate Callbacks +///------------------------------------------- + +/** + Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + + @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. + */ +- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; + +/** + Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. + + @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become. + */ +- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; + +/** + Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; + +/** + Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`. + + @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response. + */ +- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; + +/** + Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. + + @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. + */ +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block; + +///----------------------------------------------- +/// @name Setting Download Task Delegate Callbacks +///----------------------------------------------- + +/** + Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. + + @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. + */ +- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; + +/** + Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; + +/** + Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + + @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded. + */ +- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; + +@end + +#endif + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when a task begins executing. + + @deprecated Use `AFNetworkingTaskDidResumeNotification` instead. + */ +extern NSString * const AFNetworkingTaskDidStartNotification DEPRECATED_ATTRIBUTE; + +/** + Posted when a task resumes. + */ +extern NSString * const AFNetworkingTaskDidResumeNotification; + +/** + Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. + + @deprecated Use `AFNetworkingTaskDidCompleteNotification` instead. + */ +extern NSString * const AFNetworkingTaskDidFinishNotification DEPRECATED_ATTRIBUTE; + +/** + Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. + */ +extern NSString * const AFNetworkingTaskDidCompleteNotification; + +/** + Posted when a task suspends its execution. + */ +extern NSString * const AFNetworkingTaskDidSuspendNotification; + +/** + Posted when a session is invalidated. + */ +extern NSString * const AFURLSessionDidInvalidateNotification; + +/** + Posted when a session download task encountered an error when moving the temporary download file to a specified destination. + */ +extern NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; + +/** + The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. + + @deprecated Use `AFNetworkingTaskDidCompleteResponseDataKey` instead. + */ +extern NSString * const AFNetworkingTaskDidFinishResponseDataKey DEPRECATED_ATTRIBUTE; + +/** + The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. + */ +extern NSString * const AFNetworkingTaskDidCompleteResponseDataKey; + +/** + The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. + + @deprecated Use `AFNetworkingTaskDidCompleteSerializedResponseKey` instead. + */ +extern NSString * const AFNetworkingTaskDidFinishSerializedResponseKey DEPRECATED_ATTRIBUTE; + +/** + The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. + */ +extern NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; + +/** + The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. + + @deprecated Use `AFNetworkingTaskDidCompleteResponseSerializerKey` instead. + */ +extern NSString * const AFNetworkingTaskDidFinishResponseSerializerKey DEPRECATED_ATTRIBUTE; + +/** + The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. + */ +extern NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; + +/** + The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. + + @deprecated Use `AFNetworkingTaskDidCompleteAssetPathKey` instead. + */ +extern NSString * const AFNetworkingTaskDidFinishAssetPathKey DEPRECATED_ATTRIBUTE; + +/** + The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. + */ +extern NSString * const AFNetworkingTaskDidCompleteAssetPathKey; + +/** + Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. + + @deprecated Use `AFNetworkingTaskDidCompleteErrorKey` instead. + */ +extern NSString * const AFNetworkingTaskDidFinishErrorKey DEPRECATED_ATTRIBUTE; + +/** + Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. + */ +extern NSString * const AFNetworkingTaskDidCompleteErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m new file mode 100644 index 0000000..a795a07 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m @@ -0,0 +1,1169 @@ +// AFURLSessionManager.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "AFURLSessionManager.h" +#import + +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) + +static dispatch_queue_t url_session_manager_creation_queue() { + static dispatch_queue_t af_url_session_manager_creation_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL); + }); + + return af_url_session_manager_creation_queue; +} + +static dispatch_queue_t url_session_manager_processing_queue() { + static dispatch_queue_t af_url_session_manager_processing_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT); + }); + + return af_url_session_manager_processing_queue; +} + +static dispatch_group_t url_session_manager_completion_group() { + static dispatch_group_t af_url_session_manager_completion_group; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_completion_group = dispatch_group_create(); + }); + + return af_url_session_manager_completion_group; +} + +NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume"; +NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete"; +NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend"; +NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; +NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; + +NSString * const AFNetworkingTaskDidStartNotification = @"com.alamofire.networking.task.resume"; // Deprecated +NSString * const AFNetworkingTaskDidFinishNotification = @"com.alamofire.networking.task.complete"; // Deprecated + +NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; +NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; +NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; +NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; +NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; + +NSString * const AFNetworkingTaskDidFinishSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; // Deprecated +NSString * const AFNetworkingTaskDidFinishResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; // Deprecated +NSString * const AFNetworkingTaskDidFinishResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; // Deprecated +NSString * const AFNetworkingTaskDidFinishErrorKey = @"com.alamofire.networking.task.complete.error"; // Deprecated +NSString * const AFNetworkingTaskDidFinishAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; // Deprecated + +static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; + +static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3; + +static void * AFTaskStateChangedContext = &AFTaskStateChangedContext; + +typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); + +typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); +typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session); + +typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task); +typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend); +typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error); + +typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response); +typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask); +typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data); +typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse); + +typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); +typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); +typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); + +typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); + +#pragma mark - + +@interface AFURLSessionManagerTaskDelegate : NSObject +@property (nonatomic, weak) AFURLSessionManager *manager; +@property (nonatomic, strong) NSMutableData *mutableData; +@property (nonatomic, strong) NSProgress *progress; +@property (nonatomic, copy) NSURL *downloadFileURL; +@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; +@end + +@implementation AFURLSessionManagerTaskDelegate + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.mutableData = [NSMutableData data]; + + self.progress = [NSProgress progressWithTotalUnitCount:0]; + + return self; +} + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(__unused NSURLSession *)session + task:(__unused NSURLSessionTask *)task + didSendBodyData:(__unused int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend +{ + self.progress.totalUnitCount = totalBytesExpectedToSend; + self.progress.completedUnitCount = totalBytesSent; +} + +- (void)URLSession:(__unused NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + __strong AFURLSessionManager *manager = self.manager; + + __block id responseObject = nil; + + __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; + + //Performance Improvement from #2672 + NSData *data = nil; + if (self.mutableData) { + data = [self.mutableData copy]; + //We no longer need the reference, so nil it out to gain back some memory. + self.mutableData = nil; + } + + if (self.downloadFileURL) { + userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; + } else if (data) { + userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data; + } + + if (error) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, error); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + } else { + dispatch_async(url_session_manager_processing_queue(), ^{ + NSError *serializationError = nil; + responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; + + if (self.downloadFileURL) { + responseObject = self.downloadFileURL; + } + + if (responseObject) { + userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject; + } + + if (serializationError) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError; + } + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, serializationError); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + }); + } +#pragma clang diagnostic pop +} + +#pragma mark - NSURLSessionDataTaskDelegate + +- (void)URLSession:(__unused NSURLSession *)session + dataTask:(__unused NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + [self.mutableData appendData:data]; +} + +#pragma mark - NSURLSessionDownloadTaskDelegate + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + NSError *fileManagerError = nil; + self.downloadFileURL = nil; + + if (self.downloadTaskDidFinishDownloading) { + self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (self.downloadFileURL) { + [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]; + + if (fileManagerError) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; + } + } + } +} + +- (void)URLSession:(__unused NSURLSession *)session + downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask + didWriteData:(__unused int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite +{ + self.progress.totalUnitCount = totalBytesExpectedToWrite; + self.progress.completedUnitCount = totalBytesWritten; +} + +- (void)URLSession:(__unused NSURLSession *)session + downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes { + self.progress.totalUnitCount = expectedTotalBytes; + self.progress.completedUnitCount = fileOffset; +} + +@end + +#pragma mark - + +/** + * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`. + * + * See: + * - https://github.com/AFNetworking/AFNetworking/issues/1477 + * - https://github.com/AFNetworking/AFNetworking/issues/2638 + * - https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + +static inline void af_swizzleSelector(Class class, SEL originalSelector, SEL swizzledSelector) { + Method originalMethod = class_getInstanceMethod(class, originalSelector); + Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); + method_exchangeImplementations(originalMethod, swizzledMethod); +} + +static inline BOOL af_addMethod(Class class, SEL selector, Method method) { + return class_addMethod(class, selector, method_getImplementation(method), method_getTypeEncoding(method)); +} + +static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume"; +static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend"; + +@interface _AFURLSessionTaskSwizzling : NSObject + +@end + +@implementation _AFURLSessionTaskSwizzling + ++ (void)load { + /** + WARNING: Trouble Ahead + https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + + if (NSClassFromString(@"NSURLSessionTask")) { + /** + iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky. + Many Unit Tests have been built to validate as much of this behavior has possible. + Here is what we know: + - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back. + - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there. + - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`. + - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`. + - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled. + - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled. + - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there. + + Some Assumptions: + - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it. + - No background task classes override `resume` or `suspend` + + The current solution: + 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task. + 2) Grab a pointer to the original implementation of `af_resume` + 3) Check to see if the current class has an implementation of resume. If so, continue to step 4. + 4) Grab the super class of the current class. + 5) Grab a pointer for the current class to the current implementation of `resume`. + 6) Grab a pointer for the super class to the current implementation of `resume`. + 7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods + 8) Set the current class to the super class, and repeat steps 3-8 + */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionDataTask *localDataTask = [[NSURLSession sessionWithConfiguration:nil] dataTaskWithURL:nil]; +#pragma clang diagnostic pop + IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([_AFURLSessionTaskSwizzling class], @selector(af_resume))); + Class currentClass = [localDataTask class]; + + while (class_getInstanceMethod(currentClass, @selector(resume))) { + Class superClass = [currentClass superclass]; + IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume))); + IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume))); + if (classResumeIMP != superclassResumeIMP && + originalAFResumeIMP != classResumeIMP) { + [self swizzleResumeAndSuspendMethodForClass:currentClass]; + } + currentClass = [currentClass superclass]; + } + + [localDataTask cancel]; + } +} + ++ (void)swizzleResumeAndSuspendMethodForClass:(Class)class { + Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume)); + Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend)); + + af_addMethod(class, @selector(af_resume), afResumeMethod); + af_addMethod(class, @selector(af_suspend), afSuspendMethod); + + af_swizzleSelector(class, @selector(resume), @selector(af_resume)); + af_swizzleSelector(class, @selector(suspend), @selector(af_suspend)); +} + +- (NSURLSessionTaskState)state { + NSAssert(NO, @"State method should never be called in the actual dummy class"); + return NSURLSessionTaskStateCanceling; +} + +- (void)af_resume { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_resume]; + + if (state != NSURLSessionTaskStateRunning) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self]; + } +} + +- (void)af_suspend { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_suspend]; + + if (state != NSURLSessionTaskStateSuspended) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self]; + } +} +@end + +#pragma mark - + +@interface AFURLSessionManager () +@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration; +@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; +@property (readwrite, nonatomic, strong) NSURLSession *session; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier; +@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks; +@property (readwrite, nonatomic, strong) NSLock *lock; +@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; +@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession; +@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume; +@end + +@implementation AFURLSessionManager + +- (instancetype)init { + return [self initWithSessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + self = [super init]; + if (!self) { + return nil; + } + + if (!configuration) { + configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + } + + self.sessionConfiguration = configuration; + + self.operationQueue = [[NSOperationQueue alloc] init]; + self.operationQueue.maxConcurrentOperationCount = 1; + + self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; + + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + self.securityPolicy = [AFSecurityPolicy defaultPolicy]; + +#if !TARGET_OS_WATCH + self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; +#endif + + self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; + + self.lock = [[NSLock alloc] init]; + self.lock.name = AFURLSessionManagerLockName; + + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + for (NSURLSessionDataTask *task in dataTasks) { + [self addDelegateForDataTask:task completionHandler:nil]; + } + + for (NSURLSessionUploadTask *uploadTask in uploadTasks) { + [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil]; + } + + for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { + [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil]; + } + }]; + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:nil]; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - + +- (NSString *)taskDescriptionForSessionTasks { + return [NSString stringWithFormat:@"%p", self]; +} + +- (void)taskDidResume:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task]; + }); + } + } +} + +- (void)taskDidSuspend:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task]; + }); + } + } +} + +#pragma mark - + +- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + AFURLSessionManagerTaskDelegate *delegate = nil; + [self.lock lock]; + delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)]; + [self.lock unlock]; + + return delegate; +} + +- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate + forTask:(NSURLSessionTask *)task +{ + NSParameterAssert(task); + NSParameterAssert(delegate); + + [self.lock lock]; + self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; + [self.lock unlock]; +} + +- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + dataTask.taskDescription = self.taskDescriptionForSessionTasks; + [self setDelegate:delegate forTask:dataTask]; +} + +- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask + progress:(NSProgress * __autoreleasing *)progress + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + int64_t totalUnitCount = uploadTask.countOfBytesExpectedToSend; + if(totalUnitCount == NSURLSessionTransferSizeUnknown) { + NSString *contentLength = [uploadTask.originalRequest valueForHTTPHeaderField:@"Content-Length"]; + if(contentLength) { + totalUnitCount = (int64_t)[contentLength longLongValue]; + } + } + + if (delegate.progress) { + delegate.progress.totalUnitCount = totalUnitCount; + } else { + delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount]; + } + + delegate.progress.pausingHandler = ^{ + [uploadTask suspend]; + }; + delegate.progress.cancellationHandler = ^{ + [uploadTask cancel]; + }; + + if (progress) { + *progress = delegate.progress; + } + + uploadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:uploadTask]; +} + +- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask + progress:(NSProgress * __autoreleasing *)progress + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + if (destination) { + delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) { + return destination(location, task.response); + }; + } + + if (progress) { + *progress = delegate.progress; + } + + downloadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:downloadTask]; +} + +- (void)removeDelegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + [self.lock lock]; + [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; + [self.lock unlock]; +} + +- (void)removeAllDelegates { + [self.lock lock]; + [self.mutableTaskDelegatesKeyedByTaskIdentifier removeAllObjects]; + [self.lock unlock]; +} + +#pragma mark - + +- (NSArray *)tasksForKeyPath:(NSString *)keyPath { + __block NSArray *tasks = nil; + dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) { + tasks = dataTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) { + tasks = uploadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) { + tasks = downloadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) { + tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; + } + + dispatch_semaphore_signal(semaphore); + }]; + + dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); + + return tasks; +} + +- (NSArray *)tasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)dataTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)uploadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)downloadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +#pragma mark - + +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks { + dispatch_async(dispatch_get_main_queue(), ^{ + if (cancelPendingTasks) { + [self.session invalidateAndCancel]; + } else { + [self.session finishTasksAndInvalidate]; + } + }); +} + +#pragma mark - + +- (void)setResponseSerializer:(id )responseSerializer { + NSParameterAssert(responseSerializer); + + _responseSerializer = responseSerializer; +} + +#pragma mark - + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionDataTask *dataTask = nil; + dispatch_sync(url_session_manager_creation_queue(), ^{ + dataTask = [self.session dataTaskWithRequest:request]; + }); + + [self addDelegateForDataTask:dataTask completionHandler:completionHandler]; + + return dataTask; +} + +#pragma mark - + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(NSProgress * __autoreleasing *)progress + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + dispatch_sync(url_session_manager_creation_queue(), ^{ + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + }); + + if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) { + for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) { + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + } + } + + [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(NSData *)bodyData + progress:(NSProgress * __autoreleasing *)progress + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + dispatch_sync(url_session_manager_creation_queue(), ^{ + uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; + }); + + [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(NSProgress * __autoreleasing *)progress + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + dispatch_sync(url_session_manager_creation_queue(), ^{ + uploadTask = [self.session uploadTaskWithStreamedRequest:request]; + }); + + [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; + + return uploadTask; +} + +#pragma mark - + +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(NSProgress * __autoreleasing *)progress + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + __block NSURLSessionDownloadTask *downloadTask = nil; + dispatch_sync(url_session_manager_creation_queue(), ^{ + downloadTask = [self.session downloadTaskWithRequest:request]; + }); + + [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(NSProgress * __autoreleasing *)progress + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + __block NSURLSessionDownloadTask *downloadTask = nil; + dispatch_sync(url_session_manager_creation_queue(), ^{ + downloadTask = [self.session downloadTaskWithResumeData:resumeData]; + }); + + [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +#pragma mark - + +- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask { + return [[self delegateForTask:uploadTask] progress]; +} + +- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask { + return [[self delegateForTask:downloadTask] progress]; +} + +#pragma mark - + +- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block { + self.sessionDidBecomeInvalid = block; +} + +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { + self.sessionDidReceiveAuthenticationChallenge = block; +} + +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { + self.didFinishEventsForBackgroundURLSession = block; +} + +#pragma mark - + +- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block { + self.taskNeedNewBodyStream = block; +} + +- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block { + self.taskWillPerformHTTPRedirection = block; +} + +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { + self.taskDidReceiveAuthenticationChallenge = block; +} + +- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block { + self.taskDidSendBodyData = block; +} + +- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block { + self.taskDidComplete = block; +} + +#pragma mark - + +- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block { + self.dataTaskDidReceiveResponse = block; +} + +- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block { + self.dataTaskDidBecomeDownloadTask = block; +} + +- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block { + self.dataTaskDidReceiveData = block; +} + +- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block { + self.dataTaskWillCacheResponse = block; +} + +#pragma mark - + +- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block { + self.downloadTaskDidFinishDownloading = block; +} + +- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block { + self.downloadTaskDidWriteData = block; +} + +- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block { + self.downloadTaskDidResume = block; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue]; +} + +- (BOOL)respondsToSelector:(SEL)selector { + if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) { + return self.taskWillPerformHTTPRedirection != nil; + } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) { + return self.dataTaskDidReceiveResponse != nil; + } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) { + return self.dataTaskWillCacheResponse != nil; + } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) { + return self.didFinishEventsForBackgroundURLSession != nil; + } + + return [[self class] instancesRespondToSelector:selector]; +} + +#pragma mark - NSURLSessionDelegate + +- (void)URLSession:(NSURLSession *)session +didBecomeInvalidWithError:(NSError *)error +{ + if (self.sessionDidBecomeInvalid) { + self.sessionDidBecomeInvalid(session, error); + } + + [self removeAllDelegates]; + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; +} + +- (void)URLSession:(NSURLSession *)session +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + __block NSURLCredential *credential = nil; + + if (self.sessionDidReceiveAuthenticationChallenge) { + disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); + } else { + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + if (credential) { + disposition = NSURLSessionAuthChallengeUseCredential; + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } else { + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler +{ + NSURLRequest *redirectRequest = request; + + if (self.taskWillPerformHTTPRedirection) { + redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request); + } + + if (completionHandler) { + completionHandler(redirectRequest); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + __block NSURLCredential *credential = nil; + + if (self.taskDidReceiveAuthenticationChallenge) { + disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential); + } else { + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + disposition = NSURLSessionAuthChallengeUseCredential; + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + } else { + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler +{ + NSInputStream *inputStream = nil; + + if (self.taskNeedNewBodyStream) { + inputStream = self.taskNeedNewBodyStream(session, task); + } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { + inputStream = [task.originalRequest.HTTPBodyStream copy]; + } + + if (completionHandler) { + completionHandler(inputStream); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend +{ + + int64_t totalUnitCount = totalBytesExpectedToSend; + if(totalUnitCount == NSURLSessionTransferSizeUnknown) { + NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; + if(contentLength) { + totalUnitCount = (int64_t) [contentLength longLongValue]; + } + } + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalUnitCount]; + + if (self.taskDidSendBodyData) { + self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + + // delegate may be nil when completing a task in the background + if (delegate) { + [delegate URLSession:session task:task didCompleteWithError:error]; + + [self removeDelegateForTask:task]; + } + + if (self.taskDidComplete) { + self.taskDidComplete(session, task, error); + } + +} + +#pragma mark - NSURLSessionDataDelegate + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler +{ + NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; + + if (self.dataTaskDidReceiveResponse) { + disposition = self.dataTaskDidReceiveResponse(session, dataTask, response); + } + + if (completionHandler) { + completionHandler(disposition); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + if (delegate) { + [self removeDelegateForTask:dataTask]; + [self setDelegate:delegate forTask:downloadTask]; + } + + if (self.dataTaskDidBecomeDownloadTask) { + self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + [delegate URLSession:session dataTask:dataTask didReceiveData:data]; + + if (self.dataTaskDidReceiveData) { + self.dataTaskDidReceiveData(session, dataTask, data); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler +{ + NSCachedURLResponse *cachedResponse = proposedResponse; + + if (self.dataTaskWillCacheResponse) { + cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse); + } + + if (completionHandler) { + completionHandler(cachedResponse); + } +} + +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { + if (self.didFinishEventsForBackgroundURLSession) { + dispatch_async(dispatch_get_main_queue(), ^{ + self.didFinishEventsForBackgroundURLSession(session); + }); + } +} + +#pragma mark - NSURLSessionDownloadDelegate + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + if (self.downloadTaskDidFinishDownloading) { + NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (fileURL) { + delegate.downloadFileURL = fileURL; + NSError *error = nil; + [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]; + if (error) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; + } + + return; + } + } + + if (delegate) { + [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite]; + + if (self.downloadTaskDidWriteData) { + self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes]; + + if (self.downloadTaskDidResume) { + self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (id)initWithCoder:(NSCoder *)decoder { + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + + self = [self initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; +} + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/LICENSE b/TalkinToTheNet/Pods/AFNetworking/LICENSE new file mode 100644 index 0000000..91f125b --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +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. diff --git a/TalkinToTheNet/Pods/AFNetworking/README.md b/TalkinToTheNet/Pods/AFNetworking/README.md new file mode 100644 index 0000000..f25efe0 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/README.md @@ -0,0 +1,394 @@ +

+ 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 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. + +Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! + +## How To Get Started + +- [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. + +## Communication + +- 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. + +### Installation with CocoaPods + +[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). + +#### Podfile + +```ruby +platform :ios, '7.0' +pod "AFNetworking", "~> 2.0" +``` + +## Requirements + +| 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 | | + +(OS X projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). + +> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. + +## Architecture + +### NSURLConnection + +- `AFURLConnectionOperation` +- `AFHTTPRequestOperation` +- `AFHTTPRequestOperationManager` + +### NSURLSession _(iOS 7 / Mac OS X 10.9)_ + +- `AFURLSessionManager` +- `AFHTTPSessionManager` + +### Serialization + +* `` + - `AFHTTPRequestSerializer` + - `AFJSONRequestSerializer` + - `AFPropertyListRequestSerializer` +* `` + - `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 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 ``, ``, ``, and ``. + +#### 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 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. + +* Do not use Reachability to determine if the original request should be sent. + * You should try to send it. +* You can use Reachability to determine when a request should be automatically retried. + * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something. +* Network reachability is a useful tool for determining why a request might have failed. + * After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out." + +See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/wwdc/2012/#706). + +#### Shared Network Reachability + +```objective-c +[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); +}]; + +[[AFNetworkReachabilityManager sharedManager] startMonitoring]; +``` + +#### 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 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](http://cocoapods.org/): + + $ cd Tests + $ pod install + +Once testing dependencies are installed, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode. + +### Running Tests from the Command Line + +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: + + $ gem install xcpretty + +Once `xcpretty` is installed, you can execute the suite via `rake test`. + +## Credits + +AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). + +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/). + +And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). + +### Security Disclosure + +If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## License + +AFNetworking is released under the MIT license. See LICENSE for details. diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 100644 index 0000000..3c7649b --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1,80 @@ +// AFNetworkActivityIndicatorManager.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + `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 `enabled` 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 + */ +NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") +@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 after decrementing, this will stop animating the status bar network activity indicator. + */ +- (void)decrementActivityCount; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m new file mode 100644 index 0000000..cf13180 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m @@ -0,0 +1,170 @@ +// AFNetworkActivityIndicatorManager.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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" + +#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) + +#import "AFHTTPRequestOperation.h" + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 +#import "AFURLSessionManager.h" +#endif + +static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17; + +static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { + if ([[notification object] isKindOfClass:[AFURLConnectionOperation class]]) { + return [(AFURLConnectionOperation *)[notification object] request]; + } + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 + if ([[notification object] respondsToSelector:@selector(originalRequest)]) { + return [(NSURLSessionTask *)[notification object] originalRequest]; + } +#endif + + return nil; +} + +@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 +@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(networkRequestDidStart:) name:AFNetworkingOperationDidStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil]; + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; +#endif + + 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:@[NSRunLoopCommonModes]]; + } + } +} + +- (BOOL)isNetworkActivityIndicatorVisible { + return self.activityCount > 0; +} + +- (void)updateNetworkActivityIndicatorVisibility { + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]]; +} + +- (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)networkRequestDidStart:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self incrementActivityCount]; + } +} + +- (void)networkRequestDidFinish:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self decrementActivityCount]; + } +} + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h new file mode 100644 index 0000000..0c8f9b5 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h @@ -0,0 +1,63 @@ +// UIActivityIndicatorView+AFNetworking.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import + +@class AFURLConnectionOperation; + +/** + This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a request operation or session task. + */ +@interface UIActivityIndicatorView (AFNetworking) + +///---------------------------------- +/// @name Animating for Session Tasks +///---------------------------------- + +/** + Binds the animating state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; +#endif + +///--------------------------------------- +/// @name Animating for Request Operations +///--------------------------------------- + +/** + Binds the animating state to the execution state of the specified operation. + + @param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setAnimatingWithStateOfOperation:(nullable AFURLConnectionOperation *)operation; + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m new file mode 100644 index 0000000..dd362b0 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m @@ -0,0 +1,171 @@ +// UIActivityIndicatorView+AFNetworking.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "UIActivityIndicatorView+AFNetworking.h" +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import "AFHTTPRequestOperation.h" + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +#import "AFURLSessionManager.h" +#endif + +@interface AFActivityIndicatorViewNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; +#endif +- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation; + +@end + +@implementation UIActivityIndicatorView (AFNetworking) + +- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver { + AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setAnimatingWithStateOfTask:task]; +} +#endif + +- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation { + [[self af_notificationObserver] setAnimatingWithStateOfOperation:operation]; +} + +@end + +@implementation AFActivityIndicatorViewNotificationObserver + +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView +{ + self = [super init]; + if (self) { + _activityIndicatorView = activityIndicatorView; + } + return self; +} + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { + if (task.state != NSURLSessionTaskStateCompleted) { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" +#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" + if (task.state == NSURLSessionTaskStateRunning) { + [self.activityIndicatorView startAnimating]; + } else { + [self.activityIndicatorView stopAnimating]; + } +#pragma clang diagnostic pop + + [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task]; + } + } +} +#endif + +#pragma mark - + +- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; + + if (operation) { + if (![operation isFinished]) { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" +#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" + if ([operation isExecuting]) { + [self.activityIndicatorView startAnimating]; + } else { + [self.activityIndicatorView stopAnimating]; + } +#pragma clang diagnostic pop + + [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingOperationDidStartNotification object:operation]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingOperationDidFinishNotification object:operation]; + } + } +} + +#pragma mark - + +- (void)af_startAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.activityIndicatorView startAnimating]; +#pragma clang diagnostic pop + }); +} + +- (void)af_stopAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.activityIndicatorView stopAnimating]; +#pragma clang diagnostic pop + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +#endif + + [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; +} + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h new file mode 100644 index 0000000..97f5622 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h @@ -0,0 +1,99 @@ +// UIAlertView+AFNetworking.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFURLConnectionOperation; + +/** + This category adds methods to the UIKit framework's `UIAlertView` class. The methods in this category provide support for automatically showing an alert if a session task or request operation finishes with an error. Alert title and message are filled from the corresponding `localizedDescription` & `localizedRecoverySuggestion` or `localizedFailureReason` of the error. + */ +@interface UIAlertView (AFNetworking) + +///------------------------------------- +/// @name Showing Alert for Session Task +///------------------------------------- + +/** + Shows an alert view with the error of the specified session task, if any. + + @param task The session task. + @param delegate The alert view delegate. + */ +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 ++ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task + delegate:(nullable id)delegate NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); +#endif + +/** + Shows an alert view with the error of the specified session task, if any, with a custom cancel button title and other button titles. + + @param task The session task. + @param delegate The alert view delegate. + @param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title. + @param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`. + */ +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 ++ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task + delegate:(nullable id)delegate + cancelButtonTitle:(nullable NSString *)cancelButtonTitle + otherButtonTitles:(nullable NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); +#endif + +///------------------------------------------ +/// @name Showing Alert for Request Operation +///------------------------------------------ + +/** + Shows an alert view with the error of the specified request operation, if any. + + @param operation The request operation. + @param delegate The alert view delegate. + */ ++ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation + delegate:(nullable id)delegate NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); + +/** + Shows an alert view with the error of the specified request operation, if any, with a custom cancel button title and other button titles. + + @param operation The request operation. + @param delegate The alert view delegate. + @param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title. + @param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`. + */ ++ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation + delegate:(nullable id)delegate + cancelButtonTitle:(nullable NSString *)cancelButtonTitle + otherButtonTitles:(nullable NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m new file mode 100644 index 0000000..0d1e9e7 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m @@ -0,0 +1,141 @@ +// UIAlertView+AFNetworking.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "UIAlertView+AFNetworking.h" + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import "AFURLConnectionOperation.h" + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +#import "AFURLSessionManager.h" +#endif + +static void AFGetAlertViewTitleAndMessageFromError(NSError *error, NSString * __autoreleasing *title, NSString * __autoreleasing *message) { + if (error.localizedDescription && (error.localizedRecoverySuggestion || error.localizedFailureReason)) { + *title = error.localizedDescription; + + if (error.localizedRecoverySuggestion) { + *message = error.localizedRecoverySuggestion; + } else { + *message = error.localizedFailureReason; + } + } else if (error.localizedDescription) { + *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description"); + *message = error.localizedDescription; + } else { + *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description"); + *message = [NSString stringWithFormat:NSLocalizedStringFromTable(@"%@ Error: %ld", @"AFNetworking", @"Fallback Error Failure Reason Format"), error.domain, (long)error.code]; + } +} + +@implementation UIAlertView (AFNetworking) + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 ++ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task + delegate:(id)delegate +{ + [self showAlertViewForTaskWithErrorOnCompletion:task delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil]; +} + ++ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task + delegate:(id)delegate + cancelButtonTitle:(NSString *)cancelButtonTitle + otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION +{ + NSMutableArray *mutableOtherTitles = [NSMutableArray array]; + va_list otherButtonTitleList; + va_start(otherButtonTitleList, otherButtonTitles); + { + for (NSString *otherButtonTitle = otherButtonTitles; otherButtonTitle != nil; otherButtonTitle = va_arg(otherButtonTitleList, NSString *)) { + [mutableOtherTitles addObject:otherButtonTitle]; + } + } + va_end(otherButtonTitleList); + + __block __weak id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingTaskDidCompleteNotification object:task queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { + NSError *error = notification.userInfo[AFNetworkingTaskDidCompleteErrorKey]; + if (error) { + NSString *title, *message; + AFGetAlertViewTitleAndMessageFromError(error, &title, &message); + + UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil, nil]; + for (NSString *otherButtonTitle in mutableOtherTitles) { + [alertView addButtonWithTitle:otherButtonTitle]; + } + [alertView setTitle:title]; + [alertView setMessage:message]; + [alertView show]; + } + + [[NSNotificationCenter defaultCenter] removeObserver:observer]; + }]; +} +#endif + +#pragma mark - + ++ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation + delegate:(id)delegate +{ + [self showAlertViewForRequestOperationWithErrorOnCompletion:operation delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil]; +} + ++ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation + delegate:(id)delegate + cancelButtonTitle:(NSString *)cancelButtonTitle + otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION +{ + NSMutableArray *mutableOtherTitles = [NSMutableArray array]; + va_list otherButtonTitleList; + va_start(otherButtonTitleList, otherButtonTitles); + { + for (NSString *otherButtonTitle = otherButtonTitles; otherButtonTitle != nil; otherButtonTitle = va_arg(otherButtonTitleList, NSString *)) { + [mutableOtherTitles addObject:otherButtonTitle]; + } + } + va_end(otherButtonTitleList); + + __block __weak id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingOperationDidFinishNotification object:operation queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { + + if (notification.object && [notification.object isKindOfClass:[AFURLConnectionOperation class]]) { + NSError *error = [(AFURLConnectionOperation *)notification.object error]; + if (error) { + NSString *title, *message; + AFGetAlertViewTitleAndMessageFromError(error, &title, &message); + + UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil, nil]; + for (NSString *otherButtonTitle in mutableOtherTitles) { + [alertView addButtonWithTitle:otherButtonTitle]; + } + [alertView setTitle:title]; + [alertView setMessage:message]; + [alertView show]; + } + } + + [[NSNotificationCenter defaultCenter] removeObserver:observer]; + }]; +} + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h new file mode 100644 index 0000000..327bdab --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h @@ -0,0 +1,184 @@ +// UIButton+AFNetworking.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol AFURLResponseSerialization, AFImageCache; + +/** + This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. + + @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. + */ +@interface UIButton (AFNetworking) + +///---------------------------- +/// @name Accessing Image Cache +///---------------------------- + +/** + The image cache used to improve image loading performance on scroll views. By default, `UIButton` will use the `sharedImageCache` of `UIImageView`. + */ ++ (id )sharedImageCache; + +/** + Set the cache used for image loading. + + @param imageCache The image cache. + */ ++ (void)setSharedImageCache:(id )imageCache; + +///------------------------------------ +/// @name Accessing Response Serializer +///------------------------------------ + +/** + The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`. + + @discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer + */ +@property (nonatomic, strong) id imageResponseSerializer; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once 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. + + @param state The control state. + @param url The URL used for the image request. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once 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. + + @param state The control state. + @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 button will not change its image until the image request finishes. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once 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. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. + + @param state The control state. + @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 button will not change its image until the image request finishes. + @param success A block to be executed when the image request operation finishes successfully. This block has no return value and takes two arguments: the server response and the image. 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 a single argument: the error that occurred. + */ +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(nullable void (^)(NSError *error))failure; + + +///------------------------------- +/// @name Setting Background Image +///------------------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. + + If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once 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. + + @param state The control state. + @param url The URL used for the background image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once 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. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(nullable void (^)(NSError *error))failure; + + +///------------------------------ +/// @name Canceling Image Loading +///------------------------------ + +/** + Cancels any executing image operation for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelImageRequestOperationForState:(UIControlState)state; + +/** + Cancels any executing background image operation for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m new file mode 100644 index 0000000..f34631e --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m @@ -0,0 +1,293 @@ +// UIButton+AFNetworking.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "UIButton+AFNetworking.h" + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import "AFURLResponseSerialization.h" +#import "AFHTTPRequestOperation.h" + +#import "UIImageView+AFNetworking.h" + +@interface UIButton (_AFNetworking) +@end + +@implementation UIButton (_AFNetworking) + ++ (NSOperationQueue *)af_sharedImageRequestOperationQueue { + static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init]; + _af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount; + }); + + return _af_sharedImageRequestOperationQueue; +} + +#pragma mark - + +static char AFImageRequestOperationNormal; +static char AFImageRequestOperationHighlighted; +static char AFImageRequestOperationSelected; +static char AFImageRequestOperationDisabled; + +static const char * af_imageRequestOperationKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFImageRequestOperationHighlighted; + case UIControlStateSelected: + return &AFImageRequestOperationSelected; + case UIControlStateDisabled: + return &AFImageRequestOperationDisabled; + case UIControlStateNormal: + default: + return &AFImageRequestOperationNormal; + } +} + +- (AFHTTPRequestOperation *)af_imageRequestOperationForState:(UIControlState)state { + return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_imageRequestOperationKeyForState(state)); +} + +- (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_imageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +static char AFBackgroundImageRequestOperationNormal; +static char AFBackgroundImageRequestOperationHighlighted; +static char AFBackgroundImageRequestOperationSelected; +static char AFBackgroundImageRequestOperationDisabled; + +static const char * af_backgroundImageRequestOperationKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFBackgroundImageRequestOperationHighlighted; + case UIControlStateSelected: + return &AFBackgroundImageRequestOperationSelected; + case UIControlStateDisabled: + return &AFBackgroundImageRequestOperationDisabled; + case UIControlStateNormal: + default: + return &AFBackgroundImageRequestOperationNormal; + } +} + +- (AFHTTPRequestOperation *)af_backgroundImageRequestOperationForState:(UIControlState)state { + return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state)); +} + +- (void)af_setBackgroundImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIButton (AFNetworking) + ++ (id )sharedImageCache { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: [UIImageView sharedImageCache]; +#pragma clang diagnostic pop +} + ++ (void)setSharedImageCache:(id )imageCache { + objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (id )imageResponseSerializer { + static id _af_defaultImageResponseSerializer = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer]; + }); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(imageResponseSerializer)) ?: _af_defaultImageResponseSerializer; +#pragma clang diagnostic pop +} + +- (void)setImageResponseSerializer:(id )serializer { + objc_setAssociatedObject(self, @selector(imageResponseSerializer), serializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(UIImage *)placeholderImage + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(void (^)(NSError *error))failure +{ + [self cancelImageRequestOperationForState:state]; + + UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest]; + if (cachedImage) { + if (success) { + success(nil, nil, cachedImage); + } else { + [self setImage:cachedImage forState:state]; + } + + [self af_setImageRequestOperation:nil forState:state]; + } else { + if (placeholderImage) { + [self setImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + AFHTTPRequestOperation *imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; + imageRequestOperation.responseSerializer = self.imageResponseSerializer; + [imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[urlRequest URL] isEqual:[operation.request URL]]) { + if (success) { + success(operation.request, operation.response, responseObject); + } else if (responseObject) { + [strongSelf setImage:responseObject forState:state]; + } + } + [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if ([[urlRequest URL] isEqual:[operation.request URL]]) { + if (failure) { + failure(error); + } + } + }]; + + [self af_setImageRequestOperation:imageRequestOperation forState:state]; + [[[self class] af_sharedImageRequestOperationQueue] addOperation:imageRequestOperation]; + } +} + +#pragma mark - + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setBackgroundImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(UIImage *)placeholderImage + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(void (^)(NSError *error))failure +{ + [self cancelBackgroundImageRequestOperationForState:state]; + + UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest]; + if (cachedImage) { + if (success) { + success(nil, nil, cachedImage); + } else { + [self setBackgroundImage:cachedImage forState:state]; + } + + [self af_setBackgroundImageRequestOperation:nil forState:state]; + } else { + if (placeholderImage) { + [self setBackgroundImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + AFHTTPRequestOperation *backgroundImageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; + backgroundImageRequestOperation.responseSerializer = self.imageResponseSerializer; + [backgroundImageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[urlRequest URL] isEqual:[operation.request URL]]) { + if (success) { + success(operation.request, operation.response, responseObject); + } else if (responseObject) { + [strongSelf setBackgroundImage:responseObject forState:state]; + } + } + [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if ([[urlRequest URL] isEqual:[operation.request URL]]) { + if (failure) { + failure(error); + } + } + }]; + + [self af_setBackgroundImageRequestOperation:backgroundImageRequestOperation forState:state]; + [[[self class] af_sharedImageRequestOperationQueue] addOperation:backgroundImageRequestOperation]; + } +} + +#pragma mark - + +- (void)cancelImageRequestOperationForState:(UIControlState)state { + [[self af_imageRequestOperationForState:state] cancel]; + [self af_setImageRequestOperation:nil forState:state]; +} + +- (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state { + [[self af_backgroundImageRequestOperationForState:state] cancel]; + [self af_setBackgroundImageRequestOperation:nil forState:state]; +} + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h new file mode 100644 index 0000000..3292920 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h @@ -0,0 +1,35 @@ +// +// UIImage+AFNetworking.h +// +// +// Created by Paulo Ferreira on 08/07/15. +// +// 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. + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import + +@interface UIImage (AFNetworking) + ++ (UIImage*) safeImageWithData:(NSData*)data; + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h new file mode 100644 index 0000000..e33d8a0 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1,146 @@ +// UIImageView+AFNetworking.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol AFURLResponseSerialization, AFImageCache; + +/** + 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) + +///---------------------------- +/// @name Accessing Image Cache +///---------------------------- + +/** + The image cache used to improve image loading performance on scroll views. By default, this is an `NSCache` subclass conforming to the `AFImageCache` protocol, which listens for notification warnings and evicts objects accordingly. +*/ ++ (id )sharedImageCache; + +/** + Set the cache used for image loading. + + @param imageCache The image cache. + */ ++ (void)setSharedImageCache:(id )imageCache; + +///------------------------------------ +/// @name Accessing Response Serializer +///------------------------------------ + +/** + The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`. + + @discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer + */ +@property (nonatomic, strong) id imageResponseSerializer; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it once 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 `Accept` header field value of "image / *", 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; + +/** + Asynchronously downloads an image from the specified URL, and sets it once 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 `Accept` header field value of "image / *", 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:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it once 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. + + 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 applied. + + @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. 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 response parameter 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:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; + +/** + Cancels any executing image operation for the receiver, if one exists. + */ +- (void)cancelImageRequestOperation; + +@end + +#pragma mark - + +/** + The `AFImageCache` protocol is adopted by an object used to cache images loaded by the AFNetworking category on `UIImageView`. + */ +@protocol AFImageCache + +/** + Returns a cached image for the specified request, if available. + + @param request The image request. + + @return The cached image. + */ +- (nullable UIImage *)cachedImageForRequest:(NSURLRequest *)request; + +/** + Caches a particular image for the specified request. + + @param image The image to cache. + @param request The request to be used as a cache key. + */ +- (void)cacheImage:(UIImage *)image + forRequest:(NSURLRequest *)request; +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m new file mode 100644 index 0000000..c1b0e1b --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m @@ -0,0 +1,215 @@ +// UIImageView+AFNetworking.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "UIImageView+AFNetworking.h" + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import "AFHTTPRequestOperation.h" + +@interface AFImageCache : NSCache +@end + +#pragma mark - + +@interface UIImageView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFHTTPRequestOperation *af_imageRequestOperation; +@end + +@implementation UIImageView (_AFNetworking) + ++ (NSOperationQueue *)af_sharedImageRequestOperationQueue { + static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init]; + _af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount; + }); + + return _af_sharedImageRequestOperationQueue; +} + +- (AFHTTPRequestOperation *)af_imageRequestOperation { + return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_imageRequestOperation)); +} + +- (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation { + objc_setAssociatedObject(self, @selector(af_imageRequestOperation), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIImageView (AFNetworking) +@dynamic imageResponseSerializer; + ++ (id )sharedImageCache { + static AFImageCache *_af_defaultImageCache = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _af_defaultImageCache = [[AFImageCache alloc] init]; + + [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * __unused notification) { + [_af_defaultImageCache removeAllObjects]; + }]; + }); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: _af_defaultImageCache; +#pragma clang diagnostic pop +} + ++ (void)setSharedImageCache:(id )imageCache { + objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (id )imageResponseSerializer { + static id _af_defaultImageResponseSerializer = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer]; + }); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(imageResponseSerializer)) ?: _af_defaultImageResponseSerializer; +#pragma clang diagnostic pop +} + +- (void)setImageResponseSerializer:(id )serializer { + objc_setAssociatedObject(self, @selector(imageResponseSerializer), serializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#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] sharedImageCache] cachedImageForRequest:urlRequest]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + self.image = cachedImage; + } + + self.af_imageRequestOperation = nil; + } else { + if (placeholderImage) { + self.image = placeholderImage; + } + + __weak __typeof(self)weakSelf = self; + self.af_imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; + self.af_imageRequestOperation.responseSerializer = self.imageResponseSerializer; + [self.af_imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) { + if (success) { + success(urlRequest, operation.response, responseObject); + } else if (responseObject) { + strongSelf.image = responseObject; + } + + if (operation == strongSelf.af_imageRequestOperation){ + strongSelf.af_imageRequestOperation = nil; + } + } + + [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) { + if (failure) { + failure(urlRequest, operation.response, error); + } + + if (operation == strongSelf.af_imageRequestOperation){ + strongSelf.af_imageRequestOperation = nil; + } + } + }]; + + [[[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 diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h new file mode 100644 index 0000000..49850ed --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h @@ -0,0 +1,39 @@ +// UIKit+AFNetworking.h +// +// 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 +// 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. + +#if TARGET_OS_IOS +#import + +#ifndef _UIKIT_AFNETWORKING_ + #define _UIKIT_AFNETWORKING_ + + #import "AFNetworkActivityIndicatorManager.h" + + #import "UIActivityIndicatorView+AFNetworking.h" + #import "UIAlertView+AFNetworking.h" + #import "UIButton+AFNetworking.h" + #import "UIImageView+AFNetworking.h" + #import "UIProgressView+AFNetworking.h" + #import "UIRefreshControl+AFNetworking.h" + #import "UIWebView+AFNetworking.h" +#endif /* _UIKIT_AFNETWORKING_ */ +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h new file mode 100644 index 0000000..5c00d6d --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h @@ -0,0 +1,91 @@ +// UIProgressView+AFNetworking.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFURLConnectionOperation; + +/** + This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task or request operation. + */ +@interface UIProgressView (AFNetworking) + +///------------------------------------ +/// @name Setting Session Task Progress +///------------------------------------ + +/** + Binds the progress to the upload progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated; +#endif + +/** + Binds the progress to the download progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated; +#endif + +///------------------------------------ +/// @name Setting Session Task Progress +///------------------------------------ + +/** + Binds the progress to the upload progress of the specified request operation. + + @param operation The request operation. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation + animated:(BOOL)animated; + +/** + Binds the progress to the download progress of the specified request operation. + + @param operation The request operation. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation + animated:(BOOL)animated; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m new file mode 100644 index 0000000..ad2c280 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m @@ -0,0 +1,182 @@ +// UIProgressView+AFNetworking.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "UIProgressView+AFNetworking.h" + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import "AFURLConnectionOperation.h" + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +#import "AFURLSessionManager.h" +#endif + +static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; +static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; + +@interface AFURLConnectionOperation (_UIProgressView) +@property (readwrite, nonatomic, copy) void (^uploadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); +@property (readwrite, nonatomic, assign, setter = af_setUploadProgressAnimated:) BOOL af_uploadProgressAnimated; + +@property (readwrite, nonatomic, copy) void (^downloadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); +@property (readwrite, nonatomic, assign, setter = af_setDownloadProgressAnimated:) BOOL af_downloadProgressAnimated; +@end + +@implementation AFURLConnectionOperation (_UIProgressView) +@dynamic uploadProgress; // Implemented in AFURLConnectionOperation +@dynamic af_uploadProgressAnimated; + +@dynamic downloadProgress; // Implemented in AFURLConnectionOperation +@dynamic af_downloadProgressAnimated; +@end + +#pragma mark - + +@implementation UIProgressView (AFNetworking) + +- (BOOL)af_uploadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue]; +} + +- (void)af_setUploadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)af_downloadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue]; +} + +- (void)af_setDownloadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated +{ + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + + [self af_setUploadProgressAnimated:animated]; +} + +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated +{ + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + + [self af_setDownloadProgressAnimated:animated]; +} +#endif + +#pragma mark - + +- (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation + animated:(BOOL)animated +{ + __weak __typeof(self)weakSelf = self; + void (^original)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) = [operation.uploadProgress copy]; + [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { + if (original) { + original(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + if (totalBytesExpectedToWrite > 0) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + [strongSelf setProgress:(totalBytesWritten / (totalBytesExpectedToWrite * 1.0f)) animated:animated]; + } + }); + }]; +} + +- (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation + animated:(BOOL)animated +{ + __weak __typeof(self)weakSelf = self; + void (^original)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) = [operation.downloadProgress copy]; + [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { + if (original) { + original(bytesRead, totalBytesRead, totalBytesExpectedToRead); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + if (totalBytesExpectedToRead > 0) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + [strongSelf setProgress:(totalBytesRead / (totalBytesExpectedToRead * 1.0f)) animated:animated]; + } + }); + }]; +} + +#pragma mark - NSKeyValueObserving + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(__unused NSDictionary *)change + context:(void *)context +{ +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 + if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { + if ([object countOfBytesExpectedToSend] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { + if ([object countOfBytesExpectedToReceive] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { + if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { + @try { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; + + if (context == AFTaskCountOfBytesSentContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; + } + + if (context == AFTaskCountOfBytesReceivedContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; + } + } + @catch (NSException * __unused exception) {} + } + } + } +#endif +} + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h new file mode 100644 index 0000000..a65e390 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h @@ -0,0 +1,68 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2014 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 +// 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 + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFURLConnectionOperation; + +/** + This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a request operation or session task. + */ +@interface UIRefreshControl (AFNetworking) + +///----------------------------------- +/// @name Refreshing for Session Tasks +///----------------------------------- + +/** + Binds the refreshing state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; +#endif + +///---------------------------------------- +/// @name Refreshing for Request Operations +///---------------------------------------- + +/** + Binds the refreshing state to the execution state of the specified operation. + + @param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m new file mode 100644 index 0000000..4c19245 --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m @@ -0,0 +1,166 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2014 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 +// 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 "UIRefreshControl+AFNetworking.h" +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import "AFHTTPRequestOperation.h" + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +#import "AFURLSessionManager.h" +#endif + +@interface AFRefreshControlNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; +#endif +- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation; + +@end + +@implementation UIRefreshControl (AFNetworking) + +- (AFRefreshControlNotificationObserver *)af_notificationObserver { + AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; +} +#endif + +- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation { + [[self af_notificationObserver] setRefreshingWithStateOfOperation:operation]; +} + +@end + +@implementation AFRefreshControlNotificationObserver + +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl +{ + self = [super init]; + if (self) { + _refreshControl = refreshControl; + } + return self; +} + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" +#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" + if (task.state == NSURLSessionTaskStateRunning) { + [self.refreshControl beginRefreshing]; + + [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; + } else { + [self.refreshControl endRefreshing]; + } +#pragma clang diagnostic pop + } +} +#endif + +- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; + + if (operation) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" +#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" + if (![operation isFinished]) { + if ([operation isExecuting]) { + [self.refreshControl beginRefreshing]; + } else { + [self.refreshControl endRefreshing]; + } + + [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingOperationDidStartNotification object:operation]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingOperationDidFinishNotification object:operation]; + } +#pragma clang diagnostic pop + } +} + +#pragma mark - + +- (void)af_beginRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.refreshControl beginRefreshing]; +#pragma clang diagnostic pop + }); +} + +- (void)af_endRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.refreshControl endRefreshing]; +#pragma clang diagnostic pop + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +#endif + + [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; +} + +@end + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h new file mode 100644 index 0000000..5d61d6a --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h @@ -0,0 +1,86 @@ +// UIWebView+AFNetworking.h +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFHTTPRequestSerializer, AFHTTPResponseSerializer; +@protocol AFURLRequestSerialization, AFURLResponseSerialization; + +/** + This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling. + + @discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly. + */ +@interface UIWebView (AFNetworking) + +/** + The request serializer used to serialize requests made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPRequestSerializer`. + */ +@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; + +/** + The response serializer used to serialize responses made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPResponseSerializer`. + */ +@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; + +/** + Asynchronously loads the specified request. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param progress A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. + @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string. + @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 a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress + success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(nullable void (^)(NSError *error))failure; + +/** + Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. + @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. + @param progress A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. + @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data. + @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 a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + MIMEType:(nullable NSString *)MIMEType + textEncodingName:(nullable NSString *)textEncodingName + progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress + success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(nullable void (^)(NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m new file mode 100644 index 0000000..93eacaa --- /dev/null +++ b/TalkinToTheNet/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m @@ -0,0 +1,159 @@ +// UIWebView+AFNetworking.m +// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// 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 "UIWebView+AFNetworking.h" + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + +#import "AFHTTPRequestOperation.h" +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" + +@interface UIWebView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setHTTPRequestOperation:) AFHTTPRequestOperation *af_HTTPRequestOperation; +@end + +@implementation UIWebView (_AFNetworking) + +- (AFHTTPRequestOperation *)af_HTTPRequestOperation { + return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_HTTPRequestOperation)); +} + +- (void)af_setHTTPRequestOperation:(AFHTTPRequestOperation *)operation { + objc_setAssociatedObject(self, @selector(af_HTTPRequestOperation), operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIWebView (AFNetworking) + +- (AFHTTPRequestSerializer *)requestSerializer { + static AFHTTPRequestSerializer *_af_defaultRequestSerializer = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultRequestSerializer = [AFHTTPRequestSerializer serializer]; + }); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(requestSerializer)) ?: _af_defaultRequestSerializer; +#pragma clang diagnostic pop +} + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + objc_setAssociatedObject(self, @selector(requestSerializer), requestSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (AFHTTPResponseSerializer *)responseSerializer { + static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; + }); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; +#pragma clang diagnostic pop +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)loadRequest:(NSURLRequest *)request + progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress + success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(void (^)(NSError *error))failure +{ + [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) { + NSStringEncoding stringEncoding = NSUTF8StringEncoding; + if (response.textEncodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); + if (encoding != kCFStringEncodingInvalidId) { + stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); + } + } + + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; + if (success) { + string = success(response, string); + } + + return [string dataUsingEncoding:stringEncoding]; + } failure:failure]; +} + +- (void)loadRequest:(NSURLRequest *)request + MIMEType:(NSString *)MIMEType + textEncodingName:(NSString *)textEncodingName + progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress + success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(void (^)(NSError *error))failure +{ + NSParameterAssert(request); + + if (self.af_HTTPRequestOperation) { + [self.af_HTTPRequestOperation cancel]; + } + + request = [self.requestSerializer requestBySerializingRequest:request withParameters:nil error:nil]; + + self.af_HTTPRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; + self.af_HTTPRequestOperation.responseSerializer = self.responseSerializer; + + __weak __typeof(self)weakSelf = self; + [self.af_HTTPRequestOperation setDownloadProgressBlock:progress]; + [self.af_HTTPRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id __unused responseObject) { + NSData *data = success ? success(operation.response, operation.responseData) : operation.responseData; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + __strong __typeof(weakSelf) strongSelf = weakSelf; + [strongSelf loadData:data MIMEType:(MIMEType ?: [operation.response MIMEType]) textEncodingName:(textEncodingName ?: [operation.response textEncodingName]) baseURL:[operation.response URL]]; + + if ([strongSelf.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { + [strongSelf.delegate webViewDidFinishLoad:strongSelf]; + } + +#pragma clang diagnostic pop + } failure:^(AFHTTPRequestOperation * __unused operation, NSError *error) { + if (failure) { + failure(error); + } + }]; + + [self.af_HTTPRequestOperation start]; + + if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { + [self.delegate webViewDidStartLoad:self]; + } +} + +@end + +#endif diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFHTTPRequestOperation.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFHTTPRequestOperation.h new file mode 120000 index 0000000..ac762c8 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFHTTPRequestOperation.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFHTTPRequestOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFHTTPRequestOperationManager.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFHTTPRequestOperationManager.h new file mode 120000 index 0000000..9dcc623 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFHTTPRequestOperationManager.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFHTTPSessionManager.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFHTTPSessionManager.h new file mode 120000 index 0000000..56feb9f --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFHTTPSessionManager.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFHTTPSessionManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFNetworkActivityIndicatorManager.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 120000 index 0000000..67519d9 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFNetworkReachabilityManager.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFNetworkReachabilityManager.h new file mode 120000 index 0000000..68fc774 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFNetworkReachabilityManager.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFNetworkReachabilityManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFNetworking.h new file mode 120000 index 0000000..a5a38da --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFSecurityPolicy.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFSecurityPolicy.h new file mode 120000 index 0000000..fd1322d --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFSecurityPolicy.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFSecurityPolicy.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLConnectionOperation.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLConnectionOperation.h new file mode 120000 index 0000000..d9b35fb --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLConnectionOperation.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFURLConnectionOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLRequestSerialization.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLRequestSerialization.h new file mode 120000 index 0000000..ca8209b --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLRequestSerialization.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFURLRequestSerialization.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLResponseSerialization.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLResponseSerialization.h new file mode 120000 index 0000000..e36a765 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLResponseSerialization.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFURLResponseSerialization.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLSessionManager.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLSessionManager.h new file mode 120000 index 0000000..835101d --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/AFURLSessionManager.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFURLSessionManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIActivityIndicatorView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIActivityIndicatorView+AFNetworking.h new file mode 120000 index 0000000..c534ebf --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIActivityIndicatorView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIAlertView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIAlertView+AFNetworking.h new file mode 120000 index 0000000..f992813 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIAlertView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIButton+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIButton+AFNetworking.h new file mode 120000 index 0000000..8f2e221 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIButton+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIImage+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIImage+AFNetworking.h new file mode 120000 index 0000000..74f6649 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIImage+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIImageView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIImageView+AFNetworking.h new file mode 120000 index 0000000..a95d673 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIKit+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIKit+AFNetworking.h new file mode 120000 index 0000000..95017cc --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIKit+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIProgressView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIProgressView+AFNetworking.h new file mode 120000 index 0000000..730b167 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIProgressView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIRefreshControl+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIRefreshControl+AFNetworking.h new file mode 120000 index 0000000..8efd826 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIRefreshControl+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIWebView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIWebView+AFNetworking.h new file mode 120000 index 0000000..c8df6ef --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/AFNetworking/UIWebView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/NYAlertViewController/NYAlertView.h b/TalkinToTheNet/Pods/Headers/Private/NYAlertViewController/NYAlertView.h new file mode 120000 index 0000000..3527370 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/NYAlertViewController/NYAlertView.h @@ -0,0 +1 @@ +../../../NYAlertViewController/NYAlertViewController/NYAlertView.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/NYAlertViewController/NYAlertViewController.h b/TalkinToTheNet/Pods/Headers/Private/NYAlertViewController/NYAlertViewController.h new file mode 120000 index 0000000..7061264 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/NYAlertViewController/NYAlertViewController.h @@ -0,0 +1 @@ +../../../NYAlertViewController/NYAlertViewController/NYAlertViewController.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/NSData+ImageContentType.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/NSData+ImageContentType.h new file mode 120000 index 0000000..8457498 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/NSData+ImageContentType.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/NSData+ImageContentType.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDImageCache.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDImageCache.h new file mode 120000 index 0000000..0040b06 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDImageCache.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDImageCache.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageCompat.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageCompat.h new file mode 120000 index 0000000..6ca2478 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageCompat.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageCompat.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageDecoder.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageDecoder.h new file mode 120000 index 0000000..a2f3a68 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageDecoder.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageDecoder.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageDownloader.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageDownloader.h new file mode 120000 index 0000000..303b03b --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageDownloader.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageDownloader.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageDownloaderOperation.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageDownloaderOperation.h new file mode 120000 index 0000000..99441c4 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageDownloaderOperation.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageManager.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageManager.h new file mode 120000 index 0000000..1b81848 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageManager.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageOperation.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageOperation.h new file mode 120000 index 0000000..20e5b89 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImageOperation.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImagePrefetcher.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImagePrefetcher.h new file mode 120000 index 0000000..50585c6 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/SDWebImagePrefetcher.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImagePrefetcher.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIButton+WebCache.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIButton+WebCache.h new file mode 120000 index 0000000..19d2d8e --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIButton+WebCache.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIButton+WebCache.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImage+GIF.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImage+GIF.h new file mode 120000 index 0000000..14d5aad --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImage+GIF.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIImage+GIF.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImage+MultiFormat.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImage+MultiFormat.h new file mode 120000 index 0000000..1fb9650 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImage+MultiFormat.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIImage+MultiFormat.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImageView+HighlightedWebCache.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImageView+HighlightedWebCache.h new file mode 120000 index 0000000..fd4dea4 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImageView+HighlightedWebCache.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImageView+WebCache.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImageView+WebCache.h new file mode 120000 index 0000000..0c53a47 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIImageView+WebCache.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIImageView+WebCache.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIView+WebCacheOperation.h b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIView+WebCacheOperation.h new file mode 120000 index 0000000..f9890c4 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Private/SDWebImage/UIView+WebCacheOperation.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIView+WebCacheOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFHTTPRequestOperation.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFHTTPRequestOperation.h new file mode 120000 index 0000000..ac762c8 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFHTTPRequestOperation.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFHTTPRequestOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFHTTPRequestOperationManager.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFHTTPRequestOperationManager.h new file mode 120000 index 0000000..9dcc623 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFHTTPRequestOperationManager.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFHTTPSessionManager.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFHTTPSessionManager.h new file mode 120000 index 0000000..56feb9f --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFHTTPSessionManager.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFHTTPSessionManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFNetworkActivityIndicatorManager.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 120000 index 0000000..67519d9 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFNetworkReachabilityManager.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFNetworkReachabilityManager.h new file mode 120000 index 0000000..68fc774 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFNetworkReachabilityManager.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFNetworkReachabilityManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFNetworking.h new file mode 120000 index 0000000..a5a38da --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFSecurityPolicy.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFSecurityPolicy.h new file mode 120000 index 0000000..fd1322d --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFSecurityPolicy.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFSecurityPolicy.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLConnectionOperation.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLConnectionOperation.h new file mode 120000 index 0000000..d9b35fb --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLConnectionOperation.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFURLConnectionOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLRequestSerialization.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLRequestSerialization.h new file mode 120000 index 0000000..ca8209b --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLRequestSerialization.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFURLRequestSerialization.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLResponseSerialization.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLResponseSerialization.h new file mode 120000 index 0000000..e36a765 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLResponseSerialization.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFURLResponseSerialization.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLSessionManager.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLSessionManager.h new file mode 120000 index 0000000..835101d --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/AFURLSessionManager.h @@ -0,0 +1 @@ +../../../AFNetworking/AFNetworking/AFURLSessionManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIActivityIndicatorView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIActivityIndicatorView+AFNetworking.h new file mode 120000 index 0000000..c534ebf --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIActivityIndicatorView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIAlertView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIAlertView+AFNetworking.h new file mode 120000 index 0000000..f992813 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIAlertView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIButton+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIButton+AFNetworking.h new file mode 120000 index 0000000..8f2e221 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIButton+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIImage+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIImage+AFNetworking.h new file mode 120000 index 0000000..74f6649 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIImage+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIImageView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIImageView+AFNetworking.h new file mode 120000 index 0000000..a95d673 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIKit+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIKit+AFNetworking.h new file mode 120000 index 0000000..95017cc --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIKit+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIProgressView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIProgressView+AFNetworking.h new file mode 120000 index 0000000..730b167 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIProgressView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIRefreshControl+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIRefreshControl+AFNetworking.h new file mode 120000 index 0000000..8efd826 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIRefreshControl+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIWebView+AFNetworking.h b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIWebView+AFNetworking.h new file mode 120000 index 0000000..c8df6ef --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/AFNetworking/UIWebView+AFNetworking.h @@ -0,0 +1 @@ +../../../AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/NYAlertViewController/NYAlertView.h b/TalkinToTheNet/Pods/Headers/Public/NYAlertViewController/NYAlertView.h new file mode 120000 index 0000000..3527370 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/NYAlertViewController/NYAlertView.h @@ -0,0 +1 @@ +../../../NYAlertViewController/NYAlertViewController/NYAlertView.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/NYAlertViewController/NYAlertViewController.h b/TalkinToTheNet/Pods/Headers/Public/NYAlertViewController/NYAlertViewController.h new file mode 120000 index 0000000..7061264 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/NYAlertViewController/NYAlertViewController.h @@ -0,0 +1 @@ +../../../NYAlertViewController/NYAlertViewController/NYAlertViewController.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/NSData+ImageContentType.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/NSData+ImageContentType.h new file mode 120000 index 0000000..8457498 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/NSData+ImageContentType.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/NSData+ImageContentType.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDImageCache.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDImageCache.h new file mode 120000 index 0000000..0040b06 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDImageCache.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDImageCache.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageCompat.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageCompat.h new file mode 120000 index 0000000..6ca2478 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageCompat.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageCompat.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageDecoder.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageDecoder.h new file mode 120000 index 0000000..a2f3a68 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageDecoder.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageDecoder.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageDownloader.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageDownloader.h new file mode 120000 index 0000000..303b03b --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageDownloader.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageDownloader.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageDownloaderOperation.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageDownloaderOperation.h new file mode 120000 index 0000000..99441c4 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageDownloaderOperation.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageManager.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageManager.h new file mode 120000 index 0000000..1b81848 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageManager.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageManager.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageOperation.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageOperation.h new file mode 120000 index 0000000..20e5b89 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImageOperation.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImageOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImagePrefetcher.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImagePrefetcher.h new file mode 120000 index 0000000..50585c6 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/SDWebImagePrefetcher.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/SDWebImagePrefetcher.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIButton+WebCache.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIButton+WebCache.h new file mode 120000 index 0000000..19d2d8e --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIButton+WebCache.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIButton+WebCache.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImage+GIF.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImage+GIF.h new file mode 120000 index 0000000..14d5aad --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImage+GIF.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIImage+GIF.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImage+MultiFormat.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImage+MultiFormat.h new file mode 120000 index 0000000..1fb9650 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImage+MultiFormat.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIImage+MultiFormat.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImageView+HighlightedWebCache.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImageView+HighlightedWebCache.h new file mode 120000 index 0000000..fd4dea4 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImageView+HighlightedWebCache.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImageView+WebCache.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImageView+WebCache.h new file mode 120000 index 0000000..0c53a47 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIImageView+WebCache.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIImageView+WebCache.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIView+WebCacheOperation.h b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIView+WebCacheOperation.h new file mode 120000 index 0000000..f9890c4 --- /dev/null +++ b/TalkinToTheNet/Pods/Headers/Public/SDWebImage/UIView+WebCacheOperation.h @@ -0,0 +1 @@ +../../../SDWebImage/SDWebImage/UIView+WebCacheOperation.h \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Manifest.lock b/TalkinToTheNet/Pods/Manifest.lock new file mode 100644 index 0000000..cb34362 --- /dev/null +++ b/TalkinToTheNet/Pods/Manifest.lock @@ -0,0 +1,38 @@ +PODS: + - AFNetworking (2.6.0): + - AFNetworking/NSURLConnection (= 2.6.0) + - AFNetworking/NSURLSession (= 2.6.0) + - AFNetworking/Reachability (= 2.6.0) + - AFNetworking/Security (= 2.6.0) + - AFNetworking/Serialization (= 2.6.0) + - AFNetworking/UIKit (= 2.6.0) + - AFNetworking/NSURLConnection (2.6.0): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/NSURLSession (2.6.0): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/Reachability (2.6.0) + - AFNetworking/Security (2.6.0) + - AFNetworking/Serialization (2.6.0) + - AFNetworking/UIKit (2.6.0): + - AFNetworking/NSURLConnection + - AFNetworking/NSURLSession + - NYAlertViewController (1.3.0) + - SDWebImage (3.7.3): + - SDWebImage/Core (= 3.7.3) + - SDWebImage/Core (3.7.3) + +DEPENDENCIES: + - AFNetworking (~> 2.5) + - NYAlertViewController + - SDWebImage (~> 3.7) + +SPEC CHECKSUMS: + AFNetworking: 79f7eb1a0fcfa7beb409332b2ca49afe9ce53b05 + NYAlertViewController: b93f82e2c1fc6d5e9485512ddbe7b481f463a074 + SDWebImage: 1d2b1a1efda1ade1b00b6f8498865f8ddedc8a84 + +COCOAPODS: 0.38.2 diff --git a/TalkinToTheNet/Pods/NYAlertViewController/LICENSE.md b/TalkinToTheNet/Pods/NYAlertViewController/LICENSE.md new file mode 100644 index 0000000..a7b41d5 --- /dev/null +++ b/TalkinToTheNet/Pods/NYAlertViewController/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Nealon Young + +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. diff --git a/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertView.h b/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertView.h new file mode 100644 index 0000000..f220c85 --- /dev/null +++ b/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertView.h @@ -0,0 +1,58 @@ +// +// NYAlertView.h +// +// Created by Nealon Young on 7/13/15. +// Copyright (c) 2015 Nealon Young. All rights reserved. +// + +#import + +typedef NS_ENUM(NSInteger, NYAlertViewButtonType) { + NYAlertViewButtonTypeFilled, + NYAlertViewButtonTypeBordered +}; + +@interface UIButton (BackgroundColor) + +- (void)setBackgroundColor:(UIColor *)color forState:(UIControlState)state; + +@end + +@interface NYAlertViewButton : UIButton + +@property (nonatomic) NYAlertViewButtonType type; + +@property (nonatomic) CGFloat cornerRadius; + +@end + +@interface NYAlertView : UIView + +@property UILabel *titleLabel; +@property UITextView *messageTextView; +@property (nonatomic) UIView *contentView; + +@property (nonatomic) UIFont *buttonTitleFont; +@property (nonatomic) UIFont *cancelButtonTitleFont; +@property (nonatomic) UIFont *destructiveButtonTitleFont; + +@property (nonatomic) UIColor *buttonColor; +@property (nonatomic) UIColor *buttonTitleColor; +@property (nonatomic) UIColor *cancelButtonColor; +@property (nonatomic) UIColor *cancelButtonTitleColor; +@property (nonatomic) UIColor *destructiveButtonColor; +@property (nonatomic) UIColor *destructiveButtonTitleColor; + +@property (nonatomic) CGFloat buttonCornerRadius; +@property (nonatomic) CGFloat maximumWidth; + +@property (nonatomic, readonly) UIView *alertBackgroundView; + +@property (nonatomic, readonly) NSLayoutConstraint *backgroundViewVerticalCenteringConstraint; + +//@property (nonatomic) NSArray *actions; +@property (nonatomic) NSArray *actionButtons; + +@property (nonatomic) NSArray *textFields; + +@end diff --git a/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertView.m b/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertView.m new file mode 100644 index 0000000..227d52f --- /dev/null +++ b/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertView.m @@ -0,0 +1,567 @@ +// +// NYAlertView.m +// +// Created by Nealon Young on 7/13/15. +// Copyright (c) 2015 Nealon Young. All rights reserved. +// + +#import "NYAlertView.h" + +#import "NYAlertViewController.h" + +@interface NYAlertTextView : UITextView + +@end + +@implementation NYAlertTextView + +- (instancetype)initWithFrame:(CGRect)frame textContainer:(NSTextContainer *)textContainer { + self = [super initWithFrame:frame textContainer:textContainer]; + + self.textContainerInset = UIEdgeInsetsZero; + + return self; +} + +- (void)layoutSubviews { + [super layoutSubviews]; + + if (!CGSizeEqualToSize(self.bounds.size, [self intrinsicContentSize])) { + [self invalidateIntrinsicContentSize]; + } +} + +- (CGSize)intrinsicContentSize { + if ([self.text length]) { + return self.contentSize; + } else { + return CGSizeZero; + } +} + +@end + +@implementation UIButton (BackgroundColor) + +- (void)setBackgroundColor:(UIColor *)color forState:(UIControlState)state { + [self setBackgroundImage:[self imageWithColor:color] forState:state]; +} + +- (UIImage *)imageWithColor:(UIColor *)color { + CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); + UIGraphicsBeginImageContext(rect.size); + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextSetFillColorWithColor(context, [color CGColor]); + CGContextFillRect(context, rect); + + UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + + return image; +} + +@end + +@implementation NYAlertViewButton + ++ (id)buttonWithType:(UIButtonType)buttonType { + return [super buttonWithType:UIButtonTypeCustom]; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + self = [super initWithCoder:aDecoder]; + + if (self) { + [self commonInit]; + } + + return self; +} + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + + if (self) { + [self commonInit]; + } + + return self; +} + +- (void)commonInit { + self.layer.rasterizationScale = [[UIScreen mainScreen] scale]; + self.layer.shouldRasterize = YES; + + self.layer.borderWidth = 1.0f; + + self.cornerRadius = 4.0f; + self.clipsToBounds = YES; + + [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; + [self setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted]; + [self setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled]; + + [self tintColorDidChange]; +} + +- (void)setHidden:(BOOL)hidden { + [super setHidden:hidden]; + [self invalidateIntrinsicContentSize]; +} + +- (void)setEnabled:(BOOL)enabled { + [super setEnabled:enabled]; + +// if (!enabled) { +// self.backgroundColor = [UIColor lightGrayColor]; +// self.layer.borderColor = self.tintColor.CGColor; +// [self setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal]; +// } else { +// self.backgroundColor = self.tintColor; +// self.layer.borderColor = self.tintColor.CGColor; +// [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; +// } +} + +- (void)tintColorDidChange { + [super tintColorDidChange]; + + if (self.type == NYAlertViewButtonTypeFilled) { + if (self.enabled) { + [self setBackgroundColor:self.tintColor]; + } + } else { + [self setTitleColor:self.tintColor forState:UIControlStateNormal]; + } + + self.layer.borderColor = self.tintColor.CGColor; + + [self setNeedsDisplay]; +} + +- (CGFloat)cornerRadius { + return self.layer.cornerRadius; +} + +- (void)setCornerRadius:(CGFloat)cornerRadius { + self.layer.cornerRadius = cornerRadius; +} + +//- (void)setEnabled:(BOOL)enabled { +// [super setEnabled:enabled]; +// +// if (enabled) { +// self.layer.backgroundColor = self.tintColor.CGColor; +// [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; +// } else { +// self.layer.backgroundColor = [UIColor lightGrayColor].CGColor; +// [self setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal]; +// } +//} + +//- (void)setType:(NYAlertViewButtonType)type { +// _type = type; +// +// if (type == NYAlertViewButtonTypeBordered) { +// self.layer.backgroundColor = [UIColor clearColor].CGColor; +// [self setTitleColor:self.tintColor forState:UIControlStateNormal]; +// } else { +// self.layer.backgroundColor = self.tintColor.CGColor; +// [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; +// } +//} + +- (CGSize)intrinsicContentSize { + if (self.hidden) { + return CGSizeZero; + } + + return CGSizeMake([super intrinsicContentSize].width + 12.0f, 30.0f); +} + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { + [super touchesBegan:touches withEvent:event]; + [self setNeedsDisplay]; +} + +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { + [super touchesMoved:touches withEvent:event]; + [self setNeedsDisplay]; +} + +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { + [super touchesEnded:touches withEvent:event]; + [self setNeedsDisplay]; +} + +- (void)drawRect:(CGRect)rect { + [super drawRect:rect]; + + self.layer.borderColor = self.tintColor.CGColor; + + if (self.type == NYAlertViewButtonTypeBordered) { + self.layer.borderWidth = 1.0f; + } else { + self.layer.borderWidth = 0.0f; + } + + if (self.state == UIControlStateHighlighted) { + self.layer.backgroundColor = self.tintColor.CGColor; + // [self setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted]; + } else { + if (self.type == NYAlertViewButtonTypeBordered) { + self.layer.backgroundColor = nil; + [self setTitleColor:self.tintColor forState:UIControlStateNormal]; + } else { + // [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; + } + } +} + +@end + +@interface NYAlertView () + +@property (nonatomic) NSLayoutConstraint *alertBackgroundWidthConstraint; +@property (nonatomic) UIView *contentViewContainerView; +@property (nonatomic) UIView *textFieldContainerView; +@property (nonatomic) UIView *actionButtonContainerView; + +@end + +@implementation NYAlertView + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + + if (self) { + self.maximumWidth = 480.0f; + + _alertBackgroundView = [[UIView alloc] initWithFrame:CGRectZero]; + [self.alertBackgroundView setTranslatesAutoresizingMaskIntoConstraints:NO]; + self.alertBackgroundView.backgroundColor = [UIColor colorWithWhite:0.97f alpha:1.0f]; + self.alertBackgroundView.layer.cornerRadius = 6.0f; + [self addSubview:_alertBackgroundView]; + + _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero]; + [self.titleLabel setTranslatesAutoresizingMaskIntoConstraints:NO]; + self.titleLabel.numberOfLines = 2; + self.titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]; + self.titleLabel.textAlignment = NSTextAlignmentCenter; + self.titleLabel.textColor = [UIColor darkGrayColor]; + self.titleLabel.text = NSLocalizedString(@"Title Label", nil); + [self.alertBackgroundView addSubview:self.titleLabel]; + + _messageTextView = [[NYAlertTextView alloc] initWithFrame:CGRectZero]; + [self.messageTextView setTranslatesAutoresizingMaskIntoConstraints:NO]; + self.messageTextView.backgroundColor = [UIColor clearColor]; + [self.messageTextView setContentHuggingPriority:0 forAxis:UILayoutConstraintAxisVertical]; + [self.messageTextView setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical]; + self.messageTextView.editable = NO; + self.messageTextView.textAlignment = NSTextAlignmentCenter; + self.messageTextView.textColor = [UIColor darkGrayColor]; + self.messageTextView.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline]; + self.messageTextView.text = NSLocalizedString(@"Message Text View", nil); + [self.alertBackgroundView addSubview:self.messageTextView]; + + _contentViewContainerView = [[UIView alloc] initWithFrame:CGRectZero]; + [self.contentViewContainerView setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self.contentView setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical]; + [self.alertBackgroundView addSubview:self.contentViewContainerView]; + + _textFieldContainerView = [[UIView alloc] initWithFrame:CGRectZero]; + [self.textFieldContainerView setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self.textFieldContainerView setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical]; + [self.alertBackgroundView addSubview:self.textFieldContainerView]; + + _actionButtonContainerView = [[UIView alloc] initWithFrame:CGRectZero]; + [self.actionButtonContainerView setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self.actionButtonContainerView setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical]; + [self.alertBackgroundView addSubview:self.actionButtonContainerView]; + + [self addConstraint:[NSLayoutConstraint constraintWithItem:self.alertBackgroundView + attribute:NSLayoutAttributeCenterX + relatedBy:NSLayoutRelationEqual + toItem:self + attribute:NSLayoutAttributeCenterX + multiplier:1.0f + constant:0.0f]]; + + CGFloat alertBackgroundViewWidth = MIN(CGRectGetWidth([UIApplication sharedApplication].keyWindow.bounds), + CGRectGetHeight([UIApplication sharedApplication].keyWindow.bounds)) * 0.8f; + + if (alertBackgroundViewWidth > self.maximumWidth) { + alertBackgroundViewWidth = self.maximumWidth; + } + + _alertBackgroundWidthConstraint = [NSLayoutConstraint constraintWithItem:self.alertBackgroundView + attribute:NSLayoutAttributeWidth + relatedBy:NSLayoutRelationEqual + toItem:nil + attribute:NSLayoutAttributeNotAnAttribute + multiplier:0.0f + constant:alertBackgroundViewWidth]; + + [self addConstraint:self.alertBackgroundWidthConstraint]; + + _backgroundViewVerticalCenteringConstraint = [NSLayoutConstraint constraintWithItem:self.alertBackgroundView + attribute:NSLayoutAttributeCenterY + relatedBy:NSLayoutRelationEqual + toItem:self + attribute:NSLayoutAttributeCenterY + multiplier:1.0f + constant:0.0f]; + + [self addConstraint:self.backgroundViewVerticalCenteringConstraint]; + + [self addConstraint:[NSLayoutConstraint constraintWithItem:self.alertBackgroundView + attribute:NSLayoutAttributeHeight + relatedBy:NSLayoutRelationLessThanOrEqual + toItem:self + attribute:NSLayoutAttributeHeight + multiplier:0.9f + constant:0.0f]]; + + [self.alertBackgroundView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_titleLabel]-|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_titleLabel)]]; + + [self.alertBackgroundView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_messageTextView]-|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_messageTextView)]]; + + [self.alertBackgroundView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentViewContainerView]|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_contentViewContainerView)]]; + + [self.alertBackgroundView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_textFieldContainerView]|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_textFieldContainerView)]]; + + [self.alertBackgroundView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_actionButtonContainerView]|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_actionButtonContainerView)]]; + + [self.alertBackgroundView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_titleLabel]-2-[_messageTextView][_contentViewContainerView][_textFieldContainerView][_actionButtonContainerView]-|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_titleLabel, + _messageTextView, + _contentViewContainerView, + _textFieldContainerView, + _actionButtonContainerView)]]; + } + + return self; +} + + +// Pass through touches outside the backgroundView for the presentation controller to handle dismissal +- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { + for (UIView *subview in self.subviews) { + if ([subview hitTest:[self convertPoint:point toView:subview] withEvent:event]) { + return YES; + } + } + + return NO; +} + +- (void)setMaximumWidth:(CGFloat)maximumWidth { + _maximumWidth = maximumWidth; + self.alertBackgroundWidthConstraint.constant = maximumWidth; +} + +- (void)setContentView:(UIView *)contentView { + [self.contentView removeFromSuperview]; + + _contentView = contentView; + + if (contentView) { + [self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self.contentViewContainerView addSubview:self.contentView]; + + [self.contentViewContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_contentView)]]; + + [self.contentViewContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-2-[_contentView]-2-|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_contentView)]]; + } +} + +//- (void)actionButtonPressed:(NYAlertViewButton *)button { +// NYAlertAction *action = self.actions[button.tag]; +// action.handler(action); +//} + +//- (void)setActions:(NSArray *)actions { +//// _actions = actions; +//// +// NSMutableArray *buttons = [NSMutableArray array]; +// +// // Create buttons for each action +// for (int i = 0; i < [actions count]; i++) { +// UIAlertAction *action = actions[i]; +// +// NYAlertViewButton *button = [[NYAlertViewButton alloc] initWithFrame:CGRectZero]; +// +// button.tag = i; +// [button addTarget:self action:@selector(actionButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; +// +// button.cornerRadius = self.buttonCornerRadius; +// [button setTranslatesAutoresizingMaskIntoConstraints:NO]; +// [button setTitle:action.title forState:UIControlStateNormal]; +// +// if (action.style == UIAlertActionStyleCancel) { +// [button setTitleColor:self.cancelButtonTitleColor forState:UIControlStateNormal]; +// [button setTitleColor:self.cancelButtonTitleColor forState:UIControlStateHighlighted]; +// button.tintColor = self.cancelButtonColor; +// button.titleLabel.font = self.cancelButtonTitleFont; +// } else if (action.style == UIAlertActionStyleDestructive) { +// [button setTitleColor:self.destructiveButtonTitleColor forState:UIControlStateNormal]; +// [button setTitleColor:self.destructiveButtonTitleColor forState:UIControlStateHighlighted]; +// button.tintColor = self.destructiveButtonColor; +// button.titleLabel.font = self.destructiveButtonTitleFont; +// } else { +// [button setTitleColor:self.buttonTitleColor forState:UIControlStateNormal]; +// [button setTitleColor:self.buttonTitleColor forState:UIControlStateHighlighted]; +// button.tintColor = self.buttonColor; +// button.titleLabel.font = self.buttonTitleFont; +// } +// +// [buttons addObject:button]; +// } +// +// self.actionButtons = buttons; +//} + +- (void)setTextFields:(NSArray *)textFields { + for (UITextField *textField in self.textFields) { + [textField removeFromSuperview]; + } + + _textFields = textFields; + + for (int i = 0; i < [textFields count]; i++) { + UITextField *textField = textFields[i]; + [textField setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self.textFieldContainerView addSubview:textField]; + + [self.textFieldContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[textField]-|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(textField)]]; + + // Pin the first text field to the top of the text field container view + if (i == 0) { + [self.textFieldContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[textField]" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_contentViewContainerView, textField)]]; + } else { + UITextField *previousTextField = textFields[i - 1]; + + [self.textFieldContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[previousTextField]-[textField]" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(previousTextField, textField)]]; + } + + // Pin the final text field to the bottom of the text field container view + if (i == ([textFields count] - 1)) { + [self.textFieldContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[textField]|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(textField)]]; + } + } +} + +- (void)setActionButtons:(NSArray *)actionButtons { + for (UIButton *button in self.actionButtons) { + [button removeFromSuperview]; + } + + _actionButtons = actionButtons; + + // If there are 2 actions, display the buttons next to each other. Otherwise, stack the buttons vertically at full width + if ([actionButtons count] == 2) { + UIButton *firstButton = actionButtons[0]; + UIButton *lastButton = actionButtons[1]; + + [self.actionButtonContainerView addSubview:firstButton]; + [self.actionButtonContainerView addSubview:lastButton]; + + [self.actionButtonContainerView addConstraint:[NSLayoutConstraint constraintWithItem:firstButton + attribute:NSLayoutAttributeWidth + relatedBy:NSLayoutRelationEqual + toItem:lastButton + attribute:NSLayoutAttributeWidth + multiplier:1.0f + constant:0.0f]]; + + [self.actionButtonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[firstButton]-[lastButton]-|" + options:NSLayoutFormatAlignAllCenterY + metrics:nil + views:NSDictionaryOfVariableBindings(firstButton, lastButton)]]; + + [self.actionButtonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[firstButton(40)]|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_contentViewContainerView, firstButton)]]; + + [self.actionButtonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[lastButton(40)]" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(lastButton)]]; + } else { + for (int i = 0; i < [actionButtons count]; i++) { + UIButton *actionButton = actionButtons[i]; + + [self.actionButtonContainerView addSubview:actionButton]; + + [self.actionButtonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[actionButton]-|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(actionButton)]]; + + [self.actionButtonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[actionButton(40)]" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(actionButton)]]; + + if (i == 0) { + [self.actionButtonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[actionButton]" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_contentViewContainerView, actionButton)]]; + } else { + UIButton *previousButton = actionButtons[i - 1]; + + [self.actionButtonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[previousButton]-[actionButton]" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(previousButton, actionButton)]]; + } + + if (i == ([actionButtons count] - 1)) { + [self.actionButtonContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[actionButton]|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(actionButton)]]; + } + } + } +} + +@end diff --git a/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertViewController.h b/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertViewController.h new file mode 100644 index 0000000..88fb990 --- /dev/null +++ b/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertViewController.h @@ -0,0 +1,204 @@ +// +// NYAlertViewController.h +// +// Created by Nealon Young on 7/13/15. +// Copyright (c) 2015 Nealon Young. All rights reserved. +// + +#import + +@interface NYAlertAction : NSObject + ++ (instancetype)actionWithTitle:(NSString *)title style:(UIAlertActionStyle)style handler:(void (^)(NYAlertAction *action))handler; + +@property (nonatomic) NSString *title; +@property (nonatomic) UIAlertActionStyle style; +@property (nonatomic, strong) void (^handler)(NYAlertAction *action); +@property (nonatomic) BOOL enabled; + +@end + +typedef NS_ENUM(NSInteger, NYAlertViewControllerTransitionStyle) { + /** Fade in the alert view */ + NYAlertViewControllerTransitionStyleFade, + /** Slide the alert view from the top of the view */ + NYAlertViewControllerTransitionStyleSlideFromTop, + /** Slide the alert view from the bottom of the view */ + NYAlertViewControllerTransitionStyleSlideFromBottom +}; + +@interface NYAlertViewController : UIViewController + +/** + Creates an alert view controller with the specified title and message + */ ++ (instancetype)alertControllerWithTitle:(NSString *)title message:(NSString *)message; + +/** + The message displayed under the alert view's title + */ +@property (nonatomic) NSString *message; + +/** + A Boolean value that determines whether the status bar is visible when the alert view is presented + */ +@property (nonatomic) BOOL showsStatusBar; + +/** + The custom view displayed in the presented alert view + + @discussion The default value of this property is nil. Set this property to a view that you create to add the custom view to the displayed alert view. + */ +@property (nonatomic) UIView *alertViewContentView; + +/** + The transition style used to animate the alert view's presentation/dismissal transitions. + + @discussion The default value is NYAlertViewControllerTransitionStyleSlideFromTop. + */ +@property (nonatomic) NYAlertViewControllerTransitionStyle transitionStyle; + +/** + A Boolean value that determines whether the user can tap on the dimmed background surrounding the presented alert view to dismiss the alert view controller without any action handlers being executed + + @discussion The default value is NO + */ +@property (nonatomic) BOOL backgroundTapDismissalGestureEnabled; + +/** + A Boolean value that determines whether the user can swipe up or down on the presented alert view to dismiss the alert view controller without any action handlers being executed + + @discussion The default value is NO + */ +@property (nonatomic) BOOL swipeDismissalGestureEnabled; + +/** + The background color of the alert view + */ +@property (nonatomic) UIColor *alertViewBackgroundColor; + +/** + The maximum width at which to display the presented alert view + */ +@property (nonatomic) CGFloat maximumWidth; + +/** + The font used to display the title in the alert view + + @see title + */ +@property (nonatomic) UIFont *titleFont; + +/** + The font used to display the messsage in the alert view + + @see message + */ +@property (nonatomic) UIFont *messageFont; + +/** + The font used for buttons (actions with style NYAlertActionStyleDefault) in the alert view + */ +@property (nonatomic) UIFont *buttonTitleFont; + +/** + The font used for cancel buttons (actions with style NYAlertActionStyleCancel) in the alert view + */ +@property (nonatomic) UIFont *cancelButtonTitleFont; + +/** + The font used for destructive buttons (actions with style NYAlertActionStyleDestructive) in the alert view + */ +@property (nonatomic) UIFont *destructiveButtonTitleFont; + +/** + The color used to display the alert view's title + + @see title + */ +@property (nonatomic) UIColor *titleColor; + +/** + The color used to display the alert view's message + + @see message + */ +@property (nonatomic) UIColor *messageColor; + +/** + The background color for the alert view's buttons corresponsing to default style actions + */ +@property (nonatomic) UIColor *buttonColor; + +/** + The background color for the alert view's buttons corresponsing to cancel style actions + */ +@property (nonatomic) UIColor *cancelButtonColor; + +/** + The background color for the alert view's buttons corresponsing to destructive style actions + */ +@property (nonatomic) UIColor *destructiveButtonColor; + +/** + The background color for the alert view's buttons corresponsing to disabled actions + */ +@property (nonatomic) UIColor *disabledButtonColor; + +/** + The color used to display the title for buttons corresponsing to default style actions + */ +@property (nonatomic) UIColor *buttonTitleColor; + +/** + The color used to display the title for buttons corresponding to cancel style actions + */ +@property (nonatomic) UIColor *cancelButtonTitleColor; + +/** + The color used to display the title for buttons corresponsing to destructive style actions + */ +@property (nonatomic) UIColor *destructiveButtonTitleColor; + +/** + The color used to display the title for buttons corresponsing to disabled actions + */ +@property (nonatomic) UIColor *disabledButtonTitleColor; + +/** + The radius of the displayed alert view's corners + */ +@property (nonatomic) CGFloat alertViewCornerRadius; + +/** + The radius of button corners + */ +@property (nonatomic) CGFloat buttonCornerRadius; + +/** + An array of NYAlertAction objects representing the actions that the user can take in response to the alert view + */ +@property (nonatomic, readonly) NSArray *actions; + +/** + An array of UITextField objects displayed by the alert view + + @see addTextFieldWithConfigurationHandler: + */ +@property (nonatomic, readonly) NSArray *textFields; + +/** + Add an alert action object to be displayed in the alert view + + @param action The action object to display in the alert view to be presented + */ +- (void)addAction:(NYAlertAction *)action; + +/** + Add a text field object to be displayed in the alert view + + @param configurationHandler A block used to configure the text field. The block takes the text field object as a parameter, and can modify the properties of the text field prior to being displayed. + */ +- (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler; + +@end diff --git a/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertViewController.m b/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertViewController.m new file mode 100644 index 0000000..7d3e8ab --- /dev/null +++ b/TalkinToTheNet/Pods/NYAlertViewController/NYAlertViewController/NYAlertViewController.m @@ -0,0 +1,780 @@ +// +// NYAlertViewController.m +// +// Created by Nealon Young on 7/13/15. +// Copyright (c) 2015 Nealon Young. All rights reserved. +// + +#import "NYAlertViewController.h" + +#import "NYAlertView.h" + +@interface NYAlertAction () + +@property (weak, nonatomic) UIButton *actionButton; + +@end + +@implementation NYAlertAction + ++ (instancetype)actionWithTitle:(NSString *)title style:(UIAlertActionStyle)style handler:(void (^)(NYAlertAction *action))handler { + NYAlertAction *action = [[NYAlertAction alloc] init]; + action.title = title; + action.style = style; + action.handler = handler; + + return action; +} + +- (instancetype)init { + self = [super init]; + + if (self) { + _enabled = YES; + } + + return self; +} + +- (void)setEnabled:(BOOL)enabled { + _enabled = enabled; + + self.actionButton.enabled = enabled; +} + +@end + +@interface NYAlertViewPresentationAnimationController : NSObject + +@property NYAlertViewControllerTransitionStyle transitionStyle; +@property CGFloat duration; + +@end + +static CGFloat const kDefaultPresentationAnimationDuration = 0.7f; + +@implementation NYAlertViewPresentationAnimationController + +- (instancetype)init { + self = [super init]; + + if (self) { + self.duration = kDefaultPresentationAnimationDuration; + } + + return self; +} + +- (void)animateTransition:(id)transitionContext { + if (self.transitionStyle == NYAlertViewControllerTransitionStyleSlideFromTop || self.transitionStyle == NYAlertViewControllerTransitionStyleSlideFromBottom) { + UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey]; + + CGRect initialFrame = [transitionContext finalFrameForViewController:toViewController]; + + initialFrame.origin.y = self.transitionStyle == NYAlertViewControllerTransitionStyleSlideFromTop ? -(initialFrame.size.height + initialFrame.origin.y) : (initialFrame.size.height + initialFrame.origin.y); + toViewController.view.frame = initialFrame; + + [[transitionContext containerView] addSubview:toViewController.view]; + + // If we're using the slide from top transition, apply a 3D rotation effect to the alert view as it animates in + if (self.transitionStyle == NYAlertViewControllerTransitionStyleSlideFromTop) { + CATransform3D transform = CATransform3DIdentity; + transform.m34 = -1.0f / 600.0f; + transform = CATransform3DRotate(transform, M_PI_4 * 1.3f, 1.0f, 0.0f, 0.0f); + + toViewController.view.layer.zPosition = 100.0f; + toViewController.view.layer.transform = transform; + } + + [UIView animateWithDuration:[self transitionDuration:transitionContext] + delay:0.0f + usingSpringWithDamping:0.76f + initialSpringVelocity:0.2f + options:0 + animations:^{ + toViewController.view.layer.transform = CATransform3DIdentity; + toViewController.view.layer.opacity = 1.0f; + toViewController.view.frame = [transitionContext finalFrameForViewController:toViewController]; + } + completion:^(BOOL finished) { + [transitionContext completeTransition:YES]; + }]; + } else { + UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey]; + + toViewController.view.frame = [transitionContext finalFrameForViewController:toViewController]; + [[transitionContext containerView] addSubview:toViewController.view]; + + toViewController.view.layer.transform = CATransform3DMakeScale(1.2f, 1.2f, 1.2f); + toViewController.view.layer.opacity = 0.0f; + + [UIView animateWithDuration:[self transitionDuration:transitionContext] + animations:^{ + toViewController.view.layer.transform = CATransform3DIdentity; + toViewController.view.layer.opacity = 1.0f; + } + completion:^(BOOL finished) { + [transitionContext completeTransition:YES]; + }]; + } +} + +- (NSTimeInterval)transitionDuration:(id)transitionContext { + switch (self.transitionStyle) { + case NYAlertViewControllerTransitionStyleFade: + return 0.3f; + break; + + case NYAlertViewControllerTransitionStyleSlideFromTop: + case NYAlertViewControllerTransitionStyleSlideFromBottom: + return 0.6f; + } +} + +@end + +@interface NYAlertViewDismissalAnimationController : NSObject + +@property NYAlertViewControllerTransitionStyle transitionStyle; +@property CGFloat duration; + +@end + +static CGFloat const kDefaultDismissalAnimationDuration = 0.6f; + +@implementation NYAlertViewDismissalAnimationController + +- (instancetype)init { + self = [super init]; + + if (self) { + self.duration = kDefaultDismissalAnimationDuration; + } + + return self; +} + +- (void)animateTransition:(id)transitionContext { + if (self.transitionStyle == NYAlertViewControllerTransitionStyleSlideFromTop || self.transitionStyle == NYAlertViewControllerTransitionStyleSlideFromBottom) { + UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey]; + + CGRect finalFrame = [transitionContext finalFrameForViewController:fromViewController]; + finalFrame.origin.y = 1.2f * CGRectGetHeight([transitionContext containerView].frame); + + [UIView animateWithDuration:[self transitionDuration:transitionContext] + delay:0.0f + usingSpringWithDamping:0.8f + initialSpringVelocity:0.1f + options:0 + animations:^{ + fromViewController.view.frame = finalFrame; + } + completion:^(BOOL finished) { + [transitionContext completeTransition:YES]; + }]; + } else { + UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey]; + + [UIView animateWithDuration:[self transitionDuration:transitionContext] + animations:^{ + fromViewController.view.layer.opacity = 0.0f; + } + completion:^(BOOL finished) { + [transitionContext completeTransition:YES]; + }]; + } +} + +- (NSTimeInterval)transitionDuration:(id)transitionContext { + switch (self.transitionStyle) { + case NYAlertViewControllerTransitionStyleFade: + return 0.3f; + break; + + case NYAlertViewControllerTransitionStyleSlideFromTop: + case NYAlertViewControllerTransitionStyleSlideFromBottom: + return 0.6f; + }} + +@end + +@interface NYAlertViewPresentationController : UIPresentationController + +@property CGFloat presentedViewControllerHorizontalInset; +@property CGFloat presentedViewControllerVerticalInset; +@property (nonatomic) BOOL backgroundTapDismissalGestureEnabled; +@property UIView *backgroundDimmingView; + +@end + +@interface NYAlertViewPresentationController () + +- (void)tapGestureRecognized:(UITapGestureRecognizer *)gestureRecognizer; + +@end + +@implementation NYAlertViewPresentationController + +- (void)presentationTransitionWillBegin { + self.presentedViewController.view.layer.cornerRadius = 6.0f; + self.presentedViewController.view.layer.masksToBounds = YES; + + self.backgroundDimmingView = [[UIView alloc] initWithFrame:CGRectZero]; + [self.backgroundDimmingView setTranslatesAutoresizingMaskIntoConstraints:NO]; + self.backgroundDimmingView.alpha = 0.0f; + self.backgroundDimmingView.backgroundColor = [UIColor blackColor]; + [self.containerView addSubview:self.backgroundDimmingView]; + + [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_backgroundDimmingView]|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_backgroundDimmingView)]]; + + [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_backgroundDimmingView]|" + options:0 + metrics:nil + views:NSDictionaryOfVariableBindings(_backgroundDimmingView)]]; + + UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognized:)]; + [self.backgroundDimmingView addGestureRecognizer:tapGestureRecognizer]; + + // Shrink the presenting view controller, and animate in the dark background view + id transitionCoordinator = [self.presentingViewController transitionCoordinator]; + [transitionCoordinator animateAlongsideTransition:^(id context) { + self.backgroundDimmingView.alpha = 0.7f; + } + completion:nil]; +} + +- (BOOL)shouldPresentInFullscreen { + return NO; +} + +- (BOOL)shouldRemovePresentersView { + return NO; +} + +- (void)presentationTransitionDidEnd:(BOOL)completed { + [super presentationTransitionDidEnd:completed]; + + if (!completed) { + [self.backgroundDimmingView removeFromSuperview]; + } +} + +- (void)dismissalTransitionWillBegin { + [super dismissalTransitionWillBegin]; + + id transitionCoordinator = [self.presentingViewController transitionCoordinator]; + [transitionCoordinator animateAlongsideTransition:^(id context) { + self.backgroundDimmingView.alpha = 0.0f; + + self.presentingViewController.view.transform = CGAffineTransformIdentity; + } + completion:nil]; +} + +- (void)containerViewWillLayoutSubviews { + [super containerViewWillLayoutSubviews]; + + [self presentedView].frame = [self frameOfPresentedViewInContainerView]; + self.backgroundDimmingView.frame = self.containerView.bounds; +} + +- (void)dismissalTransitionDidEnd:(BOOL)completed { + [super dismissalTransitionDidEnd:completed]; + + if (completed) { + [self.backgroundDimmingView removeFromSuperview]; + } +} + +- (void)tapGestureRecognized:(UITapGestureRecognizer *)gestureRecognizer { + if (self.backgroundTapDismissalGestureEnabled) { + [self.presentingViewController dismissViewControllerAnimated:YES completion:nil]; + } +} + +@end + +@interface NYAlertViewController () + +@property NYAlertView *view; +@property UIPanGestureRecognizer *panGestureRecognizer; +@property (nonatomic, strong) id transitioningDelegate; + +- (void)panGestureRecognized:(UIPanGestureRecognizer *)gestureRecognizer; + +@end + +@implementation NYAlertViewController + +@dynamic view; + ++ (instancetype)alertControllerWithTitle:(NSString *)title message:(NSString *)message { + NYAlertViewController *alertController = [[NYAlertViewController alloc] initWithNibName:nil bundle:nil]; + alertController.title = title; + alertController.message = message; + + return alertController; +} + +- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { + self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; + + if (self) { + [self commonInit]; + } + + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + self = [super initWithCoder:aDecoder]; + + if (self) { + [self commonInit]; + } + + return self; +} + +- (void)viewDidDisappear:(BOOL)animated { + // Necessary to avoid retain cycle - http://stackoverflow.com/a/21218703/1227862 + self.transitioningDelegate = nil; + [super viewDidDisappear:animated]; +} + +- (void)commonInit { + _actions = [NSArray array]; + _textFields = [NSArray array]; + + _showsStatusBar = YES; + + _buttonTitleFont = [UIFont systemFontOfSize:16.0f]; + _cancelButtonTitleFont = [UIFont boldSystemFontOfSize:16.0f]; + _destructiveButtonTitleFont = [UIFont systemFontOfSize:16.0f]; + + _buttonColor = [UIColor darkGrayColor]; + _buttonTitleColor = [UIColor whiteColor]; + _cancelButtonColor = [UIColor darkGrayColor]; + _cancelButtonTitleColor = [UIColor whiteColor]; + _destructiveButtonColor = [UIColor colorWithRed:1.0f green:0.23f blue:0.21f alpha:1.0f]; + _destructiveButtonTitleColor = [UIColor whiteColor]; + _disabledButtonColor = [UIColor lightGrayColor]; + _disabledButtonTitleColor = [UIColor whiteColor]; + + _buttonCornerRadius = 6.0f; + + _transitionStyle = NYAlertViewControllerTransitionStyleSlideFromTop; + + self.modalPresentationStyle = UIModalPresentationCustom; + self.transitioningDelegate = self; + + self.panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognized:)]; + self.panGestureRecognizer.delegate = self; + self.panGestureRecognizer.enabled = NO; + [self.view addGestureRecognizer:self.panGestureRecognizer]; +} + +- (void)loadView { + self.view = [[NYAlertView alloc] initWithFrame:CGRectZero]; +} + +- (BOOL)prefersStatusBarHidden { + return !self.showsStatusBar; +} + +- (CGFloat)maximumWidth { + return self.view.maximumWidth; +} + +- (void)setMaximumWidth:(CGFloat)maximumWidth { + self.view.maximumWidth = maximumWidth; +} + +- (UIView *)alertViewContentView { + return self.view.contentView; +} + +- (void)setAlertViewContentView:(UIView *)alertViewContentView { + self.view.contentView = alertViewContentView; +} + +- (void)setSwipeDismissalGestureEnabled:(BOOL)swipeDismissalGestureEnabled { + _swipeDismissalGestureEnabled = swipeDismissalGestureEnabled; + + self.panGestureRecognizer.enabled = swipeDismissalGestureEnabled; +} + +- (void)panGestureRecognized:(UIPanGestureRecognizer *)gestureRecognizer { + self.view.backgroundViewVerticalCenteringConstraint.constant = [gestureRecognizer translationInView:self.view].y; + + NYAlertViewPresentationController *presentationController = (NYAlertViewPresentationController* )self.presentationController; + + CGFloat windowHeight = CGRectGetHeight([UIApplication sharedApplication].keyWindow.bounds); + presentationController.backgroundDimmingView.alpha = 0.7f - (fabs([gestureRecognizer translationInView:self.view].y) / windowHeight); + + if (gestureRecognizer.state == UIGestureRecognizerStateEnded) { + CGFloat verticalGestureVelocity = [gestureRecognizer velocityInView:self.view].y; + + // If the gesture is moving fast enough, animate the alert view offscreen and dismiss the view controller. Otherwise, animate the alert view back to its initial position + if (fabs(verticalGestureVelocity) > 500.0f) { + CGFloat backgroundViewYPosition; + + if (verticalGestureVelocity > 500.0f) { + backgroundViewYPosition = CGRectGetHeight(self.view.frame); + } else { + backgroundViewYPosition = -CGRectGetHeight(self.view.frame); + } + + CGFloat animationDuration = 500.0f / fabs(verticalGestureVelocity); + + self.view.backgroundViewVerticalCenteringConstraint.constant = backgroundViewYPosition; + [UIView animateWithDuration:animationDuration + delay:0.0f + usingSpringWithDamping:0.8f + initialSpringVelocity:0.2f + options:0 + animations:^{ + presentationController.backgroundDimmingView.alpha = 0.0f; + [self.view layoutIfNeeded]; + } + completion:^(BOOL finished) { + [self dismissViewControllerAnimated:YES completion:nil]; + }]; + } else { + self.view.backgroundViewVerticalCenteringConstraint.constant = 0.0f; + [UIView animateWithDuration:0.5f + delay:0.0f + usingSpringWithDamping:0.8f + initialSpringVelocity:0.4f + options:0 + animations:^{ + presentationController.backgroundDimmingView.alpha = 0.7f; + [self.view layoutIfNeeded]; + } + completion:nil]; + } + } +} + +- (void)viewWillAppear:(BOOL)animated { + [super viewWillAppear:animated]; + + [self createActionButtons]; + self.view.textFields = self.textFields; +} + +- (void)setAlertViewBackgroundColor:(UIColor *)alertViewBackgroundColor { + _alertViewBackgroundColor = alertViewBackgroundColor; + + self.view.alertBackgroundView.backgroundColor = alertViewBackgroundColor; +} + +- (void)createActionButtons { + NSMutableArray *buttons = [NSMutableArray array]; + + // Create buttons for each action + for (int i = 0; i < [self.actions count]; i++) { + NYAlertAction *action = self.actions[i]; + + NYAlertViewButton *button = [NYAlertViewButton buttonWithType:UIButtonTypeCustom]; + + button.tag = i; + [button addTarget:self action:@selector(actionButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; + + button.enabled = action.enabled; + + button.cornerRadius = self.buttonCornerRadius; + [button setTranslatesAutoresizingMaskIntoConstraints:NO]; + [button setTitle:action.title forState:UIControlStateNormal]; + + [button setTitleColor:self.disabledButtonTitleColor forState:UIControlStateDisabled]; + [button setBackgroundColor:self.disabledButtonColor forState:UIControlStateDisabled]; + + if (action.style == UIAlertActionStyleCancel) { + [button setTitleColor:self.cancelButtonTitleColor forState:UIControlStateNormal]; + [button setTitleColor:self.cancelButtonTitleColor forState:UIControlStateHighlighted]; + [button setBackgroundColor:self.cancelButtonColor forState:UIControlStateNormal]; + + button.titleLabel.font = self.cancelButtonTitleFont; + } else if (action.style == UIAlertActionStyleDestructive) { + [button setTitleColor:self.destructiveButtonTitleColor forState:UIControlStateNormal]; + [button setTitleColor:self.destructiveButtonTitleColor forState:UIControlStateHighlighted]; + [button setBackgroundColor:self.destructiveButtonColor forState:UIControlStateNormal]; + + button.titleLabel.font = self.destructiveButtonTitleFont; + } else { + [button setTitleColor:self.buttonTitleColor forState:UIControlStateNormal]; + [button setTitleColor:self.buttonTitleColor forState:UIControlStateHighlighted]; + [button setBackgroundColor:self.buttonColor forState:UIControlStateNormal]; + + button.titleLabel.font = self.buttonTitleFont; + } + + [buttons addObject:button]; + + action.actionButton = button; + } + + self.view.actionButtons = buttons; +} + +- (void)actionButtonPressed:(UIButton *)button { + NYAlertAction *action = self.actions[button.tag]; + action.handler(action); +} + +#pragma mark - Getters/Setters + +- (void)setTitle:(NSString *)title { + [super setTitle:title]; + + self.view.titleLabel.text = title; +} + +- (void)setMessage:(NSString *)message { + _message = message; + self.view.messageTextView.text = message; +} + +- (UIFont *)titleFont { + return self.view.titleLabel.font; +} + +- (void)setTitleFont:(UIFont *)titleFont { + self.view.titleLabel.font = titleFont; +} + +- (UIFont *)messageFont { + return self.view.messageTextView.font; +} + +- (void)setMessageFont:(UIFont *)messageFont { + self.view.messageTextView.font = messageFont; +} + +- (void)setButtonTitleFont:(UIFont *)buttonTitleFont { + _buttonTitleFont = buttonTitleFont; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (action.style != UIAlertActionStyleCancel) { + button.titleLabel.font = buttonTitleFont; + } + }]; +} + +- (void)setCancelButtonTitleFont:(UIFont *)cancelButtonTitleFont { + _cancelButtonTitleFont = cancelButtonTitleFont; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (action.style == UIAlertActionStyleCancel) { + button.titleLabel.font = cancelButtonTitleFont; + } + }]; +} + +- (void)setDestructiveButtonTitleFont:(UIFont *)destructiveButtonTitleFont { + _destructiveButtonTitleFont = destructiveButtonTitleFont; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (action.style == UIAlertActionStyleDestructive) { + button.titleLabel.font = destructiveButtonTitleFont; + } + }]; +} + +- (UIColor *)titleColor { + return self.view.titleLabel.textColor; +} + +- (void)setTitleColor:(UIColor *)titleColor { + self.view.titleLabel.textColor = titleColor; +} + +- (UIColor *)messageColor { + return self.view.messageTextView.textColor; +} + +- (void)setMessageColor:(UIColor *)messageColor { + self.view.messageTextView.textColor = messageColor; +} + +- (void)setButtonColor:(UIColor *)buttonColor { + _buttonColor = buttonColor; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (action.style != UIAlertActionStyleCancel) { + [button setBackgroundColor:buttonColor forState:UIControlStateNormal]; + } + }]; +} + +- (void)setCancelButtonColor:(UIColor *)cancelButtonColor { + _cancelButtonColor = cancelButtonColor; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (action.style == UIAlertActionStyleCancel) { + [button setBackgroundColor:cancelButtonColor forState:UIControlStateNormal]; + } + }]; +} + +- (void)setDestructiveButtonColor:(UIColor *)destructiveButtonColor { + _destructiveButtonColor = destructiveButtonColor; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (action.style == UIAlertActionStyleDestructive) { + [button setBackgroundColor:destructiveButtonColor forState:UIControlStateNormal]; + } + }]; +} + +- (void)setDisabledButtonColor:(UIColor *)disabledButtonColor { + _disabledButtonColor = disabledButtonColor; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (!action.enabled) { + [button setBackgroundColor:disabledButtonColor forState:UIControlStateNormal]; + } + }]; +} + +- (void)setButtonTitleColor:(UIColor *)buttonTitleColor { + _buttonTitleColor = buttonTitleColor; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (action.style != UIAlertActionStyleCancel) { + [button setTitleColor:buttonTitleColor forState:UIControlStateNormal]; + [button setTitleColor:buttonTitleColor forState:UIControlStateHighlighted]; + } + }]; +} + +- (void)setCancelButtonTitleColor:(UIColor *)cancelButtonTitleColor { + _cancelButtonTitleColor = cancelButtonTitleColor; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (action.style == UIAlertActionStyleCancel) { + [button setTitleColor:cancelButtonTitleColor forState:UIControlStateNormal]; + [button setTitleColor:cancelButtonTitleColor forState:UIControlStateHighlighted]; + } + }]; +} + +- (void)setDestructiveButtonTitleColor:(UIColor *)destructiveButtonTitleColor { + _destructiveButtonTitleColor = destructiveButtonTitleColor; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (action.style == UIAlertActionStyleDestructive) { + [button setTitleColor:destructiveButtonTitleColor forState:UIControlStateNormal]; + [button setTitleColor:destructiveButtonTitleColor forState:UIControlStateHighlighted]; + } + }]; +} + +- (void)setDisabledButtonTitleColor:(UIColor *)disabledButtonTitleColor { + _disabledButtonTitleColor = disabledButtonTitleColor; + + [self.view.actionButtons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) { + NYAlertAction *action = self.actions[idx]; + + if (!action.enabled) { + [button setTitleColor:disabledButtonTitleColor forState:UIControlStateNormal]; + [button setTitleColor:disabledButtonTitleColor forState:UIControlStateHighlighted]; + } + }]; +} + +- (CGFloat)alertViewCornerRadius { + return self.view.alertBackgroundView.layer.cornerRadius; +} + +- (void)setAlertViewCornerRadius:(CGFloat)alertViewCornerRadius { + self.view.alertBackgroundView.layer.cornerRadius = alertViewCornerRadius; +} + +- (void)setButtonCornerRadius:(CGFloat)buttonCornerRadius { + _buttonCornerRadius = buttonCornerRadius; + + for (NYAlertViewButton *button in self.view.actionButtons) { + button.cornerRadius = buttonCornerRadius; + } +} + +- (void)addAction:(UIAlertAction *)action { + _actions = [self.actions arrayByAddingObject:action]; +} + +- (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler { + UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero]; + textField.borderStyle = UITextBorderStyleRoundedRect; + + configurationHandler(textField); + + _textFields = [self.textFields arrayByAddingObject:textField]; +} + +- (void)buttonPressed:(UIButton *)sender { + NYAlertAction *action = self.actions[sender.tag]; + action.handler(action); +} + +#pragma mark - UIViewControllerTransitioningDelegate + +- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented + presentingViewController:(UIViewController *)presenting + sourceViewController:(UIViewController *)source { + NYAlertViewPresentationController *presentationController = [[NYAlertViewPresentationController alloc] initWithPresentedViewController:presented + presentingViewController:presenting]; + presentationController.backgroundTapDismissalGestureEnabled = self.backgroundTapDismissalGestureEnabled; + return presentationController; +} + +- (id )animationControllerForPresentedController:(UIViewController *)presented + presentingController:(UIViewController *)presenting + sourceController:(UIViewController *)source { + NYAlertViewPresentationAnimationController *presentationAnimationController = [[NYAlertViewPresentationAnimationController alloc] init]; + presentationAnimationController.transitionStyle = self.transitionStyle; + return presentationAnimationController; +} + +- (id )animationControllerForDismissedController:(UIViewController *)dismissed { + NYAlertViewDismissalAnimationController *dismissalAnimationController = [[NYAlertViewDismissalAnimationController alloc] init]; + dismissalAnimationController.transitionStyle = self.transitionStyle; + return dismissalAnimationController; +} + +#pragma mark - UIGestureRecognizerDelegate + +- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { + // Don't recognize the pan gesture in the button, so users can move their finger away after touching down + if (([touch.view isKindOfClass:[UIButton class]])) { + return NO; + } + + return YES; +} + +@end diff --git a/TalkinToTheNet/Pods/NYAlertViewController/README.md b/TalkinToTheNet/Pods/NYAlertViewController/README.md new file mode 100644 index 0000000..a842583 --- /dev/null +++ b/TalkinToTheNet/Pods/NYAlertViewController/README.md @@ -0,0 +1,104 @@ +# NYAlertViewController + +NYAlertViewController is a replacement for UIAlertController/UIAlertView with support for content views and UI customization. + +![Example](https://github.com/nealyoung/NYAlertViewController/raw/master/header.png) + +### Features +* Includes content view property for adding custom views to the alert view +* Block-based API similar to UIAlertController/UIAlertAction +* Support for all screen orientations and iPad screen sizes +* Easily add text fields with simple API identical to UIAlertController +* Choose between fade (similar to UIAlertController) or slide transition animations + +### Installation +#### Manual +Add the files to your project manually by dragging the NYAlertViewController directory into your Xcode project. + +#### CocoaPods +Add `pod 'NYAlertViewController'` to your Podfile, and run `pod install`. + +### Usage Examples +An Objectve-C example project demonstrating customization options is included in the NYAlertViewControllerDemo directory. + +#### Objective-C + +```objc +// Import the class and create an NYAlertViewController instance +#import "NYAlertViewController.h" + +// ... + +NYAlertViewController *alertViewController = [[NYAlertViewController alloc] initWithNibName:nil bundle:nil]; + +// Set a title and message +alertViewController.title = NSLocalizedString(@"Custom UI", nil); +alertViewController.message = NSLocalizedString(@"Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Donec id elit non mi porta gravida at eget metus.", nil); + +// Customize appearance as desired +alertViewController.buttonCornerRadius = 20.0f; +alertViewController.view.tintColor = self.view.tintColor; + +alertViewController.titleFont = [UIFont fontWithName:@"AvenirNext-Bold" size:19.0f]; +alertViewController.messageFont = [UIFont fontWithName:@"AvenirNext-Medium" size:16.0f]; +alertViewController.buttonTitleFont = [UIFont fontWithName:@"AvenirNext-Regular" size:alertViewController.buttonTitleFont.pointSize]; +alertViewController.cancelButtonTitleFont = [UIFont fontWithName:@"AvenirNext-Medium" size:alertViewController.cancelButtonTitleFont.pointSize]; + +alertViewController.swipeDismissalGestureEnabled = YES: +alertViewController.backgroundTapDismissalGestureEnabled = YES: + +// Add alert actions +[alertViewController addAction:[NYAlertAction actionWithTitle:NSLocalizedString(@"Done", nil) + style:UIAlertActionStyleCancel + handler:^(NYAlertAction *action) { + [self dismissViewControllerAnimated:YES completion:nil]; + }]]; + +// Present the alert view controller +[self presentViewController:alertViewController animated:YES]; +``` + +#### Swift + +```swift +import NYAlertViewController + +// ... + +let alertViewController = NYAlertViewController() + +// Set a title and message +alertViewController.title = "Custom UI" +alertViewController.message = "Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Donec id elit non mi porta gravida at eget metus." + +// Customize appearance as desired +alertViewController.buttonCornerRadius = 20.0 +alertViewController.view.tintColor = self.view.tintColor + +alertViewController.titleFont = UIFont(name: "AvenirNext-Bold", size: 19.0) +alertViewController.messageFont = UIFont(name: "AvenirNext-Medium", size: 16.0) +alertViewController.cancelButtonTitleFont = UIFont(name: "AvenirNext-Medium", size: 16.0) +alertViewController.cancelButtonTitleFont = UIFont(name: "AvenirNext-Medium", size: 16.0) + +alertViewController.swipeDismissalGestureEnabled = true +alertViewController.backgroundTapDismissalGestureEnabled = true + +// Add alert actions +let cancelAction = NYAlertAction( + title: "Done", + style: .Cancel, + handler: { (action: NYAlertAction!) -> Void in + self.dismissViewControllerAnimated(true, completion: nil) + } +) +alertViewController.addAction(cancelAction) + +// Present the alert view controller +self.presentViewController(alertViewController, animated: true, completion: nil) +``` + +### To-Dos +* Add different transition options (fade in, slide from top, etc.) + +### License +This project is released under the MIT License. diff --git a/TalkinToTheNet/Pods/Pods.xcodeproj/project.pbxproj b/TalkinToTheNet/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..502d597 --- /dev/null +++ b/TalkinToTheNet/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1028 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 01C546F4CE213CB90E63D432315942C1 /* AFNetworking-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E2A1080BBAE688641B6BDB86CFB654E /* AFNetworking-dummy.m */; }; + 022736711E461F4DBC1F3921E940A4E9 /* AFURLConnectionOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 022415DF81EFE56B71B50DF0E4E96E35 /* AFURLConnectionOperation.m */; }; + 0943A4196177D34CF59C88E4AA77B576 /* SDWebImageDecoder.m in Sources */ = {isa = PBXBuildFile; fileRef = F6810D818545BACFD21ACAB72D23DC72 /* SDWebImageDecoder.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 0CBFA0FDE2C98DEB97B2B0DC291F6F3F /* UIImageView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = E1EFD1D330A4BC70F1C4C2ED395E2258 /* UIImageView+WebCache.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 0DD83611A99AC2915F41C777525FEF04 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 22518513C47F74739B8E0153F9F32396 /* AFSecurityPolicy.m */; }; + 12AD33A36144A154E0A8F9473C3B424A /* UIProgressView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 8D1CC15A0216C2B8BF2CD8DF2E67F949 /* UIProgressView+AFNetworking.h */; }; + 13337E2C8A2701A6ADB67F9A7A0A364B /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = B371E0617A7484991F35CA4233E4F5AF /* AFURLRequestSerialization.m */; }; + 187C671AF0608FD0F82306F0B4A4BF49 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = F3490D34871627C40E25F470C5D69B6C /* AFURLSessionManager.h */; }; + 18894FC9A166263E6CB1FC6EE6AD8EFF /* SDWebImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 83F8CEA8D6C3D34590016ED7FF78B90C /* SDWebImageDownloader.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 1E19AE540A7EFDDBAEBAA0B4E9F428A2 /* AFHTTPRequestOperationManager.m in Sources */ = {isa = PBXBuildFile; fileRef = AD10C755EDA3ACD4B1FFAA8B4F2ED718 /* AFHTTPRequestOperationManager.m */; }; + 1F13401670CBCCA1006A809F5A9821FD /* UIWebView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 3B8B4246C7CAE1F0FE71B129F803250D /* UIWebView+AFNetworking.h */; }; + 2147A025B9D393774E96A88AEB786737 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 5D114FE662125F202F70F0A8E8A5A3D2 /* AFURLRequestSerialization.h */; }; + 2301D7E8195C722B269F7780A28A0C38 /* NYAlertViewController-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A4438A7C149BB67DBDBA981970536138 /* NYAlertViewController-dummy.m */; }; + 231F0DF9FD70245BFF38A3ED8344845C /* UIAlertView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E68EA0F40602611C543FB22314DD5558 /* UIAlertView+AFNetworking.h */; }; + 233BC793712FDA19AD947B2571281AF7 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 8C459D934F0E408252B506634C3E837E /* AFURLResponseSerialization.h */; }; + 2358EE556EF067512DADC50B59A15D25 /* SDWebImageManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C4C8A6792D4A925F9D3ABA38CB9537E /* SDWebImageManager.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 26B21B244340BA5A2F45F3B43F1D4926 /* UIButton+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 5099BC8D81DEDA973F9FF97BE55354BB /* UIButton+WebCache.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 26B276F6342953E80AAC247BF5CC931D /* UIAlertView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 9D7043956F7579B76AEA08E03AEE888A /* UIAlertView+AFNetworking.m */; }; + 2C6AEC70A3E09CC7BD16C30B5B941981 /* SDWebImageManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 5ECFB2161C220584CD4F649E8EAE3896 /* SDWebImageManager.h */; }; + 2CE385B9BE13A3F4F05D0C18B023EC7C /* AFNetworkActivityIndicatorManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 8873A06EBFEB9354947DE52D4836C630 /* AFNetworkActivityIndicatorManager.h */; }; + 3382F4BFE650771D3DBEA429325FA80B /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 77403F766765C11768746EAC15E59A2F /* AFURLSessionManager.m */; }; + 35781D3A40A883148EBA38103A249B6E /* AFURLConnectionOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F900AA39E79748B500B33D5C53E3EC1 /* AFURLConnectionOperation.h */; }; + 3723B6BDF682E042A291D1D9DBC61490 /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 61B8C216D508A298D69717F99E9B4C75 /* UIButton+AFNetworking.m */; }; + 37A315C532DA1A156F9676951702EFB9 /* SDWebImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 565D0DE3F083F3D803EE8CA97CDAECC5 /* SDWebImageDownloader.h */; }; + 43277991E53710BC6A43FE41448B1437 /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 407FD4DC1C2CE17EC4417C5574B46829 /* UIActivityIndicatorView+AFNetworking.m */; }; + 46C6D0143AB94CDD866FB320B9DB3C14 /* NSData+ImageContentType.h in Headers */ = {isa = PBXBuildFile; fileRef = 76C518201A486FCF7036C9F9DDBD593D /* NSData+ImageContentType.h */; }; + 49E0AD9A0C5186097C9B40E8EBDF6EB1 /* NYAlertViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = 47ADC8DE17CF04F44DAFBAC239E8C3CB /* NYAlertViewController.h */; }; + 4DF7EB0B43E458189DC7E635994F11D6 /* UIActivityIndicatorView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = AE6083A201A171D2E5A03F1EA3D5E1CB /* UIActivityIndicatorView+AFNetworking.h */; }; + 50151E9ABC4AC6EFCD9764698E392A3D /* UIImageView+HighlightedWebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = E7B5566E66AC64253CA228C460AE2931 /* UIImageView+HighlightedWebCache.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 505651BE6DF50CBA5C6BE87452D20BCF /* UIImageView+HighlightedWebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = D8DD99E890B5B9C7A22168DCDFF7F2F2 /* UIImageView+HighlightedWebCache.h */; }; + 57FDB0D84B88BA790448FB0099B256FB /* UIImage+MultiFormat.h in Headers */ = {isa = PBXBuildFile; fileRef = 6437C050025F1A8C69647B6744A18170 /* UIImage+MultiFormat.h */; }; + 5AEFDEE0BC7EF4E67216E3ECB36E5172 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = D079C4882B21742AD113F3E6CCEB26A5 /* AFSecurityPolicy.h */; }; + 646A6FC808A0B280B80AD4949D8357F8 /* UIView+WebCacheOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 44E19C4AEA9338236A9FD2DDA753E214 /* UIView+WebCacheOperation.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 65BBBBABB663C3125ED20242E8D17281 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C4914A6A14367FE0AD5D8D96EBE9E897 /* Security.framework */; }; + 683D4409569BB94EA3E3CA4B20630763 /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6DD298F4EF2F68C4B172982286D20D49 /* ImageIO.framework */; }; + 6CE4DF1BA8D682EAD12D408B9A99D22B /* UIButton+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 278C3C4D41C55149CCACB1008E430769 /* UIButton+AFNetworking.h */; }; + 751C7CA61D9FD97DF80431FC9050736F /* UIButton+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 442BD5A86D7383D426EA6C87AB86FA93 /* UIButton+WebCache.h */; }; + 75D7CEA58A5F72C5F13499A11A573EEA /* SDWebImage-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 36868875BC2FD7CD9ACA53E772A68147 /* SDWebImage-dummy.m */; }; + 79EFE75D68BB8F1E5912975F0226FEAA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1F8E9476ED04F42C4A300AC441C4BA61 /* Foundation.framework */; }; + 7B7B08A7674E6BA6D944221CE54A5CC8 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = D847D29206D0386DB9511D8A10EA6C6B /* AFNetworkReachabilityManager.m */; }; + 7F47EBDA28826BDBD28A502091E9D9FD /* SDWebImagePrefetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 2D283561CA0E408531C1CA0651571381 /* SDWebImagePrefetcher.h */; }; + 87B4BB3DF2B7E9B23BA15E1C48ECF4C1 /* NYAlertView.m in Sources */ = {isa = PBXBuildFile; fileRef = DA484305CC55E6023B26168B34B29E80 /* NYAlertView.m */; }; + 88E73B996D8355E9622B66AD1BCCB168 /* NSData+ImageContentType.m in Sources */ = {isa = PBXBuildFile; fileRef = 085ECBDDE362422A1BFD1DBE30FDB4F4 /* NSData+ImageContentType.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 898D8603930620AE3DE89A892967A505 /* SDImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 663FC8B8350D10A667A2FAF5EF29708C /* SDImageCache.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 8E2FB7E9C0E281CB50DC27109A037F19 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EBB00ABE6793A8BA390D41F722E7BFAD /* CoreGraphics.framework */; }; + 8E7D30513DB85E64E5210E25874C3D7D /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 71873DEA8728D4CE65CD02D0EE27C8F1 /* AFURLResponseSerialization.m */; }; + 90144EA34E633F7A8746D9C8BF0FF942 /* SDWebImageDownloaderOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 15D66C1B89B8779333C904B6E1F0FE50 /* SDWebImageDownloaderOperation.h */; }; + A2222CEDD905A2D387F4A9C3895A093B /* UIImage+GIF.m in Sources */ = {isa = PBXBuildFile; fileRef = 0C8BE0864137B3554F8C368D6F6EA646 /* UIImage+GIF.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + A3714795336AD70099768DDC0686F2FD /* Pods-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F2487D779A2B559DD2CB8D3CDD078CF5 /* Pods-dummy.m */; }; + A50AAA485C2E7E64D864EC5A0F4B5032 /* NYAlertViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 20CA316898A3FB8082C5A8D736B96FB5 /* NYAlertViewController.m */; }; + A6EC3E1CCB6DC24720F3D5902677421E /* SDWebImageCompat.h in Headers */ = {isa = PBXBuildFile; fileRef = 3CC3A4489FFEE078645C51D22848F697 /* SDWebImageCompat.h */; }; + A773D58B6468B559F2DAB70F8C57F985 /* SDWebImagePrefetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 21426DB0E26F4458B2B8E531ED929344 /* SDWebImagePrefetcher.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + AD22FBED3B2F3B5E300F4631FF325B0D /* SDImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 20C7708C9D92468D5D2DD3A56794B5F4 /* SDImageCache.h */; }; + ADE543DADABDAF0E7042CE7C69E16314 /* AFHTTPRequestOperationManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 636A356365AB2A0E42C7E0F42CEEEC15 /* AFHTTPRequestOperationManager.h */; }; + B108EF8640D45C3EC1F32CD7AC6DE75E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1F8E9476ED04F42C4A300AC441C4BA61 /* Foundation.framework */; }; + B582255BBD15BBF55C175C155FD38B75 /* UIRefreshControl+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 889C670A725A9F0C73B1032EE9AECC6B /* UIRefreshControl+AFNetworking.m */; }; + B6B8284F9C67767924DBCEB872ADD98C /* UIImageView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = AF32485DD93F0C5CD58EBCAA221BE880 /* UIImageView+AFNetworking.h */; }; + B8C413DC48A7DEF086868AC71F65BBAB /* NYAlertView.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F5F4F3131F68C69FBC25C552430EFFF /* NYAlertView.h */; }; + B993CFD0AF84F68D9693CE14D79B03C1 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 57EADFFAFC0AF13BE1963BC811D7F614 /* SystemConfiguration.framework */; }; + B9B24F1882156B9384823BC873391481 /* UIView+WebCacheOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 605FCA5E9AB5C444FED020AAB684D140 /* UIView+WebCacheOperation.h */; }; + BA464CC4D641DE0D23A49134F647DDFA /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = B50E4A30C3F8E0BE6E7046D46C5AC681 /* AFNetworking.h */; }; + BE46203C079336AF0A061926125805E4 /* UIWebView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 6058CB0E176A6F551F4D9CE19C4B37BA /* UIWebView+AFNetworking.m */; }; + C1185E296305793C5FC452BA59752A99 /* SDWebImageDownloaderOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = B3D5ADC47369DCB41D20305EB6B00EFA /* SDWebImageDownloaderOperation.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + C32516863188EAD0CB8D27A796372599 /* UIImage+GIF.h in Headers */ = {isa = PBXBuildFile; fileRef = 7E1763D689FFF87A52680D3FDBBCCA2F /* UIImage+GIF.h */; }; + C5B15152E2C1B98CE74480AD8E89DFDB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1F8E9476ED04F42C4A300AC441C4BA61 /* Foundation.framework */; }; + C71242AF29419BBBD08BFAEA4103B469 /* UIKit+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 89FD993FFDD6B127B3DB8010826CF430 /* UIKit+AFNetworking.h */; }; + CF8333B5FEC0C76FD7155FE88D951248 /* SDWebImageDecoder.h in Headers */ = {isa = PBXBuildFile; fileRef = FF3208FF08E5445EB9E5049F4C5D94F3 /* SDWebImageDecoder.h */; }; + D0DE08E35DE68AE2022541987BB9BBEA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1F8E9476ED04F42C4A300AC441C4BA61 /* Foundation.framework */; }; + D509B183BE1CE715C9E1D1C076F9026B /* AFHTTPRequestOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 0E531B9ED5860EC2969E75C2E2AB310B /* AFHTTPRequestOperation.h */; }; + DB1AB0C71B6ECBB52075318411CE1C99 /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = AFB26FDDE937D9EDAEA4D34D6F5EFBAD /* AFHTTPRequestOperation.m */; }; + E042F3EE15E5D06B958372257805F086 /* SDWebImageOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 1693790C9228360FA63950C2D796CFA5 /* SDWebImageOperation.h */; }; + E1B5270AD698BC12B619C2137E7761A8 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 8E65F1E4C0F1469B1BACB5D670E462BA /* AFNetworkReachabilityManager.h */; }; + E5F579FD22DFF406C43B92D0D4AA6F9E /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 3FFBC1A539FFDADA618F2D842DEB387D /* UIImageView+AFNetworking.m */; }; + EA3ACF4C310FD302FA28DC25D1167E0E /* UIImage+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 73C432714708D518989D6FC3F3831DFF /* UIImage+AFNetworking.h */; }; + EA79558D4B5E06786390BC4025991B9C /* UIRefreshControl+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 3B2DFCC215E78405680F3D21C12472E1 /* UIRefreshControl+AFNetworking.h */; }; + ED863D8E870137C432E0EFC25D08ED1E /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = AD925EEFC6EA5A6770A726D4EAFF05DF /* AFNetworkActivityIndicatorManager.m */; }; + EEC70F07E66D6E0AB32E3E8337165EFD /* UIImage+MultiFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = 7BFEE3E0C36A901C0D63CDBB8F8D490A /* UIImage+MultiFormat.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + EF2E5E9490743E84AEAD0DDCD300CF54 /* UIImageView+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 572E9757319756864DBF2880DCA92575 /* UIImageView+WebCache.h */; }; + EF9BDB9AFD7DE71960BC3A091A2C07D7 /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = C4235F32FC1E18598C8D2A8CAB18771D /* UIProgressView+AFNetworking.m */; }; + F4FDFA5A83BE4F0B473F228F6AC2C726 /* SDWebImageCompat.m in Sources */ = {isa = PBXBuildFile; fileRef = FE98519651ECB3ECA5C602AD82864FE1 /* SDWebImageCompat.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + F5A90929C28AD61047AE624020F34AD0 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = B66BC208170D52DFFD724B271C68CDEA /* AFHTTPSessionManager.h */; }; + F61F9179C69A344B8E8F4598FF69EACE /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 018F4F2B97A6685986FCC094823237BF /* AFHTTPSessionManager.m */; }; + FA70901765C550140E52F2D902EAA43F /* MobileCoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D81FAB9EC5C61111BC93E4EEFD8F1DFF /* MobileCoreServices.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 0B98213BBDE07917DB2566F430A82CEB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 5352D432641F0656C90741034E32F31E; + remoteInfo = SDWebImage; + }; + 11DFD29AF839621EBB274A111FD9D05A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7BE95AC9A0BBFBBEAF499287B01419ED; + remoteInfo = NYAlertViewController; + }; + 2834EF72D0E317B599EEDFBAC680A1A9 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = A8702230BA3973B5265272B9669A2D8C; + remoteInfo = AFNetworking; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0043492EF714E43F1E38FCB4EB0095CD /* SDWebImage-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SDWebImage-prefix.pch"; sourceTree = ""; }; + 018F4F2B97A6685986FCC094823237BF /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFHTTPSessionManager.m; path = AFNetworking/AFHTTPSessionManager.m; sourceTree = ""; }; + 022415DF81EFE56B71B50DF0E4E96E35 /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLConnectionOperation.m; path = AFNetworking/AFURLConnectionOperation.m; sourceTree = ""; }; + 050ECC314D311A3FD6C92CC38F025940 /* AFNetworking-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AFNetworking-prefix.pch"; sourceTree = ""; }; + 085ECBDDE362422A1BFD1DBE30FDB4F4 /* NSData+ImageContentType.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSData+ImageContentType.m"; path = "SDWebImage/NSData+ImageContentType.m"; sourceTree = ""; }; + 0A4CBD847C7592FEDD98FD05AA4C6B16 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Pods.debug.xcconfig; sourceTree = ""; }; + 0C8BE0864137B3554F8C368D6F6EA646 /* UIImage+GIF.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+GIF.m"; path = "SDWebImage/UIImage+GIF.m"; sourceTree = ""; }; + 0E531B9ED5860EC2969E75C2E2AB310B /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFHTTPRequestOperation.h; path = AFNetworking/AFHTTPRequestOperation.h; sourceTree = ""; }; + 15A529C27057E4A57D259CBC6E6CE49C /* Pods-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-acknowledgements.markdown"; sourceTree = ""; }; + 15D66C1B89B8779333C904B6E1F0FE50 /* SDWebImageDownloaderOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloaderOperation.h; path = SDWebImage/SDWebImageDownloaderOperation.h; sourceTree = ""; }; + 1693790C9228360FA63950C2D796CFA5 /* SDWebImageOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageOperation.h; path = SDWebImage/SDWebImageOperation.h; sourceTree = ""; }; + 1F5F4F3131F68C69FBC25C552430EFFF /* NYAlertView.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = NYAlertView.h; path = NYAlertViewController/NYAlertView.h; sourceTree = ""; }; + 1F8E9476ED04F42C4A300AC441C4BA61 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 20C7708C9D92468D5D2DD3A56794B5F4 /* SDImageCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCache.h; path = SDWebImage/SDImageCache.h; sourceTree = ""; }; + 20CA316898A3FB8082C5A8D736B96FB5 /* NYAlertViewController.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = NYAlertViewController.m; path = NYAlertViewController/NYAlertViewController.m; sourceTree = ""; }; + 21426DB0E26F4458B2B8E531ED929344 /* SDWebImagePrefetcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImagePrefetcher.m; path = SDWebImage/SDWebImagePrefetcher.m; sourceTree = ""; }; + 22518513C47F74739B8E0153F9F32396 /* AFSecurityPolicy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFSecurityPolicy.m; path = AFNetworking/AFSecurityPolicy.m; sourceTree = ""; }; + 278C3C4D41C55149CCACB1008E430769 /* UIButton+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIButton+AFNetworking.h"; path = "UIKit+AFNetworking/UIButton+AFNetworking.h"; sourceTree = ""; }; + 28DD88CAD3F7ABCDF21B1416A5B9C07A /* SDWebImage-Private.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "SDWebImage-Private.xcconfig"; sourceTree = ""; }; + 2D283561CA0E408531C1CA0651571381 /* SDWebImagePrefetcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImagePrefetcher.h; path = SDWebImage/SDWebImagePrefetcher.h; sourceTree = ""; }; + 2E2A1080BBAE688641B6BDB86CFB654E /* AFNetworking-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "AFNetworking-dummy.m"; sourceTree = ""; }; + 36868875BC2FD7CD9ACA53E772A68147 /* SDWebImage-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SDWebImage-dummy.m"; sourceTree = ""; }; + 3B2DFCC215E78405680F3D21C12472E1 /* UIRefreshControl+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIRefreshControl+AFNetworking.h"; path = "UIKit+AFNetworking/UIRefreshControl+AFNetworking.h"; sourceTree = ""; }; + 3B8B4246C7CAE1F0FE71B129F803250D /* UIWebView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIWebView+AFNetworking.h"; path = "UIKit+AFNetworking/UIWebView+AFNetworking.h"; sourceTree = ""; }; + 3CC3A4489FFEE078645C51D22848F697 /* SDWebImageCompat.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageCompat.h; path = SDWebImage/SDWebImageCompat.h; sourceTree = ""; }; + 3FFBC1A539FFDADA618F2D842DEB387D /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+AFNetworking.m"; path = "UIKit+AFNetworking/UIImageView+AFNetworking.m"; sourceTree = ""; }; + 407FD4DC1C2CE17EC4417C5574B46829 /* UIActivityIndicatorView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIActivityIndicatorView+AFNetworking.m"; path = "UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m"; sourceTree = ""; }; + 4310B691A187384B36CFCD234D2A8A73 /* AFNetworking.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = AFNetworking.xcconfig; sourceTree = ""; }; + 442BD5A86D7383D426EA6C87AB86FA93 /* UIButton+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIButton+WebCache.h"; path = "SDWebImage/UIButton+WebCache.h"; sourceTree = ""; }; + 44E19C4AEA9338236A9FD2DDA753E214 /* UIView+WebCacheOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+WebCacheOperation.m"; path = "SDWebImage/UIView+WebCacheOperation.m"; sourceTree = ""; }; + 47ADC8DE17CF04F44DAFBAC239E8C3CB /* NYAlertViewController.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = NYAlertViewController.h; path = NYAlertViewController/NYAlertViewController.h; sourceTree = ""; }; + 4C4C8A6792D4A925F9D3ABA38CB9537E /* SDWebImageManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageManager.m; path = SDWebImage/SDWebImageManager.m; sourceTree = ""; }; + 4F900AA39E79748B500B33D5C53E3EC1 /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLConnectionOperation.h; path = AFNetworking/AFURLConnectionOperation.h; sourceTree = ""; }; + 5099BC8D81DEDA973F9FF97BE55354BB /* UIButton+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIButton+WebCache.m"; path = "SDWebImage/UIButton+WebCache.m"; sourceTree = ""; }; + 52C06B2128A7E67B9FCFE0D3BBF8D68D /* AFNetworking-Private.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "AFNetworking-Private.xcconfig"; sourceTree = ""; }; + 565D0DE3F083F3D803EE8CA97CDAECC5 /* SDWebImageDownloader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloader.h; path = SDWebImage/SDWebImageDownloader.h; sourceTree = ""; }; + 572E9757319756864DBF2880DCA92575 /* UIImageView+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImageView+WebCache.h"; path = "SDWebImage/UIImageView+WebCache.h"; sourceTree = ""; }; + 57EADFFAFC0AF13BE1963BC811D7F614 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/SystemConfiguration.framework; sourceTree = DEVELOPER_DIR; }; + 59844B7182D752CD65158163227EB4A2 /* NYAlertViewController-Private.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "NYAlertViewController-Private.xcconfig"; sourceTree = ""; }; + 5D114FE662125F202F70F0A8E8A5A3D2 /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLRequestSerialization.h; path = AFNetworking/AFURLRequestSerialization.h; sourceTree = ""; }; + 5ECFB2161C220584CD4F649E8EAE3896 /* SDWebImageManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageManager.h; path = SDWebImage/SDWebImageManager.h; sourceTree = ""; }; + 6058CB0E176A6F551F4D9CE19C4B37BA /* UIWebView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIWebView+AFNetworking.m"; path = "UIKit+AFNetworking/UIWebView+AFNetworking.m"; sourceTree = ""; }; + 605FCA5E9AB5C444FED020AAB684D140 /* UIView+WebCacheOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+WebCacheOperation.h"; path = "SDWebImage/UIView+WebCacheOperation.h"; sourceTree = ""; }; + 61B8C216D508A298D69717F99E9B4C75 /* UIButton+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIButton+AFNetworking.m"; path = "UIKit+AFNetworking/UIButton+AFNetworking.m"; sourceTree = ""; }; + 636A356365AB2A0E42C7E0F42CEEEC15 /* AFHTTPRequestOperationManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFHTTPRequestOperationManager.h; path = AFNetworking/AFHTTPRequestOperationManager.h; sourceTree = ""; }; + 641AE05DD55E5E6AC1590CD7B4A18F97 /* Pods-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-resources.sh"; sourceTree = ""; }; + 6437C050025F1A8C69647B6744A18170 /* UIImage+MultiFormat.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+MultiFormat.h"; path = "SDWebImage/UIImage+MultiFormat.h"; sourceTree = ""; }; + 663FC8B8350D10A667A2FAF5EF29708C /* SDImageCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCache.m; path = SDWebImage/SDImageCache.m; sourceTree = ""; }; + 6DD298F4EF2F68C4B172982286D20D49 /* ImageIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ImageIO.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/ImageIO.framework; sourceTree = DEVELOPER_DIR; }; + 71873DEA8728D4CE65CD02D0EE27C8F1 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLResponseSerialization.m; path = AFNetworking/AFURLResponseSerialization.m; sourceTree = ""; }; + 73C432714708D518989D6FC3F3831DFF /* UIImage+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+AFNetworking.h"; path = "UIKit+AFNetworking/UIImage+AFNetworking.h"; sourceTree = ""; }; + 76C518201A486FCF7036C9F9DDBD593D /* NSData+ImageContentType.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSData+ImageContentType.h"; path = "SDWebImage/NSData+ImageContentType.h"; sourceTree = ""; }; + 77403F766765C11768746EAC15E59A2F /* AFURLSessionManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLSessionManager.m; path = AFNetworking/AFURLSessionManager.m; sourceTree = ""; }; + 7BFEE3E0C36A901C0D63CDBB8F8D490A /* UIImage+MultiFormat.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+MultiFormat.m"; path = "SDWebImage/UIImage+MultiFormat.m"; sourceTree = ""; }; + 7E1763D689FFF87A52680D3FDBBCCA2F /* UIImage+GIF.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+GIF.h"; path = "SDWebImage/UIImage+GIF.h"; sourceTree = ""; }; + 83F8CEA8D6C3D34590016ED7FF78B90C /* SDWebImageDownloader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloader.m; path = SDWebImage/SDWebImageDownloader.m; sourceTree = ""; }; + 8873A06EBFEB9354947DE52D4836C630 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFNetworkActivityIndicatorManager.h; path = "UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h"; sourceTree = ""; }; + 889C670A725A9F0C73B1032EE9AECC6B /* UIRefreshControl+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIRefreshControl+AFNetworking.m"; path = "UIKit+AFNetworking/UIRefreshControl+AFNetworking.m"; sourceTree = ""; }; + 89FD993FFDD6B127B3DB8010826CF430 /* UIKit+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIKit+AFNetworking.h"; path = "UIKit+AFNetworking/UIKit+AFNetworking.h"; sourceTree = ""; }; + 8C459D934F0E408252B506634C3E837E /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLResponseSerialization.h; path = AFNetworking/AFURLResponseSerialization.h; sourceTree = ""; }; + 8D1CC15A0216C2B8BF2CD8DF2E67F949 /* UIProgressView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIProgressView+AFNetworking.h"; path = "UIKit+AFNetworking/UIProgressView+AFNetworking.h"; sourceTree = ""; }; + 8E65F1E4C0F1469B1BACB5D670E462BA /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFNetworkReachabilityManager.h; path = AFNetworking/AFNetworkReachabilityManager.h; sourceTree = ""; }; + 97761F18069D216587219465D7CB7581 /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Pods.release.xcconfig; sourceTree = ""; }; + 9D7043956F7579B76AEA08E03AEE888A /* UIAlertView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIAlertView+AFNetworking.m"; path = "UIKit+AFNetworking/UIAlertView+AFNetworking.m"; sourceTree = ""; }; + A4438A7C149BB67DBDBA981970536138 /* NYAlertViewController-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "NYAlertViewController-dummy.m"; sourceTree = ""; }; + A4AD22B555291336B7E6CF92B2FBFCFA /* libNYAlertViewController.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libNYAlertViewController.a; sourceTree = BUILT_PRODUCTS_DIR; }; + A4E3C75131DB73B535BA7338F6201845 /* libSDWebImage.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libSDWebImage.a; sourceTree = BUILT_PRODUCTS_DIR; }; + AD10C755EDA3ACD4B1FFAA8B4F2ED718 /* AFHTTPRequestOperationManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperationManager.m; path = AFNetworking/AFHTTPRequestOperationManager.m; sourceTree = ""; }; + AD925EEFC6EA5A6770A726D4EAFF05DF /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFNetworkActivityIndicatorManager.m; path = "UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m"; sourceTree = ""; }; + AE6083A201A171D2E5A03F1EA3D5E1CB /* UIActivityIndicatorView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIActivityIndicatorView+AFNetworking.h"; path = "UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h"; sourceTree = ""; }; + AF32485DD93F0C5CD58EBCAA221BE880 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImageView+AFNetworking.h"; path = "UIKit+AFNetworking/UIImageView+AFNetworking.h"; sourceTree = ""; }; + AFB26FDDE937D9EDAEA4D34D6F5EFBAD /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = AFNetworking/AFHTTPRequestOperation.m; sourceTree = ""; }; + B371E0617A7484991F35CA4233E4F5AF /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLRequestSerialization.m; path = AFNetworking/AFURLRequestSerialization.m; sourceTree = ""; }; + B3D5ADC47369DCB41D20305EB6B00EFA /* SDWebImageDownloaderOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloaderOperation.m; path = SDWebImage/SDWebImageDownloaderOperation.m; sourceTree = ""; }; + B50E4A30C3F8E0BE6E7046D46C5AC681 /* AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = AFNetworking/AFNetworking.h; sourceTree = ""; }; + B66BC208170D52DFFD724B271C68CDEA /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFHTTPSessionManager.h; path = AFNetworking/AFHTTPSessionManager.h; sourceTree = ""; }; + BA6428E9F66FD5A23C0A2E06ED26CD2F /* Podfile */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + BF59BC15D23E1E1912C8F334E7236813 /* Pods-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-acknowledgements.plist"; sourceTree = ""; }; + C2847D2C594C3389AD7F9E91BE1DE8CB /* SDWebImage.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SDWebImage.xcconfig; sourceTree = ""; }; + C4235F32FC1E18598C8D2A8CAB18771D /* UIProgressView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIProgressView+AFNetworking.m"; path = "UIKit+AFNetworking/UIProgressView+AFNetworking.m"; sourceTree = ""; }; + C4914A6A14367FE0AD5D8D96EBE9E897 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; }; + CD010680C85F788B911EEFD181CE0508 /* libAFNetworking.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libAFNetworking.a; sourceTree = BUILT_PRODUCTS_DIR; }; + D079C4882B21742AD113F3E6CCEB26A5 /* AFSecurityPolicy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFSecurityPolicy.h; path = AFNetworking/AFSecurityPolicy.h; sourceTree = ""; }; + D650338A44A806BF5ADF792DE4CAE859 /* NYAlertViewController-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "NYAlertViewController-prefix.pch"; sourceTree = ""; }; + D81FAB9EC5C61111BC93E4EEFD8F1DFF /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/MobileCoreServices.framework; sourceTree = DEVELOPER_DIR; }; + D847D29206D0386DB9511D8A10EA6C6B /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFNetworkReachabilityManager.m; path = AFNetworking/AFNetworkReachabilityManager.m; sourceTree = ""; }; + D8DD99E890B5B9C7A22168DCDFF7F2F2 /* UIImageView+HighlightedWebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImageView+HighlightedWebCache.h"; path = "SDWebImage/UIImageView+HighlightedWebCache.h"; sourceTree = ""; }; + DA484305CC55E6023B26168B34B29E80 /* NYAlertView.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = NYAlertView.m; path = NYAlertViewController/NYAlertView.m; sourceTree = ""; }; + E1EFD1D330A4BC70F1C4C2ED395E2258 /* UIImageView+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+WebCache.m"; path = "SDWebImage/UIImageView+WebCache.m"; sourceTree = ""; }; + E68EA0F40602611C543FB22314DD5558 /* UIAlertView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIAlertView+AFNetworking.h"; path = "UIKit+AFNetworking/UIAlertView+AFNetworking.h"; sourceTree = ""; }; + E7B5566E66AC64253CA228C460AE2931 /* UIImageView+HighlightedWebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+HighlightedWebCache.m"; path = "SDWebImage/UIImageView+HighlightedWebCache.m"; sourceTree = ""; }; + EBB00ABE6793A8BA390D41F722E7BFAD /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/CoreGraphics.framework; sourceTree = DEVELOPER_DIR; }; + F2485F442C1BFC22A4DFA066BC82D878 /* NYAlertViewController.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = NYAlertViewController.xcconfig; sourceTree = ""; }; + F2487D779A2B559DD2CB8D3CDD078CF5 /* Pods-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-dummy.m"; sourceTree = ""; }; + F3490D34871627C40E25F470C5D69B6C /* AFURLSessionManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLSessionManager.h; path = AFNetworking/AFURLSessionManager.h; sourceTree = ""; }; + F6810D818545BACFD21ACAB72D23DC72 /* SDWebImageDecoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDecoder.m; path = SDWebImage/SDWebImageDecoder.m; sourceTree = ""; }; + FD7F9C592A1A3AFD5A10039A10CD8936 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; + FE98519651ECB3ECA5C602AD82864FE1 /* SDWebImageCompat.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageCompat.m; path = SDWebImage/SDWebImageCompat.m; sourceTree = ""; }; + FF3208FF08E5445EB9E5049F4C5D94F3 /* SDWebImageDecoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDecoder.h; path = SDWebImage/SDWebImageDecoder.h; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 212E3A8E9F17F74C6FBF57FE0D761B5D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8E2FB7E9C0E281CB50DC27109A037F19 /* CoreGraphics.framework in Frameworks */, + D0DE08E35DE68AE2022541987BB9BBEA /* Foundation.framework in Frameworks */, + FA70901765C550140E52F2D902EAA43F /* MobileCoreServices.framework in Frameworks */, + 65BBBBABB663C3125ED20242E8D17281 /* Security.framework in Frameworks */, + B993CFD0AF84F68D9693CE14D79B03C1 /* SystemConfiguration.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6483CA59DE76B7505AC83F07E09B7794 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + B108EF8640D45C3EC1F32CD7AC6DE75E /* Foundation.framework in Frameworks */, + 683D4409569BB94EA3E3CA4B20630763 /* ImageIO.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 68AD976126A3DB9413DFB3E3AE18328E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C5B15152E2C1B98CE74480AD8E89DFDB /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E639F79C79CD5379B7AF3D4A8CECBC9F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 79EFE75D68BB8F1E5912975F0226FEAA /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0F75DF6C7C5F002280EC53F48E80B587 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 999792CF8282488E81EFA3F843572F37 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 226D2C3791EE3D31AEAC5E68A3B2B02F /* Pods */ = { + isa = PBXGroup; + children = ( + 422DD58C87C9A2F9A78EC228DDC39C9E /* AFNetworking */, + 87BBAD54FC4CD8FE6C8883E7B4068C45 /* NYAlertViewController */, + B8283A9132057E6B2B86A24F9D7FD3A8 /* SDWebImage */, + ); + name = Pods; + sourceTree = ""; + }; + 2770CA5BA7589328F83EB0D955B5A03C /* Support Files */ = { + isa = PBXGroup; + children = ( + C2847D2C594C3389AD7F9E91BE1DE8CB /* SDWebImage.xcconfig */, + 28DD88CAD3F7ABCDF21B1416A5B9C07A /* SDWebImage-Private.xcconfig */, + 36868875BC2FD7CD9ACA53E772A68147 /* SDWebImage-dummy.m */, + 0043492EF714E43F1E38FCB4EB0095CD /* SDWebImage-prefix.pch */, + ); + name = "Support Files"; + path = "../Target Support Files/SDWebImage"; + sourceTree = ""; + }; + 2E40BBBAE93E3C1ED6330B7EB75E0F64 /* Reachability */ = { + isa = PBXGroup; + children = ( + 8E65F1E4C0F1469B1BACB5D670E462BA /* AFNetworkReachabilityManager.h */, + D847D29206D0386DB9511D8A10EA6C6B /* AFNetworkReachabilityManager.m */, + ); + name = Reachability; + sourceTree = ""; + }; + 2E5CC126B8417901A2D91CD01001F30E /* NSURLConnection */ = { + isa = PBXGroup; + children = ( + 0E531B9ED5860EC2969E75C2E2AB310B /* AFHTTPRequestOperation.h */, + AFB26FDDE937D9EDAEA4D34D6F5EFBAD /* AFHTTPRequestOperation.m */, + 636A356365AB2A0E42C7E0F42CEEEC15 /* AFHTTPRequestOperationManager.h */, + AD10C755EDA3ACD4B1FFAA8B4F2ED718 /* AFHTTPRequestOperationManager.m */, + 4F900AA39E79748B500B33D5C53E3EC1 /* AFURLConnectionOperation.h */, + 022415DF81EFE56B71B50DF0E4E96E35 /* AFURLConnectionOperation.m */, + ); + name = NSURLConnection; + sourceTree = ""; + }; + 358851D4CE86710B944F54D95940FA0D /* NSURLSession */ = { + isa = PBXGroup; + children = ( + B66BC208170D52DFFD724B271C68CDEA /* AFHTTPSessionManager.h */, + 018F4F2B97A6685986FCC094823237BF /* AFHTTPSessionManager.m */, + F3490D34871627C40E25F470C5D69B6C /* AFURLSessionManager.h */, + 77403F766765C11768746EAC15E59A2F /* AFURLSessionManager.m */, + ); + name = NSURLSession; + sourceTree = ""; + }; + 422DD58C87C9A2F9A78EC228DDC39C9E /* AFNetworking */ = { + isa = PBXGroup; + children = ( + B50E4A30C3F8E0BE6E7046D46C5AC681 /* AFNetworking.h */, + 2E5CC126B8417901A2D91CD01001F30E /* NSURLConnection */, + 358851D4CE86710B944F54D95940FA0D /* NSURLSession */, + 2E40BBBAE93E3C1ED6330B7EB75E0F64 /* Reachability */, + A224EB56E02D8146D08A0C94D8DF5548 /* Security */, + EDDBD48136CD32CAF8DB20DF1CCE6C11 /* Serialization */, + 424AA63F2018AF503A717AE67BB47371 /* Support Files */, + CFF180D17C762F808917D931689F0A1B /* UIKit */, + ); + path = AFNetworking; + sourceTree = ""; + }; + 424AA63F2018AF503A717AE67BB47371 /* Support Files */ = { + isa = PBXGroup; + children = ( + 4310B691A187384B36CFCD234D2A8A73 /* AFNetworking.xcconfig */, + 52C06B2128A7E67B9FCFE0D3BBF8D68D /* AFNetworking-Private.xcconfig */, + 2E2A1080BBAE688641B6BDB86CFB654E /* AFNetworking-dummy.m */, + 050ECC314D311A3FD6C92CC38F025940 /* AFNetworking-prefix.pch */, + ); + name = "Support Files"; + path = "../Target Support Files/AFNetworking"; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + BA6428E9F66FD5A23C0A2E06ED26CD2F /* Podfile */, + 0F75DF6C7C5F002280EC53F48E80B587 /* Frameworks */, + 226D2C3791EE3D31AEAC5E68A3B2B02F /* Pods */, + CCA510CFBEA2D207524CDA0D73C3B561 /* Products */, + D2411A5FE7F7A004607BED49990C37F4 /* Targets Support Files */, + ); + sourceTree = ""; + }; + 87BBAD54FC4CD8FE6C8883E7B4068C45 /* NYAlertViewController */ = { + isa = PBXGroup; + children = ( + 1F5F4F3131F68C69FBC25C552430EFFF /* NYAlertView.h */, + DA484305CC55E6023B26168B34B29E80 /* NYAlertView.m */, + 47ADC8DE17CF04F44DAFBAC239E8C3CB /* NYAlertViewController.h */, + 20CA316898A3FB8082C5A8D736B96FB5 /* NYAlertViewController.m */, + C6A7896E57EB56B11B8A34F5F3B63640 /* Support Files */, + ); + path = NYAlertViewController; + sourceTree = ""; + }; + 952EEBFAF8F7E620423C9F156F25A506 /* Pods */ = { + isa = PBXGroup; + children = ( + 15A529C27057E4A57D259CBC6E6CE49C /* Pods-acknowledgements.markdown */, + BF59BC15D23E1E1912C8F334E7236813 /* Pods-acknowledgements.plist */, + F2487D779A2B559DD2CB8D3CDD078CF5 /* Pods-dummy.m */, + 641AE05DD55E5E6AC1590CD7B4A18F97 /* Pods-resources.sh */, + 0A4CBD847C7592FEDD98FD05AA4C6B16 /* Pods.debug.xcconfig */, + 97761F18069D216587219465D7CB7581 /* Pods.release.xcconfig */, + ); + name = Pods; + path = "Target Support Files/Pods"; + sourceTree = ""; + }; + 999792CF8282488E81EFA3F843572F37 /* iOS */ = { + isa = PBXGroup; + children = ( + EBB00ABE6793A8BA390D41F722E7BFAD /* CoreGraphics.framework */, + 1F8E9476ED04F42C4A300AC441C4BA61 /* Foundation.framework */, + 6DD298F4EF2F68C4B172982286D20D49 /* ImageIO.framework */, + D81FAB9EC5C61111BC93E4EEFD8F1DFF /* MobileCoreServices.framework */, + C4914A6A14367FE0AD5D8D96EBE9E897 /* Security.framework */, + 57EADFFAFC0AF13BE1963BC811D7F614 /* SystemConfiguration.framework */, + ); + name = iOS; + sourceTree = ""; + }; + A224EB56E02D8146D08A0C94D8DF5548 /* Security */ = { + isa = PBXGroup; + children = ( + D079C4882B21742AD113F3E6CCEB26A5 /* AFSecurityPolicy.h */, + 22518513C47F74739B8E0153F9F32396 /* AFSecurityPolicy.m */, + ); + name = Security; + sourceTree = ""; + }; + B8283A9132057E6B2B86A24F9D7FD3A8 /* SDWebImage */ = { + isa = PBXGroup; + children = ( + E53F99AEA4184CF9A2E2B7EC84CF979C /* Core */, + 2770CA5BA7589328F83EB0D955B5A03C /* Support Files */, + ); + path = SDWebImage; + sourceTree = ""; + }; + C6A7896E57EB56B11B8A34F5F3B63640 /* Support Files */ = { + isa = PBXGroup; + children = ( + F2485F442C1BFC22A4DFA066BC82D878 /* NYAlertViewController.xcconfig */, + 59844B7182D752CD65158163227EB4A2 /* NYAlertViewController-Private.xcconfig */, + A4438A7C149BB67DBDBA981970536138 /* NYAlertViewController-dummy.m */, + D650338A44A806BF5ADF792DE4CAE859 /* NYAlertViewController-prefix.pch */, + ); + name = "Support Files"; + path = "../Target Support Files/NYAlertViewController"; + sourceTree = ""; + }; + CCA510CFBEA2D207524CDA0D73C3B561 /* Products */ = { + isa = PBXGroup; + children = ( + CD010680C85F788B911EEFD181CE0508 /* libAFNetworking.a */, + A4AD22B555291336B7E6CF92B2FBFCFA /* libNYAlertViewController.a */, + FD7F9C592A1A3AFD5A10039A10CD8936 /* libPods.a */, + A4E3C75131DB73B535BA7338F6201845 /* libSDWebImage.a */, + ); + name = Products; + sourceTree = ""; + }; + CFF180D17C762F808917D931689F0A1B /* UIKit */ = { + isa = PBXGroup; + children = ( + 8873A06EBFEB9354947DE52D4836C630 /* AFNetworkActivityIndicatorManager.h */, + AD925EEFC6EA5A6770A726D4EAFF05DF /* AFNetworkActivityIndicatorManager.m */, + AE6083A201A171D2E5A03F1EA3D5E1CB /* UIActivityIndicatorView+AFNetworking.h */, + 407FD4DC1C2CE17EC4417C5574B46829 /* UIActivityIndicatorView+AFNetworking.m */, + E68EA0F40602611C543FB22314DD5558 /* UIAlertView+AFNetworking.h */, + 9D7043956F7579B76AEA08E03AEE888A /* UIAlertView+AFNetworking.m */, + 278C3C4D41C55149CCACB1008E430769 /* UIButton+AFNetworking.h */, + 61B8C216D508A298D69717F99E9B4C75 /* UIButton+AFNetworking.m */, + 73C432714708D518989D6FC3F3831DFF /* UIImage+AFNetworking.h */, + AF32485DD93F0C5CD58EBCAA221BE880 /* UIImageView+AFNetworking.h */, + 3FFBC1A539FFDADA618F2D842DEB387D /* UIImageView+AFNetworking.m */, + 89FD993FFDD6B127B3DB8010826CF430 /* UIKit+AFNetworking.h */, + 8D1CC15A0216C2B8BF2CD8DF2E67F949 /* UIProgressView+AFNetworking.h */, + C4235F32FC1E18598C8D2A8CAB18771D /* UIProgressView+AFNetworking.m */, + 3B2DFCC215E78405680F3D21C12472E1 /* UIRefreshControl+AFNetworking.h */, + 889C670A725A9F0C73B1032EE9AECC6B /* UIRefreshControl+AFNetworking.m */, + 3B8B4246C7CAE1F0FE71B129F803250D /* UIWebView+AFNetworking.h */, + 6058CB0E176A6F551F4D9CE19C4B37BA /* UIWebView+AFNetworking.m */, + ); + name = UIKit; + sourceTree = ""; + }; + D2411A5FE7F7A004607BED49990C37F4 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 952EEBFAF8F7E620423C9F156F25A506 /* Pods */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + E53F99AEA4184CF9A2E2B7EC84CF979C /* Core */ = { + isa = PBXGroup; + children = ( + 76C518201A486FCF7036C9F9DDBD593D /* NSData+ImageContentType.h */, + 085ECBDDE362422A1BFD1DBE30FDB4F4 /* NSData+ImageContentType.m */, + 20C7708C9D92468D5D2DD3A56794B5F4 /* SDImageCache.h */, + 663FC8B8350D10A667A2FAF5EF29708C /* SDImageCache.m */, + 3CC3A4489FFEE078645C51D22848F697 /* SDWebImageCompat.h */, + FE98519651ECB3ECA5C602AD82864FE1 /* SDWebImageCompat.m */, + FF3208FF08E5445EB9E5049F4C5D94F3 /* SDWebImageDecoder.h */, + F6810D818545BACFD21ACAB72D23DC72 /* SDWebImageDecoder.m */, + 565D0DE3F083F3D803EE8CA97CDAECC5 /* SDWebImageDownloader.h */, + 83F8CEA8D6C3D34590016ED7FF78B90C /* SDWebImageDownloader.m */, + 15D66C1B89B8779333C904B6E1F0FE50 /* SDWebImageDownloaderOperation.h */, + B3D5ADC47369DCB41D20305EB6B00EFA /* SDWebImageDownloaderOperation.m */, + 5ECFB2161C220584CD4F649E8EAE3896 /* SDWebImageManager.h */, + 4C4C8A6792D4A925F9D3ABA38CB9537E /* SDWebImageManager.m */, + 1693790C9228360FA63950C2D796CFA5 /* SDWebImageOperation.h */, + 2D283561CA0E408531C1CA0651571381 /* SDWebImagePrefetcher.h */, + 21426DB0E26F4458B2B8E531ED929344 /* SDWebImagePrefetcher.m */, + 442BD5A86D7383D426EA6C87AB86FA93 /* UIButton+WebCache.h */, + 5099BC8D81DEDA973F9FF97BE55354BB /* UIButton+WebCache.m */, + 7E1763D689FFF87A52680D3FDBBCCA2F /* UIImage+GIF.h */, + 0C8BE0864137B3554F8C368D6F6EA646 /* UIImage+GIF.m */, + 6437C050025F1A8C69647B6744A18170 /* UIImage+MultiFormat.h */, + 7BFEE3E0C36A901C0D63CDBB8F8D490A /* UIImage+MultiFormat.m */, + D8DD99E890B5B9C7A22168DCDFF7F2F2 /* UIImageView+HighlightedWebCache.h */, + E7B5566E66AC64253CA228C460AE2931 /* UIImageView+HighlightedWebCache.m */, + 572E9757319756864DBF2880DCA92575 /* UIImageView+WebCache.h */, + E1EFD1D330A4BC70F1C4C2ED395E2258 /* UIImageView+WebCache.m */, + 605FCA5E9AB5C444FED020AAB684D140 /* UIView+WebCacheOperation.h */, + 44E19C4AEA9338236A9FD2DDA753E214 /* UIView+WebCacheOperation.m */, + ); + name = Core; + sourceTree = ""; + }; + EDDBD48136CD32CAF8DB20DF1CCE6C11 /* Serialization */ = { + isa = PBXGroup; + children = ( + 5D114FE662125F202F70F0A8E8A5A3D2 /* AFURLRequestSerialization.h */, + B371E0617A7484991F35CA4233E4F5AF /* AFURLRequestSerialization.m */, + 8C459D934F0E408252B506634C3E837E /* AFURLResponseSerialization.h */, + 71873DEA8728D4CE65CD02D0EE27C8F1 /* AFURLResponseSerialization.m */, + ); + name = Serialization; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 70E692A35509AA009F46AAA3DCB430E9 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 46C6D0143AB94CDD866FB320B9DB3C14 /* NSData+ImageContentType.h in Headers */, + AD22FBED3B2F3B5E300F4631FF325B0D /* SDImageCache.h in Headers */, + A6EC3E1CCB6DC24720F3D5902677421E /* SDWebImageCompat.h in Headers */, + CF8333B5FEC0C76FD7155FE88D951248 /* SDWebImageDecoder.h in Headers */, + 37A315C532DA1A156F9676951702EFB9 /* SDWebImageDownloader.h in Headers */, + 90144EA34E633F7A8746D9C8BF0FF942 /* SDWebImageDownloaderOperation.h in Headers */, + 2C6AEC70A3E09CC7BD16C30B5B941981 /* SDWebImageManager.h in Headers */, + E042F3EE15E5D06B958372257805F086 /* SDWebImageOperation.h in Headers */, + 7F47EBDA28826BDBD28A502091E9D9FD /* SDWebImagePrefetcher.h in Headers */, + 751C7CA61D9FD97DF80431FC9050736F /* UIButton+WebCache.h in Headers */, + C32516863188EAD0CB8D27A796372599 /* UIImage+GIF.h in Headers */, + 57FDB0D84B88BA790448FB0099B256FB /* UIImage+MultiFormat.h in Headers */, + 505651BE6DF50CBA5C6BE87452D20BCF /* UIImageView+HighlightedWebCache.h in Headers */, + EF2E5E9490743E84AEAD0DDCD300CF54 /* UIImageView+WebCache.h in Headers */, + B9B24F1882156B9384823BC873391481 /* UIView+WebCacheOperation.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CC9CE9F53F8327CD57AF48CD633E8825 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + D509B183BE1CE715C9E1D1C076F9026B /* AFHTTPRequestOperation.h in Headers */, + ADE543DADABDAF0E7042CE7C69E16314 /* AFHTTPRequestOperationManager.h in Headers */, + F5A90929C28AD61047AE624020F34AD0 /* AFHTTPSessionManager.h in Headers */, + 2CE385B9BE13A3F4F05D0C18B023EC7C /* AFNetworkActivityIndicatorManager.h in Headers */, + E1B5270AD698BC12B619C2137E7761A8 /* AFNetworkReachabilityManager.h in Headers */, + BA464CC4D641DE0D23A49134F647DDFA /* AFNetworking.h in Headers */, + 5AEFDEE0BC7EF4E67216E3ECB36E5172 /* AFSecurityPolicy.h in Headers */, + 35781D3A40A883148EBA38103A249B6E /* AFURLConnectionOperation.h in Headers */, + 2147A025B9D393774E96A88AEB786737 /* AFURLRequestSerialization.h in Headers */, + 233BC793712FDA19AD947B2571281AF7 /* AFURLResponseSerialization.h in Headers */, + 187C671AF0608FD0F82306F0B4A4BF49 /* AFURLSessionManager.h in Headers */, + 4DF7EB0B43E458189DC7E635994F11D6 /* UIActivityIndicatorView+AFNetworking.h in Headers */, + 231F0DF9FD70245BFF38A3ED8344845C /* UIAlertView+AFNetworking.h in Headers */, + 6CE4DF1BA8D682EAD12D408B9A99D22B /* UIButton+AFNetworking.h in Headers */, + EA3ACF4C310FD302FA28DC25D1167E0E /* UIImage+AFNetworking.h in Headers */, + B6B8284F9C67767924DBCEB872ADD98C /* UIImageView+AFNetworking.h in Headers */, + C71242AF29419BBBD08BFAEA4103B469 /* UIKit+AFNetworking.h in Headers */, + 12AD33A36144A154E0A8F9473C3B424A /* UIProgressView+AFNetworking.h in Headers */, + EA79558D4B5E06786390BC4025991B9C /* UIRefreshControl+AFNetworking.h in Headers */, + 1F13401670CBCCA1006A809F5A9821FD /* UIWebView+AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D2365E9224DDF3E8977DBE9AAFA2462F /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B8C413DC48A7DEF086868AC71F65BBAB /* NYAlertView.h in Headers */, + 49E0AD9A0C5186097C9B40E8EBDF6EB1 /* NYAlertViewController.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 5352D432641F0656C90741034E32F31E /* SDWebImage */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1C450805480F718FD16967298BD9381E /* Build configuration list for PBXNativeTarget "SDWebImage" */; + buildPhases = ( + ED4867DE87E22E526FE5CFF638C86F4D /* Sources */, + 6483CA59DE76B7505AC83F07E09B7794 /* Frameworks */, + 70E692A35509AA009F46AAA3DCB430E9 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SDWebImage; + productName = SDWebImage; + productReference = A4E3C75131DB73B535BA7338F6201845 /* libSDWebImage.a */; + productType = "com.apple.product-type.library.static"; + }; + 7BE95AC9A0BBFBBEAF499287B01419ED /* NYAlertViewController */ = { + isa = PBXNativeTarget; + buildConfigurationList = C474D983C061C1603A4E1634B94A667E /* Build configuration list for PBXNativeTarget "NYAlertViewController" */; + buildPhases = ( + FDE03C895EAEDD03D22178BDF34CA17B /* Sources */, + E639F79C79CD5379B7AF3D4A8CECBC9F /* Frameworks */, + D2365E9224DDF3E8977DBE9AAFA2462F /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = NYAlertViewController; + productName = NYAlertViewController; + productReference = A4AD22B555291336B7E6CF92B2FBFCFA /* libNYAlertViewController.a */; + productType = "com.apple.product-type.library.static"; + }; + A8702230BA3973B5265272B9669A2D8C /* AFNetworking */ = { + isa = PBXNativeTarget; + buildConfigurationList = 34363FD6AEAF495B9B2013569B3F0789 /* Build configuration list for PBXNativeTarget "AFNetworking" */; + buildPhases = ( + D1C3201BD63186FB94BF5D3CC1692BEC /* Sources */, + 212E3A8E9F17F74C6FBF57FE0D761B5D /* Frameworks */, + CC9CE9F53F8327CD57AF48CD633E8825 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = AFNetworking; + productName = AFNetworking; + productReference = CD010680C85F788B911EEFD181CE0508 /* libAFNetworking.a */; + productType = "com.apple.product-type.library.static"; + }; + DE0613D202B96865B88BC5C31312BB70 /* Pods */ = { + isa = PBXNativeTarget; + buildConfigurationList = BB870F6E11EA2CBE91B0DCCD15BBC5F9 /* Build configuration list for PBXNativeTarget "Pods" */; + buildPhases = ( + 1A5FD56B8E33F80740A5A7E181A15DB9 /* Sources */, + 68AD976126A3DB9413DFB3E3AE18328E /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 48E9B53299D53B2A22DA70F63416A31C /* PBXTargetDependency */, + 7918C71675A0D955F0E1F07F34F53435 /* PBXTargetDependency */, + 0BED8073F304916F9F7FDEF05C98FB17 /* PBXTargetDependency */, + ); + name = Pods; + productName = Pods; + productReference = FD7F9C592A1A3AFD5A10039A10CD8936 /* libPods.a */; + productType = "com.apple.product-type.library.static"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0700; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = CCA510CFBEA2D207524CDA0D73C3B561 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A8702230BA3973B5265272B9669A2D8C /* AFNetworking */, + 7BE95AC9A0BBFBBEAF499287B01419ED /* NYAlertViewController */, + DE0613D202B96865B88BC5C31312BB70 /* Pods */, + 5352D432641F0656C90741034E32F31E /* SDWebImage */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 1A5FD56B8E33F80740A5A7E181A15DB9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A3714795336AD70099768DDC0686F2FD /* Pods-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D1C3201BD63186FB94BF5D3CC1692BEC /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DB1AB0C71B6ECBB52075318411CE1C99 /* AFHTTPRequestOperation.m in Sources */, + 1E19AE540A7EFDDBAEBAA0B4E9F428A2 /* AFHTTPRequestOperationManager.m in Sources */, + F61F9179C69A344B8E8F4598FF69EACE /* AFHTTPSessionManager.m in Sources */, + ED863D8E870137C432E0EFC25D08ED1E /* AFNetworkActivityIndicatorManager.m in Sources */, + 7B7B08A7674E6BA6D944221CE54A5CC8 /* AFNetworkReachabilityManager.m in Sources */, + 01C546F4CE213CB90E63D432315942C1 /* AFNetworking-dummy.m in Sources */, + 0DD83611A99AC2915F41C777525FEF04 /* AFSecurityPolicy.m in Sources */, + 022736711E461F4DBC1F3921E940A4E9 /* AFURLConnectionOperation.m in Sources */, + 13337E2C8A2701A6ADB67F9A7A0A364B /* AFURLRequestSerialization.m in Sources */, + 8E7D30513DB85E64E5210E25874C3D7D /* AFURLResponseSerialization.m in Sources */, + 3382F4BFE650771D3DBEA429325FA80B /* AFURLSessionManager.m in Sources */, + 43277991E53710BC6A43FE41448B1437 /* UIActivityIndicatorView+AFNetworking.m in Sources */, + 26B276F6342953E80AAC247BF5CC931D /* UIAlertView+AFNetworking.m in Sources */, + 3723B6BDF682E042A291D1D9DBC61490 /* UIButton+AFNetworking.m in Sources */, + E5F579FD22DFF406C43B92D0D4AA6F9E /* UIImageView+AFNetworking.m in Sources */, + EF9BDB9AFD7DE71960BC3A091A2C07D7 /* UIProgressView+AFNetworking.m in Sources */, + B582255BBD15BBF55C175C155FD38B75 /* UIRefreshControl+AFNetworking.m in Sources */, + BE46203C079336AF0A061926125805E4 /* UIWebView+AFNetworking.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ED4867DE87E22E526FE5CFF638C86F4D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 88E73B996D8355E9622B66AD1BCCB168 /* NSData+ImageContentType.m in Sources */, + 898D8603930620AE3DE89A892967A505 /* SDImageCache.m in Sources */, + 75D7CEA58A5F72C5F13499A11A573EEA /* SDWebImage-dummy.m in Sources */, + F4FDFA5A83BE4F0B473F228F6AC2C726 /* SDWebImageCompat.m in Sources */, + 0943A4196177D34CF59C88E4AA77B576 /* SDWebImageDecoder.m in Sources */, + 18894FC9A166263E6CB1FC6EE6AD8EFF /* SDWebImageDownloader.m in Sources */, + C1185E296305793C5FC452BA59752A99 /* SDWebImageDownloaderOperation.m in Sources */, + 2358EE556EF067512DADC50B59A15D25 /* SDWebImageManager.m in Sources */, + A773D58B6468B559F2DAB70F8C57F985 /* SDWebImagePrefetcher.m in Sources */, + 26B21B244340BA5A2F45F3B43F1D4926 /* UIButton+WebCache.m in Sources */, + A2222CEDD905A2D387F4A9C3895A093B /* UIImage+GIF.m in Sources */, + EEC70F07E66D6E0AB32E3E8337165EFD /* UIImage+MultiFormat.m in Sources */, + 50151E9ABC4AC6EFCD9764698E392A3D /* UIImageView+HighlightedWebCache.m in Sources */, + 0CBFA0FDE2C98DEB97B2B0DC291F6F3F /* UIImageView+WebCache.m in Sources */, + 646A6FC808A0B280B80AD4949D8357F8 /* UIView+WebCacheOperation.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FDE03C895EAEDD03D22178BDF34CA17B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 87B4BB3DF2B7E9B23BA15E1C48ECF4C1 /* NYAlertView.m in Sources */, + 2301D7E8195C722B269F7780A28A0C38 /* NYAlertViewController-dummy.m in Sources */, + A50AAA485C2E7E64D864EC5A0F4B5032 /* NYAlertViewController.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 0BED8073F304916F9F7FDEF05C98FB17 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SDWebImage; + target = 5352D432641F0656C90741034E32F31E /* SDWebImage */; + targetProxy = 0B98213BBDE07917DB2566F430A82CEB /* PBXContainerItemProxy */; + }; + 48E9B53299D53B2A22DA70F63416A31C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = AFNetworking; + target = A8702230BA3973B5265272B9669A2D8C /* AFNetworking */; + targetProxy = 2834EF72D0E317B599EEDFBAC680A1A9 /* PBXContainerItemProxy */; + }; + 7918C71675A0D955F0E1F07F34F53435 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = NYAlertViewController; + target = 7BE95AC9A0BBFBBEAF499287B01419ED /* NYAlertViewController */; + targetProxy = 11DFD29AF839621EBB274A111FD9D05A /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 1CE0B2D926CB7F5AAB5DE1F7E73EE84D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 97761F18069D216587219465D7CB7581 /* Pods.release.xcconfig */; + buildSettings = { + ENABLE_STRICT_OBJC_MSGSEND = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Release; + }; + 34F10E5BEC581A221C8663804D6ED75C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 28DD88CAD3F7ABCDF21B1416A5B9C07A /* SDWebImage-Private.xcconfig */; + buildSettings = { + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_PREFIX_HEADER = "Target Support Files/SDWebImage/SDWebImage-prefix.pch"; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Debug; + }; + 511103F7F15A7E8F83B268EA03462CAB /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = "RELEASE=1"; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 617F2ABDE6AFE79806737CA93DEEDA60 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 59844B7182D752CD65158163227EB4A2 /* NYAlertViewController-Private.xcconfig */; + buildSettings = { + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_PREFIX_HEADER = "Target Support Files/NYAlertViewController/NYAlertViewController-prefix.pch"; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Debug; + }; + 69B413F1ACA618A0BB8527CBB37AFAD9 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 52C06B2128A7E67B9FCFE0D3BBF8D68D /* AFNetworking-Private.xcconfig */; + buildSettings = { + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_PREFIX_HEADER = "Target Support Files/AFNetworking/AFNetworking-prefix.pch"; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Debug; + }; + 92DCB26BE0782CAA15782E2808D6B79F /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 52C06B2128A7E67B9FCFE0D3BBF8D68D /* AFNetworking-Private.xcconfig */; + buildSettings = { + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_PREFIX_HEADER = "Target Support Files/AFNetworking/AFNetworking-prefix.pch"; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Release; + }; + 95CF39FA8B03203AF30AE10AD236CDBD /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 59844B7182D752CD65158163227EB4A2 /* NYAlertViewController-Private.xcconfig */; + buildSettings = { + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_PREFIX_HEADER = "Target Support Files/NYAlertViewController/NYAlertViewController-prefix.pch"; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Release; + }; + AA05AF9C3A14EE0E32F42C6E6D42D34F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + ONLY_ACTIVE_ARCH = YES; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + F196F586159A1AD411E07099FB9798E3 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0A4CBD847C7592FEDD98FD05AA4C6B16 /* Pods.debug.xcconfig */; + buildSettings = { + ENABLE_STRICT_OBJC_MSGSEND = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Debug; + }; + FDC0542C0881642B5FC49A66C5349059 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 28DD88CAD3F7ABCDF21B1416A5B9C07A /* SDWebImage-Private.xcconfig */; + buildSettings = { + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_PREFIX_HEADER = "Target Support Files/SDWebImage/SDWebImage-prefix.pch"; + IPHONEOS_DEPLOYMENT_TARGET = 8.4; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1C450805480F718FD16967298BD9381E /* Build configuration list for PBXNativeTarget "SDWebImage" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 34F10E5BEC581A221C8663804D6ED75C /* Debug */, + FDC0542C0881642B5FC49A66C5349059 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AA05AF9C3A14EE0E32F42C6E6D42D34F /* Debug */, + 511103F7F15A7E8F83B268EA03462CAB /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 34363FD6AEAF495B9B2013569B3F0789 /* Build configuration list for PBXNativeTarget "AFNetworking" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 69B413F1ACA618A0BB8527CBB37AFAD9 /* Debug */, + 92DCB26BE0782CAA15782E2808D6B79F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + BB870F6E11EA2CBE91B0DCCD15BBC5F9 /* Build configuration list for PBXNativeTarget "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F196F586159A1AD411E07099FB9798E3 /* Debug */, + 1CE0B2D926CB7F5AAB5DE1F7E73EE84D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C474D983C061C1603A4E1634B94A667E /* Build configuration list for PBXNativeTarget "NYAlertViewController" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 617F2ABDE6AFE79806737CA93DEEDA60 /* Debug */, + 95CF39FA8B03203AF30AE10AD236CDBD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/TalkinToTheNet/Pods/SDWebImage/LICENSE b/TalkinToTheNet/Pods/SDWebImage/LICENSE new file mode 100644 index 0000000..ae783e1 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009 Olivier Poitrey + +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. + diff --git a/TalkinToTheNet/Pods/SDWebImage/README.md b/TalkinToTheNet/Pods/SDWebImage/README.md new file mode 100644 index 0000000..bc47123 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/README.md @@ -0,0 +1,315 @@ +Web Image +========= +[![Build Status](http://img.shields.io/travis/rs/SDWebImage/master.svg?style=flat)](https://travis-ci.org/rs/SDWebImage) +[![Pod Version](http://img.shields.io/cocoapods/v/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) +[![Pod Platform](http://img.shields.io/cocoapods/p/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) +[![Pod License](http://img.shields.io/cocoapods/l/SDWebImage.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0.html) +[![Dependency Status](https://www.versioneye.com/objective-c/sdwebimage/3.3/badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage/3.3) +[![Reference Status](https://www.versioneye.com/objective-c/sdwebimage/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage/references) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/rs/SDWebImage) + +This library provides a category for UIImageView with support for remote images coming from the web. + +It provides: + +- An UIImageView category adding web image and cache management to the Cocoa Touch framework +- An asynchronous image downloader +- An asynchronous memory + disk image caching with automatic cache expiration handling +- Animated GIF support +- WebP format support +- A background image decompression +- A guarantee that the same URL won't be downloaded several times +- A guarantee that bogus URLs won't be retried again and again +- A guarantee that main thread will never be blocked +- Performances! +- Use GCD and ARC +- Arm64 support + +NOTE: The version 3.0 of SDWebImage isn't fully backward compatible with 2.0 and requires iOS 5.1.1 +minimum deployement version. If you need iOS < 5.0 support, please use the last [2.0 version](https://github.com/rs/SDWebImage/tree/2.0-compat). + +[How is SDWebImage better than X?](https://github.com/rs/SDWebImage/wiki/How-is-SDWebImage-better-than-X%3F) + +Who Use It +---------- + +Find out [who uses SDWebImage](https://github.com/rs/SDWebImage/wiki/Who-Uses-SDWebImage) and add your app to the list. + +How To Use +---------- + +API documentation is available at [CocoaDocs - SDWebImage](http://cocoadocs.org/docsets/SDWebImage/) + +### Using UIImageView+WebCache category with UITableView + +Just #import the UIImageView+WebCache.h header, and call the sd_setImageWithURL:placeholderImage: +method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be +handled for you, from async downloads to caching management. + +```objective-c +#import + +... + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *MyIdentifier = @"MyIdentifier"; + + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; + + if (cell == nil) + { + cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault + reuseIdentifier:MyIdentifier] autorelease]; + } + + // Here we use the new provided sd_setImageWithURL: method to load the web image + [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] + placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; + + cell.textLabel.text = @"My Text"; + return cell; +} +``` + +### Using blocks + +With blocks, you can be notified about the image download progress and whenever the image retrival +has completed with success or not: + +```objective-c +// Here we use the new provided sd_setImageWithURL: method to load the web image +[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] + placeholderImage:[UIImage imageNamed:@"placeholder.png"] + completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {... completion code here ...}]; +``` + +Note: neither your success nor failure block will be call if your image request is canceled before completion. + +### Using SDWebImageManager + +The SDWebImageManager is the class behind the UIImageView+WebCache category. It ties the +asynchronous downloader with the image cache store. You can use this class directly to benefit +from web image downloading with caching in another context than a UIView (ie: with Cocoa). + +Here is a simple example of how to use SDWebImageManager: + +```objective-c +SDWebImageManager *manager = [SDWebImageManager sharedManager]; +[manager downloadImageWithURL:imageURL + options:0 + progress:^(NSInteger receivedSize, NSInteger expectedSize) { + // progression tracking code + } + completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (image) { + // do something with image + } + }]; +``` + +### Using Asynchronous Image Downloader Independently + +It's also possible to use the async image downloader independently: + +```objective-c +[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL + options:0 + progress:^(NSInteger receivedSize, NSInteger expectedSize) + { + // progression tracking code + } + completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) + { + if (image && finished) + { + // do something with image + } + }]; +``` + +### Using Asynchronous Image Caching Independently + +It is also possible to use the async based image cache store independently. SDImageCache +maintains a memory cache and an optional disk cache. Disk cache write operations are performed +asynchronous so it doesn't add unnecessary latency to the UI. + +The SDImageCache class provides a singleton instance for convenience but you can create your own +instance if you want to create separated cache namespace. + +To lookup the cache, you use the `queryDiskCacheForKey:done:` method. If the method returns nil, it means the cache +doesn't currently own the image. You are thus responsible for generating and caching it. The cache +key is an application unique identifier for the image to cache. It is generally the absolute URL of +the image. + +```objective-c +SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"myNamespace"]; +[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image) +{ + // image is not nil if image was found +}]; +``` + +By default SDImageCache will lookup the disk cache if an image can't be found in the memory cache. +You can prevent this from happening by calling the alternative method `imageFromMemoryCacheForKey:`. + +To store an image into the cache, you use the storeImage:forKey: method: + +```objective-c +[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey]; +``` + +By default, the image will be stored in memory cache as well as on disk cache (asynchronously). If +you want only the memory cache, use the alternative method storeImage:forKey:toDisk: with a negative +third argument. + +### Using cache key filter + +Sometime, you may not want to use the image URL as cache key because part of the URL is dynamic +(i.e.: for access control purpose). SDWebImageManager provides a way to set a cache key filter that +takes the NSURL as input, and output a cache key NSString. + +The following example sets a filter in the application delegate that will remove any query-string from +the URL before to use it as a cache key: + +```objective-c +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL *url) { + url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; + return [url absoluteString]; + }; + + // Your app init code... + return YES; +} +``` + + +Common Problems +--------------- + +### Using dynamic image size with UITableViewCell + +UITableView determines the size of the image by the first image set for a cell. If your remote images +don't have the same size as your placeholder image, you may experience strange anamorphic scaling issue. +The following article gives a way to workaround this issue: + +[http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/](http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/) + + +### Handle image refresh + +SDWebImage does very aggressive caching by default. It ignores all kind of caching control header returned by the HTTP server and cache the returned images with no time restriction. It implies your images URLs are static URLs pointing to images that never change. If the pointed image happen to change, some parts of the URL should change accordingly. + +If you don't control the image server you're using, you may not be able to change the URL when its content is updated. This is the case for Facebook avatar URLs for instance. In such case, you may use the `SDWebImageRefreshCached` flag. This will slightly degrade the performance but will respect the HTTP caching control headers: + +``` objective-c +[imageView sd_setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"] + placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"] + options:SDWebImageRefreshCached]; +``` + +### Add a progress indicator + +See this category: https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage + +Installation +------------ + +There are three ways to use SDWebImage in your project: +- using Cocoapods +- copying all the files into your project +- importing the project as a static library + +### Installation with CocoaPods + +[CocoaPods](http://cocoapods.org/) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects. See the [Get Started](http://cocoapods.org/#get_started) section for more details. + +#### Podfile +``` +platform :ios, '6.1' +pod 'SDWebImage', '~>3.7' +``` + +### Installation with Carthage (iOS 8+) + +[Carthage](https://github.com/Carthage/Carthage) is a lightweight dependency manager for Swift and Objective-C. It leverages CocoaTouch modules and ins less invasive than CocoaPods. + +To install with carthage, follow the instruction on [Carthage](https://github.com/Carthage/Carthage) + +#### Cartfile +``` +github "rs/SDWebImage" +``` + +#### Usage +Swift + +``` +import WebImage + +``` + +Objective-C + +``` +@import WebImage; +``` + +### Installation by cloning the repository + +In order to gain access to all the files from the repository, you should clone it. +``` +git clone --recursive https://github.com/rs/SDWebImage.git +``` + +### Add the SDWebImage project to your project + +- Download and unzip the last version of the framework from the [download page](https://github.com/rs/SDWebImage/releases) +- Right-click on the project navigator and select "Add Files to "Your Project": +- In the dialog, select SDWebImage.framework: +- Check the "Copy items into destination group's folder (if needed)" checkbox + +### Add dependencies + +- In you application project app’s target settings, find the "Build Phases" section and open the "Link Binary With Libraries" block: +- Click the "+" button again and select the "ImageIO.framework", this is needed by the progressive download feature: + +### Add Linker Flag + +Open the "Build Settings" tab, in the "Linking" section, locate the "Other Linker Flags" setting and add the "-ObjC" flag: + +![Other Linker Flags](http://dl.dropbox.com/u/123346/SDWebImage/10_other_linker_flags.jpg) + +Alternatively, if this causes compilation problems with frameworks that extend optional libraries, such as Parse, RestKit or opencv2, instead of the -ObjC flag use: +``` +-force_load SDWebImage.framework/Versions/Current/SDWebImage +``` + +If you're using Cocoa Pods and have any frameworks that extend optional libraries, such as Parsen RestKit or opencv2, instead of the -ObjC flag use: +``` +-force_load $(TARGET_BUILD_DIR)/libPods.a +``` + +### Import headers in your source files + +In the source files where you need to use the library, import the header file: + +```objective-c +#import +``` + +### Build Project + +At this point your workspace should build without error. If you are having problem, post to the Issue and the +community can help you solve it. + +Future Enhancements +------------------- + +- LRU memory cache cleanup instead of reset on memory warning + +## Licenses + +All source code is licensed under the [MIT License](https://raw.github.com/rs/SDWebImage/master/LICENSE). diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.h new file mode 100644 index 0000000..69c76dc --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.h @@ -0,0 +1,26 @@ +// +// Created by Fabrice Aneche on 06/01/14. +// Copyright (c) 2014 Dailymotion. All rights reserved. +// + +#import + +@interface NSData (ImageContentType) + +/** + * Compute the content type for an image data + * + * @param data the input data + * + * @return the content type as string (i.e. image/jpeg, image/gif) + */ ++ (NSString *)sd_contentTypeForImageData:(NSData *)data; + +@end + + +@interface NSData (ImageContentTypeDeprecated) + ++ (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`"); + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.m new file mode 100644 index 0000000..0941cfa --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.m @@ -0,0 +1,49 @@ +// +// Created by Fabrice Aneche on 06/01/14. +// Copyright (c) 2014 Dailymotion. All rights reserved. +// + +#import "NSData+ImageContentType.h" + + +@implementation NSData (ImageContentType) + ++ (NSString *)sd_contentTypeForImageData:(NSData *)data { + uint8_t c; + [data getBytes:&c length:1]; + switch (c) { + case 0xFF: + return @"image/jpeg"; + case 0x89: + return @"image/png"; + case 0x47: + return @"image/gif"; + case 0x49: + case 0x4D: + return @"image/tiff"; + case 0x52: + // R as RIFF for WEBP + if ([data length] < 12) { + return nil; + } + + NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; + if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { + return @"image/webp"; + } + + return nil; + } + return nil; +} + +@end + + +@implementation NSData (ImageContentTypeDeprecated) + ++ (NSString *)contentTypeForImageData:(NSData *)data { + return [self sd_contentTypeForImageData:data]; +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDImageCache.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDImageCache.h new file mode 100644 index 0000000..8e08aa1 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDImageCache.h @@ -0,0 +1,262 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NS_ENUM(NSInteger, SDImageCacheType) { + /** + * The image wasn't available the SDWebImage caches, but was downloaded from the web. + */ + SDImageCacheTypeNone, + /** + * The image was obtained from the disk cache. + */ + SDImageCacheTypeDisk, + /** + * The image was obtained from the memory cache. + */ + SDImageCacheTypeMemory +}; + +typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); + +typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); + +typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); + +/** + * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed + * asynchronous so it doesn’t add unnecessary latency to the UI. + */ +@interface SDImageCache : NSObject + +/** + * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory. + * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. + */ +@property (assign, nonatomic) BOOL shouldDecompressImages; + +/** + * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. + */ +@property (assign, nonatomic) NSUInteger maxMemoryCost; + +/** + * The maximum number of objects the cache should hold. + */ +@property (assign, nonatomic) NSUInteger maxMemoryCountLimit; + +/** + * The maximum length of time to keep an image in the cache, in seconds + */ +@property (assign, nonatomic) NSInteger maxCacheAge; + +/** + * The maximum size of the cache, in bytes. + */ +@property (assign, nonatomic) NSUInteger maxCacheSize; + +/** + * Returns global shared cache instance + * + * @return SDImageCache global instance + */ ++ (SDImageCache *)sharedImageCache; + +/** + * Init a new cache store with a specific namespace + * + * @param ns The namespace to use for this cache store + */ +- (id)initWithNamespace:(NSString *)ns; + +/** + * Init a new cache store with a specific namespace and directory + * + * @param ns The namespace to use for this cache store + * @param directory Directory to cache disk images in + */ +- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory; + +-(NSString *)makeDiskCachePath:(NSString*)fullNamespace; + +/** + * Add a read-only cache path to search for images pre-cached by SDImageCache + * Useful if you want to bundle pre-loaded images with your app + * + * @param path The path to use for this read-only cache path + */ +- (void)addReadOnlyCachePath:(NSString *)path; + +/** + * Store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + */ +- (void)storeImage:(UIImage *)image forKey:(NSString *)key; + +/** + * Store an image into memory and optionally disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES + */ +- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; + +/** + * Store an image into memory and optionally disk cache at the given key. + * + * @param image The image to store + * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage + * @param imageData The image data as returned by the server, this representation will be used for disk storage + * instead of converting the given image object into a storable/compressed image format in order + * to save quality and CPU + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES + */ +- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; + +/** + * Query the disk cache asynchronously. + * + * @param key The unique key used to store the wanted image + */ +- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; + +/** + * Query the memory cache synchronously. + * + * @param key The unique key used to store the wanted image + */ +- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; + +/** + * Query the disk cache synchronously after checking the memory cache. + * + * @param key The unique key used to store the wanted image + */ +- (UIImage *)imageFromDiskCacheForKey:(NSString *)key; + +/** + * Remove the image from memory and disk cache synchronously + * + * @param key The unique image cache key + */ +- (void)removeImageForKey:(NSString *)key; + + +/** + * Remove the image from memory and disk cache asynchronously + * + * @param key The unique image cache key + * @param completion An block that should be executed after the image has been removed (optional) + */ +- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; + +/** + * Remove the image from memory and optionally disk cache asynchronously + * + * @param key The unique image cache key + * @param fromDisk Also remove cache entry from disk if YES + */ +- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; + +/** + * Remove the image from memory and optionally disk cache asynchronously + * + * @param key The unique image cache key + * @param fromDisk Also remove cache entry from disk if YES + * @param completion An block that should be executed after the image has been removed (optional) + */ +- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; + +/** + * Clear all memory cached images + */ +- (void)clearMemory; + +/** + * Clear all disk cached images. Non-blocking method - returns immediately. + * @param completion An block that should be executed after cache expiration completes (optional) + */ +- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; + +/** + * Clear all disk cached images + * @see clearDiskOnCompletion: + */ +- (void)clearDisk; + +/** + * Remove all expired cached image from disk. Non-blocking method - returns immediately. + * @param completionBlock An block that should be executed after cache expiration completes (optional) + */ +- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; + +/** + * Remove all expired cached image from disk + * @see cleanDiskWithCompletionBlock: + */ +- (void)cleanDisk; + +/** + * Get the size used by the disk cache + */ +- (NSUInteger)getSize; + +/** + * Get the number of images in the disk cache + */ +- (NSUInteger)getDiskCount; + +/** + * Asynchronously calculate the disk cache's size. + */ +- (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; + +/** + * Async check if image exists in disk cache already (does not load the image) + * + * @param key the key describing the url + * @param completionBlock the block to be executed when the check is done. + * @note the completion block will be always executed on the main queue + */ +- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; + +/** + * Check if image exists in disk cache already (does not load the image) + * + * @param key the key describing the url + * + * @return YES if an image exists for the given key + */ +- (BOOL)diskImageExistsWithKey:(NSString *)key; + +/** + * Get the cache path for a certain key (needs the cache path root folder) + * + * @param key the key (can be obtained from url using cacheKeyForURL) + * @param path the cach path root folder + * + * @return the cache path + */ +- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; + +/** + * Get the default cache path for a certain key + * + * @param key the key (can be obtained from url using cacheKeyForURL) + * + * @return the default cache path + */ +- (NSString *)defaultCachePathForKey:(NSString *)key; + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDImageCache.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDImageCache.m new file mode 100644 index 0000000..2202602 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDImageCache.m @@ -0,0 +1,601 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCache.h" +#import "SDWebImageDecoder.h" +#import "UIImage+MultiFormat.h" +#import + +// See https://github.com/rs/SDWebImage/pull/1141 for discussion +@interface AutoPurgeCache : NSCache +@end + +@implementation AutoPurgeCache + +- (id)init +{ + self = [super init]; + if (self) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; + } + return self; +} + +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; + +} + +@end + +static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week +// PNG signature bytes and data (below) +static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; +static NSData *kPNGSignatureData = nil; + +BOOL ImageDataHasPNGPreffix(NSData *data); + +BOOL ImageDataHasPNGPreffix(NSData *data) { + NSUInteger pngSignatureLength = [kPNGSignatureData length]; + if ([data length] >= pngSignatureLength) { + if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) { + return YES; + } + } + + return NO; +} + +FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) { + return image.size.height * image.size.width * image.scale * image.scale; +} + +@interface SDImageCache () + +@property (strong, nonatomic) NSCache *memCache; +@property (strong, nonatomic) NSString *diskCachePath; +@property (strong, nonatomic) NSMutableArray *customPaths; +@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue; + +@end + + +@implementation SDImageCache { + NSFileManager *_fileManager; +} + ++ (SDImageCache *)sharedImageCache { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (id)init { + return [self initWithNamespace:@"default"]; +} + +- (id)initWithNamespace:(NSString *)ns { + NSString *path = [self makeDiskCachePath:ns]; + return [self initWithNamespace:ns diskCacheDirectory:path]; +} + +- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory { + if ((self = [super init])) { + NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; + + // initialise PNG signature data + kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8]; + + // Create IO serial queue + _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); + + // Init default values + _maxCacheAge = kDefaultCacheMaxCacheAge; + + // Init the memory cache + _memCache = [[AutoPurgeCache alloc] init]; + _memCache.name = fullNamespace; + + // Init the disk cache + if (directory != nil) { + _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace]; + } else { + NSString *path = [self makeDiskCachePath:ns]; + _diskCachePath = path; + } + + // Set decompression to YES + _shouldDecompressImages = YES; + + dispatch_sync(_ioQueue, ^{ + _fileManager = [NSFileManager new]; + }); + +#if TARGET_OS_IPHONE + // Subscribe to app events + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(clearMemory) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(cleanDisk) + name:UIApplicationWillTerminateNotification + object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(backgroundCleanDisk) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; +#endif + } + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + SDDispatchQueueRelease(_ioQueue); +} + +- (void)addReadOnlyCachePath:(NSString *)path { + if (!self.customPaths) { + self.customPaths = [NSMutableArray new]; + } + + if (![self.customPaths containsObject:path]) { + [self.customPaths addObject:path]; + } +} + +- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path { + NSString *filename = [self cachedFileNameForKey:key]; + return [path stringByAppendingPathComponent:filename]; +} + +- (NSString *)defaultCachePathForKey:(NSString *)key { + return [self cachePathForKey:key inPath:self.diskCachePath]; +} + +#pragma mark SDImageCache (private) + +- (NSString *)cachedFileNameForKey:(NSString *)key { + const char *str = [key UTF8String]; + if (str == NULL) { + str = ""; + } + unsigned char r[CC_MD5_DIGEST_LENGTH]; + CC_MD5(str, (CC_LONG)strlen(str), r); + NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]]; + + return filename; +} + +#pragma mark ImageCache + +// Init the disk cache +-(NSString *)makeDiskCachePath:(NSString*)fullNamespace{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + return [paths[0] stringByAppendingPathComponent:fullNamespace]; +} + +- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk { + if (!image || !key) { + return; + } + + NSUInteger cost = SDCacheCostForImage(image); + [self.memCache setObject:image forKey:key cost:cost]; + + if (toDisk) { + dispatch_async(self.ioQueue, ^{ + NSData *data = imageData; + + if (image && (recalculate || !data)) { +#if TARGET_OS_IPHONE + // We need to determine if the image is a PNG or a JPEG + // PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html) + // The first eight bytes of a PNG file always contain the following (decimal) values: + // 137 80 78 71 13 10 26 10 + + // If the imageData is nil (i.e. if trying to save a UIImage directly or the image was transformed on download) + // and the image has an alpha channel, we will consider it PNG to avoid losing the transparency + int alphaInfo = CGImageGetAlphaInfo(image.CGImage); + BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone || + alphaInfo == kCGImageAlphaNoneSkipFirst || + alphaInfo == kCGImageAlphaNoneSkipLast); + BOOL imageIsPng = hasAlpha; + + // But if we have an image data, we will look at the preffix + if ([imageData length] >= [kPNGSignatureData length]) { + imageIsPng = ImageDataHasPNGPreffix(imageData); + } + + if (imageIsPng) { + data = UIImagePNGRepresentation(image); + } + else { + data = UIImageJPEGRepresentation(image, (CGFloat)1.0); + } +#else + data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil]; +#endif + } + + if (data) { + if (![_fileManager fileExistsAtPath:_diskCachePath]) { + [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; + } + + [_fileManager createFileAtPath:[self defaultCachePathForKey:key] contents:data attributes:nil]; + } + }); + } +} + +- (void)storeImage:(UIImage *)image forKey:(NSString *)key { + [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES]; +} + +- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk { + [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk]; +} + +- (BOOL)diskImageExistsWithKey:(NSString *)key { + BOOL exists = NO; + + // this is an exception to access the filemanager on another queue than ioQueue, but we are using the shared instance + // from apple docs on NSFileManager: The methods of the shared NSFileManager object can be called from multiple threads safely. + exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key]]; + + return exists; +} + +- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { + dispatch_async(_ioQueue, ^{ + BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]]; + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(exists); + }); + } + }); +} + +- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key { + return [self.memCache objectForKey:key]; +} + +- (UIImage *)imageFromDiskCacheForKey:(NSString *)key { + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + if (image) { + return image; + } + + // Second check the disk cache... + UIImage *diskImage = [self diskImageForKey:key]; + if (diskImage) { + NSUInteger cost = SDCacheCostForImage(diskImage); + [self.memCache setObject:diskImage forKey:key cost:cost]; + } + + return diskImage; +} + +- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key { + NSString *defaultPath = [self defaultCachePathForKey:key]; + NSData *data = [NSData dataWithContentsOfFile:defaultPath]; + if (data) { + return data; + } + + NSArray *customPaths = [self.customPaths copy]; + for (NSString *path in customPaths) { + NSString *filePath = [self cachePathForKey:key inPath:path]; + NSData *imageData = [NSData dataWithContentsOfFile:filePath]; + if (imageData) { + return imageData; + } + } + + return nil; +} + +- (UIImage *)diskImageForKey:(NSString *)key { + NSData *data = [self diskImageDataBySearchingAllPathsForKey:key]; + if (data) { + UIImage *image = [UIImage sd_imageWithData:data]; + image = [self scaledImageForKey:key image:image]; + if (self.shouldDecompressImages) { + image = [UIImage decodedImageWithImage:image]; + } + return image; + } + else { + return nil; + } +} + +- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { + return SDScaledImageForKey(key, image); +} + +- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock { + if (!doneBlock) { + return nil; + } + + if (!key) { + doneBlock(nil, SDImageCacheTypeNone); + return nil; + } + + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + if (image) { + doneBlock(image, SDImageCacheTypeMemory); + return nil; + } + + NSOperation *operation = [NSOperation new]; + dispatch_async(self.ioQueue, ^{ + if (operation.isCancelled) { + return; + } + + @autoreleasepool { + UIImage *diskImage = [self diskImageForKey:key]; + if (diskImage) { + NSUInteger cost = SDCacheCostForImage(diskImage); + [self.memCache setObject:diskImage forKey:key cost:cost]; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + doneBlock(diskImage, SDImageCacheTypeDisk); + }); + } + }); + + return operation; +} + +- (void)removeImageForKey:(NSString *)key { + [self removeImageForKey:key withCompletion:nil]; +} + +- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion { + [self removeImageForKey:key fromDisk:YES withCompletion:completion]; +} + +- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk { + [self removeImageForKey:key fromDisk:fromDisk withCompletion:nil]; +} + +- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion { + + if (key == nil) { + return; + } + + [self.memCache removeObjectForKey:key]; + + if (fromDisk) { + dispatch_async(self.ioQueue, ^{ + [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil]; + + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(); + }); + } + }); + } else if (completion){ + completion(); + } + +} + +- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost { + self.memCache.totalCostLimit = maxMemoryCost; +} + +- (NSUInteger)maxMemoryCost { + return self.memCache.totalCostLimit; +} + +- (NSUInteger)maxMemoryCountLimit { + return self.memCache.countLimit; +} + +- (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit { + self.memCache.countLimit = maxCountLimit; +} + +- (void)clearMemory { + [self.memCache removeAllObjects]; +} + +- (void)clearDisk { + [self clearDiskOnCompletion:nil]; +} + +- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion +{ + dispatch_async(self.ioQueue, ^{ + [_fileManager removeItemAtPath:self.diskCachePath error:nil]; + [_fileManager createDirectoryAtPath:self.diskCachePath + withIntermediateDirectories:YES + attributes:nil + error:NULL]; + + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(); + }); + } + }); +} + +- (void)cleanDisk { + [self cleanDiskWithCompletionBlock:nil]; +} + +- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock { + dispatch_async(self.ioQueue, ^{ + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]; + + // This enumerator prefetches useful properties for our cache files. + NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL + includingPropertiesForKeys:resourceKeys + options:NSDirectoryEnumerationSkipsHiddenFiles + errorHandler:NULL]; + + NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge]; + NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary]; + NSUInteger currentCacheSize = 0; + + // Enumerate all of the files in the cache directory. This loop has two purposes: + // + // 1. Removing files that are older than the expiration date. + // 2. Storing file attributes for the size-based cleanup pass. + NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init]; + for (NSURL *fileURL in fileEnumerator) { + NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL]; + + // Skip directories. + if ([resourceValues[NSURLIsDirectoryKey] boolValue]) { + continue; + } + + // Remove files that are older than the expiration date; + NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey]; + if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) { + [urlsToDelete addObject:fileURL]; + continue; + } + + // Store a reference to this file and account for its total size. + NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; + currentCacheSize += [totalAllocatedSize unsignedIntegerValue]; + [cacheFiles setObject:resourceValues forKey:fileURL]; + } + + for (NSURL *fileURL in urlsToDelete) { + [_fileManager removeItemAtURL:fileURL error:nil]; + } + + // If our remaining disk cache exceeds a configured maximum size, perform a second + // size-based cleanup pass. We delete the oldest files first. + if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) { + // Target half of our maximum cache size for this cleanup pass. + const NSUInteger desiredCacheSize = self.maxCacheSize / 2; + + // Sort the remaining cache files by their last modification time (oldest first). + NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent + usingComparator:^NSComparisonResult(id obj1, id obj2) { + return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]]; + }]; + + // Delete files until we fall below our desired cache size. + for (NSURL *fileURL in sortedFiles) { + if ([_fileManager removeItemAtURL:fileURL error:nil]) { + NSDictionary *resourceValues = cacheFiles[fileURL]; + NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; + currentCacheSize -= [totalAllocatedSize unsignedIntegerValue]; + + if (currentCacheSize < desiredCacheSize) { + break; + } + } + } + } + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(); + }); + } + }); +} + +- (void)backgroundCleanDisk { + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { + return; + } + UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)]; + __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ + // Clean up any unfinished task business by marking where you + // stopped or ending the task outright. + [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid; + }]; + + // Start the long-running task and return immediately. + [self cleanDiskWithCompletionBlock:^{ + [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid; + }]; +} + +- (NSUInteger)getSize { + __block NSUInteger size = 0; + dispatch_sync(self.ioQueue, ^{ + NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; + for (NSString *fileName in fileEnumerator) { + NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName]; + NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; + size += [attrs fileSize]; + } + }); + return size; +} + +- (NSUInteger)getDiskCount { + __block NSUInteger count = 0; + dispatch_sync(self.ioQueue, ^{ + NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; + count = [[fileEnumerator allObjects] count]; + }); + return count; +} + +- (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock { + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + + dispatch_async(self.ioQueue, ^{ + NSUInteger fileCount = 0; + NSUInteger totalSize = 0; + + NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL + includingPropertiesForKeys:@[NSFileSize] + options:NSDirectoryEnumerationSkipsHiddenFiles + errorHandler:NULL]; + + for (NSURL *fileURL in fileEnumerator) { + NSNumber *fileSize; + [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; + totalSize += [fileSize unsignedIntegerValue]; + fileCount += 1; + } + + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(fileCount, totalSize); + }); + } + }); +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageCompat.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageCompat.h new file mode 100644 index 0000000..9773545 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageCompat.h @@ -0,0 +1,72 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Jamie Pinkham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +#ifdef __OBJC_GC__ +#error SDWebImage does not support Objective-C Garbage Collection +#endif + +#if __IPHONE_OS_VERSION_MIN_REQUIRED != 20000 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 +#error SDWebImage doesn't support Deployement Target version < 5.0 +#endif + +#if !TARGET_OS_IPHONE +#import +#ifndef UIImage +#define UIImage NSImage +#endif +#ifndef UIImageView +#define UIImageView NSImageView +#endif +#else + +#import + +#endif + +#ifndef NS_ENUM +#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type +#endif + +#ifndef NS_OPTIONS +#define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type +#endif + +#if OS_OBJECT_USE_OBJC + #undef SDDispatchQueueRelease + #undef SDDispatchQueueSetterSementics + #define SDDispatchQueueRelease(q) + #define SDDispatchQueueSetterSementics strong +#else +#undef SDDispatchQueueRelease +#undef SDDispatchQueueSetterSementics +#define SDDispatchQueueRelease(q) (dispatch_release(q)) +#define SDDispatchQueueSetterSementics assign +#endif + +extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); + +typedef void(^SDWebImageNoParamsBlock)(); + +extern NSString *const SDWebImageErrorDomain; + +#define dispatch_main_sync_safe(block)\ + if ([NSThread isMainThread]) {\ + block();\ + } else {\ + dispatch_sync(dispatch_get_main_queue(), block);\ + } + +#define dispatch_main_async_safe(block)\ + if ([NSThread isMainThread]) {\ + block();\ + } else {\ + dispatch_async(dispatch_get_main_queue(), block);\ + } diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageCompat.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageCompat.m new file mode 100644 index 0000000..54fb60e --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageCompat.m @@ -0,0 +1,51 @@ +// +// SDWebImageCompat.m +// SDWebImage +// +// Created by Olivier Poitrey on 11/12/12. +// Copyright (c) 2012 Dailymotion. All rights reserved. +// + +#import "SDWebImageCompat.h" + +#if !__has_feature(objc_arc) +#error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag +#endif + +inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) { + if (!image) { + return nil; + } + + if ([image.images count] > 0) { + NSMutableArray *scaledImages = [NSMutableArray array]; + + for (UIImage *tempImage in image.images) { + [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; + } + + return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; + } + else { + if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { + CGFloat scale = 1.0; + if (key.length >= 8) { + NSRange range = [key rangeOfString:@"@2x."]; + if (range.location != NSNotFound) { + scale = 2.0; + } + + range = [key rangeOfString:@"@3x."]; + if (range.location != NSNotFound) { + scale = 3.0; + } + } + + UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; + image = scaledImage; + } + return image; + } +} + +NSString *const SDWebImageErrorDomain = @"SDWebImageErrorDomain"; diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.h new file mode 100644 index 0000000..0176a7b --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.h @@ -0,0 +1,18 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * Created by james on 9/28/11. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +@interface UIImage (ForceDecode) + ++ (UIImage *)decodedImageWithImage:(UIImage *)image; + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.m new file mode 100644 index 0000000..79ddb30 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.m @@ -0,0 +1,72 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * Created by james on 9/28/11. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDecoder.h" + +@implementation UIImage (ForceDecode) + ++ (UIImage *)decodedImageWithImage:(UIImage *)image { + if (image.images) { + // Do not decode animated images + return image; + } + + CGImageRef imageRef = image.CGImage; + CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); + CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; + + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); + BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || + infoMask == kCGImageAlphaNoneSkipFirst || + infoMask == kCGImageAlphaNoneSkipLast); + + // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. + // https://developer.apple.com/library/mac/#qa/qa1037/_index.html + if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { + // Unset the old alpha info. + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + + // Set noneSkipFirst. + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } + // Some PNGs tell us they have alpha but only 3 components. Odd. + else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { + // Unset the old alpha info. + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } + + // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. + CGContextRef context = CGBitmapContextCreate(NULL, + imageSize.width, + imageSize.height, + CGImageGetBitsPerComponent(imageRef), + 0, + colorSpace, + bitmapInfo); + CGColorSpaceRelease(colorSpace); + + // If failed, return undecompressed image + if (!context) return image; + + CGContextDrawImage(context, imageRect, imageRef); + CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); + + CGContextRelease(context); + + UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; + CGImageRelease(decompressedImageRef); + return decompressedImage; +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.h new file mode 100644 index 0000000..b8db86f --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.h @@ -0,0 +1,186 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" + +typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { + SDWebImageDownloaderLowPriority = 1 << 0, + SDWebImageDownloaderProgressiveDownload = 1 << 1, + + /** + * By default, request prevent the of NSURLCache. With this flag, NSURLCache + * is used with default policies. + */ + SDWebImageDownloaderUseNSURLCache = 1 << 2, + + /** + * Call completion block with nil image/imageData if the image was read from NSURLCache + * (to be combined with `SDWebImageDownloaderUseNSURLCache`). + */ + + SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, + /** + * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for + * extra time in background to let the request finish. If the background task expires the operation will be cancelled. + */ + + SDWebImageDownloaderContinueInBackground = 1 << 4, + + /** + * Handles cookies stored in NSHTTPCookieStore by setting + * NSMutableURLRequest.HTTPShouldHandleCookies = YES; + */ + SDWebImageDownloaderHandleCookies = 1 << 5, + + /** + * Enable to allow untrusted SSL ceriticates. + * Useful for testing purposes. Use with caution in production. + */ + SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, + + /** + * Put the image in the high priority queue. + */ + SDWebImageDownloaderHighPriority = 1 << 7, +}; + +typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { + /** + * Default value. All download operations will execute in queue style (first-in-first-out). + */ + SDWebImageDownloaderFIFOExecutionOrder, + + /** + * All download operations will execute in stack style (last-in-first-out). + */ + SDWebImageDownloaderLIFOExecutionOrder +}; + +extern NSString *const SDWebImageDownloadStartNotification; +extern NSString *const SDWebImageDownloadStopNotification; + +typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); + +typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); + +typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); + +/** + * Asynchronous downloader dedicated and optimized for image loading. + */ +@interface SDWebImageDownloader : NSObject + +/** + * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory. + * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. + */ +@property (assign, nonatomic) BOOL shouldDecompressImages; + +@property (assign, nonatomic) NSInteger maxConcurrentDownloads; + +/** + * Shows the current amount of downloads that still need to be downloaded + */ +@property (readonly, nonatomic) NSUInteger currentDownloadCount; + + +/** + * The timeout value (in seconds) for the download operation. Default: 15.0. + */ +@property (assign, nonatomic) NSTimeInterval downloadTimeout; + + +/** + * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. + */ +@property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; + +/** + * Singleton method, returns the shared instance + * + * @return global shared instance of downloader class + */ ++ (SDWebImageDownloader *)sharedDownloader; + +/** + * Set username + */ +@property (strong, nonatomic) NSString *username; + +/** + * Set password + */ +@property (strong, nonatomic) NSString *password; + +/** + * Set filter to pick headers for downloading image HTTP request. + * + * This block will be invoked for each downloading image request, returned + * NSDictionary will be used as headers in corresponding HTTP request. + */ +@property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; + +/** + * Set a value for a HTTP header to be appended to each download HTTP request. + * + * @param value The value for the header field. Use `nil` value to remove the header. + * @param field The name of the header field to set. + */ +- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; + +/** + * Returns the value of the specified HTTP header field. + * + * @return The value associated with the header field field, or `nil` if there is no corresponding header field. + */ +- (NSString *)valueForHTTPHeaderField:(NSString *)field; + +/** + * Sets a subclass of `SDWebImageDownloaderOperation` as the default + * `NSOperation` to be used each time SDWebImage constructs a request + * operation to download an image. + * + * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set + * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. + */ +- (void)setOperationClass:(Class)operationClass; + +/** + * Creates a SDWebImageDownloader async downloader instance with a given URL + * + * The delegate will be informed when the image is finish downloaded or an error has happen. + * + * @see SDWebImageDownloaderDelegate + * + * @param url The URL to the image to download + * @param options The options to be used for this download + * @param progressBlock A block called repeatedly while the image is downloading + * @param completedBlock A block called once the download is completed. + * If the download succeeded, the image parameter is set, in case of error, + * error parameter is set with the error. The last parameter is always YES + * if SDWebImageDownloaderProgressiveDownload isn't use. With the + * SDWebImageDownloaderProgressiveDownload option, this block is called + * repeatedly with the partial image object and the finished argument set to NO + * before to be called a last time with the full image and finished argument + * set to YES. In case of error, the finished argument is always YES. + * + * @return A cancellable SDWebImageOperation + */ +- (id )downloadImageWithURL:(NSURL *)url + options:(SDWebImageDownloaderOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Sets the download queue suspension state + */ +- (void)setSuspended:(BOOL)suspended; + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.m new file mode 100644 index 0000000..acda892 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.m @@ -0,0 +1,228 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloader.h" +#import "SDWebImageDownloaderOperation.h" +#import + +static NSString *const kProgressCallbackKey = @"progress"; +static NSString *const kCompletedCallbackKey = @"completed"; + +@interface SDWebImageDownloader () + +@property (strong, nonatomic) NSOperationQueue *downloadQueue; +@property (weak, nonatomic) NSOperation *lastAddedOperation; +@property (assign, nonatomic) Class operationClass; +@property (strong, nonatomic) NSMutableDictionary *URLCallbacks; +@property (strong, nonatomic) NSMutableDictionary *HTTPHeaders; +// This queue is used to serialize the handling of the network responses of all the download operation in a single queue +@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue; + +@end + +@implementation SDWebImageDownloader + ++ (void)initialize { + // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) + // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import + if (NSClassFromString(@"SDNetworkActivityIndicator")) { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; +#pragma clang diagnostic pop + + // Remove observer in case it was previously added. + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"startActivity") + name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"stopActivity") + name:SDWebImageDownloadStopNotification object:nil]; + } +} + ++ (SDWebImageDownloader *)sharedDownloader { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (id)init { + if ((self = [super init])) { + _operationClass = [SDWebImageDownloaderOperation class]; + _shouldDecompressImages = YES; + _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; + _downloadQueue = [NSOperationQueue new]; + _downloadQueue.maxConcurrentOperationCount = 6; + _URLCallbacks = [NSMutableDictionary new]; +#ifdef SD_WEBP + _HTTPHeaders = [@{@"Accept": @"image/webp,image/*;q=0.8"} mutableCopy]; +#else + _HTTPHeaders = [@{@"Accept": @"image/*;q=0.8"} mutableCopy]; +#endif + _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); + _downloadTimeout = 15.0; + } + return self; +} + +- (void)dealloc { + [self.downloadQueue cancelAllOperations]; + SDDispatchQueueRelease(_barrierQueue); +} + +- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field { + if (value) { + self.HTTPHeaders[field] = value; + } + else { + [self.HTTPHeaders removeObjectForKey:field]; + } +} + +- (NSString *)valueForHTTPHeaderField:(NSString *)field { + return self.HTTPHeaders[field]; +} + +- (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { + _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; +} + +- (NSUInteger)currentDownloadCount { + return _downloadQueue.operationCount; +} + +- (NSInteger)maxConcurrentDownloads { + return _downloadQueue.maxConcurrentOperationCount; +} + +- (void)setOperationClass:(Class)operationClass { + _operationClass = operationClass ?: [SDWebImageDownloaderOperation class]; +} + +- (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock { + __block SDWebImageDownloaderOperation *operation; + __weak __typeof(self)wself = self; + + [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{ + NSTimeInterval timeoutInterval = wself.downloadTimeout; + if (timeoutInterval == 0.0) { + timeoutInterval = 15.0; + } + + // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise + NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval]; + request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); + request.HTTPShouldUsePipelining = YES; + if (wself.headersFilter) { + request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]); + } + else { + request.allHTTPHeaderFields = wself.HTTPHeaders; + } + operation = [[wself.operationClass alloc] initWithRequest:request + options:options + progress:^(NSInteger receivedSize, NSInteger expectedSize) { + SDWebImageDownloader *sself = wself; + if (!sself) return; + __block NSArray *callbacksForURL; + dispatch_sync(sself.barrierQueue, ^{ + callbacksForURL = [sself.URLCallbacks[url] copy]; + }); + for (NSDictionary *callbacks in callbacksForURL) { + SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey]; + if (callback) callback(receivedSize, expectedSize); + } + } + completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { + SDWebImageDownloader *sself = wself; + if (!sself) return; + __block NSArray *callbacksForURL; + dispatch_barrier_sync(sself.barrierQueue, ^{ + callbacksForURL = [sself.URLCallbacks[url] copy]; + if (finished) { + [sself.URLCallbacks removeObjectForKey:url]; + } + }); + for (NSDictionary *callbacks in callbacksForURL) { + SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey]; + if (callback) callback(image, data, error, finished); + } + } + cancelled:^{ + SDWebImageDownloader *sself = wself; + if (!sself) return; + dispatch_barrier_async(sself.barrierQueue, ^{ + [sself.URLCallbacks removeObjectForKey:url]; + }); + }]; + operation.shouldDecompressImages = wself.shouldDecompressImages; + + if (wself.username && wself.password) { + operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession]; + } + + if (options & SDWebImageDownloaderHighPriority) { + operation.queuePriority = NSOperationQueuePriorityHigh; + } else if (options & SDWebImageDownloaderLowPriority) { + operation.queuePriority = NSOperationQueuePriorityLow; + } + + [wself.downloadQueue addOperation:operation]; + if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { + // Emulate LIFO execution order by systematically adding new operations as last operation's dependency + [wself.lastAddedOperation addDependency:operation]; + wself.lastAddedOperation = operation; + } + }]; + + return operation; +} + +- (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback { + // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. + if (url == nil) { + if (completedBlock != nil) { + completedBlock(nil, nil, nil, NO); + } + return; + } + + dispatch_barrier_sync(self.barrierQueue, ^{ + BOOL first = NO; + if (!self.URLCallbacks[url]) { + self.URLCallbacks[url] = [NSMutableArray new]; + first = YES; + } + + // Handle single download of simultaneous download request for the same URL + NSMutableArray *callbacksForURL = self.URLCallbacks[url]; + NSMutableDictionary *callbacks = [NSMutableDictionary new]; + if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; + if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; + [callbacksForURL addObject:callbacks]; + self.URLCallbacks[url] = callbacksForURL; + + if (first) { + createCallback(); + } + }); +} + +- (void)setSuspended:(BOOL)suspended { + [self.downloadQueue setSuspended:suspended]; +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h new file mode 100644 index 0000000..dd48b22 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h @@ -0,0 +1,78 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageDownloader.h" +#import "SDWebImageOperation.h" + +extern NSString *const SDWebImageDownloadStartNotification; +extern NSString *const SDWebImageDownloadReceiveResponseNotification; +extern NSString *const SDWebImageDownloadStopNotification; +extern NSString *const SDWebImageDownloadFinishNotification; + +@interface SDWebImageDownloaderOperation : NSOperation + +/** + * The request used by the operation's connection. + */ +@property (strong, nonatomic, readonly) NSURLRequest *request; + + +@property (assign, nonatomic) BOOL shouldDecompressImages; + +/** + * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. + * + * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. + */ +@property (nonatomic, assign) BOOL shouldUseCredentialStorage; + +/** + * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. + * + * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. + */ +@property (nonatomic, strong) NSURLCredential *credential; + +/** + * The SDWebImageDownloaderOptions for the receiver. + */ +@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; + +/** + * The expected size of data. + */ +@property (assign, nonatomic) NSInteger expectedSize; + +/** + * The response returned by the operation's connection. + */ +@property (strong, nonatomic) NSURLResponse *response; + +/** + * Initializes a `SDWebImageDownloaderOperation` object + * + * @see SDWebImageDownloaderOperation + * + * @param request the URL request + * @param options downloader options + * @param progressBlock the block executed when a new chunk of data arrives. + * @note the progress block is executed on a background queue + * @param completedBlock the block executed when the download is done. + * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue + * @param cancelBlock the block executed if the download (operation) is cancelled + * + * @return the initialized instance + */ +- (id)initWithRequest:(NSURLRequest *)request + options:(SDWebImageDownloaderOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageDownloaderCompletedBlock)completedBlock + cancelled:(SDWebImageNoParamsBlock)cancelBlock; + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.m new file mode 100644 index 0000000..5a8bd11 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.m @@ -0,0 +1,466 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageDecoder.h" +#import "UIImage+MultiFormat.h" +#import +#import "SDWebImageManager.h" + +NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; +NSString *const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification"; +NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; +NSString *const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification"; + +@interface SDWebImageDownloaderOperation () + +@property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock; +@property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock; +@property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock; + +@property (assign, nonatomic, getter = isExecuting) BOOL executing; +@property (assign, nonatomic, getter = isFinished) BOOL finished; +@property (strong, nonatomic) NSMutableData *imageData; +@property (strong, nonatomic) NSURLConnection *connection; +@property (strong, atomic) NSThread *thread; + +#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 +@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; +#endif + +@end + +@implementation SDWebImageDownloaderOperation { + size_t width, height; + UIImageOrientation orientation; + BOOL responseFromCached; +} + +@synthesize executing = _executing; +@synthesize finished = _finished; + +- (id)initWithRequest:(NSURLRequest *)request + options:(SDWebImageDownloaderOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageDownloaderCompletedBlock)completedBlock + cancelled:(SDWebImageNoParamsBlock)cancelBlock { + if ((self = [super init])) { + _request = request; + _shouldDecompressImages = YES; + _shouldUseCredentialStorage = YES; + _options = options; + _progressBlock = [progressBlock copy]; + _completedBlock = [completedBlock copy]; + _cancelBlock = [cancelBlock copy]; + _executing = NO; + _finished = NO; + _expectedSize = 0; + responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called + } + return self; +} + +- (void)start { + @synchronized (self) { + if (self.isCancelled) { + self.finished = YES; + [self reset]; + return; + } + +#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + BOOL hasApplication = UIApplicationClass && [UIApplicationClass respondsToSelector:@selector(sharedApplication)]; + if (hasApplication && [self shouldContinueWhenAppEntersBackground]) { + __weak __typeof__ (self) wself = self; + UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)]; + self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{ + __strong __typeof (wself) sself = wself; + + if (sself) { + [sself cancel]; + + [app endBackgroundTask:sself.backgroundTaskId]; + sself.backgroundTaskId = UIBackgroundTaskInvalid; + } + }]; + } +#endif + + self.executing = YES; + self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; + self.thread = [NSThread currentThread]; + } + + [self.connection start]; + + if (self.connection) { + if (self.progressBlock) { + self.progressBlock(0, NSURLResponseUnknownLength); + } + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self]; + }); + + if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) { + // Make sure to run the runloop in our background thread so it can process downloaded data + // Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5 + // not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466) + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false); + } + else { + CFRunLoopRun(); + } + + if (!self.isFinished) { + [self.connection cancel]; + [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]]; + } + } + else { + if (self.completedBlock) { + self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES); + } + } + +#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { + return; + } + if (self.backgroundTaskId != UIBackgroundTaskInvalid) { + UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)]; + [app endBackgroundTask:self.backgroundTaskId]; + self.backgroundTaskId = UIBackgroundTaskInvalid; + } +#endif +} + +- (void)cancel { + @synchronized (self) { + if (self.thread) { + [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO]; + } + else { + [self cancelInternal]; + } + } +} + +- (void)cancelInternalAndStop { + if (self.isFinished) return; + [self cancelInternal]; + CFRunLoopStop(CFRunLoopGetCurrent()); +} + +- (void)cancelInternal { + if (self.isFinished) return; + [super cancel]; + if (self.cancelBlock) self.cancelBlock(); + + if (self.connection) { + [self.connection cancel]; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; + }); + + // As we cancelled the connection, its callback won't be called and thus won't + // maintain the isFinished and isExecuting flags. + if (self.isExecuting) self.executing = NO; + if (!self.isFinished) self.finished = YES; + } + + [self reset]; +} + +- (void)done { + self.finished = YES; + self.executing = NO; + [self reset]; +} + +- (void)reset { + self.cancelBlock = nil; + self.completedBlock = nil; + self.progressBlock = nil; + self.connection = nil; + self.imageData = nil; + self.thread = nil; +} + +- (void)setFinished:(BOOL)finished { + [self willChangeValueForKey:@"isFinished"]; + _finished = finished; + [self didChangeValueForKey:@"isFinished"]; +} + +- (void)setExecuting:(BOOL)executing { + [self willChangeValueForKey:@"isExecuting"]; + _executing = executing; + [self didChangeValueForKey:@"isExecuting"]; +} + +- (BOOL)isConcurrent { + return YES; +} + +#pragma mark NSURLConnection (delegate) + +- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { + + //'304 Not Modified' is an exceptional one + if (![response respondsToSelector:@selector(statusCode)] || ([((NSHTTPURLResponse *)response) statusCode] < 400 && [((NSHTTPURLResponse *)response) statusCode] != 304)) { + NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0; + self.expectedSize = expected; + if (self.progressBlock) { + self.progressBlock(0, expected); + } + + self.imageData = [[NSMutableData alloc] initWithCapacity:expected]; + self.response = response; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:self]; + }); + } + else { + NSUInteger code = [((NSHTTPURLResponse *)response) statusCode]; + + //This is the case when server returns '304 Not Modified'. It means that remote image is not changed. + //In case of 304 we need just cancel the operation and return cached image from the cache. + if (code == 304) { + [self cancelInternal]; + } else { + [self.connection cancel]; + } + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; + }); + + if (self.completedBlock) { + self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES); + } + CFRunLoopStop(CFRunLoopGetCurrent()); + [self done]; + } +} + +- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { + [self.imageData appendData:data]; + + if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) { + // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ + // Thanks to the author @Nyx0uf + + // Get the total bytes downloaded + const NSInteger totalSize = self.imageData.length; + + // Update the data source, we must pass ALL the data, not just the new bytes + CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)self.imageData, NULL); + + if (width + height == 0) { + CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); + if (properties) { + NSInteger orientationValue = -1; + CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); + if (val) CFNumberGetValue(val, kCFNumberLongType, &height); + val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); + if (val) CFNumberGetValue(val, kCFNumberLongType, &width); + val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); + if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); + CFRelease(properties); + + // When we draw to Core Graphics, we lose orientation information, + // which means the image below born of initWithCGIImage will be + // oriented incorrectly sometimes. (Unlike the image born of initWithData + // in connectionDidFinishLoading.) So save it here and pass it on later. + orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)]; + } + + } + + if (width + height > 0 && totalSize < self.expectedSize) { + // Create the image + CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); + +#ifdef TARGET_OS_IPHONE + // Workaround for iOS anamorphic image + if (partialImageRef) { + const size_t partialHeight = CGImageGetHeight(partialImageRef); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst); + CGColorSpaceRelease(colorSpace); + if (bmContext) { + CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef); + CGImageRelease(partialImageRef); + partialImageRef = CGBitmapContextCreateImage(bmContext); + CGContextRelease(bmContext); + } + else { + CGImageRelease(partialImageRef); + partialImageRef = nil; + } + } +#endif + + if (partialImageRef) { + UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation]; + NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; + UIImage *scaledImage = [self scaledImageForKey:key image:image]; + if (self.shouldDecompressImages) { + image = [UIImage decodedImageWithImage:scaledImage]; + } + else { + image = scaledImage; + } + CGImageRelease(partialImageRef); + dispatch_main_sync_safe(^{ + if (self.completedBlock) { + self.completedBlock(image, nil, nil, NO); + } + }); + } + } + + CFRelease(imageSource); + } + + if (self.progressBlock) { + self.progressBlock(self.imageData.length, self.expectedSize); + } +} + ++ (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value { + switch (value) { + case 1: + return UIImageOrientationUp; + case 3: + return UIImageOrientationDown; + case 8: + return UIImageOrientationLeft; + case 6: + return UIImageOrientationRight; + case 2: + return UIImageOrientationUpMirrored; + case 4: + return UIImageOrientationDownMirrored; + case 5: + return UIImageOrientationLeftMirrored; + case 7: + return UIImageOrientationRightMirrored; + default: + return UIImageOrientationUp; + } +} + +- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { + return SDScaledImageForKey(key, image); +} + +- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection { + SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock; + @synchronized(self) { + CFRunLoopStop(CFRunLoopGetCurrent()); + self.thread = nil; + self.connection = nil; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadFinishNotification object:self]; + }); + } + + if (![[NSURLCache sharedURLCache] cachedResponseForRequest:_request]) { + responseFromCached = NO; + } + + if (completionBlock) { + if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) { + completionBlock(nil, nil, nil, YES); + } else if (self.imageData) { + UIImage *image = [UIImage sd_imageWithData:self.imageData]; + NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; + image = [self scaledImageForKey:key image:image]; + + // Do not force decoding animated GIFs + if (!image.images) { + if (self.shouldDecompressImages) { + image = [UIImage decodedImageWithImage:image]; + } + } + if (CGSizeEqualToSize(image.size, CGSizeZero)) { + completionBlock(nil, nil, [NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES); + } + else { + completionBlock(image, self.imageData, nil, YES); + } + } else { + completionBlock(nil, nil, [NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Image data is nil"}], YES); + } + } + self.completionBlock = nil; + [self done]; +} + +- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { + @synchronized(self) { + CFRunLoopStop(CFRunLoopGetCurrent()); + self.thread = nil; + self.connection = nil; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; + }); + } + + if (self.completedBlock) { + self.completedBlock(nil, nil, error, YES); + } + self.completionBlock = nil; + [self done]; +} + +- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { + responseFromCached = NO; // If this method is called, it means the response wasn't read from cache + if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) { + // Prevents caching of responses + return nil; + } + else { + return cachedResponse; + } +} + +- (BOOL)shouldContinueWhenAppEntersBackground { + return self.options & SDWebImageDownloaderContinueInBackground; +} + +- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { + return self.shouldUseCredentialStorage; +} + +- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates) && + [challenge.sender respondsToSelector:@selector(performDefaultHandlingForAuthenticationChallenge:)]) { + [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge]; + } else { + NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; + } + } else { + if ([challenge previousFailureCount] == 0) { + if (self.credential) { + [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; + } else { + [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; + } + } else { + [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; + } + } +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageManager.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageManager.h new file mode 100644 index 0000000..7f80e24 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageManager.h @@ -0,0 +1,299 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" +#import "SDWebImageDownloader.h" +#import "SDImageCache.h" + +typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { + /** + * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. + * This flag disable this blacklisting. + */ + SDWebImageRetryFailed = 1 << 0, + + /** + * By default, image downloads are started during UI interactions, this flags disable this feature, + * leading to delayed download on UIScrollView deceleration for instance. + */ + SDWebImageLowPriority = 1 << 1, + + /** + * This flag disables on-disk caching + */ + SDWebImageCacheMemoryOnly = 1 << 2, + + /** + * This flag enables progressive download, the image is displayed progressively during download as a browser would do. + * By default, the image is only displayed once completely downloaded. + */ + SDWebImageProgressiveDownload = 1 << 3, + + /** + * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. + * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. + * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. + * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. + * + * Use this flag only if you can't make your URLs static with embeded cache busting parameter. + */ + SDWebImageRefreshCached = 1 << 4, + + /** + * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for + * extra time in background to let the request finish. If the background task expires the operation will be cancelled. + */ + SDWebImageContinueInBackground = 1 << 5, + + /** + * Handles cookies stored in NSHTTPCookieStore by setting + * NSMutableURLRequest.HTTPShouldHandleCookies = YES; + */ + SDWebImageHandleCookies = 1 << 6, + + /** + * Enable to allow untrusted SSL ceriticates. + * Useful for testing purposes. Use with caution in production. + */ + SDWebImageAllowInvalidSSLCertificates = 1 << 7, + + /** + * By default, image are loaded in the order they were queued. This flag move them to + * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which + * could take a while). + */ + SDWebImageHighPriority = 1 << 8, + + /** + * By default, placeholder images are loaded while the image is loading. This flag will delay the loading + * of the placeholder image until after the image has finished loading. + */ + SDWebImageDelayPlaceholder = 1 << 9, + + /** + * We usually don't call transformDownloadedImage delegate method on animated images, + * as most transformation code would mangle it. + * Use this flag to transform them anyway. + */ + SDWebImageTransformAnimatedImage = 1 << 10, + + /** + * By default, image is added to the imageView after download. But in some cases, we want to + * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) + * Use this flag if you want to manually set the image in the completion when success + */ + SDWebImageAvoidAutoSetImage = 1 << 11 +}; + +typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL); + +typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); + +typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url); + + +@class SDWebImageManager; + +@protocol SDWebImageManagerDelegate + +@optional + +/** + * Controls which image should be downloaded when the image is not found in the cache. + * + * @param imageManager The current `SDWebImageManager` + * @param imageURL The url of the image to be downloaded + * + * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. + */ +- (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; + +/** + * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. + * NOTE: This method is called from a global queue in order to not to block the main thread. + * + * @param imageManager The current `SDWebImageManager` + * @param image The image to transform + * @param imageURL The url of the image to transform + * + * @return The transformed image object. + */ +- (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; + +@end + +/** + * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. + * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). + * You can use this class directly to benefit from web image downloading with caching in another context than + * a UIView. + * + * Here is a simple example of how to use SDWebImageManager: + * + * @code + +SDWebImageManager *manager = [SDWebImageManager sharedManager]; +[manager downloadImageWithURL:imageURL + options:0 + progress:nil + completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (image) { + // do something with image + } + }]; + + * @endcode + */ +@interface SDWebImageManager : NSObject + +@property (weak, nonatomic) id delegate; + +@property (strong, nonatomic, readonly) SDImageCache *imageCache; +@property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; + +/** + * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can + * be used to remove dynamic part of an image URL. + * + * The following example sets a filter in the application delegate that will remove any query-string from the + * URL before to use it as a cache key: + * + * @code + +[[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { + url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; + return [url absoluteString]; +}]; + + * @endcode + */ +@property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter; + +/** + * Returns global SDWebImageManager instance. + * + * @return SDWebImageManager shared instance + */ ++ (SDWebImageManager *)sharedManager; + +/** + * Downloads the image at the given URL if not present in cache or return the cached version otherwise. + * + * @param url The URL to the image + * @param options A mask to specify options to use for this request + * @param progressBlock A block called while image is downloading + * @param completedBlock A block called when operation has been completed. + * + * This parameter is required. + * + * This block has no return value and takes the requested UIImage as first parameter. + * In case of error the image parameter is nil and the second parameter may contain an NSError. + * + * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache + * or from the memory cache or from the network. + * + * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is + * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the + * block is called a last time with the full image and the last parameter set to YES. + * + * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation + */ +- (id )downloadImageWithURL:(NSURL *)url + options:(SDWebImageOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; + +/** + * Saves image to cache for given URL + * + * @param image The image to cache + * @param url The URL to the image + * + */ + +- (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url; + +/** + * Cancel all current opreations + */ +- (void)cancelAll; + +/** + * Check one or more operations running + */ +- (BOOL)isRunning; + +/** + * Check if image has already been cached + * + * @param url image url + * + * @return if the image was already cached + */ +- (BOOL)cachedImageExistsForURL:(NSURL *)url; + +/** + * Check if image has already been cached on disk only + * + * @param url image url + * + * @return if the image was already cached (disk only) + */ +- (BOOL)diskImageExistsForURL:(NSURL *)url; + +/** + * Async check if image has already been cached + * + * @param url image url + * @param completionBlock the block to be executed when the check is finished + * + * @note the completion block is always executed on the main queue + */ +- (void)cachedImageExistsForURL:(NSURL *)url + completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; + +/** + * Async check if image has already been cached on disk only + * + * @param url image url + * @param completionBlock the block to be executed when the check is finished + * + * @note the completion block is always executed on the main queue + */ +- (void)diskImageExistsForURL:(NSURL *)url + completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; + + +/** + *Return the cache key for a given URL + */ +- (NSString *)cacheKeyForURL:(NSURL *)url; + +@end + + +#pragma mark - Deprecated + +typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`"); +typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`"); + + +@interface SDWebImageManager (Deprecated) + +/** + * Downloads the image at the given URL if not present in cache or return the cached version otherwise. + * + * @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:` + */ +- (id )downloadWithURL:(NSURL *)url + options:(SDWebImageOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`"); + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageManager.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageManager.m new file mode 100644 index 0000000..3980ced --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageManager.m @@ -0,0 +1,354 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageManager.h" +#import + +@interface SDWebImageCombinedOperation : NSObject + +@property (assign, nonatomic, getter = isCancelled) BOOL cancelled; +@property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock; +@property (strong, nonatomic) NSOperation *cacheOperation; + +@end + +@interface SDWebImageManager () + +@property (strong, nonatomic, readwrite) SDImageCache *imageCache; +@property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader; +@property (strong, nonatomic) NSMutableSet *failedURLs; +@property (strong, nonatomic) NSMutableArray *runningOperations; + +@end + +@implementation SDWebImageManager + ++ (id)sharedManager { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (id)init { + if ((self = [super init])) { + _imageCache = [self createCache]; + _imageDownloader = [SDWebImageDownloader sharedDownloader]; + _failedURLs = [NSMutableSet new]; + _runningOperations = [NSMutableArray new]; + } + return self; +} + +- (SDImageCache *)createCache { + return [SDImageCache sharedImageCache]; +} + +- (NSString *)cacheKeyForURL:(NSURL *)url { + if (self.cacheKeyFilter) { + return self.cacheKeyFilter(url); + } + else { + return [url absoluteString]; + } +} + +- (BOOL)cachedImageExistsForURL:(NSURL *)url { + NSString *key = [self cacheKeyForURL:url]; + if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES; + return [self.imageCache diskImageExistsWithKey:key]; +} + +- (BOOL)diskImageExistsForURL:(NSURL *)url { + NSString *key = [self cacheKeyForURL:url]; + return [self.imageCache diskImageExistsWithKey:key]; +} + +- (void)cachedImageExistsForURL:(NSURL *)url + completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { + NSString *key = [self cacheKeyForURL:url]; + + BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil); + + if (isInMemoryCache) { + // making sure we call the completion block on the main queue + dispatch_async(dispatch_get_main_queue(), ^{ + if (completionBlock) { + completionBlock(YES); + } + }); + return; + } + + [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { + // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch + if (completionBlock) { + completionBlock(isInDiskCache); + } + }]; +} + +- (void)diskImageExistsForURL:(NSURL *)url + completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { + NSString *key = [self cacheKeyForURL:url]; + + [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { + // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch + if (completionBlock) { + completionBlock(isInDiskCache); + } + }]; +} + +- (id )downloadImageWithURL:(NSURL *)url + options:(SDWebImageOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageCompletionWithFinishedBlock)completedBlock { + // Invoking this method without a completedBlock is pointless + NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead"); + + // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't + // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. + if ([url isKindOfClass:NSString.class]) { + url = [NSURL URLWithString:(NSString *)url]; + } + + // Prevents app crashing on argument type error like sending NSNull instead of NSURL + if (![url isKindOfClass:NSURL.class]) { + url = nil; + } + + __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; + __weak SDWebImageCombinedOperation *weakOperation = operation; + + BOOL isFailedUrl = NO; + @synchronized (self.failedURLs) { + isFailedUrl = [self.failedURLs containsObject:url]; + } + + if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { + dispatch_main_sync_safe(^{ + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]; + completedBlock(nil, error, SDImageCacheTypeNone, YES, url); + }); + return operation; + } + + @synchronized (self.runningOperations) { + [self.runningOperations addObject:operation]; + } + NSString *key = [self cacheKeyForURL:url]; + + operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) { + if (operation.isCancelled) { + @synchronized (self.runningOperations) { + [self.runningOperations removeObject:operation]; + } + + return; + } + + if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) { + if (image && options & SDWebImageRefreshCached) { + dispatch_main_sync_safe(^{ + // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image + // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. + completedBlock(image, nil, cacheType, YES, url); + }); + } + + // download if no image or requested to refresh anyway, and download allowed by delegate + SDWebImageDownloaderOptions downloaderOptions = 0; + if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; + if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; + if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; + if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; + if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; + if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; + if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; + if (image && options & SDWebImageRefreshCached) { + // force progressive off if image already cached but forced refreshing + downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; + // ignore image read from NSURLCache if image if cached but force refreshing + downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; + } + id subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) { + if (weakOperation.isCancelled) { + // Do nothing if the operation was cancelled + // See #699 for more details + // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data + } + else if (error) { + dispatch_main_sync_safe(^{ + if (!weakOperation.isCancelled) { + completedBlock(nil, error, SDImageCacheTypeNone, finished, url); + } + }); + + BOOL shouldBeFailedURLAlliOSVersion = (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut); + BOOL shouldBeFailedURLiOS7 = (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1 && error.code != NSURLErrorInternationalRoamingOff && error.code != NSURLErrorCallIsActive && error.code != NSURLErrorDataNotAllowed); + if (shouldBeFailedURLAlliOSVersion || shouldBeFailedURLiOS7) { + @synchronized (self.failedURLs) { + [self.failedURLs addObject:url]; + } + } + } + else { + if ((options & SDWebImageRetryFailed)) { + @synchronized (self.failedURLs) { + [self.failedURLs removeObject:url]; + } + } + + BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); + + if (options & SDWebImageRefreshCached && image && !downloadedImage) { + // Image refresh hit the NSURLCache cache, do not call the completion block + } + else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; + + if (transformedImage && finished) { + BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage]; + [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:(imageWasTransformed ? nil : data) forKey:key toDisk:cacheOnDisk]; + } + + dispatch_main_sync_safe(^{ + if (!weakOperation.isCancelled) { + completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url); + } + }); + }); + } + else { + if (downloadedImage && finished) { + [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk]; + } + + dispatch_main_sync_safe(^{ + if (!weakOperation.isCancelled) { + completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url); + } + }); + } + } + + if (finished) { + @synchronized (self.runningOperations) { + [self.runningOperations removeObject:operation]; + } + } + }]; + operation.cancelBlock = ^{ + [subOperation cancel]; + + @synchronized (self.runningOperations) { + [self.runningOperations removeObject:weakOperation]; + } + }; + } + else if (image) { + dispatch_main_sync_safe(^{ + if (!weakOperation.isCancelled) { + completedBlock(image, nil, cacheType, YES, url); + } + }); + @synchronized (self.runningOperations) { + [self.runningOperations removeObject:operation]; + } + } + else { + // Image not in cache and download disallowed by delegate + dispatch_main_sync_safe(^{ + if (!weakOperation.isCancelled) { + completedBlock(nil, nil, SDImageCacheTypeNone, YES, url); + } + }); + @synchronized (self.runningOperations) { + [self.runningOperations removeObject:operation]; + } + } + }]; + + return operation; +} + +- (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url { + if (image && url) { + NSString *key = [self cacheKeyForURL:url]; + [self.imageCache storeImage:image forKey:key toDisk:YES]; + } +} + +- (void)cancelAll { + @synchronized (self.runningOperations) { + NSArray *copiedOperations = [self.runningOperations copy]; + [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; + [self.runningOperations removeObjectsInArray:copiedOperations]; + } +} + +- (BOOL)isRunning { + return self.runningOperations.count > 0; +} + +@end + + +@implementation SDWebImageCombinedOperation + +- (void)setCancelBlock:(SDWebImageNoParamsBlock)cancelBlock { + // check if the operation is already cancelled, then we just call the cancelBlock + if (self.isCancelled) { + if (cancelBlock) { + cancelBlock(); + } + _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes + } else { + _cancelBlock = [cancelBlock copy]; + } +} + +- (void)cancel { + self.cancelled = YES; + if (self.cacheOperation) { + [self.cacheOperation cancel]; + self.cacheOperation = nil; + } + if (self.cancelBlock) { + self.cancelBlock(); + + // TODO: this is a temporary fix to #809. + // Until we can figure the exact cause of the crash, going with the ivar instead of the setter +// self.cancelBlock = nil; + _cancelBlock = nil; + } +} + +@end + + +@implementation SDWebImageManager (Deprecated) + +// deprecated method, uses the non deprecated method +// adapter for the completion block +- (id )downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock { + return [self downloadImageWithURL:url + options:options + progress:progressBlock + completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, finished); + } + }]; +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageOperation.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageOperation.h new file mode 100644 index 0000000..71094ee --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImageOperation.h @@ -0,0 +1,15 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +@protocol SDWebImageOperation + +- (void)cancel; + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.h new file mode 100644 index 0000000..7bb67ac --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.h @@ -0,0 +1,103 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageManager.h" + +@class SDWebImagePrefetcher; + +@protocol SDWebImagePrefetcherDelegate + +@optional + +/** + * Called when an image was prefetched. + * + * @param imagePrefetcher The current image prefetcher + * @param imageURL The image url that was prefetched + * @param finishedCount The total number of images that were prefetched (successful or not) + * @param totalCount The total number of images that were to be prefetched + */ +- (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; + +/** + * Called when all images are prefetched. + * @param imagePrefetcher The current image prefetcher + * @param totalCount The total number of images that were prefetched (whether successful or not) + * @param skippedCount The total number of images that were skipped + */ +- (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; + +@end + +typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); +typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); + +/** + * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. + */ +@interface SDWebImagePrefetcher : NSObject + +/** + * The web image manager + */ +@property (strong, nonatomic, readonly) SDWebImageManager *manager; + +/** + * Maximum number of URLs to prefetch at the same time. Defaults to 3. + */ +@property (nonatomic, assign) NSUInteger maxConcurrentDownloads; + +/** + * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. + */ +@property (nonatomic, assign) SDWebImageOptions options; + +/** + * Queue options for Prefetcher. Defaults to Main Queue. + */ +@property (nonatomic, assign) dispatch_queue_t prefetcherQueue; + +@property (weak, nonatomic) id delegate; + +/** + * Return the global image prefetcher instance. + */ ++ (SDWebImagePrefetcher *)sharedImagePrefetcher; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, + * currently one image is downloaded at a time, + * and skips images for failed downloads and proceed to the next image in the list + * + * @param urls list of URLs to prefetch + */ +- (void)prefetchURLs:(NSArray *)urls; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, + * currently one image is downloaded at a time, + * and skips images for failed downloads and proceed to the next image in the list + * + * @param urls list of URLs to prefetch + * @param progressBlock block to be called when progress updates; + * first parameter is the number of completed (successful or not) requests, + * second parameter is the total number of images originally requested to be prefetched + * @param completionBlock block to be called when prefetching is completed + * first param is the number of completed (successful or not) requests, + * second parameter is the number of skipped requests + */ +- (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; + +/** + * Remove and cancel queued list + */ +- (void)cancelPrefetching; + + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.m new file mode 100644 index 0000000..8756bd0 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.m @@ -0,0 +1,145 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImagePrefetcher.h" + +#if (!defined(DEBUG) && !defined (SD_VERBOSE)) || defined(SD_LOG_NONE) +#define NSLog(...) +#endif + +@interface SDWebImagePrefetcher () + +@property (strong, nonatomic) SDWebImageManager *manager; +@property (strong, nonatomic) NSArray *prefetchURLs; +@property (assign, nonatomic) NSUInteger requestedCount; +@property (assign, nonatomic) NSUInteger skippedCount; +@property (assign, nonatomic) NSUInteger finishedCount; +@property (assign, nonatomic) NSTimeInterval startedTime; +@property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock; +@property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock; + +@end + +@implementation SDWebImagePrefetcher + ++ (SDWebImagePrefetcher *)sharedImagePrefetcher { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (id)init { + if ((self = [super init])) { + _manager = [SDWebImageManager new]; + _options = SDWebImageLowPriority; + _prefetcherQueue = dispatch_get_main_queue(); + self.maxConcurrentDownloads = 3; + } + return self; +} + +- (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { + self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; +} + +- (NSUInteger)maxConcurrentDownloads { + return self.manager.imageDownloader.maxConcurrentDownloads; +} + +- (void)startPrefetchingAtIndex:(NSUInteger)index { + if (index >= self.prefetchURLs.count) return; + self.requestedCount++; + [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (!finished) return; + self.finishedCount++; + + if (image) { + if (self.progressBlock) { + self.progressBlock(self.finishedCount,[self.prefetchURLs count]); + } + NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count)); + } + else { + if (self.progressBlock) { + self.progressBlock(self.finishedCount,[self.prefetchURLs count]); + } + NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count)); + + // Add last failed + self.skippedCount++; + } + if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { + [self.delegate imagePrefetcher:self + didPrefetchURL:self.prefetchURLs[index] + finishedCount:self.finishedCount + totalCount:self.prefetchURLs.count + ]; + } + if (self.prefetchURLs.count > self.requestedCount) { + dispatch_async(self.prefetcherQueue, ^{ + [self startPrefetchingAtIndex:self.requestedCount]; + }); + } + else if (self.finishedCount == self.requestedCount) { + [self reportStatus]; + if (self.completionBlock) { + self.completionBlock(self.finishedCount, self.skippedCount); + self.completionBlock = nil; + } + self.progressBlock = nil; + } + }]; +} + +- (void)reportStatus { + NSUInteger total = [self.prefetchURLs count]; + NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime); + if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { + [self.delegate imagePrefetcher:self + didFinishWithTotalCount:(total - self.skippedCount) + skippedCount:self.skippedCount + ]; + } +} + +- (void)prefetchURLs:(NSArray *)urls { + [self prefetchURLs:urls progress:nil completed:nil]; +} + +- (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock { + [self cancelPrefetching]; // Prevent duplicate prefetch request + self.startedTime = CFAbsoluteTimeGetCurrent(); + self.prefetchURLs = urls; + self.completionBlock = completionBlock; + self.progressBlock = progressBlock; + + if(urls.count == 0){ + if(completionBlock){ + completionBlock(0,0); + } + }else{ + // Starts prefetching from the very first image on the list with the max allowed concurrency + NSUInteger listCount = self.prefetchURLs.count; + for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { + [self startPrefetchingAtIndex:i]; + } + } +} + +- (void)cancelPrefetching { + self.prefetchURLs = nil; + self.skippedCount = 0; + self.requestedCount = 0; + self.finishedCount = 0; + [self.manager cancelAll]; +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIButton+WebCache.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIButton+WebCache.h new file mode 100644 index 0000000..48ad0d5 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIButton+WebCache.h @@ -0,0 +1,229 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIButtonView. + */ +@interface UIButton (WebCache) + +/** + * Get the current image URL. + */ +- (NSURL *)sd_currentImageURL; + +/** + * Get the image URL for a control state. + * + * @param state Which state you want to know the URL for. The values are described in UIControlState. + */ +- (NSURL *)sd_imageURLForState:(UIControlState)state; + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the backgroundImageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state; + +/** + * Set the backgroundImageView `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; + +/** + * Set the backgroundImageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the backgroundImageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the backgroundImageView `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the backgroundImageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Cancel the current image download + */ +- (void)sd_cancelImageLoadForState:(UIControlState)state; + +/** + * Cancel the current backgroundImage download + */ +- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state; + +@end + + +@interface UIButton (WebCacheDeprecated) + +- (NSURL *)currentImageURL __deprecated_msg("Use `sd_currentImageURL`"); +- (NSURL *)imageURLForState:(UIControlState)state __deprecated_msg("Use `sd_imageURLForState:`"); + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:`"); +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:`"); +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:`"); + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:completed:`"); +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:completed:`"); +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:completed:`"); + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:`"); +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:`"); +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:`"); + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:completed:`"); +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:completed:`"); +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:completed:`"); + +- (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelImageLoadForState:`"); +- (void)cancelBackgroundImageLoadForState:(UIControlState)state __deprecated_msg("Use `sd_cancelBackgroundImageLoadForState:`"); + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIButton+WebCache.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIButton+WebCache.m new file mode 100644 index 0000000..33f7c29 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIButton+WebCache.m @@ -0,0 +1,260 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIButton+WebCache.h" +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" + +static char imageURLStorageKey; + +@implementation UIButton (WebCache) + +- (NSURL *)sd_currentImageURL { + NSURL *url = self.imageURLStorage[@(self.state)]; + + if (!url) { + url = self.imageURLStorage[@(UIControlStateNormal)]; + } + + return url; +} + +- (NSURL *)sd_imageURLForState:(UIControlState)state { + return self.imageURLStorage[@(state)]; +} + +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state { + [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; +} + +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { + + [self setImage:placeholder forState:state]; + [self sd_cancelImageLoadForState:state]; + + if (!url) { + [self.imageURLStorage removeObjectForKey:@(state)]; + + dispatch_main_async_safe(^{ + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; + if (completedBlock) { + completedBlock(nil, error, SDImageCacheTypeNone, url); + } + }); + + return; + } + + self.imageURLStorage[@(state)] = url; + + __weak __typeof(self)wself = self; + id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (!wself) return; + dispatch_main_sync_safe(^{ + __strong UIButton *sself = wself; + if (!sself) return; + if (image) { + [sself setImage:image forState:state]; + } + if (completedBlock && finished) { + completedBlock(image, error, cacheType, url); + } + }); + }]; + [self sd_setImageLoadOperation:operation forState:state]; +} + +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_cancelImageLoadForState:state]; + + [self setBackgroundImage:placeholder forState:state]; + + if (url) { + __weak __typeof(self)wself = self; + id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (!wself) return; + dispatch_main_sync_safe(^{ + __strong UIButton *sself = wself; + if (!sself) return; + if (image) { + [sself setBackgroundImage:image forState:state]; + } + if (completedBlock && finished) { + completedBlock(image, error, cacheType, url); + } + }); + }]; + [self sd_setBackgroundImageLoadOperation:operation forState:state]; + } else { + dispatch_main_async_safe(^{ + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; + if (completedBlock) { + completedBlock(nil, error, SDImageCacheTypeNone, url); + } + }); + } +} + +- (void)sd_setImageLoadOperation:(id)operation forState:(UIControlState)state { + [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; +} + +- (void)sd_cancelImageLoadForState:(UIControlState)state { + [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; +} + +- (void)sd_setBackgroundImageLoadOperation:(id)operation forState:(UIControlState)state { + [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; +} + +- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { + [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; +} + +- (NSMutableDictionary *)imageURLStorage { + NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); + if (!storage) + { + storage = [NSMutableDictionary dictionary]; + objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + + return storage; +} + +@end + + +@implementation UIButton (WebCacheDeprecated) + +- (NSURL *)currentImageURL { + return [self sd_currentImageURL]; +} + +- (NSURL *)imageURLForState:(UIControlState)state { + return [self sd_imageURLForState:state]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state { + [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)cancelCurrentImageLoad { + // in a backwards compatible manner, cancel for current state + [self sd_cancelImageLoadForState:self.state]; +} + +- (void)cancelBackgroundImageLoadForState:(UIControlState)state { + [self sd_cancelBackgroundImageLoadForState:state]; +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+GIF.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+GIF.h new file mode 100755 index 0000000..084f424 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+GIF.h @@ -0,0 +1,19 @@ +// +// UIImage+GIF.h +// LBGIFImage +// +// Created by Laurin Brandner on 06.01.12. +// Copyright (c) 2012 __MyCompanyName__. All rights reserved. +// + +#import + +@interface UIImage (GIF) + ++ (UIImage *)sd_animatedGIFNamed:(NSString *)name; + ++ (UIImage *)sd_animatedGIFWithData:(NSData *)data; + +- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size; + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+GIF.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+GIF.m new file mode 100755 index 0000000..a703637 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+GIF.m @@ -0,0 +1,158 @@ +// +// UIImage+GIF.m +// LBGIFImage +// +// Created by Laurin Brandner on 06.01.12. +// Copyright (c) 2012 __MyCompanyName__. All rights reserved. +// + +#import "UIImage+GIF.h" +#import + +@implementation UIImage (GIF) + ++ (UIImage *)sd_animatedGIFWithData:(NSData *)data { + if (!data) { + return nil; + } + + CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); + + size_t count = CGImageSourceGetCount(source); + + UIImage *animatedImage; + + if (count <= 1) { + animatedImage = [[UIImage alloc] initWithData:data]; + } + else { + NSMutableArray *images = [NSMutableArray array]; + + NSTimeInterval duration = 0.0f; + + for (size_t i = 0; i < count; i++) { + CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); + + duration += [self sd_frameDurationAtIndex:i source:source]; + + [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; + + CGImageRelease(image); + } + + if (!duration) { + duration = (1.0f / 10.0f) * count; + } + + animatedImage = [UIImage animatedImageWithImages:images duration:duration]; + } + + CFRelease(source); + + return animatedImage; +} + ++ (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { + float frameDuration = 0.1f; + CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); + NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; + NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; + + NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; + if (delayTimeUnclampedProp) { + frameDuration = [delayTimeUnclampedProp floatValue]; + } + else { + + NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; + if (delayTimeProp) { + frameDuration = [delayTimeProp floatValue]; + } + } + + // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. + // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify + // a duration of <= 10 ms. See and + // for more information. + + if (frameDuration < 0.011f) { + frameDuration = 0.100f; + } + + CFRelease(cfFrameProperties); + return frameDuration; +} + ++ (UIImage *)sd_animatedGIFNamed:(NSString *)name { + CGFloat scale = [UIScreen mainScreen].scale; + + if (scale > 1.0f) { + NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; + + NSData *data = [NSData dataWithContentsOfFile:retinaPath]; + + if (data) { + return [UIImage sd_animatedGIFWithData:data]; + } + + NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; + + data = [NSData dataWithContentsOfFile:path]; + + if (data) { + return [UIImage sd_animatedGIFWithData:data]; + } + + return [UIImage imageNamed:name]; + } + else { + NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; + + NSData *data = [NSData dataWithContentsOfFile:path]; + + if (data) { + return [UIImage sd_animatedGIFWithData:data]; + } + + return [UIImage imageNamed:name]; + } +} + +- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { + if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { + return self; + } + + CGSize scaledSize = size; + CGPoint thumbnailPoint = CGPointZero; + + CGFloat widthFactor = size.width / self.size.width; + CGFloat heightFactor = size.height / self.size.height; + CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; + scaledSize.width = self.size.width * scaleFactor; + scaledSize.height = self.size.height * scaleFactor; + + if (widthFactor > heightFactor) { + thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; + } + else if (widthFactor < heightFactor) { + thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; + } + + NSMutableArray *scaledImages = [NSMutableArray array]; + + UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); + + for (UIImage *image in self.images) { + [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; + UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); + + [scaledImages addObject:newImage]; + } + + UIGraphicsEndImageContext(); + + return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.h new file mode 100644 index 0000000..186ebc0 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.h @@ -0,0 +1,15 @@ +// +// UIImage+MultiFormat.h +// SDWebImage +// +// Created by Olivier Poitrey on 07/06/13. +// Copyright (c) 2013 Dailymotion. All rights reserved. +// + +#import + +@interface UIImage (MultiFormat) + ++ (UIImage *)sd_imageWithData:(NSData *)data; + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.m new file mode 100644 index 0000000..a830754 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.m @@ -0,0 +1,118 @@ +// +// UIImage+MultiFormat.m +// SDWebImage +// +// Created by Olivier Poitrey on 07/06/13. +// Copyright (c) 2013 Dailymotion. All rights reserved. +// + +#import "UIImage+MultiFormat.h" +#import "UIImage+GIF.h" +#import "NSData+ImageContentType.h" +#import + +#ifdef SD_WEBP +#import "UIImage+WebP.h" +#endif + +@implementation UIImage (MultiFormat) + ++ (UIImage *)sd_imageWithData:(NSData *)data { + if (!data) { + return nil; + } + + UIImage *image; + NSString *imageContentType = [NSData sd_contentTypeForImageData:data]; + if ([imageContentType isEqualToString:@"image/gif"]) { + image = [UIImage sd_animatedGIFWithData:data]; + } +#ifdef SD_WEBP + else if ([imageContentType isEqualToString:@"image/webp"]) + { + image = [UIImage sd_imageWithWebPData:data]; + } +#endif + else { + image = [[UIImage alloc] initWithData:data]; + UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; + if (orientation != UIImageOrientationUp) { + image = [UIImage imageWithCGImage:image.CGImage + scale:image.scale + orientation:orientation]; + } + } + + + return image; +} + + ++(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData { + UIImageOrientation result = UIImageOrientationUp; + CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); + if (imageSource) { + CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); + if (properties) { + CFTypeRef val; + int exifOrientation; + val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); + if (val) { + CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); + result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; + } // else - if it's not set it remains at up + CFRelease((CFTypeRef) properties); + } else { + //NSLog(@"NO PROPERTIES, FAIL"); + } + CFRelease(imageSource); + } + return result; +} + +#pragma mark EXIF orientation tag converter +// Convert an EXIF image orientation to an iOS one. +// reference see here: http://sylvana.net/jpegcrop/exif_orientation.html ++ (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { + UIImageOrientation orientation = UIImageOrientationUp; + switch (exifOrientation) { + case 1: + orientation = UIImageOrientationUp; + break; + + case 3: + orientation = UIImageOrientationDown; + break; + + case 8: + orientation = UIImageOrientationLeft; + break; + + case 6: + orientation = UIImageOrientationRight; + break; + + case 2: + orientation = UIImageOrientationUpMirrored; + break; + + case 4: + orientation = UIImageOrientationDownMirrored; + break; + + case 5: + orientation = UIImageOrientationLeftMirrored; + break; + + case 7: + orientation = UIImageOrientationRightMirrored; + break; + default: + break; + } + return orientation; +} + + + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h new file mode 100644 index 0000000..57f708f --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h @@ -0,0 +1,100 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state. + */ +@interface UIImageView (HighlightedWebCache) + +/** + * Set the imageView `highlightedImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setHighlightedImageWithURL:(NSURL *)url; + +/** + * Set the imageView `highlightedImage` with an `url` and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options; + +/** + * Set the imageView `highlightedImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the imageView `highlightedImage` with an `url` and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the imageView `highlightedImage` with an `url` and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Cancel the current download + */ +- (void)sd_cancelCurrentHighlightedImageLoad; + +@end + + +@interface UIImageView (HighlightedWebCacheDeprecated) + +- (void)setHighlightedImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:`"); +- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:`"); +- (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:completed:`"); +- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:completed:`"); +- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:progress:completed:`"); + +- (void)cancelCurrentHighlightedImageLoad __deprecated_msg("Use `sd_cancelCurrentHighlightedImageLoad`"); + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m new file mode 100644 index 0000000..eed798f --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m @@ -0,0 +1,107 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImageView+HighlightedWebCache.h" +#import "UIView+WebCacheOperation.h" + +#define UIImageViewHighlightedWebCacheOperationKey @"highlightedImage" + +@implementation UIImageView (HighlightedWebCache) + +- (void)sd_setHighlightedImageWithURL:(NSURL *)url { + [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; +} + +- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { + [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; +} + +- (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_cancelCurrentHighlightedImageLoad]; + + if (url) { + __weak __typeof(self)wself = self; + id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (!wself) return; + dispatch_main_sync_safe (^ + { + if (!wself) return; + if (image) { + wself.highlightedImage = image; + [wself setNeedsLayout]; + } + if (completedBlock && finished) { + completedBlock(image, error, cacheType, url); + } + }); + }]; + [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey]; + } else { + dispatch_main_async_safe(^{ + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; + if (completedBlock) { + completedBlock(nil, error, SDImageCacheTypeNone, url); + } + }); + } +} + +- (void)sd_cancelCurrentHighlightedImageLoad { + [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey]; +} + +@end + + +@implementation UIImageView (HighlightedWebCacheDeprecated) + +- (void)setHighlightedImageWithURL:(NSURL *)url { + [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; +} + +- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { + [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; +} + +- (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:0 progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)cancelCurrentHighlightedImageLoad { + [self sd_cancelCurrentHighlightedImageLoad]; +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.h new file mode 100644 index 0000000..e7489f4 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.h @@ -0,0 +1,201 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIImageView. + * + * Usage with a UITableViewCell sub-class: + * + * @code + +#import + +... + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *MyIdentifier = @"MyIdentifier"; + + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; + + if (cell == nil) { + cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] + autorelease]; + } + + // Here we use the provided sd_setImageWithURL: method to load the web image + // Ensure you use a placeholder image otherwise cells will be initialized with no image + [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] + placeholderImage:[UIImage imageNamed:@"placeholder"]]; + + cell.textLabel.text = @"My Text"; + return cell; +} + + * @endcode + */ +@interface UIImageView (WebCache) + +/** + * Get the current image URL. + * + * Note that because of the limitations of categories this property can get out of sync + * if you use sd_setImage: directly. + */ +- (NSURL *)sd_imageURL; + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setImageWithURL:(NSURL *)url; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url` and a optionaly placeholder image. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; + +/** + * Download an array of images and starts them in an animation loop + * + * @param arrayOfURLs An array of NSURL + */ +- (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs; + +/** + * Cancel the current download + */ +- (void)sd_cancelCurrentImageLoad; + +- (void)sd_cancelCurrentAnimationImagesLoad; + +@end + + +@interface UIImageView (WebCacheDeprecated) + +- (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`"); + +- (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`"); +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`"); +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`"); + +- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`"); +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`"); +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`"); +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:progress:completed:`"); + +- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`"); + +- (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`"); + +- (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`"); + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.m new file mode 100644 index 0000000..162c49a --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.m @@ -0,0 +1,202 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImageView+WebCache.h" +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" + +static char imageURLKey; + +@implementation UIImageView (WebCache) + +- (void)sd_setImageWithURL:(NSURL *)url { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { + [self sd_cancelCurrentImageLoad]; + objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + if (!(options & SDWebImageDelayPlaceholder)) { + dispatch_main_async_safe(^{ + self.image = placeholder; + }); + } + + if (url) { + __weak __typeof(self)wself = self; + id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (!wself) return; + dispatch_main_sync_safe(^{ + if (!wself) return; + if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) + { + completedBlock(image, error, cacheType, url); + return; + } + else if (image) { + wself.image = image; + [wself setNeedsLayout]; + } else { + if ((options & SDWebImageDelayPlaceholder)) { + wself.image = placeholder; + [wself setNeedsLayout]; + } + } + if (completedBlock && finished) { + completedBlock(image, error, cacheType, url); + } + }); + }]; + [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; + } else { + dispatch_main_async_safe(^{ + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; + if (completedBlock) { + completedBlock(nil, error, SDImageCacheTypeNone, url); + } + }); + } +} + +- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { + NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; + UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key]; + + [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; +} + +- (NSURL *)sd_imageURL { + return objc_getAssociatedObject(self, &imageURLKey); +} + +- (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { + [self sd_cancelCurrentAnimationImagesLoad]; + __weak __typeof(self)wself = self; + + NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; + + for (NSURL *logoImageURL in arrayOfURLs) { + id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (!wself) return; + dispatch_main_sync_safe(^{ + __strong UIImageView *sself = wself; + [sself stopAnimating]; + if (sself && image) { + NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; + if (!currentImages) { + currentImages = [[NSMutableArray alloc] init]; + } + [currentImages addObject:image]; + + sself.animationImages = currentImages; + [sself setNeedsLayout]; + } + [sself startAnimating]; + }); + }]; + [operationsArray addObject:operation]; + } + + [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"]; +} + +- (void)sd_cancelCurrentImageLoad { + [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; +} + +- (void)sd_cancelCurrentAnimationImagesLoad { + [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; +} + +@end + + +@implementation UIImageView (WebCacheDeprecated) + +- (NSURL *)imageURL { + return [self sd_imageURL]; +} + +- (void)setImageWithURL:(NSURL *)url { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType); + } + }]; +} + +- (void)cancelCurrentArrayLoad { + [self sd_cancelCurrentAnimationImagesLoad]; +} + +- (void)cancelCurrentImageLoad { + [self sd_cancelCurrentImageLoad]; +} + +- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { + [self sd_setAnimationImagesWithURLs:arrayOfURLs]; +} + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.h b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.h new file mode 100644 index 0000000..6719036 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.h @@ -0,0 +1,36 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageManager.h" + +@interface UIView (WebCacheOperation) + +/** + * Set the image load operation (storage in a UIView based dictionary) + * + * @param operation the operation + * @param key key for storing the operation + */ +- (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key; + +/** + * Cancel all operations for the current UIView and key + * + * @param key key for identifying the operations + */ +- (void)sd_cancelImageLoadOperationWithKey:(NSString *)key; + +/** + * Just remove the operations corresponding to the current UIView and key without cancelling them + * + * @param key key for identifying the operations + */ +- (void)sd_removeImageLoadOperationWithKey:(NSString *)key; + +@end diff --git a/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.m b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.m new file mode 100644 index 0000000..9219478 --- /dev/null +++ b/TalkinToTheNet/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.m @@ -0,0 +1,55 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIView+WebCacheOperation.h" +#import "objc/runtime.h" + +static char loadOperationKey; + +@implementation UIView (WebCacheOperation) + +- (NSMutableDictionary *)operationDictionary { + NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); + if (operations) { + return operations; + } + operations = [NSMutableDictionary dictionary]; + objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return operations; +} + +- (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key { + [self sd_cancelImageLoadOperationWithKey:key]; + NSMutableDictionary *operationDictionary = [self operationDictionary]; + [operationDictionary setObject:operation forKey:key]; +} + +- (void)sd_cancelImageLoadOperationWithKey:(NSString *)key { + // Cancel in progress downloader from queue + NSMutableDictionary *operationDictionary = [self operationDictionary]; + id operations = [operationDictionary objectForKey:key]; + if (operations) { + if ([operations isKindOfClass:[NSArray class]]) { + for (id operation in operations) { + if (operation) { + [operation cancel]; + } + } + } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ + [(id) operations cancel]; + } + [operationDictionary removeObjectForKey:key]; + } +} + +- (void)sd_removeImageLoadOperationWithKey:(NSString *)key { + NSMutableDictionary *operationDictionary = [self operationDictionary]; + [operationDictionary removeObjectForKey:key]; +} + +@end diff --git a/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking-Private.xcconfig b/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking-Private.xcconfig new file mode 100644 index 0000000..67d4299 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking-Private.xcconfig @@ -0,0 +1,6 @@ +#include "AFNetworking.xcconfig" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/AFNetworking" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" "${PODS_ROOT}/Headers/Public/NYAlertViewController" "${PODS_ROOT}/Headers/Public/SDWebImage" +OTHER_LDFLAGS = ${AFNETWORKING_OTHER_LDFLAGS} +PODS_ROOT = ${SRCROOT} +SKIP_INSTALL = YES \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m b/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m new file mode 100644 index 0000000..6a29cf8 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_AFNetworking : NSObject +@end +@implementation PodsDummy_AFNetworking +@end diff --git a/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch b/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch new file mode 100644 index 0000000..1e116a3 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch @@ -0,0 +1,11 @@ +#ifdef __OBJC__ +#import +#endif + +#ifndef TARGET_OS_IOS + #define TARGET_OS_IOS TARGET_OS_IPHONE +#endif + +#ifndef TARGET_OS_WATCH + #define TARGET_OS_WATCH 0 +#endif diff --git a/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking.xcconfig b/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking.xcconfig new file mode 100644 index 0000000..b0b2d52 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/AFNetworking/AFNetworking.xcconfig @@ -0,0 +1 @@ +AFNETWORKING_OTHER_LDFLAGS = -framework "CoreGraphics" -framework "MobileCoreServices" -framework "Security" -framework "SystemConfiguration" \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController-Private.xcconfig b/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController-Private.xcconfig new file mode 100644 index 0000000..7fd67ee --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController-Private.xcconfig @@ -0,0 +1,5 @@ +#include "NYAlertViewController.xcconfig" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/NYAlertViewController" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" "${PODS_ROOT}/Headers/Public/NYAlertViewController" "${PODS_ROOT}/Headers/Public/SDWebImage" +PODS_ROOT = ${SRCROOT} +SKIP_INSTALL = YES \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController-dummy.m b/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController-dummy.m new file mode 100644 index 0000000..f0f9cb2 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_NYAlertViewController : NSObject +@end +@implementation PodsDummy_NYAlertViewController +@end diff --git a/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController-prefix.pch b/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController.xcconfig b/TalkinToTheNet/Pods/Target Support Files/NYAlertViewController/NYAlertViewController.xcconfig new file mode 100644 index 0000000..e69de29 diff --git a/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-acknowledgements.markdown b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-acknowledgements.markdown new file mode 100644 index 0000000..d116f3c --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-acknowledgements.markdown @@ -0,0 +1,75 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## AFNetworking + +Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +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. + + +## NYAlertViewController + +The MIT License (MIT) + +Copyright (c) 2014 Nealon Young + +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. + + +## SDWebImage + +Copyright (c) 2009 Olivier Poitrey + +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 diff --git a/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-acknowledgements.plist b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-acknowledgements.plist new file mode 100644 index 0000000..4b2b1b7 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-acknowledgements.plist @@ -0,0 +1,113 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +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. + + Title + AFNetworking + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2014 Nealon Young + +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. + + Title + NYAlertViewController + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2009 Olivier Poitrey <rs@dailymotion.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. + + + Title + SDWebImage + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - http://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-dummy.m b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-dummy.m new file mode 100644 index 0000000..ade64bd --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods : NSObject +@end +@implementation PodsDummy_Pods +@end diff --git a/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-resources.sh b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-resources.sh new file mode 100755 index 0000000..ea685a2 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods-resources.sh @@ -0,0 +1,95 @@ +#!/bin/sh +set -e + +mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +realpath() { + DIRECTORY="$(cd "${1%/*}" && pwd)" + FILENAME="${1##*/}" + echo "$DIRECTORY/$FILENAME" +} + +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" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm\"" + xcrun mapc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE=$(realpath "${PODS_ROOT}/$1") + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + /*) + echo "$1" + echo "$1" >> "$RESOURCES_TO_COPY" + ;; + *) + echo "${PODS_ROOT}/$1" + echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + 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" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; + esac + + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "`realpath $PODS_ROOT`*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/TalkinToTheNet/Pods/Target Support Files/Pods/Pods.debug.xcconfig b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods.debug.xcconfig new file mode 100644 index 0000000..508b813 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods.debug.xcconfig @@ -0,0 +1,5 @@ +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" "${PODS_ROOT}/Headers/Public/NYAlertViewController" "${PODS_ROOT}/Headers/Public/SDWebImage" +OTHER_CFLAGS = $(inherited) -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/AFNetworking" -isystem "${PODS_ROOT}/Headers/Public/NYAlertViewController" -isystem "${PODS_ROOT}/Headers/Public/SDWebImage" +OTHER_LDFLAGS = $(inherited) -ObjC -l"AFNetworking" -l"NYAlertViewController" -l"SDWebImage" -framework "CoreGraphics" -framework "ImageIO" -framework "MobileCoreServices" -framework "Security" -framework "SystemConfiguration" +PODS_ROOT = ${SRCROOT}/Pods \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Target Support Files/Pods/Pods.release.xcconfig b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods.release.xcconfig new file mode 100644 index 0000000..508b813 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/Pods/Pods.release.xcconfig @@ -0,0 +1,5 @@ +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" "${PODS_ROOT}/Headers/Public/NYAlertViewController" "${PODS_ROOT}/Headers/Public/SDWebImage" +OTHER_CFLAGS = $(inherited) -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/AFNetworking" -isystem "${PODS_ROOT}/Headers/Public/NYAlertViewController" -isystem "${PODS_ROOT}/Headers/Public/SDWebImage" +OTHER_LDFLAGS = $(inherited) -ObjC -l"AFNetworking" -l"NYAlertViewController" -l"SDWebImage" -framework "CoreGraphics" -framework "ImageIO" -framework "MobileCoreServices" -framework "Security" -framework "SystemConfiguration" +PODS_ROOT = ${SRCROOT}/Pods \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage-Private.xcconfig b/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage-Private.xcconfig new file mode 100644 index 0000000..bc25080 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage-Private.xcconfig @@ -0,0 +1,6 @@ +#include "SDWebImage.xcconfig" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/SDWebImage" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" "${PODS_ROOT}/Headers/Public/NYAlertViewController" "${PODS_ROOT}/Headers/Public/SDWebImage" +OTHER_LDFLAGS = ${SDWEBIMAGE_OTHER_LDFLAGS} +PODS_ROOT = ${SRCROOT} +SKIP_INSTALL = YES \ No newline at end of file diff --git a/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m b/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m new file mode 100644 index 0000000..86d2b5f --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SDWebImage : NSObject +@end +@implementation PodsDummy_SDWebImage +@end diff --git a/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch b/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage.xcconfig b/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage.xcconfig new file mode 100644 index 0000000..6ac563d --- /dev/null +++ b/TalkinToTheNet/Pods/Target Support Files/SDWebImage/SDWebImage.xcconfig @@ -0,0 +1 @@ +SDWEBIMAGE_OTHER_LDFLAGS = -framework "ImageIO" \ No newline at end of file diff --git a/TalkinToTheNet/Pods/ZTDropDownTextField/LICENSE b/TalkinToTheNet/Pods/ZTDropDownTextField/LICENSE new file mode 100644 index 0000000..a3422dd --- /dev/null +++ b/TalkinToTheNet/Pods/ZTDropDownTextField/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Ziyang Tan + +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. \ No newline at end of file diff --git a/TalkinToTheNet/Pods/ZTDropDownTextField/README.md b/TalkinToTheNet/Pods/ZTDropDownTextField/README.md new file mode 100755 index 0000000..62ce48c --- /dev/null +++ b/TalkinToTheNet/Pods/ZTDropDownTextField/README.md @@ -0,0 +1,182 @@ +# ZTDropDownTextField + + +## Table of contents + + * [Features](#features) + * [Demo](#demo) + * [Installation](#installation) + * [Cocoapods](#cocoapods) + * [Source files](#source-files) + * [Example](#example) + * [Usage](#usage) + * [Basics](#basics) + * [DataSourceDelegate](#datasourcedelegate) + * [Customization](#customization) + * [Requirments](#requirements) + * [Credit](#credit) + * [Remains to do](#remains-to-do) + * [License](#license) + +*** + +## Features + + * [x] Provide dropdown suggestions below UITextField + * [x] Alterantive of UISearchController + * [x] Dropdown list will hide automatially, when user tap outside of it + * [x] Implemented with AutoLayout, support both portrait and landscape + * [x] Provide delegate methods for dropdown list events + * [x] Dropdown list UI is customizable + * [x] Swift Dynamic Framework, easy to integrate + +## Demo + +Portrait | Landscape +------------- | ------------- +[![Portrait](ZTDropDownTextField-Map-Portrait.gif)](ZTDropDownTextField-Portrait.gif) | [![Slide Animation](ZTDropDownTextField-Map-Landscape.gif)](ZTDropDownTextField-Lanscape.gif) + +Slide Animation | Expand Animation | Flip Animation +------------- | ------------- | --------------- +[![Slide Animation](ZTDropDownTextField-Slide.gif)](ZTDropDownTextField-Slide.gif) | [![Slide Animation](ZTDropDownTextField-Expand.gif)](ZTDropDownTextField-Expand.gif) | [![Flip Animation](ZTDropDownTextField-Flip.gif)](ZTDropDownTextField-Flip.gif) + +## Installation + +### Cocoapods + +[CocoaPods](http://www.cocoapods.org) recommended to use ZTDropDownTextField. + +1. Add `pod 'ZTDropDownTextField'` to your *Podfile*. +2. Install the pod(s) by running `pod install`. +3. Include ZTDropDownTextField wherever you need it with `import ZTDropDownTextField`. + + +### Source files + +1. Download the [latest code version](https://github.com/ziyang0621/ZTDropDownTextField/archive/master.zip) or add the repository as a git submodule to your git-tracked project. +2. Drag and drop ZTDropDownTextField directory from the archive in your project navigator. Make sure to select *Copy items* when asked if you extracted the code archive outside of your project. +3. Include ZTDropDownTextField wherever you need it with `import ZTDropDownTextField`. + +### Example +1. Download the [latest code version](https://github.com/ziyang0621/ZTDropDownTextField/archive/master.zip) +2. Double click to open the `ZTDropDownTextField.xcworkspace` file + +## Usage + +Check out the provided example app for how you can use the ZTDropDownTextField. + +### Basics + +Add the following import to the top of your Swift file which needs a dropdown textfield. + + ```swift + import ZTDropDownTextField + ``` + +### IBOutlet + +You can declare a ZTDropDownTextField with an IBOutlet and connect it to your storyboard or nib file. + + ```swift + @IBOutlet weak var dropDownTextField: ZTDropDownTextField! + ``` + +### DataSourceDelegate + +There are 3 delegate methods which you have to implement, if your view controller conform with `ZTDropDownTextFieldDataSourceDelegate`. + +You can let your view controller become a `ZTDropDownTextFieldDataSourceDelegate` by doing the following: + + ```swift + dropDownTextField.dataSourceDelegate = self + ``` + +Example of implementing `ZTDropDownTextFieldDataSourceDelegate` method + + ```swift +extension ViewController: ZTDropDownTextFieldDataSourceDelegate { + func dropDownTextField(dropDownTextField: ZTDropDownTextField, numberOfRowsInSection section: Int) -> Int { + return myList.count + } + + func dropDownTextField(dropDownTextField: ZTDropDownTextField, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { + var cell = dropDownTextField.dropDownTableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell + if cell == nil { + cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell") + } + + cell!.textLabel!.text = myList[indexPath.row] + + return cell! + } + + func dropDownTextField(dropdownTextField: ZTDropDownTextField, didSelectRowAtIndexPath indexPath: NSIndexPath) { + println("drop down list row did select") + } +} + ``` + +## Customization + +The dropdown list can have 3 different animations, including `Basic`, `Slide`, `Expand` and `Flip`. See the animations in [Demo](#demo). +```swift +public enum ZTDropDownAnimationStyle { + case Basic + case Slide + case Expand + case Flip +} +``` +```swift + dropDownTextField.animationStyle = .Slide +``` + + +The `rowHeight` and `dropDownTableViewHeight` can be customized by changing the value of these 2 variables +```swift + public var rowHeight:CGFloat = 50 + public var dropDownTableViewHeight: CGFloat = 150 +``` + +## Requirements + +* Xcode 6 +* iOS 7 +* ARC +* Frameworks: + * UIKit + +## Remains to do + +- [ ] Swift 2.0 +- [ ] More customizations + + +## Credit + +- [Facebook pop](https://github.com/facebook/pop) + + +## License + + The MIT License (MIT) + + Copyright (c) 2015 Ziyang Tan + + 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. diff --git a/TalkinToTheNet/Pods/ZTDropDownTextField/ZTDropDownTextField/ZTDropDownTextField-Bridging-Header.h b/TalkinToTheNet/Pods/ZTDropDownTextField/ZTDropDownTextField/ZTDropDownTextField-Bridging-Header.h new file mode 100644 index 0000000..d83dc67 --- /dev/null +++ b/TalkinToTheNet/Pods/ZTDropDownTextField/ZTDropDownTextField/ZTDropDownTextField-Bridging-Header.h @@ -0,0 +1,5 @@ +// +// Use this file to import your target's public headers that you would like to expose to Swift. +// + +#import \ No newline at end of file diff --git a/TalkinToTheNet/Pods/ZTDropDownTextField/ZTDropDownTextField/ZTDropDownTextField.swift b/TalkinToTheNet/Pods/ZTDropDownTextField/ZTDropDownTextField/ZTDropDownTextField.swift new file mode 100644 index 0000000..7f1559b --- /dev/null +++ b/TalkinToTheNet/Pods/ZTDropDownTextField/ZTDropDownTextField/ZTDropDownTextField.swift @@ -0,0 +1,171 @@ +// +// ZTDropDownTextField.swift +// ZTDropDownTextField +// +// Created by Ziyang Tan on 7/30/15. +// Copyright (c) 2015 Ziyang Tan. All rights reserved. +// + +import UIKit + +// MARK: Animation Style Enum +public enum ZTDropDownAnimationStyle { + case Basic + case Slide + case Expand + case Flip +} + +// MARK: Dropdown Delegate +public protocol ZTDropDownTextFieldDataSourceDelegate: NSObjectProtocol { + func dropDownTextField(dropDownTextField: ZTDropDownTextField, numberOfRowsInSection section: Int) -> Int + func dropDownTextField(dropDownTextField: ZTDropDownTextField, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell + func dropDownTextField(dropDownTextField: ZTDropDownTextField, didSelectRowAtIndexPath indexPath: NSIndexPath) +} + +public class ZTDropDownTextField: UITextField { + + // MARK: Instance Variables + public var dropDownTableView: UITableView! + public var rowHeight:CGFloat = 50 + public var dropDownTableViewHeight: CGFloat = 150 + public var animationStyle: ZTDropDownAnimationStyle = .Basic + public weak var dataSourceDelegate: ZTDropDownTextFieldDataSourceDelegate? + private var heightConstraint: NSLayoutConstraint! + + // MARK: Init Methods + required public init(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setupTextField() + } + + override init(frame: CGRect) { + super.init(frame: frame) + setupTextField() + } + + + // MARK: Setup Methods + private func setupTextField() { + addTarget(self, action: "editingChanged:", forControlEvents:.EditingChanged) + } + + private func setupTableView() { + if dropDownTableView == nil { + + dropDownTableView = UITableView() + dropDownTableView.backgroundColor = UIColor.whiteColor() + dropDownTableView.layer.cornerRadius = 10.0 + dropDownTableView.layer.borderColor = UIColor.lightGrayColor().CGColor + dropDownTableView.layer.borderWidth = 1.0 + dropDownTableView.showsVerticalScrollIndicator = false + dropDownTableView.delegate = self + dropDownTableView.dataSource = self + dropDownTableView.estimatedRowHeight = rowHeight + + superview!.addSubview(dropDownTableView) + superview!.bringSubviewToFront(dropDownTableView) + + dropDownTableView.setTranslatesAutoresizingMaskIntoConstraints(false) + + let leftConstraint = NSLayoutConstraint(item: dropDownTableView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0) + let rightConstraint = NSLayoutConstraint(item: dropDownTableView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0) + heightConstraint = NSLayoutConstraint(item: dropDownTableView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: dropDownTableViewHeight) + let topConstraint = NSLayoutConstraint(item: dropDownTableView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 1) + + NSLayoutConstraint.activateConstraints([leftConstraint, rightConstraint, heightConstraint, topConstraint]) + + let tapGesture = UITapGestureRecognizer(target: self, action: "tapped:") + tapGesture.numberOfTapsRequired = 1 + tapGesture.cancelsTouchesInView = false + superview!.addGestureRecognizer(tapGesture) + } + + } + + private func tableViewAppearanceChange(appear: Bool) { + switch animationStyle { + case .Basic: + let basicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) + basicAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) + basicAnimation.toValue = appear ? 1 : 0 + dropDownTableView.pop_addAnimation(basicAnimation, forKey: "basic") + case .Slide: + let basicAnimation = POPBasicAnimation(propertyNamed: kPOPLayoutConstraintConstant) + basicAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) + basicAnimation.toValue = appear ? dropDownTableViewHeight : 0 + heightConstraint.pop_addAnimation(basicAnimation, forKey: "heightConstraint") + case .Expand: + let springAnimation = POPSpringAnimation(propertyNamed: kPOPViewSize) + springAnimation.springSpeed = dropDownTableViewHeight / 100 + springAnimation.springBounciness = 10.0 + let width = appear ? CGRectGetWidth(frame) : 0 + let height = appear ? dropDownTableViewHeight : 0 + springAnimation.toValue = NSValue(CGSize: CGSize(width: width, height: height)) + dropDownTableView.pop_addAnimation(springAnimation, forKey: "expand") + case .Flip: + var identity = CATransform3DIdentity + identity.m34 = -1.0/1000 + let angle = appear ? CGFloat(0) : CGFloat(M_PI_2) + let rotationTransform = CATransform3DRotate(identity, angle, 0.0, 1.0, 0.0) + UIView.animateWithDuration(0.5, animations: { () -> Void in + self.dropDownTableView.layer.transform = rotationTransform + }) + } + } + + // MARK: Target Methods + func tapped(gesture: UIGestureRecognizer) { + let location = gesture.locationInView(superview) + if !CGRectContainsPoint(dropDownTableView.frame, location) { + if let dropDownTableView = dropDownTableView { + self.tableViewAppearanceChange(false) + } + } + } + + func editingChanged(textField: UITextField) { + if count(textField.text) > 0 { + setupTableView() + self.tableViewAppearanceChange(true) + } else { + if let dropDownTableView = dropDownTableView { + self.tableViewAppearanceChange(false) + } + } + } + +} + +// Mark: UITableViewDataSoruce +extension ZTDropDownTextField: UITableViewDataSource { + public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + if let dataSourceDelegate = dataSourceDelegate { + if dataSourceDelegate.respondsToSelector(Selector("dropDownTextField:numberOfRowsInSection:")) { + return dataSourceDelegate.dropDownTextField(self, numberOfRowsInSection: section) + } + } + return 0 + } + + public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { + if let dataSourceDelegate = dataSourceDelegate { + if dataSourceDelegate.respondsToSelector(Selector("dropDownTextField:cellForRowAtIndexPath:")) { + return dataSourceDelegate.dropDownTextField(self, cellForRowAtIndexPath: indexPath) + } + } + return UITableViewCell() + } +} + +// Mark: UITableViewDelegate +extension ZTDropDownTextField: UITableViewDelegate { + public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { + if let dataSourceDelegate = dataSourceDelegate { + if dataSourceDelegate.respondsToSelector(Selector("dropDownTextField:didSelectRowAtIndexPath:")) { + dataSourceDelegate.dropDownTextField(self, didSelectRowAtIndexPath: indexPath) + } + } + self.tableViewAppearanceChange(false) + } +} \ No newline at end of file diff --git a/TalkinToTheNet/Pods/pop/LICENSE b/TalkinToTheNet/Pods/pop/LICENSE new file mode 100644 index 0000000..642126f --- /dev/null +++ b/TalkinToTheNet/Pods/pop/LICENSE @@ -0,0 +1,30 @@ +BSD License + +For Pop software + +Copyright (c) 2014, Facebook, Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/TalkinToTheNet/Pods/pop/README.md b/TalkinToTheNet/Pods/pop/README.md new file mode 100644 index 0000000..addb18a --- /dev/null +++ b/TalkinToTheNet/Pods/pop/README.md @@ -0,0 +1,203 @@ +![pop](https://github.com/facebook/pop/blob/master/Images/pop.gif?raw=true) + +Pop is an extensible animation engine for iOS and OS X. In addition to basic static animations, it supports spring and decay dynamic animations, making it useful for building realistic, physics-based interactions. The API allows quick integration with existing Objective-C codebases and enables the animation of any property on any object. It's a mature and well-tested framework that drives all the animations and transitions in [Paper](http://www.facebook.com/paper). + +[![Build Status](https://travis-ci.org/facebook/pop.svg)](https://travis-ci.org/facebook/pop) + +## Installation + +Pop is available on [CocoaPods](http://cocoapods.org). Just add the following to your project Podfile: + +```ruby +pod 'pop', '~> 1.0' +``` + +Bugs are first fixed in master and then made available via a designated release. If you tend to live on the bleeding edge, you can use Pop from master with the following Podfile entry: + +```ruby +pod 'pop', :git => 'https://github.com/facebook/pop.git' +``` + +## Non-CocoaPods Installation + +### iOS 8 Embedded Framework +By adding the project to your project and adding pop.embedded framework to the Embedded Binaries section on the General tab of your app's target, you can set up pop in seconds! This also enables `@import pop` syntax with header modules. + +**Note**: because of some awkward limitations with Xcode, embedded binaries must share the same name as the module and must have `.framework` as an extension. This means that you'll see two pop.frameworks when adding embedded binaries (one for OS X, and one for iOS). You'll need to be sure to add the iOS one, and since this list is populated in order of targets, it's safe to assume it's the second one. You can verify the correct one was chosen by checking the path next to the framework listed: `Debug-iphoneos`. + +![Embedded Binaries](Images/EmbeddedBinaries.png?raw=true) + +**Note 2**: this method does not currently play nicely with workspaces. For some unknown reason, Xcode simply rejects adding pop.framework as an embedded binary when pop.xcodeproj is placed in the workspace. This only works when pop.xcodeproj is added as a subproject to the current target's project. + +### Advanced +Alternatively, you can add the project to your workspace and adopt the provided configuration files or manually copy the files under the pop subdirectory into your project. If installing manually, ensure the C++ standard library is also linked by including `-lc++` to your project linker flags. + +## Usage + +Pop adopts the Core Animation explicit animation programming model. Use by including the following import: + +```objective-c +#import +``` + +or if you're using the embedded framework: + +```objective-c +@import pop; +``` + +### Start, Stop & Update + +To start an animation, add it to the object you wish to animate: + +```objective-c +POPSpringAnimation *anim = [POPSpringAnimation animation]; +... +[layer pop_addAnimation:anim forKey:@"myKey"]; +``` + +To stop an animation, remove it from the object referencing the key specified on start: + +```objective-c +[layer pop_removeAnimationForKey:@"myKey"]; +``` + +The key can also be used to query for the existence of an animation. Updating the toValue of a running animation can provide the most seamless way to change course: + +```objective-c +anim = [layer pop_animationForKey:@"myKey"]; +if (anim) { + /* update to value to new destination */ + anim.toValue = @(42.0); +} else { + /* create and start a new animation */ + .... +} +``` + +While a layer was used in the above examples, the Pop interface is implemented as a category addition on NSObject. Any NSObject or subclass can be animated. + +### Types + +There are four concrete animation types: spring, decay, basic and custom. + +Spring animations can be used to give objects a delightful bounce. In this example, we use a spring animation to animate a layer's bounds from its current value to (0, 0, 400, 400): + +```objective-c +POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerBounds]; +anim.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 400, 400)]; +[layer pop_addAnimation:anim forKey:@"size"]; +``` +Decay animations can be used to gradually slow an object to a halt. In this example, we decay a layer's positionX from it's current value and velocity 1000pts per second: + +```objective-c +POPDecayAnimation *anim = [POPDecayAnimation animationWithPropertyNamed:kPOPLayerPositionX]; +anim.velocity = @(1000.); +[layer pop_addAnimation:anim forKey:@"slide"]; +``` + +Basic animations can be used to interpolate values over a specified time period. To use an ease-in ease-out animation to animate a view's alpha from 0.0 to 1.0 over the default duration: +```objective-c +POPBasicAnimation *anim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha]; +anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; +anim.fromValue = @(0.0); +anim.toValue = @(1.0); +[view pop_addAnimation:anim forKey:@"fade"]; +``` +`POPCustomAnimation` makes creating custom animations and transitions easier by handling CADisplayLink and associated time-step management. See header for more details. + + +### Properties + +The property animated is specified by the `POPAnimatableProperty` class. In this example we create a spring animation and explicitly set the animatable property corresponding to `-[CALayer bounds]`: + +```objective-c +POPSpringAnimation *anim = [POPSpringAnimation animation]; +anim.property = [POPAnimatableProperty propertyWithName:kPOPLayerBounds]; +``` + +The framework provides many common layer and view animatable properties out of box. You can animate a custom property by creating a new instance of the class. In this example, we declare a custom volume property: + +```objective-c +prop = [POPAnimatableProperty propertyWithName:@"com.foo.radio.volume" initializer:^(POPMutableAnimatableProperty *prop) { + // read value + prop.readBlock = ^(id obj, CGFloat values[]) { + values[0] = [obj volume]; + }; + // write value + prop.writeBlock = ^(id obj, const CGFloat values[]) { + [obj setVolume:values[0]]; + }; + // dynamics threshold + prop.threshold = 0.01; +}]; + +anim.property = prop; +``` + +For a complete listing of provided animatable properties, as well more information on declaring custom properties see `POPAnimatableProperty.h`. + + +### Debugging + +Here are a few tips when debugging. Pop obeys the Simulator's Toggle Slow Animations setting. Try enabling it to slow down animations and more easily observe interactions. + +Consider naming your animations. This will allow you to more easily identify them when referencing them, either via logging or in the debugger: + +```objective-c +anim.name = @"springOpen"; +``` + +Each animation comes with an associated tracer. The tracer allows you to record all animation-related events, in a fast and efficient manner, allowing you to query and analyze them after animation completion. The below example starts the tracer and configures it to log all events on animation completion: + +```objective-c +POPAnimationTracer *tracer = anim.tracer; +tracer.shouldLogAndResetOnCompletion = YES; +[tracer start]; +``` + +See `POPAnimationTracer.h` for more details. + +## Testing + +Pop has extensive unit test coverage. To install test dependencies, navigate to the root pop directory and type: + +```sh +pod install +``` + +Assuming CocoaPods is installed, this will include the necessary OCMock dependency to the unit test targets. + +## SceneKit + +Due to SceneKit requiring iOS 8 and OS X 10.9, POP's SceneKit extensions aren't provided out of box. Unfortunately, [weakly linked frameworks](https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html) cannot be used due to issues mentioned in the [Xcode 6.1 Release Notes](https://developer.apple.com/library/ios/releasenotes/DeveloperTools/RN-Xcode/Chapters/xc6_release_notes.html). + +To remedy this, you can easily opt-in to use SceneKit! Simply add this to the Preprocessor Macros section of your Xcode Project: + +``` +POP_USE_SCENEKIT=1 +``` + +## Resources + +A collection of links to external resources that may prove valuable: + +* [AGGeometryKit+POP - Animating Quadrilaterals with Pop](https://github.com/hfossli/aggeometrykit-pop) +* [Apple – Core Animation Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreAnimation_guide/Introduction/Introduction.html) +* [iOS Development Tips – UIScrollView-like deceleration with Pop](http://iosdevtips.co/post/84571595353/replicating-uiscrollviews-deceleration-with-facebook) +* [Pop Playground – Repository of Pop animation examples](https://github.com/callmeed/pop-playground) +* [Pop Playground 2 – Playing with Facebook's framework](http://victorbaro.com/2014/05/pop-playground-playing-with-facebooks-framework/) +* [POP-MCAnimate – Concise syntax for the Pop animation framework](https://github.com/matthewcheok/POP-MCAnimate) +* [Popping - Great examples in one project](https://github.com/schneiderandre/popping) +* [Rebound – Spring Animations for Android](http://facebook.github.io/rebound/) +* [Tapity Tutorial – Getting Started with Pop](http://tapity.com/tutorial-getting-started-with-pop/) +* [Tweaks – Easily adjust parameters for iOS apps in development](https://github.com/facebook/tweaks) +* [POP Tutorial in 5 steps](https://github.com/maxmyers/FacebookPop) +* [VBFPopFlatButton – Flat animatable button, using Pop to transition between states](https://github.com/victorBaro/VBFPopFlatButton) + +## Contributing +See the CONTRIBUTING file for how to help out. + +## License + +Pop is released under a BSD License. See LICENSE file for details. diff --git a/TalkinToTheNet/Pods/pop/pop/POP.h b/TalkinToTheNet/Pods/pop/pop/POP.h new file mode 100644 index 0000000..72adba7 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POP.h @@ -0,0 +1,29 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#ifndef POP_POP_H +#define POP_POP_H + +#import + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import + +#endif /* POP_POP_H */ diff --git a/TalkinToTheNet/Pods/pop/pop/POPAction.h b/TalkinToTheNet/Pods/pop/pop/POPAction.h new file mode 100644 index 0000000..85cca19 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAction.h @@ -0,0 +1,67 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#ifndef POPACTION_H +#define POPACTION_H + +#import + +#import + +#ifdef __cplusplus + +namespace POP { + + /** + @abstract Disables Core Animation actions using RAII. + @discussion The disablement of actions is scoped to the current transaction. + */ + class ActionDisabler + { + BOOL state; + + public: + ActionDisabler() POP_NOTHROW + { + state = [CATransaction disableActions]; + [CATransaction setDisableActions:YES]; + } + + ~ActionDisabler() + { + [CATransaction setDisableActions:state]; + } + }; + + /** + @abstract Enables Core Animation actions using RAII. + @discussion The enablement of actions is scoped to the current transaction. + */ + class ActionEnabler + { + BOOL state; + + public: + ActionEnabler() POP_NOTHROW + { + state = [CATransaction disableActions]; + [CATransaction setDisableActions:NO]; + } + + ~ActionEnabler() + { + [CATransaction setDisableActions:state]; + } + }; + +} + +#endif /* __cplusplus */ + +#endif /* POPACTION_H */ diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimatableProperty.h b/TalkinToTheNet/Pods/pop/pop/POPAnimatableProperty.h new file mode 100644 index 0000000..1636783 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimatableProperty.h @@ -0,0 +1,249 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import + +#import + +@class POPMutableAnimatableProperty; + +/** + @abstract Describes an animatable property. + */ +@interface POPAnimatableProperty : NSObject + +/** + @abstract Property accessor. + @param name The name of the property. + @return The animatable property with that name or nil if it does not exist. + @discussion Common animatable properties are included by default. Use the provided constants to reference. + */ ++ (id)propertyWithName:(NSString *)name; + +/** + @abstract The designated initializer. + @param name The name of the property. + @param block The block used to configure the property on creation. + @return The animatable property with name if it exists, otherwise a newly created instance configured by block. + @discussion Custom properties should use reverse-DNS naming. A newly created instance is only mutable in the scope of block. Once constructed, a property becomes immutable. + */ ++ (id)propertyWithName:(NSString *)name initializer:(void (^)(POPMutableAnimatableProperty *prop))block; + +/** + @abstract The name of the property. + @discussion Used to uniquely identify an animatable property. + */ +@property (readonly, nonatomic, copy) NSString *name; + +/** + @abstract Block used to read values from a property into an array of floats. + */ +@property (readonly, nonatomic, copy) void (^readBlock)(id obj, CGFloat values[]); + +/** + @abstract Block used to write values from an array of floats into a property. + */ +@property (readonly, nonatomic, copy) void (^writeBlock)(id obj, const CGFloat values[]); + +/** + @abstract The threshold value used when determining completion of dynamics simulations. + */ +@property (readonly, nonatomic, assign) CGFloat threshold; + +@end + +/** + @abstract A mutable animatable property intended for configuration. + */ +@interface POPMutableAnimatableProperty : POPAnimatableProperty + +/** + @abstract A read-write version of POPAnimatableProperty name property. + */ +@property (readwrite, nonatomic, copy) NSString *name; + +/** + @abstract A read-write version of POPAnimatableProperty readBlock property. + */ +@property (readwrite, nonatomic, copy) void (^readBlock)(id obj, CGFloat values[]); + +/** + @abstract A read-write version of POPAnimatableProperty writeBlock property. + */ +@property (readwrite, nonatomic, copy) void (^writeBlock)(id obj, const CGFloat values[]); + +/** + @abstract A read-write version of POPAnimatableProperty threshold property. + */ +@property (readwrite, nonatomic, assign) CGFloat threshold; + +@end + +/** + Common CALayer property names. + */ +extern NSString * const kPOPLayerBackgroundColor; +extern NSString * const kPOPLayerBounds; +extern NSString * const kPOPLayerCornerRadius; +extern NSString * const kPOPLayerBorderWidth; +extern NSString * const kPOPLayerBorderColor; +extern NSString * const kPOPLayerOpacity; +extern NSString * const kPOPLayerPosition; +extern NSString * const kPOPLayerPositionX; +extern NSString * const kPOPLayerPositionY; +extern NSString * const kPOPLayerRotation; +extern NSString * const kPOPLayerRotationX; +extern NSString * const kPOPLayerRotationY; +extern NSString * const kPOPLayerScaleX; +extern NSString * const kPOPLayerScaleXY; +extern NSString * const kPOPLayerScaleY; +extern NSString * const kPOPLayerSize; +extern NSString * const kPOPLayerSubscaleXY; +extern NSString * const kPOPLayerSubtranslationX; +extern NSString * const kPOPLayerSubtranslationXY; +extern NSString * const kPOPLayerSubtranslationY; +extern NSString * const kPOPLayerSubtranslationZ; +extern NSString * const kPOPLayerTranslationX; +extern NSString * const kPOPLayerTranslationXY; +extern NSString * const kPOPLayerTranslationY; +extern NSString * const kPOPLayerTranslationZ; +extern NSString * const kPOPLayerZPosition; +extern NSString * const kPOPLayerShadowColor; +extern NSString * const kPOPLayerShadowOffset; +extern NSString * const kPOPLayerShadowOpacity; +extern NSString * const kPOPLayerShadowRadius; + +/** + Common CAShapeLayer property names. + */ +extern NSString * const kPOPShapeLayerStrokeStart; +extern NSString * const kPOPShapeLayerStrokeEnd; +extern NSString * const kPOPShapeLayerStrokeColor; +extern NSString * const kPOPShapeLayerFillColor; +extern NSString * const kPOPShapeLayerLineWidth; + +/** + Common NSLayoutConstraint property names. + */ +extern NSString * const kPOPLayoutConstraintConstant; + + +#if TARGET_OS_IPHONE + +/** + Common UIView property names. + */ +extern NSString * const kPOPViewAlpha; +extern NSString * const kPOPViewBackgroundColor; +extern NSString * const kPOPViewBounds; +extern NSString * const kPOPViewCenter; +extern NSString * const kPOPViewFrame; +extern NSString * const kPOPViewScaleX; +extern NSString * const kPOPViewScaleXY; +extern NSString * const kPOPViewScaleY; +extern NSString * const kPOPViewSize; +extern NSString * const kPOPViewTintColor; + +/** + Common UIScrollView property names. + */ +extern NSString * const kPOPScrollViewContentOffset; +extern NSString * const kPOPScrollViewContentSize; +extern NSString * const kPOPScrollViewZoomScale; +extern NSString * const kPOPScrollViewContentInset; + +/** + Common UITableView property names. + */ +extern NSString * const kPOPTableViewContentOffset; +extern NSString * const kPOPTableViewContentSize; + +/** + Common UICollectionView property names. + */ +extern NSString * const kPOPCollectionViewContentOffset; +extern NSString * const kPOPCollectionViewContentSize; + +/** + Common UINavigationBar property names. + */ +extern NSString * const kPOPNavigationBarBarTintColor; + +/** + Common UIToolbar property names. + */ +extern NSString * const kPOPToolbarBarTintColor; + +/** + Common UITabBar property names. + */ +extern NSString * const kPOPTabBarBarTintColor; + +/** + Common UILabel property names. + */ +extern NSString * const kPOPLabelTextColor; + +#else + +/** + Common NSView property names. + */ +extern NSString * const kPOPViewFrame; +extern NSString * const kPOPViewBounds; +extern NSString * const kPOPViewAlphaValue; +extern NSString * const kPOPViewFrameRotation; +extern NSString * const kPOPViewFrameCenterRotation; +extern NSString * const kPOPViewBoundsRotation; + +/** + Common NSWindow property names. + */ +extern NSString * const kPOPWindowFrame; +extern NSString * const kPOPWindowAlphaValue; +extern NSString * const kPOPWindowBackgroundColor; + +#endif + +#if SCENEKIT_SDK_AVAILABLE + +/** + Common SceneKit property names. + */ +extern NSString * const kPOPSCNNodePosition; +extern NSString * const kPOPSCNNodePositionX; +extern NSString * const kPOPSCNNodePositionY; +extern NSString * const kPOPSCNNodePositionZ; +extern NSString * const kPOPSCNNodeTranslation; +extern NSString * const kPOPSCNNodeTranslationX; +extern NSString * const kPOPSCNNodeTranslationY; +extern NSString * const kPOPSCNNodeTranslationZ; +extern NSString * const kPOPSCNNodeRotation; +extern NSString * const kPOPSCNNodeRotationX; +extern NSString * const kPOPSCNNodeRotationY; +extern NSString * const kPOPSCNNodeRotationZ; +extern NSString * const kPOPSCNNodeRotationW; +extern NSString * const kPOPSCNNodeEulerAngles; +extern NSString * const kPOPSCNNodeEulerAnglesX; +extern NSString * const kPOPSCNNodeEulerAnglesY; +extern NSString * const kPOPSCNNodeEulerAnglesZ; +extern NSString * const kPOPSCNNodeOrientation; +extern NSString * const kPOPSCNNodeOrientationX; +extern NSString * const kPOPSCNNodeOrientationY; +extern NSString * const kPOPSCNNodeOrientationZ; +extern NSString * const kPOPSCNNodeOrientationW; +extern NSString * const kPOPSCNNodeScale; +extern NSString * const kPOPSCNNodeScaleX; +extern NSString * const kPOPSCNNodeScaleY; +extern NSString * const kPOPSCNNodeScaleZ; +extern NSString * const kPOPSCNNodeScaleXY; + +#endif diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimatableProperty.mm b/TalkinToTheNet/Pods/pop/pop/POPAnimatableProperty.mm new file mode 100644 index 0000000..c8b3130 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimatableProperty.mm @@ -0,0 +1,1282 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimatableProperty.h" + +#import + +#import "POPAnimationRuntime.h" +#import "POPCGUtils.h" +#import "POPDefines.h" +#import "POPLayerExtras.h" + +// common threshold definitions +static CGFloat const kPOPThresholdColor = 0.01; +static CGFloat const kPOPThresholdPoint = 1.0; +static CGFloat const kPOPThresholdOpacity = 0.01; +static CGFloat const kPOPThresholdScale = 0.005; +static CGFloat const kPOPThresholdRotation = 0.01; +static CGFloat const kPOPThresholdRadius = 0.01; + +#pragma mark - Static + +// CALayer +NSString * const kPOPLayerBackgroundColor = @"backgroundColor"; +NSString * const kPOPLayerBounds = @"bounds"; +NSString * const kPOPLayerCornerRadius = @"cornerRadius"; +NSString * const kPOPLayerBorderWidth = @"borderWidth"; +NSString * const kPOPLayerBorderColor = @"borderColor"; +NSString * const kPOPLayerOpacity = @"opacity"; +NSString * const kPOPLayerPosition = @"position"; +NSString * const kPOPLayerPositionX = @"positionX"; +NSString * const kPOPLayerPositionY = @"positionY"; +NSString * const kPOPLayerRotation = @"rotation"; +NSString * const kPOPLayerRotationX = @"rotationX"; +NSString * const kPOPLayerRotationY = @"rotationY"; +NSString * const kPOPLayerScaleX = @"scaleX"; +NSString * const kPOPLayerScaleXY = @"scaleXY"; +NSString * const kPOPLayerScaleY = @"scaleY"; +NSString * const kPOPLayerSize = @"size"; +NSString * const kPOPLayerSubscaleXY = @"subscaleXY"; +NSString * const kPOPLayerSubtranslationX = @"subtranslationX"; +NSString * const kPOPLayerSubtranslationXY = @"subtranslationXY"; +NSString * const kPOPLayerSubtranslationY = @"subtranslationY"; +NSString * const kPOPLayerSubtranslationZ = @"subtranslationZ"; +NSString * const kPOPLayerTranslationX = @"translationX"; +NSString * const kPOPLayerTranslationXY = @"translationXY"; +NSString * const kPOPLayerTranslationY = @"translationY"; +NSString * const kPOPLayerTranslationZ = @"translationZ"; +NSString * const kPOPLayerZPosition = @"zPosition"; +NSString * const kPOPLayerShadowColor = @"shadowColor"; +NSString * const kPOPLayerShadowOffset = @"shadowOffset"; +NSString * const kPOPLayerShadowOpacity = @"shadowOpacity"; +NSString * const kPOPLayerShadowRadius = @"shadowRadius"; + +// CAShapeLayer +NSString * const kPOPShapeLayerStrokeStart = @"shapeLayer.strokeStart"; +NSString * const kPOPShapeLayerStrokeEnd = @"shapeLayer.strokeEnd"; +NSString * const kPOPShapeLayerStrokeColor = @"shapeLayer.strokeColor"; +NSString * const kPOPShapeLayerFillColor = @"shapeLayer.fillColor"; +NSString * const kPOPShapeLayerLineWidth = @"shapeLayer.lineWidth"; + +// NSLayoutConstraint +NSString * const kPOPLayoutConstraintConstant = @"layoutConstraint.constant"; + +#if TARGET_OS_IPHONE + +// UIView +NSString * const kPOPViewAlpha = @"view.alpha"; +NSString * const kPOPViewBackgroundColor = @"view.backgroundColor"; +NSString * const kPOPViewBounds = kPOPLayerBounds; +NSString * const kPOPViewCenter = @"view.center"; +NSString * const kPOPViewFrame = @"view.frame"; +NSString * const kPOPViewScaleX = @"view.scaleX"; +NSString * const kPOPViewScaleXY = @"view.scaleXY"; +NSString * const kPOPViewScaleY = @"view.scaleY"; +NSString * const kPOPViewSize = kPOPLayerSize; +NSString * const kPOPViewTintColor = @"view.tintColor"; + +// UIScrollView +NSString * const kPOPScrollViewContentOffset = @"scrollView.contentOffset"; +NSString * const kPOPScrollViewContentSize = @"scrollView.contentSize"; +NSString * const kPOPScrollViewZoomScale = @"scrollView.zoomScale"; +NSString * const kPOPScrollViewContentInset = @"scrollView.contentInset"; + +// UITableView +NSString * const kPOPTableViewContentOffset = kPOPScrollViewContentOffset; +NSString * const kPOPTableViewContentSize = kPOPScrollViewContentSize; + +// UICollectionView +NSString * const kPOPCollectionViewContentOffset = kPOPScrollViewContentOffset; +NSString * const kPOPCollectionViewContentSize = kPOPScrollViewContentSize; + +// UINavigationBar +NSString * const kPOPNavigationBarBarTintColor = @"navigationBar.barTintColor"; + +// UIToolbar +NSString * const kPOPToolbarBarTintColor = kPOPNavigationBarBarTintColor; + +// UITabBar +NSString * const kPOPTabBarBarTintColor = kPOPNavigationBarBarTintColor; + +// UILabel +NSString * const kPOPLabelTextColor = @"label.textColor"; + +#else + +// NSView +NSString * const kPOPViewFrame = @"view.frame"; +NSString * const kPOPViewBounds = @"view.bounds"; +NSString * const kPOPViewAlphaValue = @"view.alphaValue"; +NSString * const kPOPViewFrameRotation = @"view.frameRotation"; +NSString * const kPOPViewFrameCenterRotation = @"view.frameCenterRotation"; +NSString * const kPOPViewBoundsRotation = @"view.boundsRotation"; + +// NSWindow +NSString * const kPOPWindowFrame = @"window.frame"; +NSString * const kPOPWindowAlphaValue = @"window.alphaValue"; +NSString * const kPOPWindowBackgroundColor = @"window.backgroundColor"; + +#endif + +#if SCENEKIT_SDK_AVAILABLE + +// SceneKit +NSString * const kPOPSCNNodePosition = @"scnode.position"; +NSString * const kPOPSCNNodePositionX = @"scnnode.position.x"; +NSString * const kPOPSCNNodePositionY = @"scnnode.position.y"; +NSString * const kPOPSCNNodePositionZ = @"scnnode.position.z"; +NSString * const kPOPSCNNodeTranslation = @"scnnode.translation"; +NSString * const kPOPSCNNodeTranslationX = @"scnnode.translation.x"; +NSString * const kPOPSCNNodeTranslationY = @"scnnode.translation.y"; +NSString * const kPOPSCNNodeTranslationZ = @"scnnode.translation.z"; +NSString * const kPOPSCNNodeRotation = @"scnnode.rotation"; +NSString * const kPOPSCNNodeRotationX = @"scnnode.rotation.x"; +NSString * const kPOPSCNNodeRotationY = @"scnnode.rotation.y"; +NSString * const kPOPSCNNodeRotationZ = @"scnnode.rotation.z"; +NSString * const kPOPSCNNodeRotationW = @"scnnode.rotation.w"; +NSString * const kPOPSCNNodeEulerAngles = @"scnnode.eulerAngles"; +NSString * const kPOPSCNNodeEulerAnglesX = @"scnnode.eulerAngles.x"; +NSString * const kPOPSCNNodeEulerAnglesY = @"scnnode.eulerAngles.y"; +NSString * const kPOPSCNNodeEulerAnglesZ = @"scnnode.eulerAngles.z"; +NSString * const kPOPSCNNodeOrientation = @"scnnode.orientation"; +NSString * const kPOPSCNNodeOrientationX = @"scnnode.orientation.x"; +NSString * const kPOPSCNNodeOrientationY = @"scnnode.orientation.y"; +NSString * const kPOPSCNNodeOrientationZ = @"scnnode.orientation.z"; +NSString * const kPOPSCNNodeOrientationW = @"scnnode.orientation.w"; +NSString * const kPOPSCNNodeScale = @"scnnode.scale"; +NSString * const kPOPSCNNodeScaleX = @"scnnode.scale.x"; +NSString * const kPOPSCNNodeScaleY = @"scnnode.scale.y"; +NSString * const kPOPSCNNodeScaleZ = @"scnnode.scale.z"; +NSString * const kPOPSCNNodeScaleXY = @"scnnode.scale.xy"; + +#endif + +/** + State structure internal to static animatable property. + */ +typedef struct +{ + NSString *name; + pop_animatable_read_block readBlock; + pop_animatable_write_block writeBlock; + CGFloat threshold; +} _POPStaticAnimatablePropertyState; +typedef _POPStaticAnimatablePropertyState POPStaticAnimatablePropertyState; + +static POPStaticAnimatablePropertyState _staticStates[] = +{ + /* CALayer */ + + {kPOPLayerBackgroundColor, + ^(CALayer *obj, CGFloat values[]) { + POPCGColorGetRGBAComponents(obj.backgroundColor, values); + }, + ^(CALayer *obj, const CGFloat values[]) { + CGColorRef color = POPCGColorRGBACreate(values); + [obj setBackgroundColor:color]; + CGColorRelease(color); + }, + kPOPThresholdColor + }, + + {kPOPLayerBounds, + ^(CALayer *obj, CGFloat values[]) { + values_from_rect(values, [obj bounds]); + }, + ^(CALayer *obj, const CGFloat values[]) { + [obj setBounds:values_to_rect(values)]; + }, + kPOPThresholdPoint + }, + + {kPOPLayerCornerRadius, + ^(CALayer *obj, CGFloat values[]) { + values[0] = [obj cornerRadius]; + }, + ^(CALayer *obj, const CGFloat values[]) { + [obj setCornerRadius:values[0]]; + }, + kPOPThresholdRadius + }, + + {kPOPLayerBorderWidth, + ^(CALayer *obj, CGFloat values[]) { + values[0] = [obj borderWidth]; + }, + ^(CALayer *obj, const CGFloat values[]) { + [obj setBorderWidth:values[0]]; + }, + 0.01 + }, + + {kPOPLayerBorderColor, + ^(CALayer *obj, CGFloat values[]) { + POPCGColorGetRGBAComponents(obj.borderColor, values); + }, + ^(CALayer *obj, const CGFloat values[]) { + CGColorRef color = POPCGColorRGBACreate(values); + [obj setBorderColor:color]; + CGColorRelease(color); + }, + kPOPThresholdColor + }, + + {kPOPLayerPosition, + ^(CALayer *obj, CGFloat values[]) { + values_from_point(values, [(CALayer *)obj position]); + }, + ^(CALayer *obj, const CGFloat values[]) { + [obj setPosition:values_to_point(values)]; + }, + kPOPThresholdPoint + }, + + {kPOPLayerPositionX, + ^(CALayer *obj, CGFloat values[]) { + values[0] = [(CALayer *)obj position].x; + }, + ^(CALayer *obj, const CGFloat values[]) { + CGPoint p = [(CALayer *)obj position]; + p.x = values[0]; + [obj setPosition:p]; + }, + kPOPThresholdPoint + }, + + {kPOPLayerPositionY, + ^(CALayer *obj, CGFloat values[]) { + values[0] = [(CALayer *)obj position].y; + }, + ^(CALayer *obj, const CGFloat values[]) { + CGPoint p = [(CALayer *)obj position]; + p.y = values[0]; + [obj setPosition:p]; + }, + kPOPThresholdPoint + }, + + {kPOPLayerOpacity, + ^(CALayer *obj, CGFloat values[]) { + values[0] = [obj opacity]; + }, + ^(CALayer *obj, const CGFloat values[]) { + [obj setOpacity:((float)values[0])]; + }, + kPOPThresholdOpacity + }, + + {kPOPLayerScaleX, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetScaleX(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetScaleX(obj, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPLayerScaleY, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetScaleY(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetScaleY(obj, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPLayerScaleXY, + ^(CALayer *obj, CGFloat values[]) { + values_from_point(values, POPLayerGetScaleXY(obj)); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetScaleXY(obj, values_to_point(values)); + }, + kPOPThresholdScale + }, + + {kPOPLayerSubscaleXY, + ^(CALayer *obj, CGFloat values[]) { + values_from_point(values, POPLayerGetSubScaleXY(obj)); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetSubScaleXY(obj, values_to_point(values)); + }, + kPOPThresholdScale + }, + + {kPOPLayerTranslationX, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetTranslationX(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetTranslationX(obj, values[0]); + }, + kPOPThresholdPoint + }, + + {kPOPLayerTranslationY, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetTranslationY(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetTranslationY(obj, values[0]); + }, + kPOPThresholdPoint + }, + + {kPOPLayerTranslationZ, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetTranslationZ(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetTranslationZ(obj, values[0]); + }, + kPOPThresholdPoint + }, + + {kPOPLayerTranslationXY, + ^(CALayer *obj, CGFloat values[]) { + values_from_point(values, POPLayerGetTranslationXY(obj)); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetTranslationXY(obj, values_to_point(values)); + }, + kPOPThresholdPoint + }, + + {kPOPLayerSubtranslationX, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetSubTranslationX(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetSubTranslationX(obj, values[0]); + }, + kPOPThresholdPoint + }, + + {kPOPLayerSubtranslationY, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetSubTranslationY(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetSubTranslationY(obj, values[0]); + }, + kPOPThresholdPoint + }, + + {kPOPLayerSubtranslationZ, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetSubTranslationZ(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetSubTranslationZ(obj, values[0]); + }, + kPOPThresholdPoint + }, + + {kPOPLayerSubtranslationXY, + ^(CALayer *obj, CGFloat values[]) { + values_from_point(values, POPLayerGetSubTranslationXY(obj)); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetSubTranslationXY(obj, values_to_point(values)); + }, + kPOPThresholdPoint + }, + + {kPOPLayerZPosition, + ^(CALayer *obj, CGFloat values[]) { + values[0] = [obj zPosition]; + }, + ^(CALayer *obj, const CGFloat values[]) { + [obj setZPosition:values[0]]; + }, + kPOPThresholdPoint + }, + + {kPOPLayerSize, + ^(CALayer *obj, CGFloat values[]) { + values_from_size(values, [obj bounds].size); + }, + ^(CALayer *obj, const CGFloat values[]) { + CGSize size = values_to_size(values); + if (size.width < 0. || size.height < 0.) + return; + + CGRect b = [obj bounds]; + b.size = size; + [obj setBounds:b]; + }, + kPOPThresholdPoint + }, + + {kPOPLayerRotation, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetRotation(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetRotation(obj, values[0]); + }, + kPOPThresholdRotation + }, + + {kPOPLayerRotationY, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetRotationY(obj); + }, + ^(id obj, const CGFloat values[]) { + POPLayerSetRotationY(obj, values[0]); + }, + kPOPThresholdRotation + }, + + {kPOPLayerRotationX, + ^(CALayer *obj, CGFloat values[]) { + values[0] = POPLayerGetRotationX(obj); + }, + ^(CALayer *obj, const CGFloat values[]) { + POPLayerSetRotationX(obj, values[0]); + }, + kPOPThresholdRotation + }, + + {kPOPLayerShadowColor, + ^(CALayer *obj, CGFloat values[]) { + POPCGColorGetRGBAComponents(obj.shadowColor, values); + }, + ^(CALayer *obj, const CGFloat values[]) { + CGColorRef color = POPCGColorRGBACreate(values); + [obj setShadowColor:color]; + CGColorRelease(color); + }, + 0.01 + }, + + {kPOPLayerShadowOffset, + ^(CALayer *obj, CGFloat values[]) { + values_from_size(values, [obj shadowOffset]); + }, + ^(CALayer *obj, const CGFloat values[]) { + CGSize size = values_to_size(values); + [obj setShadowOffset:size]; + }, + 0.01 + }, + + {kPOPLayerShadowOpacity, + ^(CALayer *obj, CGFloat values[]) { + values[0] = [obj shadowOpacity]; + }, + ^(CALayer *obj, const CGFloat values[]) { + [obj setShadowOpacity:values[0]]; + }, + kPOPThresholdOpacity + }, + + {kPOPLayerShadowRadius, + ^(CALayer *obj, CGFloat values[]) { + values[0] = [obj shadowRadius]; + }, + ^(CALayer *obj, const CGFloat values[]) { + [obj setShadowRadius:values[0]]; + }, + kPOPThresholdRadius + }, + + /* CAShapeLayer */ + + {kPOPShapeLayerStrokeStart, + ^(CAShapeLayer *obj, CGFloat values[]) { + values[0] = obj.strokeStart; + }, + ^(CAShapeLayer *obj, const CGFloat values[]) { + obj.strokeStart = values[0]; + }, + 0.01 + }, + + {kPOPShapeLayerStrokeEnd, + ^(CAShapeLayer *obj, CGFloat values[]) { + values[0] = obj.strokeEnd; + }, + ^(CAShapeLayer *obj, const CGFloat values[]) { + obj.strokeEnd = values[0]; + }, + 0.01 + }, + + {kPOPShapeLayerStrokeColor, + ^(CAShapeLayer *obj, CGFloat values[]) { + POPCGColorGetRGBAComponents(obj.strokeColor, values); + }, + ^(CAShapeLayer *obj, const CGFloat values[]) { + CGColorRef color = POPCGColorRGBACreate(values); + [obj setStrokeColor:color]; + CGColorRelease(color); + }, + kPOPThresholdColor + }, + + {kPOPShapeLayerFillColor, + ^(CAShapeLayer *obj, CGFloat values[]) { + POPCGColorGetRGBAComponents(obj.fillColor, values); + }, + ^(CAShapeLayer *obj, const CGFloat values[]) { + CGColorRef color = POPCGColorRGBACreate(values); + [obj setFillColor:color]; + CGColorRelease(color); + }, + kPOPThresholdColor + }, + + {kPOPShapeLayerLineWidth, + ^(CAShapeLayer *obj, CGFloat values[]) { + values[0] = obj.lineWidth; + }, + ^(CAShapeLayer *obj, const CGFloat values[]) { + obj.lineWidth = values[0]; + }, + 0.01 + }, + + {kPOPLayoutConstraintConstant, + ^(NSLayoutConstraint *obj, CGFloat values[]) { + values[0] = obj.constant; + }, + ^(NSLayoutConstraint *obj, const CGFloat values[]) { + obj.constant = values[0]; + }, + 0.01 + }, + +#if TARGET_OS_IPHONE + + /* UIView */ + + {kPOPViewAlpha, + ^(UIView *obj, CGFloat values[]) { + values[0] = obj.alpha; + }, + ^(UIView *obj, const CGFloat values[]) { + obj.alpha = values[0]; + }, + kPOPThresholdOpacity + }, + + {kPOPViewBackgroundColor, + ^(UIView *obj, CGFloat values[]) { + POPUIColorGetRGBAComponents(obj.backgroundColor, values); + }, + ^(UIView *obj, const CGFloat values[]) { + obj.backgroundColor = POPUIColorRGBACreate(values); + }, + kPOPThresholdColor + }, + + {kPOPViewCenter, + ^(UIView *obj, CGFloat values[]) { + values_from_point(values, obj.center); + }, + ^(UIView *obj, const CGFloat values[]) { + obj.center = values_to_point(values); + }, + kPOPThresholdPoint + }, + + {kPOPViewFrame, + ^(UIView *obj, CGFloat values[]) { + values_from_rect(values, obj.frame); + }, + ^(UIView *obj, const CGFloat values[]) { + obj.frame = values_to_rect(values); + }, + kPOPThresholdPoint + }, + + {kPOPViewScaleX, + ^(UIView *obj, CGFloat values[]) { + values[0] = POPLayerGetScaleX(obj.layer); + }, + ^(UIView *obj, const CGFloat values[]) { + POPLayerSetScaleX(obj.layer, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPViewScaleY, + ^(UIView *obj, CGFloat values[]) { + values[0] = POPLayerGetScaleY(obj.layer); + }, + ^(UIView *obj, const CGFloat values[]) { + POPLayerSetScaleY(obj.layer, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPViewScaleXY, + ^(UIView *obj, CGFloat values[]) { + values_from_point(values, POPLayerGetScaleXY(obj.layer)); + }, + ^(UIView *obj, const CGFloat values[]) { + POPLayerSetScaleXY(obj.layer, values_to_point(values)); + }, + kPOPThresholdScale + }, + + {kPOPViewTintColor, + ^(UIView *obj, CGFloat values[]) { + POPUIColorGetRGBAComponents(obj.tintColor, values); + }, + ^(UIView *obj, const CGFloat values[]) { + obj.tintColor = POPUIColorRGBACreate(values); + }, + kPOPThresholdColor + }, + + /* UIScrollView */ + + {kPOPScrollViewContentOffset, + ^(UIScrollView *obj, CGFloat values[]) { + values_from_point(values, obj.contentOffset); + }, + ^(UIScrollView *obj, const CGFloat values[]) { + [obj setContentOffset:values_to_point(values) animated:NO]; + }, + kPOPThresholdPoint + }, + + {kPOPScrollViewContentSize, + ^(UIScrollView *obj, CGFloat values[]) { + values_from_size(values, obj.contentSize); + }, + ^(UIScrollView *obj, const CGFloat values[]) { + obj.contentSize = values_to_size(values); + }, + kPOPThresholdPoint + }, + + {kPOPScrollViewZoomScale, + ^(UIScrollView *obj, CGFloat values[]) { + values[0]=obj.zoomScale; + }, + ^(UIScrollView *obj, const CGFloat values[]) { + obj.zoomScale=values[0]; + }, + kPOPThresholdScale + }, + + {kPOPScrollViewContentInset, + ^(UIScrollView *obj, CGFloat values[]) { + values[0] = obj.contentInset.top; + values[1] = obj.contentInset.left; + values[2] = obj.contentInset.bottom; + values[3] = obj.contentInset.right; + }, + ^(UIScrollView *obj, const CGFloat values[]) { + obj.contentInset = values_to_edge_insets(values); + }, + kPOPThresholdPoint + }, + + /* UINavigationBar */ + + {kPOPNavigationBarBarTintColor, + ^(UINavigationBar *obj, CGFloat values[]) { + POPUIColorGetRGBAComponents(obj.barTintColor, values); + }, + ^(UINavigationBar *obj, const CGFloat values[]) { + obj.barTintColor = POPUIColorRGBACreate(values); + }, + kPOPThresholdColor + }, + + /* UILabel */ + + {kPOPLabelTextColor, + ^(UILabel *obj, CGFloat values[]) { + POPUIColorGetRGBAComponents(obj.textColor, values); + }, + ^(UILabel *obj, const CGFloat values[]) { + obj.textColor = POPUIColorRGBACreate(values); + }, + kPOPThresholdColor + }, + +#else + + /* NSView */ + + {kPOPViewFrame, + ^(NSView *obj, CGFloat values[]) { + values_from_rect(values, NSRectToCGRect(obj.frame)); + }, + ^(NSView *obj, const CGFloat values[]) { + obj.frame = NSRectFromCGRect(values_to_rect(values)); + }, + kPOPThresholdPoint + }, + + {kPOPViewBounds, + ^(NSView *obj, CGFloat values[]) { + values_from_rect(values, NSRectToCGRect(obj.frame)); + }, + ^(NSView *obj, const CGFloat values[]) { + obj.bounds = NSRectFromCGRect(values_to_rect(values)); + }, + kPOPThresholdPoint + }, + + {kPOPViewAlphaValue, + ^(NSView *obj, CGFloat values[]) { + values[0] = obj.alphaValue; + }, + ^(NSView *obj, const CGFloat values[]) { + obj.alphaValue = values[0]; + }, + kPOPThresholdOpacity + }, + + {kPOPViewFrameRotation, + ^(NSView *obj, CGFloat values[]) { + values[0] = obj.frameRotation; + }, + ^(NSView *obj, const CGFloat values[]) { + obj.frameRotation = values[0]; + }, + kPOPThresholdRotation + }, + + {kPOPViewFrameCenterRotation, + ^(NSView *obj, CGFloat values[]) { + values[0] = obj.frameCenterRotation; + }, + ^(NSView *obj, const CGFloat values[]) { + obj.frameCenterRotation = values[0]; + }, + kPOPThresholdRotation + }, + + {kPOPViewBoundsRotation, + ^(NSView *obj, CGFloat values[]) { + values[0] = obj.boundsRotation; + }, + ^(NSView *obj, const CGFloat values[]) { + obj.boundsRotation = values[0]; + }, + kPOPThresholdRotation + }, + + /* NSWindow */ + + {kPOPWindowFrame, + ^(NSWindow *obj, CGFloat values[]) { + values_from_rect(values, NSRectToCGRect(obj.frame)); + }, + ^(NSWindow *obj, const CGFloat values[]) { + [obj setFrame:NSRectFromCGRect(values_to_rect(values)) display:YES]; + }, + kPOPThresholdPoint + }, + + {kPOPWindowAlphaValue, + ^(NSWindow *obj, CGFloat values[]) { + values[0] = obj.alphaValue; + }, + ^(NSWindow *obj, const CGFloat values[]) { + obj.alphaValue = values[0]; + }, + kPOPThresholdOpacity + }, + + {kPOPWindowBackgroundColor, + ^(NSWindow *obj, CGFloat values[]) { + POPNSColorGetRGBAComponents(obj.backgroundColor, values); + }, + ^(NSWindow *obj, const CGFloat values[]) { + obj.backgroundColor = POPNSColorRGBACreate(values); + }, + kPOPThresholdColor + }, + +#endif + +#if SCENEKIT_SDK_AVAILABLE + + /* SceneKit */ + + {kPOPSCNNodePosition, + ^(SCNNode *obj, CGFloat values[]) { + values_from_vec3(values, obj.position); + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.position = values_to_vec3(values); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodePositionX, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.position.x; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.position = SCNVector3Make(values[0], obj.position.y, obj.position.z); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodePositionY, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.position.y; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.position = SCNVector3Make(obj.position.x, values[0], obj.position.z); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodePositionZ, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.position.z; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.position = SCNVector3Make(obj.position.x, obj.position.y, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeTranslation, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.transform.m41; + values[1] = obj.transform.m42; + values[2] = obj.transform.m43; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.transform = SCNMatrix4MakeTranslation(values[0], values[1], values[2]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeTranslationX, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.transform.m41; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.transform = SCNMatrix4MakeTranslation(values[0], obj.transform.m42, obj.transform.m43); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeTranslationY, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.transform.m42; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.transform = SCNMatrix4MakeTranslation(obj.transform.m41, values[0], obj.transform.m43); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeTranslationY, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.transform.m43; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.transform = SCNMatrix4MakeTranslation(obj.transform.m41, obj.transform.m42, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeRotation, + ^(SCNNode *obj, CGFloat values[]) { + values_from_vec4(values, obj.rotation); + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.rotation = values_to_vec4(values); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeRotationX, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.rotation.x; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.rotation = SCNVector4Make(1.0, obj.rotation.y, obj.rotation.z, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeRotationY, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.rotation.y; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.rotation = SCNVector4Make(obj.rotation.x, 1.0, obj.rotation.z, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeRotationZ, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.rotation.z; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.rotation = SCNVector4Make(obj.rotation.x, obj.rotation.y, 1.0, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeRotationW, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.rotation.w; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.rotation = SCNVector4Make(obj.rotation.x, obj.rotation.y, obj.rotation.z, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeEulerAngles, + ^(SCNNode *obj, CGFloat values[]) { + values_from_vec3(values, obj.eulerAngles); + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.eulerAngles = values_to_vec3(values); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeEulerAnglesX, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.eulerAngles.x; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.eulerAngles = SCNVector3Make(values[0], obj.eulerAngles.y, obj.eulerAngles.z); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeEulerAnglesY, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.eulerAngles.y; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.eulerAngles = SCNVector3Make(obj.eulerAngles.x, values[0], obj.eulerAngles.z); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeEulerAnglesZ, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.eulerAngles.z; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.eulerAngles = SCNVector3Make(obj.eulerAngles.x, obj.eulerAngles.y, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeOrientation, + ^(SCNNode *obj, CGFloat values[]) { + values_from_vec4(values, obj.orientation); + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.orientation = values_to_vec4(values); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeOrientationX, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.orientation.x; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.orientation = SCNVector4Make(values[0], obj.orientation.y, obj.orientation.z, obj.orientation.w); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeOrientationY, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.orientation.y; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.orientation = SCNVector4Make(obj.orientation.x, values[0], obj.orientation.z, obj.orientation.w); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeOrientationZ, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.orientation.z; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.orientation = SCNVector4Make(obj.orientation.x, obj.orientation.y, values[0], obj.orientation.w); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeOrientationW, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.orientation.w; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.orientation = SCNVector4Make(obj.orientation.x, obj.orientation.y, obj.orientation.z, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeScale, + ^(SCNNode *obj, CGFloat values[]) { + values_from_vec3(values, obj.scale); + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.scale = values_to_vec3(values); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeScaleX, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.scale.x; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.scale = SCNVector3Make(values[0], obj.scale.y, obj.scale.z); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeScaleY, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.scale.y; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.position = SCNVector3Make(obj.scale.x, values[0], obj.scale.z); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeScaleZ, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.scale.z; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.scale = SCNVector3Make(obj.scale.x, obj.scale.y, values[0]); + }, + kPOPThresholdScale + }, + + {kPOPSCNNodeScaleXY, + ^(SCNNode *obj, CGFloat values[]) { + values[0] = obj.scale.x; + values[1] = obj.scale.y; + }, + ^(SCNNode *obj, const CGFloat values[]) { + obj.scale = SCNVector3Make(values[0], values[1], obj.scale.z); + }, + kPOPThresholdScale + }, + +#endif + +}; + +static NSUInteger staticIndexWithName(NSString *aName) +{ + NSUInteger idx = 0; + + while (idx < POP_ARRAY_COUNT(_staticStates)) { + if ([_staticStates[idx].name isEqualToString:aName]) + return idx; + idx++; + } + + return NSNotFound; +} + +/** + Concrete static property class. + */ +@interface POPStaticAnimatableProperty : POPAnimatableProperty +{ +@public + POPStaticAnimatablePropertyState *_state; +} +@end + +@implementation POPStaticAnimatableProperty + +- (NSString *)name +{ + return _state->name; +} + +- (pop_animatable_read_block)readBlock +{ + return _state->readBlock; +} + +- (pop_animatable_write_block)writeBlock +{ + return _state->writeBlock; +} + +- (CGFloat)threshold +{ + return _state->threshold; +} + +@end + +#pragma mark - Concrete + +/** + Concrete immutable property class. + */ +@interface POPConcreteAnimatableProperty : POPAnimatableProperty +- (instancetype)initWithName:(NSString *)name readBlock:(pop_animatable_read_block)read writeBlock:(pop_animatable_write_block)write threshold:(CGFloat)threshold; +@end + +@implementation POPConcreteAnimatableProperty + +// default synthesis +@synthesize name, readBlock, writeBlock, threshold; + +- (instancetype)initWithName:(NSString *)aName readBlock:(pop_animatable_read_block)aReadBlock writeBlock:(pop_animatable_write_block)aWriteBlock threshold:(CGFloat)aThreshold +{ + self = [super init]; + if (nil != self) { + name = [aName copy]; + readBlock = [aReadBlock copy]; + writeBlock = [aWriteBlock copy]; + threshold = aThreshold; + } + return self; +} +@end + +#pragma mark - Mutable + +@implementation POPMutableAnimatableProperty + +// default synthesis +@synthesize name, readBlock, writeBlock, threshold; + +@end + +#pragma mark - Cluster + +/** + Singleton placeholder property class to support class cluster. + */ +@interface POPPlaceholderAnimatableProperty : POPAnimatableProperty + +@end + +@implementation POPPlaceholderAnimatableProperty + +// default synthesis +@synthesize name, readBlock, writeBlock, threshold; + +@end + +/** + Cluster class. + */ +@implementation POPAnimatableProperty + +// avoid creating backing ivars +@dynamic name, readBlock, writeBlock, threshold; + +static POPAnimatableProperty *placeholder = nil; + ++ (void)initialize +{ + if (self == [POPAnimatableProperty class]) { + placeholder = [POPPlaceholderAnimatableProperty alloc]; + } +} + ++ (id)allocWithZone:(struct _NSZone *)zone +{ + if (self == [POPAnimatableProperty class]) { + if (nil == placeholder) { + placeholder = [super allocWithZone:zone]; + } + return placeholder; + } + return [super allocWithZone:zone]; +} + +- (id)copyWithZone:(NSZone *)zone +{ + if ([self isKindOfClass:[POPMutableAnimatableProperty class]]) { + POPConcreteAnimatableProperty *copyProperty = [[POPConcreteAnimatableProperty alloc] initWithName:self.name readBlock:self.readBlock writeBlock:self.writeBlock threshold:self.threshold]; + return copyProperty; + } else { + return self; + } +} + +- (id)mutableCopyWithZone:(NSZone *)zone +{ + POPMutableAnimatableProperty *copyProperty = [[POPMutableAnimatableProperty alloc] init]; + copyProperty.name = self.name; + copyProperty.readBlock = self.readBlock; + copyProperty.writeBlock = self.writeBlock; + copyProperty.threshold = self.threshold; + return copyProperty; +} + ++ (id)propertyWithName:(NSString *)aName +{ + return [self propertyWithName:aName initializer:NULL]; +} + ++ (id)propertyWithName:(NSString *)aName initializer:(void (^)(POPMutableAnimatableProperty *prop))aBlock +{ + POPAnimatableProperty *prop = nil; + + static NSMutableDictionary *_propertyDict = nil; + if (nil == _propertyDict) { + _propertyDict = [[NSMutableDictionary alloc] initWithCapacity:10]; + } + + prop = _propertyDict[aName]; + if (nil != prop) { + return prop; + } + + NSUInteger staticIdx = staticIndexWithName(aName); + + if (NSNotFound != staticIdx) { + POPStaticAnimatableProperty *staticProp = [[POPStaticAnimatableProperty alloc] init]; + staticProp->_state = &_staticStates[staticIdx]; + _propertyDict[aName] = staticProp; + prop = staticProp; + } else if (NULL != aBlock) { + POPMutableAnimatableProperty *mutableProp = [[POPMutableAnimatableProperty alloc] init]; + mutableProp.name = aName; + mutableProp.threshold = 1.0; + aBlock(mutableProp); + prop = [mutableProp copy]; + } + + return prop; +} + +- (NSString *)description +{ + NSMutableString *s = [NSMutableString stringWithFormat:@"%@ name:%@ threshold:%f", super.description, self.name, self.threshold]; + return s; +} + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimation.h b/TalkinToTheNet/Pods/pop/pop/POPAnimation.h new file mode 100644 index 0000000..3c710f2 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimation.h @@ -0,0 +1,188 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import +#import + +@class CAMediaTimingFunction; + +/** + @abstract The abstract animation base class. + @discussion Instantiate and use one of the concrete animation subclasses. + */ +@interface POPAnimation : NSObject + +/** + @abstract The name of the animation. + @discussion Optional property to help identify the animation. + */ +@property (copy, nonatomic) NSString *name; + +/** + @abstract The beginTime of the animation in media time. + @discussion Defaults to 0 and starts immediately. + */ +@property (assign, nonatomic) CFTimeInterval beginTime; + +/** + @abstract The animation delegate. + @discussion See {@ref POPAnimationDelegate} for details. + */ +@property (weak, nonatomic) id delegate; + +/** + @abstract The animation tracer. + @discussion Returns the existing tracer, creating one if needed. Call start/stop on the tracer to toggle event collection. + */ +@property (readonly, nonatomic) POPAnimationTracer *tracer; + +/** + @abstract Optional block called on animation start. + */ +@property (copy, nonatomic) void (^animationDidStartBlock)(POPAnimation *anim); + +/** + @abstract Optional block called when value meets or exceeds to value. + */ +@property (copy, nonatomic) void (^animationDidReachToValueBlock)(POPAnimation *anim); + +/** + @abstract Optional block called on animation completion. + */ +@property (copy, nonatomic) void (^completionBlock)(POPAnimation *anim, BOOL finished); + +/** + @abstract Optional block called each frame animation is applied. + */ +@property (copy, nonatomic) void (^animationDidApplyBlock)(POPAnimation *anim); + +/** + @abstract Flag indicating whether animation should be removed on completion. + @discussion Setting to NO can facilitate animation reuse. Defaults to YES. + */ +@property (assign, nonatomic) BOOL removedOnCompletion; + +/** + @abstract Flag indicating whether animation is paused. + @discussion A paused animation is excluded from the list of active animations. On initial creation, defaults to YES. On animation addition, the animation is implicity unpaused. On animation completion, the animation is implicity paused including for animations with removedOnCompletion set to NO. + */ +@property (assign, nonatomic, getter = isPaused) BOOL paused; + +/** + @abstract Flag indicating whether animation autoreverses. + @discussion An animation that autoreverses will have twice the duration before it is considered finished. It will animate to the toValue, stop, then animate back to the original fromValue. The delegate methods are called as follows: + + 1) animationDidStart: is called at the beginning, as usual, and then after each toValue is reached and the autoreverse is going to start. + 2) animationDidReachToValue: is called every time the toValue is reached. The toValue is swapped with the fromValue at the end of each animation segment. This means that with autoreverses set to YES, the animationDidReachToValue: delegate method will be called a minimum of twice. + 3) animationDidStop:finished: is called every time the toValue is reached, the finished argument will be NO if the autoreverse is not yet complete. + */ +@property (assign, nonatomic) BOOL autoreverses; + +/** + @abstract The number of times to repeat the animation. + @discussion A repeatCount of 0 or 1 means that the animation will not repeat, just like Core Animation. A repeatCount of 2 or greater means that the animation will run that many times before stopping. The delegate methods are called as follows: + + 1) animationDidStart: is called at the beginning of each animation repeat. + 2) animationDidReachToValue: is called every time the toValue is reached. + 3) animationDidStop:finished: is called every time the toValue is reached, the finished argument will be NO if the autoreverse is not yet complete. + +When combined with the autoreverses property, a singular animation is effectively twice as long. + */ +@property (assign, nonatomic) NSInteger repeatCount; + +/** + @abstract Repeat the animation forever. + @discussion This property will make the animation repeat forever. The value of the repeatCount property is undefined when this property is set. The finished parameter of the delegate callback animationDidStop:finished: will always be NO. + */ +@property (assign, nonatomic) BOOL repeatForever; + +@end + +/** + @abstract The animation delegate. + */ +@protocol POPAnimationDelegate +@optional + +/** + @abstract Called on animation start. + @param anim The relevant animation. + */ +- (void)pop_animationDidStart:(POPAnimation *)anim; + +/** + @abstract Called when value meets or exceeds to value. + @param anim The relevant animation. + */ +- (void)pop_animationDidReachToValue:(POPAnimation *)anim; + +/** + @abstract Called on animation stop. + @param anim The relevant animation. + @param finished Flag indicating finished state. Flag is true if the animation reached completion before being removed. + */ +- (void)pop_animationDidStop:(POPAnimation *)anim finished:(BOOL)finished; + +/** + @abstract Called each frame animation is applied. + @param anim The relevant animation. + */ +- (void)pop_animationDidApply:(POPAnimation *)anim; + +@end + + +@interface NSObject (POP) + +/** + @abstract Add an animation to the reciver. + @param anim The animation to add. + @param key The key used to identify the animation. + @discussion The 'key' may be any string such that only one animation per unique key is added per object. + */ +- (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key; + +/** + @abstract Remove all animations attached to the receiver. + */ +- (void)pop_removeAllAnimations; + +/** + @abstract Remove any animation attached to the receiver for 'key'. + @param key The key used to identify the animation. + */ +- (void)pop_removeAnimationForKey:(NSString *)key; + +/** + @abstract Returns an array containing the keys of all animations currently attached to the receiver. + @param The order of keys reflects the order in which animations will be applied. + */ +- (NSArray *)pop_animationKeys; + +/** + @abstract Returns any animation attached to the receiver. + @param key The key used to identify the animation. + @returns The animation currently attached, or nil if no such animation exists. + */ +- (id)pop_animationForKey:(NSString *)key; + +@end + +/** + * This implementation of NSCopying does not do any copying of animation's state, but only configuration. + * i.e. you cannot copy an animation and expect to apply it to a view and have the copied animation pick up where the original left off. + * Two common uses of copying animations: + * * you need to apply the same animation to multiple different views. + * * you need to absolutely ensure that the the caller of your function cannot mutate the animation once it's been passed in. + */ +@interface POPAnimation (NSCopying) + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimation.mm b/TalkinToTheNet/Pods/pop/pop/POPAnimation.mm new file mode 100644 index 0000000..75bdeb1 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimation.mm @@ -0,0 +1,303 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimationExtras.h" +#import "POPAnimationInternal.h" + +#import + +#import "POPAction.h" +#import "POPAnimationRuntime.h" +#import "POPAnimationTracerInternal.h" +#import "POPAnimatorPrivate.h" + +using namespace POP; + +#pragma mark - POPAnimation + +@implementation POPAnimation +@synthesize solver = _solver; +@synthesize currentValue = _currentValue; +@synthesize progressMarkers = _progressMarkers; + +#pragma mark - Lifecycle + +- (id)init +{ + [NSException raise:NSStringFromClass([self class]) format:@"Attempting to instantiate an abstract class. Use a concrete subclass instead."]; + return nil; +} + +- (id)_init +{ + self = [super init]; + if (nil != self) { + [self _initState]; + } + return self; +} + +- (void)_initState +{ + _state = new POPAnimationState(self); +} + +- (void)dealloc +{ + if (_state) { + delete _state; + _state = NULL; + }; +} + +#pragma mark - Properties + +- (id)delegate +{ + return _state->delegate; +} + +- (void)setDelegate:(id)delegate +{ + _state->setDelegate(delegate); +} + +- (BOOL)isPaused +{ + return _state->paused; +} + +- (void)setPaused:(BOOL)paused +{ + _state->setPaused(paused ? true : false); +} + +- (NSInteger)repeatCount +{ + if (_state->autoreverses) { + return _state->repeatCount / 2; + } else { + return _state->repeatCount; + } +} + +- (void)setRepeatCount:(NSInteger)repeatCount +{ + if (repeatCount > 0) { + if (repeatCount > NSIntegerMax / 2) { + repeatCount = NSIntegerMax / 2; + } + + if (_state->autoreverses) { + _state->repeatCount = (repeatCount * 2); + } else { + _state->repeatCount = repeatCount; + } + } +} + +- (BOOL)autoreverses +{ + return _state->autoreverses; +} + +- (void)setAutoreverses:(BOOL)autoreverses +{ + _state->autoreverses = autoreverses; + if (autoreverses) { + if (_state->repeatCount == 0) { + [self setRepeatCount:1]; + } + } +} + +FB_PROPERTY_GET(POPAnimationState, type, POPAnimationType); +DEFINE_RW_PROPERTY_OBJ_COPY(POPAnimationState, animationDidStartBlock, setAnimationDidStartBlock:, POPAnimationDidStartBlock); +DEFINE_RW_PROPERTY_OBJ_COPY(POPAnimationState, animationDidReachToValueBlock, setAnimationDidReachToValueBlock:, POPAnimationDidReachToValueBlock); +DEFINE_RW_PROPERTY_OBJ_COPY(POPAnimationState, completionBlock, setCompletionBlock:, POPAnimationCompletionBlock); +DEFINE_RW_PROPERTY_OBJ_COPY(POPAnimationState, animationDidApplyBlock, setAnimationDidApplyBlock:, POPAnimationDidApplyBlock); +DEFINE_RW_PROPERTY_OBJ_COPY(POPAnimationState, name, setName:, NSString*); +DEFINE_RW_PROPERTY(POPAnimationState, beginTime, setBeginTime:, CFTimeInterval); +DEFINE_RW_FLAG(POPAnimationState, removedOnCompletion, removedOnCompletion, setRemovedOnCompletion:); +DEFINE_RW_FLAG(POPAnimationState, repeatForever, repeatForever, setRepeatForever:); + +- (id)valueForUndefinedKey:(NSString *)key +{ + return _state->dict[key]; +} + +- (void)setValue:(id)value forUndefinedKey:(NSString *)key +{ + if (!value) { + [_state->dict removeObjectForKey:key]; + } else { + if (!_state->dict) + _state->dict = [[NSMutableDictionary alloc] init]; + _state->dict[key] = value; + } +} + +- (POPAnimationTracer *)tracer +{ + if (!_state->tracer) { + _state->tracer = [[POPAnimationTracer alloc] initWithAnimation:self]; + } + return _state->tracer; +} + +- (NSString *)description +{ + NSMutableString *s = [NSMutableString stringWithFormat:@"<%@:%p", NSStringFromClass([self class]), self]; + [self _appendDescription:s debug:NO]; + [s appendString:@">"]; + return s; +} + +- (NSString *)debugDescription +{ + NSMutableString *s = [NSMutableString stringWithFormat:@"<%@:%p", NSStringFromClass([self class]), self]; + [self _appendDescription:s debug:YES]; + [s appendString:@">"]; + return s; +} + +#pragma mark - Utility + +POPAnimationState *POPAnimationGetState(POPAnimation *a) +{ + return a->_state; +} + +- (BOOL)_advance:(id)object currentTime:(CFTimeInterval)currentTime elapsedTime:(CFTimeInterval)elapsedTime +{ + return YES; +} + +- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug +{ + if (_state->name) + [s appendFormat:@"; name = %@", _state->name]; + + if (!self.removedOnCompletion) + [s appendFormat:@"; removedOnCompletion = %@", POPStringFromBOOL(self.removedOnCompletion)]; + + if (debug) { + if (_state->active) + [s appendFormat:@"; active = %@", POPStringFromBOOL(_state->active)]; + + if (_state->paused) + [s appendFormat:@"; paused = %@", POPStringFromBOOL(_state->paused)]; + } + + if (_state->beginTime) { + [s appendFormat:@"; beginTime = %f", _state->beginTime]; + } + + for (NSString *key in _state->dict) { + [s appendFormat:@"; %@ = %@", key, _state->dict[key]]; + } +} + +@end + + +#pragma mark - POPPropertyAnimation + +#pragma mark - POPBasicAnimation + +#pragma mark - POPDecayAnimation + +@implementation NSObject (POP) + +- (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key +{ + [[POPAnimator sharedAnimator] addAnimation:anim forObject:self key:key]; +} + +- (void)pop_removeAllAnimations +{ + [[POPAnimator sharedAnimator] removeAllAnimationsForObject:self]; +} + +- (void)pop_removeAnimationForKey:(NSString *)key +{ + [[POPAnimator sharedAnimator] removeAnimationForObject:self key:key]; +} + +- (NSArray *)pop_animationKeys +{ + return [[POPAnimator sharedAnimator] animationKeysForObject:self]; +} + +- (id)pop_animationForKey:(NSString *)key +{ + return [[POPAnimator sharedAnimator] animationForObject:self key:key]; +} + +@end + +@implementation NSProxy (POP) + +- (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key +{ + [[POPAnimator sharedAnimator] addAnimation:anim forObject:self key:key]; +} + +- (void)pop_removeAllAnimations +{ + [[POPAnimator sharedAnimator] removeAllAnimationsForObject:self]; +} + +- (void)pop_removeAnimationForKey:(NSString *)key +{ + [[POPAnimator sharedAnimator] removeAnimationForObject:self key:key]; +} + +- (NSArray *)pop_animationKeys +{ + return [[POPAnimator sharedAnimator] animationKeysForObject:self]; +} + +- (id)pop_animationForKey:(NSString *)key +{ + return [[POPAnimator sharedAnimator] animationForObject:self key:key]; +} + +@end + +@implementation POPAnimation (NSCopying) + +- (instancetype)copyWithZone:(NSZone *)zone +{ + /* + * Must use [self class] instead of POPAnimation so that subclasses can call this via super. + * Even though POPAnimation and POPPropertyAnimation throw exceptions on init, + * it's safe to call it since you can only copy objects that have been successfully created. + */ + POPAnimation *copy = [[[self class] allocWithZone:zone] init]; + + if (copy) { + copy.name = self.name; + copy.beginTime = self.beginTime; + copy.delegate = self.delegate; + copy.animationDidStartBlock = self.animationDidStartBlock; + copy.animationDidReachToValueBlock = self.animationDidReachToValueBlock; + copy.completionBlock = self.completionBlock; + copy.animationDidApplyBlock = self.animationDidApplyBlock; + copy.removedOnCompletion = self.removedOnCompletion; + + copy.autoreverses = self.autoreverses; + copy.repeatCount = self.repeatCount; + copy.repeatForever = self.repeatForever; + } + + return copy; +} + +@end \ No newline at end of file diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationEvent.h b/TalkinToTheNet/Pods/pop/pop/POPAnimationEvent.h new file mode 100644 index 0000000..e761091 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationEvent.h @@ -0,0 +1,69 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +/** + @abstract Enumeraton of animation event types. + */ +typedef NS_ENUM(NSUInteger, POPAnimationEventType) { + kPOPAnimationEventPropertyRead = 0, + kPOPAnimationEventPropertyWrite, + kPOPAnimationEventToValueUpdate, + kPOPAnimationEventFromValueUpdate, + kPOPAnimationEventVelocityUpdate, + kPOPAnimationEventBouncinessUpdate, + kPOPAnimationEventSpeedUpdate, + kPOPAnimationEventFrictionUpdate, + kPOPAnimationEventMassUpdate, + kPOPAnimationEventTensionUpdate, + kPOPAnimationEventDidStart, + kPOPAnimationEventDidStop, + kPOPAnimationEventDidReachToValue, + kPOPAnimationEventAutoreversed +}; + +/** + @abstract The base animation event class. + */ +@interface POPAnimationEvent : NSObject + +/** + @abstract The event type. See {@ref POPAnimationEventType} for possible values. + */ +@property (readonly, nonatomic, assign) POPAnimationEventType type; + +/** + @abstract The time of event. + */ +@property (readonly, nonatomic, assign) CFTimeInterval time; + +/** + @abstract Optional string describing the animation at time of event. + */ +@property (readonly, nonatomic, copy) NSString *animationDescription; + +@end + +/** + @abstract An animation event subclass for recording value and velocity. + */ +@interface POPAnimationValueEvent : POPAnimationEvent + +/** + @abstract The value recorded. + */ +@property (readonly, nonatomic, strong) id value; + +/** + @abstract The velocity recorded, if any. + */ +@property (readonly, nonatomic, strong) id velocity; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationEvent.mm b/TalkinToTheNet/Pods/pop/pop/POPAnimationEvent.mm new file mode 100644 index 0000000..d3a13b6 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationEvent.mm @@ -0,0 +1,108 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimationEvent.h" +#import "POPAnimationEventInternal.h" + +static NSString *stringFromType(POPAnimationEventType aType) +{ + switch (aType) { + case kPOPAnimationEventPropertyRead: + return @"read"; + case kPOPAnimationEventPropertyWrite: + return @"write"; + case kPOPAnimationEventToValueUpdate: + return @"toValue"; + case kPOPAnimationEventFromValueUpdate: + return @"fromValue"; + case kPOPAnimationEventVelocityUpdate: + return @"velocity"; + case kPOPAnimationEventSpeedUpdate: + return @"speed"; + case kPOPAnimationEventBouncinessUpdate: + return @"bounciness"; + case kPOPAnimationEventFrictionUpdate: + return @"friction"; + case kPOPAnimationEventMassUpdate: + return @"mass"; + case kPOPAnimationEventTensionUpdate: + return @"tension"; + case kPOPAnimationEventDidStart: + return @"didStart"; + case kPOPAnimationEventDidStop: + return @"didStop"; + case kPOPAnimationEventDidReachToValue: + return @"didReachToValue"; + case kPOPAnimationEventAutoreversed: + return @"autoreversed"; + default: + return nil; + } +} + +@implementation POPAnimationEvent +@synthesize type = _type; +@synthesize time = _time; +@synthesize animationDescription = _animationDescription; + +- (instancetype)initWithType:(POPAnimationEventType)aType time:(CFTimeInterval)aTime +{ + self = [super init]; + if (nil != self) { + _type = aType; + _time = aTime; + } + return self; +} + +- (NSString *)description +{ + NSMutableString *s = [NSMutableString stringWithFormat:@""]; + return s; +} + +// subclass override +- (void)_appendDescription:(NSMutableString *)s +{ + if (0 != _animationDescription.length) { + [s appendFormat:@"; animation = %@", _animationDescription]; + } +} + +@end + +@implementation POPAnimationValueEvent +@synthesize value = _value; +@synthesize velocity = _velocity; + +- (instancetype)initWithType:(POPAnimationEventType)aType time:(CFTimeInterval)aTime value:(id)aValue +{ + self = [self initWithType:aType time:aTime]; + if (nil != self) { + _value = aValue; + } + return self; +} + +- (void)_appendDescription:(NSMutableString *)s +{ + [super _appendDescription:s]; + + if (nil != _value) { + [s appendFormat:@"; value = %@", _value]; + } + + if (nil != _velocity) { + [s appendFormat:@"; velocity = %@", _velocity]; + } +} + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationEventInternal.h b/TalkinToTheNet/Pods/pop/pop/POPAnimationEventInternal.h new file mode 100644 index 0000000..398d59b --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationEventInternal.h @@ -0,0 +1,41 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import "POPAnimationEvent.h" + +@interface POPAnimationEvent () + +/** + @abstract Default initializer. + */ +- (instancetype)initWithType:(POPAnimationEventType)type time:(CFTimeInterval)time; + +/** + @abstract Readwrite redefinition of public property. + */ +@property (readwrite, nonatomic, copy) NSString *animationDescription; + +@end + +@interface POPAnimationValueEvent () + +/** + @abstract Default initializer. + */ +- (instancetype)initWithType:(POPAnimationEventType)type time:(CFTimeInterval)time value:(id)value; + +/** + @abstract Readwrite redefinition of public property. + */ +@property (readwrite, nonatomic, strong) id velocity; + +@end + diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationExtras.h b/TalkinToTheNet/Pods/pop/pop/POPAnimationExtras.h new file mode 100644 index 0000000..4b3d237 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationExtras.h @@ -0,0 +1,43 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import +#import + +/** + @abstract The current drag coefficient. + @discussion A value greater than 1.0 indicates Simulator slow-motion animations are enabled. Defaults to 1.0. + */ +extern CGFloat POPAnimationDragCoefficient(); + +@interface CAAnimation (POPAnimationExtras) + +/** + @abstract Apply the current drag coefficient to animation speed. + @discussion Convenience utility to respect Simulator slow-motion animation settings. + */ +- (void)pop_applyDragCoefficient; + +@end + +@interface POPSpringAnimation (POPAnimationExtras) + +/** + @abstract Converts from spring bounciness and speed to tension, friction and mass dynamics values. + */ ++ (void)convertBounciness:(CGFloat)bounciness speed:(CGFloat)speed toTension:(CGFloat *)outTension friction:(CGFloat *)outFriction mass:(CGFloat *)outMass; + +/** + @abstract Converts from dynamics tension, friction and mass to spring bounciness and speed values. + */ ++ (void)convertTension:(CGFloat)tension friction:(CGFloat)friction toBounciness:(CGFloat *)outBounciness speed:(CGFloat *)outSpeed; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationExtras.mm b/TalkinToTheNet/Pods/pop/pop/POPAnimationExtras.mm new file mode 100644 index 0000000..0a6d6c9 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationExtras.mm @@ -0,0 +1,117 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimationExtras.h" +#import "POPAnimationPrivate.h" + +#if TARGET_OS_IPHONE +#import +#endif + +#if TARGET_IPHONE_SIMULATOR +UIKIT_EXTERN float UIAnimationDragCoefficient(); // UIKit private drag coeffient, use judiciously +#endif + +#import "POPMath.h" + +CGFloat POPAnimationDragCoefficient() +{ +#if TARGET_IPHONE_SIMULATOR + return UIAnimationDragCoefficient(); +#else + return 1.0; +#endif +} + +@implementation CAAnimation (POPAnimationExtras) + +- (void)pop_applyDragCoefficient +{ + CGFloat k = POPAnimationDragCoefficient(); + if (k != 0 && k != 1) + self.speed = 1 / k; +} + +@end + +@implementation POPSpringAnimation (POPAnimationExtras) + +static const CGFloat POPBouncy3NormalizationRange = 20.0; +static const CGFloat POPBouncy3NormalizationScale = 1.7; +static const CGFloat POPBouncy3BouncinessNormalizedMin = 0.0; +static const CGFloat POPBouncy3BouncinessNormalizedMax = 0.8; +static const CGFloat POPBouncy3SpeedNormalizedMin = 0.5; +static const CGFloat POPBouncy3SpeedNormalizedMax = 200; +static const CGFloat POPBouncy3FrictionInterpolationMax = 0.01; + ++ (void)convertBounciness:(CGFloat)bounciness speed:(CGFloat)speed toTension:(CGFloat *)outTension friction:(CGFloat *)outFriction mass:(CGFloat *)outMass +{ + double b = POPNormalize(bounciness / POPBouncy3NormalizationScale, 0, POPBouncy3NormalizationRange); + b = POPProjectNormal(b, POPBouncy3BouncinessNormalizedMin, POPBouncy3BouncinessNormalizedMax); + + double s = POPNormalize(speed / POPBouncy3NormalizationScale, 0, POPBouncy3NormalizationRange); + + CGFloat tension = POPProjectNormal(s, POPBouncy3SpeedNormalizedMin, POPBouncy3SpeedNormalizedMax); + CGFloat friction = POPQuadraticOutInterpolation(b, POPBouncy3NoBounce(tension), POPBouncy3FrictionInterpolationMax); + + tension = POP_ANIMATION_TENSION_FOR_QC_TENSION(tension); + friction = POP_ANIMATION_FRICTION_FOR_QC_FRICTION(friction); + + if (outTension) { + *outTension = tension; + } + + if (outFriction) { + *outFriction = friction; + } + + if (outMass) { + *outMass = 1.0; + } +} + ++ (void)convertTension:(CGFloat)tension friction:(CGFloat)friction toBounciness:(CGFloat *)outBounciness speed:(CGFloat *)outSpeed +{ + // Convert to QC values, in which our calculations are done. + CGFloat qcFriction = QC_FRICTION_FOR_POP_ANIMATION_FRICTION(friction); + CGFloat qcTension = QC_TENSION_FOR_POP_ANIMATION_TENSION(tension); + + // Friction is a function of bounciness and tension, according to the following: + // friction = POPQuadraticOutInterpolation(b, POPBouncy3NoBounce(tension), POPBouncy3FrictionInterpolationMax); + // Solve for bounciness, given a tension and friction. + + CGFloat nobounceTension = POPBouncy3NoBounce(qcTension); + CGFloat bounciness1, bounciness2; + + POPQuadraticSolve((nobounceTension - POPBouncy3FrictionInterpolationMax), // a + 2 * (POPBouncy3FrictionInterpolationMax - nobounceTension), // b + (nobounceTension - qcFriction), // c + bounciness1, // x1 + bounciness2); // x2 + + + // Choose the quadratic solution within the normalized bounciness range + CGFloat projectedNormalizedBounciness = (bounciness2 < POPBouncy3BouncinessNormalizedMax) ? bounciness2 : bounciness1; + CGFloat projectedNormalizedSpeed = qcTension; + + // Reverse projection + normalization + CGFloat bounciness = ((POPBouncy3NormalizationRange * POPBouncy3NormalizationScale) / (POPBouncy3BouncinessNormalizedMax - POPBouncy3BouncinessNormalizedMin)) * (projectedNormalizedBounciness - POPBouncy3BouncinessNormalizedMin); + CGFloat speed = ((POPBouncy3NormalizationRange * POPBouncy3NormalizationScale) / (POPBouncy3SpeedNormalizedMax - POPBouncy3SpeedNormalizedMin)) * (projectedNormalizedSpeed - POPBouncy3SpeedNormalizedMin); + + // Write back results + if (outBounciness) { + *outBounciness = bounciness; + } + + if (outSpeed) { + *outSpeed = speed; + } +} + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationInternal.h b/TalkinToTheNet/Pods/pop/pop/POPAnimationInternal.h new file mode 100644 index 0000000..317364f --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationInternal.h @@ -0,0 +1,505 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimation.h" + +#import + +#import "POPAction.h" +#import "POPAnimationRuntime.h" +#import "POPAnimationTracerInternal.h" +#import "POPSpringSolver.h" + +using namespace POP; + +/** + Enumeration of supported animation types. + */ +enum POPAnimationType +{ + kPOPAnimationSpring, + kPOPAnimationDecay, + kPOPAnimationBasic, + kPOPAnimationCustom, +}; + +typedef struct +{ + CGFloat progress; + bool reached; +} POPProgressMarker; + +typedef void (^POPAnimationDidStartBlock)(POPAnimation *anim); +typedef void (^POPAnimationDidReachToValueBlock)(POPAnimation *anim); +typedef void (^POPAnimationCompletionBlock)(POPAnimation *anim, BOOL finished); +typedef void (^POPAnimationDidApplyBlock)(POPAnimation *anim); + +@interface POPAnimation() +- (instancetype)_init; + +@property (assign, nonatomic) SpringSolver4d *solver; +@property (readonly, nonatomic) POPAnimationType type; + +/** + The current animation value, updated while animation is progressing. + */ +@property (copy, nonatomic, readonly) id currentValue; + +/** + An array of optional progress markers. For each marker specified, the animation delegate will be informed when progress meets or exceeds the value specified. Specifying values outside of the [0, 1] range will give undefined results. + */ +@property (copy, nonatomic) NSArray *progressMarkers; + +/** + Return YES to indicate animation should continue animating. + */ +- (BOOL)_advance:(id)object currentTime:(CFTimeInterval)currentTime elapsedTime:(CFTimeInterval)elapsedTime; + +/** + Subclass override point to append animation description. + */ +- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug; + +@end + +NS_INLINE NSString *describe(VectorConstRef vec) +{ + return NULL == vec ? @"null" : vec->toString(); +} + +NS_INLINE Vector4r vector4(VectorConstRef vec) +{ + return NULL == vec ? Vector4r::Zero() : vec->vector4r(); +} + +NS_INLINE Vector4d vector4d(VectorConstRef vec) +{ + if (NULL == vec) { + return Vector4d::Zero(); + } else { + return vec->vector4r().cast(); + } +} + +NS_INLINE bool vec_equal(VectorConstRef v1, VectorConstRef v2) +{ + if (v1 == v2) { + return true; + } + if (!v1 || !v2) { + return false; + } + return *v1 == *v2; +} + +NS_INLINE CGFloat * vec_data(VectorRef vec) +{ + return NULL == vec ? NULL : vec->data(); +} + +template +struct ComputeProgressFunctor { + CGFloat operator()(const T &value, const T &start, const T &end) const { + return 0; + } +}; + +template<> +struct ComputeProgressFunctor { + CGFloat operator()(const Vector4r &value, const Vector4r &start, const Vector4r &end) const { + CGFloat s = (value - start).squaredNorm(); // distance from start + CGFloat e = (value - end).squaredNorm(); // distance from end + CGFloat d = (end - start).squaredNorm(); // distance from start to end + + if (0 == d) { + return 1; + } else if (s > e) { + // s -------- p ---- e OR s ------- e ---- p + return sqrtr(s/d); + } else { + // s --- p --------- e OR p ---- s ------- e + return 1 - sqrtr(e/d); + } + } +}; + +struct _POPAnimationState; +struct _POPDecayAnimationState; +struct _POPPropertyAnimationState; + +extern _POPAnimationState *POPAnimationGetState(POPAnimation *a); + + +#define FB_FLAG_GET(stype, flag, getter) \ +- (BOOL)getter { \ + return ((stype *)_state)->flag; \ +} + +#define FB_FLAG_SET(stype, flag, mutator) \ +- (void)mutator (BOOL)value { \ + if (value == ((stype *)_state)->flag) \ + return; \ + ((stype *)_state)->flag = value; \ +} + +#define DEFINE_RW_FLAG(stype, flag, getter, mutator) \ + FB_FLAG_GET (stype, flag, getter) \ + FB_FLAG_SET (stype, flag, mutator) + +#define FB_PROPERTY_GET(stype, property, ctype) \ +- (ctype)property { \ + return ((stype *)_state)->property; \ +} + +#define FB_PROPERTY_SET(stype, property, mutator, ctype, ...) \ +- (void)mutator (ctype)value { \ + if (value == ((stype *)_state)->property) \ + return; \ + ((stype *)_state)->property = value; \ + __VA_ARGS__ \ +} + +#define FB_PROPERTY_SET_OBJ_COPY(stype, property, mutator, ctype, ...) \ +- (void)mutator (ctype)value { \ + if (value == ((stype *)_state)->property) \ + return; \ + ((stype *)_state)->property = [value copy]; \ + __VA_ARGS__ \ +} + +#define DEFINE_RW_PROPERTY(stype, flag, mutator, ctype, ...) \ + FB_PROPERTY_GET (stype, flag, ctype) \ + FB_PROPERTY_SET (stype, flag, mutator, ctype, __VA_ARGS__) + +#define DEFINE_RW_PROPERTY_OBJ(stype, flag, mutator, ctype, ...) \ + FB_PROPERTY_GET (stype, flag, ctype) \ + FB_PROPERTY_SET (stype, flag, mutator, ctype, __VA_ARGS__) + +#define DEFINE_RW_PROPERTY_OBJ_COPY(stype, flag, mutator, ctype, ...) \ + FB_PROPERTY_GET (stype, flag, ctype) \ + FB_PROPERTY_SET_OBJ_COPY (stype, flag, mutator, ctype, __VA_ARGS__) + + +/** + Internal delegate definition. + */ +@interface NSObject (POPAnimationDelegateInternal) +- (void)pop_animation:(POPAnimation *)anim didReachProgress:(CGFloat)progress; +@end + +struct _POPAnimationState +{ + id __unsafe_unretained self; + POPAnimationType type; + NSString *name; + NSUInteger ID; + CFTimeInterval beginTime; + CFTimeInterval startTime; + CFTimeInterval lastTime; + id __weak delegate; + POPAnimationDidStartBlock animationDidStartBlock; + POPAnimationDidReachToValueBlock animationDidReachToValueBlock; + POPAnimationCompletionBlock completionBlock; + POPAnimationDidApplyBlock animationDidApplyBlock; + NSMutableDictionary *dict; + POPAnimationTracer *tracer; + CGFloat progress; + NSInteger repeatCount; + + bool active:1; + bool paused:1; + bool removedOnCompletion:1; + + bool delegateDidStart:1; + bool delegateDidStop:1; + bool delegateDidProgress:1; + bool delegateDidApply:1; + bool delegateDidReachToValue:1; + + bool additive:1; + bool didReachToValue:1; + bool tracing:1; // corresponds to tracer started + bool userSpecifiedDynamics:1; + bool autoreverses:1; + bool repeatForever:1; + bool customFinished:1; + + _POPAnimationState(id __unsafe_unretained anim) : + self(anim), + type((POPAnimationType)0), + name(nil), + ID(0), + beginTime(0), + startTime(0), + lastTime(0), + delegate(nil), + animationDidStartBlock(nil), + animationDidReachToValueBlock(nil), + completionBlock(nil), + animationDidApplyBlock(nil), + dict(nil), + tracer(nil), + progress(0), + repeatCount(0), + active(false), + paused(true), + removedOnCompletion(true), + delegateDidStart(false), + delegateDidStop(false), + delegateDidProgress(false), + delegateDidApply(false), + delegateDidReachToValue(false), + additive(false), + didReachToValue(false), + tracing(false), + userSpecifiedDynamics(false), + autoreverses(false), + repeatForever(false), + customFinished(false) {} + + virtual ~_POPAnimationState() + { + name = nil; + dict = nil; + tracer = nil; + animationDidStartBlock = NULL; + animationDidReachToValueBlock = NULL; + completionBlock = NULL; + animationDidApplyBlock = NULL; + } + + bool isCustom() { + return kPOPAnimationCustom == type; + } + + bool isStarted() { + return 0 != startTime; + } + + id getDelegate() { + return delegate; + } + + void setDelegate(id d) { + if (d != delegate) { + delegate = d; + delegateDidStart = [d respondsToSelector:@selector(pop_animationDidStart:)]; + delegateDidStop = [d respondsToSelector:@selector(pop_animationDidStop:finished:)]; + delegateDidProgress = [d respondsToSelector:@selector(pop_animation:didReachProgress:)]; + delegateDidApply = [d respondsToSelector:@selector(pop_animationDidApply:)]; + delegateDidReachToValue = [d respondsToSelector:@selector(pop_animationDidReachToValue:)]; + } + } + + bool getPaused() { + return paused; + } + + void setPaused(bool f) { + if (f != paused) { + paused = f; + if (!paused) { + reset(false); + } + } + } + + CGFloat getProgress() { + return progress; + } + + /* returns true if started */ + bool startIfNeeded(id obj, CFTimeInterval time, CFTimeInterval offset) + { + bool started = false; + + // detect start based on time + if (0 == startTime && time >= beginTime + offset) { + + // activate & unpause + active = true; + setPaused(false); + + // note start time + startTime = lastTime = time; + started = true; + } + + // ensure values for running animation + bool running = active && !paused; + if (running) { + willRun(started, obj); + } + + // handle start + if (started) { + handleDidStart(); + } + + return started; + } + + void stop(bool removing, bool done) { + if (active) + { + // delegate progress one last time + if (done) { + delegateProgress(); + } + + if (removing) { + active = false; + } + + handleDidStop(done); + } else { + + // stopped before even started + // delegate start and stop regardless; matches CA behavior + if (!isStarted()) { + handleDidStart(); + handleDidStop(false); + } + } + + setPaused(true); + } + + virtual void handleDidStart() + { + if (delegateDidStart) { + ActionEnabler enabler; + [delegate pop_animationDidStart:self]; + } + + POPAnimationDidStartBlock block = animationDidStartBlock; + if (block != NULL) { + ActionEnabler enabler; + block(self); + } + + if (tracing) { + [tracer didStart]; + } + } + + void handleDidStop(BOOL done) + { + if (delegateDidStop) { + ActionEnabler enabler; + [delegate pop_animationDidStop:self finished:done]; + } + + // add another strong reference to completion block before callout + POPAnimationCompletionBlock block = completionBlock; + if (block != NULL) { + ActionEnabler enabler; + block(self, done); + } + + if (tracing) { + [tracer didStop:done]; + } + } + + /* virtual functions */ + virtual bool isDone() { + if (isCustom()) { + return customFinished; + } + + return false; + } + + bool advanceTime(CFTimeInterval time, id obj) { + bool advanced = false; + bool computedProgress = false; + CFTimeInterval dt = time - lastTime; + + switch (type) { + case kPOPAnimationSpring: + advanced = advance(time, dt, obj); + break; + case kPOPAnimationDecay: + advanced = advance(time, dt, obj); + break; + case kPOPAnimationBasic: { + advanced = advance(time, dt, obj); + computedProgress = true; + break; + } + case kPOPAnimationCustom: { + customFinished = [self _advance:obj currentTime:time elapsedTime:dt] ? false : true; + advanced = true; + break; + } + default: + break; + } + + if (advanced) { + + // estimate progress + if (!computedProgress) { + computeProgress(); + } + + // delegate progress + delegateProgress(); + + // update time + lastTime = time; + } + + return advanced; + } + + virtual void willRun(bool started, id obj) {} + virtual bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) { return false; } + virtual void computeProgress() {} + virtual void delegateProgress() {} + + virtual void delegateApply() { + if (delegateDidApply) { + ActionEnabler enabler; + [delegate pop_animationDidApply:self]; + } + + POPAnimationDidApplyBlock block = animationDidApplyBlock; + if (block != NULL) { + ActionEnabler enabler; + block(self); + } + } + + virtual void reset(bool all) { + startTime = 0; + lastTime = 0; + } +}; + +typedef struct _POPAnimationState POPAnimationState; + + +@interface POPAnimation () +{ +@protected + struct _POPAnimationState *_state; +} + +@end + +// NSProxy extensions, for testing pursposes +@interface NSProxy (POP) +- (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key; +- (void)pop_removeAllAnimations; +- (void)pop_removeAnimationForKey:(NSString *)key; +- (NSArray *)pop_animationKeys; +- (POPAnimation *)pop_animationForKey:(NSString *)key; +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationPrivate.h b/TalkinToTheNet/Pods/pop/pop/POPAnimationPrivate.h new file mode 100644 index 0000000..c0f06c5 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationPrivate.h @@ -0,0 +1,16 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#define POP_ANIMATION_FRICTION_FOR_QC_FRICTION(qcFriction) (25.0 + (((qcFriction - 8.0) / 2.0) * (25.0 - 19.0))) +#define POP_ANIMATION_TENSION_FOR_QC_TENSION(qcTension) (194.0 + (((qcTension - 30.0) / 50.0) * (375.0 - 194.0))) + +#define QC_FRICTION_FOR_POP_ANIMATION_FRICTION(fbFriction) (8.0 + 2.0 * ((fbFriction - 25.0)/(25.0 - 19.0))) +#define QC_TENSION_FOR_POP_ANIMATION_TENSION(fbTension) (30.0 + 50.0 * ((fbTension - 194.0)/(375.0 - 194.0))) diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationRuntime.h b/TalkinToTheNet/Pods/pop/pop/POPAnimationRuntime.h new file mode 100644 index 0000000..902c312 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationRuntime.h @@ -0,0 +1,103 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import + +#import "POPVector.h" + +enum POPValueType +{ + kPOPValueUnknown = 0, + kPOPValueInteger, + kPOPValueFloat, + kPOPValuePoint, + kPOPValueSize, + kPOPValueRect, + kPOPValueEdgeInsets, + kPOPValueAffineTransform, + kPOPValueTransform, + kPOPValueRange, + kPOPValueColor, + kPOPValueSCNVector3, + kPOPValueSCNVector4, +}; + +using namespace POP; + +/** + Returns value type based on objc type description, given list of supported value types and length. + */ +extern POPValueType POPSelectValueType(const char *objctype, const POPValueType *types, size_t length); + +/** + Returns value type based on objc object, given a list of supported value types and length. + */ +extern POPValueType POPSelectValueType(id obj, const POPValueType *types, size_t length); + +/** + Array of all value types. + */ +extern const POPValueType kPOPAnimatableAllTypes[12]; + +/** + Array of all value types supported for animation. + */ +extern const POPValueType kPOPAnimatableSupportTypes[10]; + +/** + Returns a string description of a value type. + */ +extern NSString *POPValueTypeToString(POPValueType t); + +/** + Returns a mutable dictionary of weak pointer keys to weak pointer values. + */ +extern CFMutableDictionaryRef POPDictionaryCreateMutableWeakPointerToWeakPointer(NSUInteger capacity) CF_RETURNS_RETAINED; + +/** + Returns a mutable dictionary of weak pointer keys to weak pointer values. + */ +extern CFMutableDictionaryRef POPDictionaryCreateMutableWeakPointerToStrongObject(NSUInteger capacity) CF_RETURNS_RETAINED; + +/** + Box a vector. + */ +extern id POPBox(VectorConstRef vec, POPValueType type, bool force = false); + +/** + Unbox a vector. + */ +extern VectorRef POPUnbox(id value, POPValueType &type, NSUInteger &count, bool validate); + +/** + Read/write block typedefs for convenience. + */ +typedef void(^pop_animatable_read_block)(id obj, CGFloat *value); +typedef void(^pop_animatable_write_block)(id obj, const CGFloat *value); + +/** + Read object value and return a Vector4r. + */ +NS_INLINE Vector4r read_values(pop_animatable_read_block read, id obj, size_t count) +{ + Vector4r vec = Vector4r::Zero(); + if (0 == count) + return vec; + + read(obj, vec.data()); + + return vec; +} + +NS_INLINE NSString *POPStringFromBOOL(BOOL value) +{ + return value ? @"YES" : @"NO"; +} diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationRuntime.mm b/TalkinToTheNet/Pods/pop/pop/POPAnimationRuntime.mm new file mode 100644 index 0000000..371e009 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationRuntime.mm @@ -0,0 +1,329 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimationRuntime.h" + +#import + +#import + +#if TARGET_OS_IPHONE +#import +#endif + +#import "POPCGUtils.h" +#import "POPDefines.h" +#import "POPGeometry.h" +#import "POPVector.h" + +static Boolean pointerEqual(const void *ptr1, const void *ptr2) { + return ptr1 == ptr2; +} + +static CFHashCode pointerHash(const void *ptr) { + return (CFHashCode)(ptr); +} + +CFMutableDictionaryRef POPDictionaryCreateMutableWeakPointerToWeakPointer(NSUInteger capacity) +{ + CFDictionaryKeyCallBacks kcb = kCFTypeDictionaryKeyCallBacks; + + // weak, pointer keys + kcb.retain = NULL; + kcb.release = NULL; + kcb.equal = pointerEqual; + kcb.hash = pointerHash; + + CFDictionaryValueCallBacks vcb = kCFTypeDictionaryValueCallBacks; + + // weak, pointer values + vcb.retain = NULL; + vcb.release = NULL; + vcb.equal = pointerEqual; + + return CFDictionaryCreateMutable(NULL, capacity, &kcb, &vcb); +} + +CFMutableDictionaryRef POPDictionaryCreateMutableWeakPointerToStrongObject(NSUInteger capacity) +{ + CFDictionaryKeyCallBacks kcb = kCFTypeDictionaryKeyCallBacks; + + // weak, pointer keys + kcb.retain = NULL; + kcb.release = NULL; + kcb.equal = pointerEqual; + kcb.hash = pointerHash; + + // strong, object values + CFDictionaryValueCallBacks vcb = kCFTypeDictionaryValueCallBacks; + + return CFDictionaryCreateMutable(NULL, capacity, &kcb, &vcb); +} + +static bool FBCompareTypeEncoding(const char *objctype, POPValueType type) +{ + switch (type) + { + case kPOPValueFloat: + return (strcmp(objctype, @encode(float)) == 0 + || strcmp(objctype, @encode(double)) == 0 + ); + + case kPOPValuePoint: + return (strcmp(objctype, @encode(CGPoint)) == 0 +#if !TARGET_OS_IPHONE + || strcmp(objctype, @encode(NSPoint)) == 0 +#endif + ); + + case kPOPValueSize: + return (strcmp(objctype, @encode(CGSize)) == 0 +#if !TARGET_OS_IPHONE + || strcmp(objctype, @encode(NSSize)) == 0 +#endif + ); + + case kPOPValueRect: + return (strcmp(objctype, @encode(CGRect)) == 0 +#if !TARGET_OS_IPHONE + || strcmp(objctype, @encode(NSRect)) == 0 +#endif + ); + case kPOPValueEdgeInsets: +#if TARGET_OS_IPHONE + return strcmp(objctype, @encode(UIEdgeInsets)) == 0; +#else + return false; +#endif + + case kPOPValueAffineTransform: + return strcmp(objctype, @encode(CGAffineTransform)) == 0; + + case kPOPValueTransform: + return strcmp(objctype, @encode(CATransform3D)) == 0; + + case kPOPValueRange: + return strcmp(objctype, @encode(CFRange)) == 0 + || strcmp(objctype, @encode (NSRange)) == 0; + + case kPOPValueInteger: + return (strcmp(objctype, @encode(int)) == 0 + || strcmp(objctype, @encode(unsigned int)) == 0 + || strcmp(objctype, @encode(short)) == 0 + || strcmp(objctype, @encode(unsigned short)) == 0 + || strcmp(objctype, @encode(long)) == 0 + || strcmp(objctype, @encode(unsigned long)) == 0 + || strcmp(objctype, @encode(long long)) == 0 + || strcmp(objctype, @encode(unsigned long long)) == 0 + ); + + case kPOPValueSCNVector3: +#if SCENEKIT_SDK_AVAILABLE + return strcmp(objctype, @encode(SCNVector3)) == 0; +#else + return false; +#endif + + case kPOPValueSCNVector4: +#if SCENEKIT_SDK_AVAILABLE + return strcmp(objctype, @encode(SCNVector4)) == 0; +#else + return false; +#endif + + default: + return false; + } +} + +POPValueType POPSelectValueType(const char *objctype, const POPValueType *types, size_t length) +{ + if (NULL != objctype) { + for (size_t idx = 0; idx < length; idx++) { + if (FBCompareTypeEncoding(objctype, types[idx])) + return types[idx]; + } + } + return kPOPValueUnknown; +} + +POPValueType POPSelectValueType(id obj, const POPValueType *types, size_t length) +{ + if ([obj isKindOfClass:[NSValue class]]) { + return POPSelectValueType([obj objCType], types, length); + } else if (NULL != POPCGColorWithColor(obj)) { + return kPOPValueColor; + } + return kPOPValueUnknown; +} + +const POPValueType kPOPAnimatableAllTypes[12] = {kPOPValueInteger, kPOPValueFloat, kPOPValuePoint, kPOPValueSize, kPOPValueRect, kPOPValueEdgeInsets, kPOPValueAffineTransform, kPOPValueTransform, kPOPValueRange, kPOPValueColor, kPOPValueSCNVector3, kPOPValueSCNVector4}; + +const POPValueType kPOPAnimatableSupportTypes[10] = {kPOPValueInteger, kPOPValueFloat, kPOPValuePoint, kPOPValueSize, kPOPValueRect, kPOPValueEdgeInsets, kPOPValueColor, kPOPValueSCNVector3, kPOPValueSCNVector4}; + +NSString *POPValueTypeToString(POPValueType t) +{ + switch (t) { + case kPOPValueUnknown: + return @"unknown"; + case kPOPValueInteger: + return @"int"; + case kPOPValueFloat: + return @"CGFloat"; + case kPOPValuePoint: + return @"CGPoint"; + case kPOPValueSize: + return @"CGSize"; + case kPOPValueRect: + return @"CGRect"; + case kPOPValueEdgeInsets: + return @"UIEdgeInsets"; + case kPOPValueAffineTransform: + return @"CGAffineTransform"; + case kPOPValueTransform: + return @"CATransform3D"; + case kPOPValueRange: + return @"CFRange"; + case kPOPValueColor: + return @"CGColorRef"; + case kPOPValueSCNVector3: + return @"SCNVector3"; + case kPOPValueSCNVector4: + return @"SCNVector4"; + default: + return nil; + } +} + +id POPBox(VectorConstRef vec, POPValueType type, bool force) +{ + if (NULL == vec) + return nil; + + switch (type) { + case kPOPValueInteger: + case kPOPValueFloat: + return @(vec->data()[0]); + break; + case kPOPValuePoint: + return [NSValue valueWithCGPoint:vec->cg_point()]; + break; + case kPOPValueSize: + return [NSValue valueWithCGSize:vec->cg_size()]; + break; + case kPOPValueRect: + return [NSValue valueWithCGRect:vec->cg_rect()]; + break; +#if TARGET_OS_IPHONE + case kPOPValueEdgeInsets: + return [NSValue valueWithUIEdgeInsets:vec->ui_edge_insets()]; + break; +#endif + case kPOPValueColor: { + return (__bridge_transfer id)vec->cg_color(); + break; + } +#if SCENEKIT_SDK_AVAILABLE + case kPOPValueSCNVector3: { + return [NSValue valueWithSCNVector3:vec->scn_vector3()]; + break; + } + case kPOPValueSCNVector4: { + return [NSValue valueWithSCNVector4:vec->scn_vector4()]; + break; + } +#endif + default: + return force ? [NSValue valueWithCGPoint:vec->cg_point()] : nil; + break; + } +} + +static VectorRef vectorize(id value, POPValueType type) +{ + Vector *vec = NULL; + + switch (type) { + case kPOPValueInteger: + case kPOPValueFloat: +#if CGFLOAT_IS_DOUBLE + vec = Vector::new_cg_float([value doubleValue]); +#else + vec = Vector::new_cg_float([value floatValue]); +#endif + break; + case kPOPValuePoint: + vec = Vector::new_cg_point([value CGPointValue]); + break; + case kPOPValueSize: + vec = Vector::new_cg_size([value CGSizeValue]); + break; + case kPOPValueRect: + vec = Vector::new_cg_rect([value CGRectValue]); + break; +#if TARGET_OS_IPHONE + case kPOPValueEdgeInsets: + vec = Vector::new_ui_edge_insets([value UIEdgeInsetsValue]); + break; +#endif + case kPOPValueAffineTransform: + vec = Vector::new_cg_affine_transform([value CGAffineTransformValue]); + break; + case kPOPValueColor: + vec = Vector::new_cg_color(POPCGColorWithColor(value)); + break; +#if SCENEKIT_SDK_AVAILABLE + case kPOPValueSCNVector3: + vec = Vector::new_scn_vector3([value SCNVector3Value]); + break; + case kPOPValueSCNVector4: + vec = Vector::new_scn_vector4([value SCNVector4Value]); + break; +#endif + default: + break; + } + + return VectorRef(vec); +} + +VectorRef POPUnbox(id value, POPValueType &animationType, NSUInteger &count, bool validate) +{ + if (nil == value) { + count = 0; + return VectorRef(NULL); + } + + // determine type of value + POPValueType valueType = POPSelectValueType(value, kPOPAnimatableSupportTypes, POP_ARRAY_COUNT(kPOPAnimatableSupportTypes)); + + // handle unknown types + if (kPOPValueUnknown == valueType) { + NSString *valueDesc = [[value class] description]; + [NSException raise:@"Unsuported value" format:@"Animating %@ values is not supported", valueDesc]; + } + + // vectorize + VectorRef vec = vectorize(value, valueType); + + if (kPOPValueUnknown == animationType || 0 == count) { + // update animation type based on value type + animationType = valueType; + if (NULL != vec) { + count = vec->size(); + } + } else if (validate) { + // allow for mismatched types, so long as vector size matches + if (count != vec->size()) { + [NSException raise:@"Invalid value" format:@"%@ should be of type %@", value, POPValueTypeToString(animationType)]; + } + } + + return vec; +} diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationTracer.h b/TalkinToTheNet/Pods/pop/pop/POPAnimationTracer.h new file mode 100644 index 0000000..72b26c3 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationTracer.h @@ -0,0 +1,60 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import + +@class POPAnimation; + +/** + @abstract Tracer of animation events to fasciliate unit testing & debugging. + */ +@interface POPAnimationTracer : NSObject + +/** + @abstract Start recording events. + */ +- (void)start; + +/** + @abstract Stop recording events. + */ +- (void)stop; + +/** + @abstract Resets any recoded events. Continues recording events if already started. + */ +- (void)reset; + +/** + @abstract Property representing all recorded events. + @discussion Events are returned in order of occurence. + */ +@property (nonatomic, assign, readonly) NSArray *allEvents; + +/** + @abstract Property representing all recorded write events for convenience. + @discussion Events are returned in order of occurence. + */ +@property (nonatomic, assign, readonly) NSArray *writeEvents; + +/** + @abstract Queries for events of specified type. + @param type The type of event to return. + @returns An array of events of specified type in order of occurence. + */ +- (NSArray *)eventsWithType:(POPAnimationEventType)type; + +/** + @abstract Property indicating whether tracer should automatically log events and reset collection on animation completion. + */ +@property (nonatomic, assign) BOOL shouldLogAndResetOnCompletion; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationTracer.mm b/TalkinToTheNet/Pods/pop/pop/POPAnimationTracer.mm new file mode 100644 index 0000000..243fb9b --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationTracer.mm @@ -0,0 +1,191 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimationTracer.h" + +#import + +#import "POPAnimationEventInternal.h" +#import "POPAnimationInternal.h" +#import "POPSpringAnimation.h" + +@implementation POPAnimationTracer +{ + __weak POPAnimation *_animation; + POPAnimationState *_animationState; + NSMutableArray *_events; + BOOL _animationHasVelocity; +} +@synthesize shouldLogAndResetOnCompletion = _shouldLogAndResetOnCompletion; + +static POPAnimationEvent *create_event(POPAnimationTracer *self, POPAnimationEventType type, id value = nil, bool recordAnimation = false) +{ + bool useLocalTime = 0 != self->_animationState->startTime; + CFTimeInterval time = useLocalTime + ? self->_animationState->lastTime - self->_animationState->startTime + : self->_animationState->lastTime; + + POPAnimationEvent *event; + + if (!value) { + event = [[POPAnimationEvent alloc] initWithType:type time:time]; + } else { + event = [[POPAnimationValueEvent alloc] initWithType:type time:time value:value]; + if (self->_animationHasVelocity) { + [(POPAnimationValueEvent *)event setVelocity:[(POPSpringAnimation *)self->_animation velocity]]; + } + } + + if (recordAnimation) { + event.animationDescription = [self->_animation description]; + } + + return event; +} + +- (id)initWithAnimation:(POPAnimation *)anAnim +{ + self = [super init]; + if (nil != self) { + _animation = anAnim; + _animationState = POPAnimationGetState(anAnim); + _events = [[NSMutableArray alloc] initWithCapacity:50]; + _animationHasVelocity = [anAnim respondsToSelector:@selector(velocity)]; + } + return self; +} + +- (void)readPropertyValue:(id)aValue +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventPropertyRead, aValue); + [_events addObject:event]; +} + +- (void)writePropertyValue:(id)aValue +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventPropertyWrite, aValue); + [_events addObject:event]; +} + +- (void)updateToValue:(id)aValue +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventToValueUpdate, aValue); + [_events addObject:event]; +} + +- (void)updateFromValue:(id)aValue +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventFromValueUpdate, aValue); + [_events addObject:event]; +} + +- (void)updateVelocity:(id)aValue +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventVelocityUpdate, aValue); + [_events addObject:event]; +} + +- (void)updateSpeed:(float)aFloat +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventSpeedUpdate, @(aFloat)); + [_events addObject:event]; +} + +- (void)updateBounciness:(float)aFloat +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventBouncinessUpdate, @(aFloat)); + [_events addObject:event]; +} + +- (void)updateFriction:(float)aFloat +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventFrictionUpdate, @(aFloat)); + [_events addObject:event]; +} + +- (void)updateMass:(float)aFloat +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventMassUpdate, @(aFloat)); + [_events addObject:event]; +} + +- (void)updateTension:(float)aFloat +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventTensionUpdate, @(aFloat)); + [_events addObject:event]; +} + +- (void)didStart +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventDidStart, nil, true); + [_events addObject:event]; +} + +- (void)didStop:(BOOL)finished +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventDidStop, @(finished), true); + [_events addObject:event]; + + if (_shouldLogAndResetOnCompletion) { + NSLog(@"events:%@", self.allEvents); + [self reset]; + } +} + +- (void)didReachToValue:(id)aValue +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventDidReachToValue, aValue); + [_events addObject:event]; +} + +- (void)autoreversed +{ + POPAnimationEvent *event = create_event(self, kPOPAnimationEventAutoreversed); + [_events addObject:event]; +} + +- (void)start +{ + POPAnimationState *s = POPAnimationGetState(_animation); + s->tracing = true; +} + +- (void)stop +{ + POPAnimationState *s = POPAnimationGetState(_animation); + s->tracing = false; +} + +- (void)reset +{ + [_events removeAllObjects]; +} + +- (NSArray *)allEvents +{ + return [_events copy]; +} + +- (NSArray *)writeEvents +{ + return [self eventsWithType:kPOPAnimationEventPropertyWrite]; +} + +- (NSArray *)eventsWithType:(POPAnimationEventType)aType +{ + NSMutableArray *array = [NSMutableArray array]; + for (POPAnimationEvent *event in _events) { + if (aType == event.type) { + [array addObject:event]; + } + } + return array; +} + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimationTracerInternal.h b/TalkinToTheNet/Pods/pop/pop/POPAnimationTracerInternal.h new file mode 100644 index 0000000..00958e1 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimationTracerInternal.h @@ -0,0 +1,96 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import + +@interface POPAnimationTracer (Internal) + +/** + @abstract Designated initalizer. Pass the animation being traced. + */ +- (instancetype)initWithAnimation:(POPAnimation *)anAnim; + +/** + @abstract Records read value. + */ +- (void)readPropertyValue:(id)aValue; + +/** + @abstract Records write value. + */ +- (void)writePropertyValue:(id)aValue; + +/** + Records to value update. + */ +- (void)updateToValue:(id)aValue; + +/** + @abstract Records from value update. + */ +- (void)updateFromValue:(id)aValue; + +/** + @abstract Records from value update. + */ +- (void)updateVelocity:(id)aValue; + +/** + @abstract Records bounciness update. + */ +- (void)updateBounciness:(float)aFloat; + +/** + @abstract Records speed update. + */ +- (void)updateSpeed:(float)aFloat; + +/** + @abstract Records friction update. + */ +- (void)updateFriction:(float)aFloat; + +/** + @abstract Records mass update. + */ +- (void)updateMass:(float)aFloat; + +/** + @abstract Records tension update. + */ +- (void)updateTension:(float)aFloat; + +/** + @abstract Records did add. + */ +- (void)didAdd; + +/** + @abstract Records did start. + */ +- (void)didStart; + +/** + @abstract Records did stop. + */ +- (void)didStop:(BOOL)finished; + +/** + @abstract Records did reach to value. + */ +- (void)didReachToValue:(id)aValue; + +/** + @abstract Records when an autoreverse animation takes place. + */ +- (void)autoreversed; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimator.h b/TalkinToTheNet/Pods/pop/pop/POPAnimator.h new file mode 100644 index 0000000..5310bed --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimator.h @@ -0,0 +1,47 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +@protocol POPAnimatorDelegate; + +/** + @abstract The animator class renders animations. + */ +@interface POPAnimator : NSObject + +/** + @abstract The shared animator instance. + @discussion Consumers should generally use the shared instance in lieu of creating new instances. + */ ++ (instancetype)sharedAnimator; + +/** + @abstract The optional animator delegate. + */ +@property (weak, nonatomic) id delegate; + +@end + +/** + @abstract The animator delegate. + */ +@protocol POPAnimatorDelegate + +/** + @abstract Called on each frame before animation application. + */ +- (void)animatorWillAnimate:(POPAnimator *)animator; + +/** + @abstract Called on each frame after animation application. + */ +- (void)animatorDidAnimate:(POPAnimator *)animator; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimator.mm b/TalkinToTheNet/Pods/pop/pop/POPAnimator.mm new file mode 100644 index 0000000..6b2a770 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimator.mm @@ -0,0 +1,806 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimator.h" +#import "POPAnimatorPrivate.h" + +#import +#import + +#if !TARGET_OS_IPHONE +#import +#endif + +#import + +#import + +#import "POPAnimation.h" +#import "POPAnimationExtras.h" +#import "POPBasicAnimationInternal.h" +#import "POPDecayAnimation.h" + +using namespace std; +using namespace POP; + +#define ENABLE_LOGGING_DEBUG 0 +#define ENABLE_LOGGING_INFO 0 + +#if ENABLE_LOGGING_DEBUG +#define FBLogAnimDebug NSLog +#else +#define FBLogAnimDebug(...) +#endif + +#if ENABLE_LOGGING_INFO +#define FBLogAnimInfo NSLog +#else +#define FBLogAnimInfo(...) +#endif + +class POPAnimatorItem +{ +public: + id __weak object; + NSString *key; + POPAnimation *animation; + NSInteger refCount; + id __unsafe_unretained unretainedObject; + + POPAnimatorItem(id o, NSString *k, POPAnimation *a) POP_NOTHROW + { + object = o; + key = [k copy]; + animation = a; + refCount = 1; + unretainedObject = o; + } + + ~POPAnimatorItem() + { + } + + bool operator==(const POPAnimatorItem& o) const { + return unretainedObject == o.unretainedObject && animation == o.animation && [key isEqualToString:o.key]; + } + +}; + +typedef std::shared_ptr POPAnimatorItemRef; +typedef std::shared_ptr POPAnimatorItemConstRef; + +typedef std::list POPAnimatorItemList; +typedef POPAnimatorItemList::iterator POPAnimatorItemListIterator; +typedef POPAnimatorItemList::const_iterator POPAnimatorItemListConstIterator; + +static BOOL _disableBackgroundThread = YES; + +@interface POPAnimator () +{ +#if TARGET_OS_IPHONE + CADisplayLink *_displayLink; +#else + CVDisplayLinkRef _displayLink; + int32_t _enqueuedRender; +#endif + POPAnimatorItemList _list; + CFMutableDictionaryRef _dict; + NSMutableArray *_observers; + POPAnimatorItemList _pendingList; + CFRunLoopObserverRef _pendingListObserver; + CFTimeInterval _slowMotionStartTime; + CFTimeInterval _slowMotionLastTime; + CFTimeInterval _slowMotionAccumulator; + CFTimeInterval _beginTime; + OSSpinLock _lock; + BOOL _disableDisplayLink; +} +@end + +@implementation POPAnimator +@synthesize delegate = _delegate; +@synthesize disableDisplayLink = _disableDisplayLink; +@synthesize beginTime = _beginTime; + +#if !TARGET_OS_IPHONE +static CVReturn displayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *now, const CVTimeStamp *outputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *context) +{ + if (_disableBackgroundThread) { + __unsafe_unretained POPAnimator *pa = (__bridge POPAnimator *)context; + int32_t* enqueuedRender = &pa->_enqueuedRender; + if (*enqueuedRender == 0) { + OSAtomicIncrement32(enqueuedRender); + dispatch_async(dispatch_get_main_queue(), ^{ + [(__bridge POPAnimator*)context render]; + OSAtomicDecrement32(enqueuedRender); + }); + } + } else { + [(__bridge POPAnimator*)context render]; + } + return kCVReturnSuccess; +} +#endif + +// call while holding lock +static void updateDisplayLink(POPAnimator *self) +{ + BOOL paused = (0 == self->_observers.count && self->_list.empty()) || self->_disableDisplayLink; + +#if TARGET_OS_IPHONE + if (paused != self->_displayLink.paused) { + FBLogAnimInfo(paused ? @"pausing display link" : @"unpausing display link"); + self->_displayLink.paused = paused; + } +#else + if (paused == CVDisplayLinkIsRunning(self->_displayLink)) { + FBLogAnimInfo(paused ? @"pausing display link" : @"unpausing display link"); + if (paused) { + CVDisplayLinkStop(self->_displayLink); + } else { + CVDisplayLinkStart(self->_displayLink); + } + } +#endif +} + +static void updateAnimatable(id obj, POPPropertyAnimationState *anim, bool shouldAvoidExtraneousWrite = false) +{ + // handle user-initiated stop or pause; hault animation + if (!anim->active || anim->paused) + return; + + if (anim->hasValue()) { + pop_animatable_write_block write = anim->property.writeBlock; + if (NULL == write) + return; + + // current animation value + VectorRef currentVec = anim->currentValue(); + + if (!anim->additive) { + + // if avoiding extraneous writes and we have a read block defined + if (shouldAvoidExtraneousWrite) { + + pop_animatable_read_block read = anim->property.readBlock; + if (read) { + // compare current animation value with object value + Vector4r currentValue = currentVec->vector4r(); + Vector4r objectValue = read_values(read, obj, anim->valueCount); + if (objectValue == currentValue) { + return; + } + } + } + + // update previous values; support animation convergence + anim->previous2Vec = anim->previousVec; + anim->previousVec = currentVec; + + // write value + write(obj, currentVec->data()); + if (anim->tracing) { + [anim->tracer writePropertyValue:POPBox(currentVec, anim->valueType, true)]; + } + } else { + pop_animatable_read_block read = anim->property.readBlock; + NSCAssert(read, @"additive requires an animatable property readBlock"); + if (NULL == read) { + return; + } + + // object value + Vector4r objectValue = read_values(read, obj, anim->valueCount); + + // current value + Vector4r currentValue = currentVec->vector4r(); + + // determine animation change + if (anim->previousVec) { + Vector4r previousValue = anim->previousVec->vector4r(); + currentValue -= previousValue; + } + + // avoid writing no change + if (shouldAvoidExtraneousWrite && currentValue == Vector4r::Zero()) { + return; + } + + // add to object value + currentValue += objectValue; + + // update previous values; support animation convergence + anim->previous2Vec = anim->previousVec; + anim->previousVec = currentVec; + + // write value + write(obj, currentValue.data()); + if (anim->tracing) { + [anim->tracer writePropertyValue:POPBox(currentVec, anim->valueType, true)]; + } + } + } +} + +static void applyAnimationTime(id obj, POPAnimationState *state, CFTimeInterval time) +{ + if (!state->advanceTime(time, obj)) { + return; + } + + POPPropertyAnimationState *ps = dynamic_cast(state); + if (NULL != ps) { + updateAnimatable(obj, ps); + } + + state->delegateApply(); +} + +static void applyAnimationToValue(id obj, POPAnimationState *state) +{ + POPPropertyAnimationState *ps = dynamic_cast(state); + + if (NULL != ps) { + + // finalize progress + ps->finalizeProgress(); + + // write to value, updating only if needed + updateAnimatable(obj, ps, true); + } + + state->delegateApply(); +} + +static POPAnimation *deleteDictEntry(POPAnimator *self, id __unsafe_unretained obj, NSString *key, BOOL cleanup = YES) +{ + POPAnimation *anim = nil; + + // lock + OSSpinLockLock(&self->_lock); + + NSMutableDictionary *keyAnimationsDict = (__bridge id)CFDictionaryGetValue(self->_dict, (__bridge void *)obj); + if (keyAnimationsDict) { + + anim = keyAnimationsDict[key]; + if (anim) { + + // remove key + [keyAnimationsDict removeObjectForKey:key]; + + // cleanup empty dictionaries + if (cleanup && 0 == keyAnimationsDict.count) { + CFDictionaryRemoveValue(self->_dict, (__bridge void *)obj); + } + } + } + + // unlock + OSSpinLockUnlock(&self->_lock); + return anim; +} + +static void stopAndCleanup(POPAnimator *self, POPAnimatorItemRef item, bool shouldRemove, bool finished) +{ + // remove + if (shouldRemove) { + deleteDictEntry(self, item->unretainedObject, item->key); + } + + // stop + POPAnimationState *state = POPAnimationGetState(item->animation); + state->stop(shouldRemove, finished); + + if (shouldRemove) { + // lock + OSSpinLockLock(&self->_lock); + + // find item in list + // may have already been removed on animationDidStop: + POPAnimatorItemListIterator find_iter = find(self->_list.begin(), self->_list.end(), item); + BOOL found = find_iter != self->_list.end(); + + if (found) { + self->_list.erase(find_iter); + } + + // unlock + OSSpinLockUnlock(&self->_lock); + } +} + ++ (id)sharedAnimator +{ + static POPAnimator* _animator = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _animator = [[POPAnimator alloc] init]; + }); + return _animator; +} + ++ (BOOL)disableBackgroundThread +{ + return _disableBackgroundThread; +} + ++ (void)setDisableBackgroundThread:(BOOL)flag +{ + _disableBackgroundThread = flag; +} + +#pragma mark - Lifecycle + +- (id)init +{ + self = [super init]; + if (nil == self) return nil; + +#if TARGET_OS_IPHONE + _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(render)]; + _displayLink.paused = YES; + [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; +#else + CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink); + CVDisplayLinkSetOutputCallback(_displayLink, displayLinkCallback, (__bridge void *)self); +#endif + + _dict = POPDictionaryCreateMutableWeakPointerToStrongObject(5); + _lock = OS_SPINLOCK_INIT; + + return self; +} + +- (void)dealloc +{ +#if TARGET_OS_IPHONE + [_displayLink invalidate]; +#else + CVDisplayLinkStop(_displayLink); + CVDisplayLinkRelease(_displayLink); +#endif + [self _clearPendingListObserver]; +} + +#pragma mark - Utility + +- (void)_processPendingList +{ + // rendering pending animations + CFTimeInterval time = [self _currentRenderTime]; + [self _renderTime:(0 != _beginTime) ? _beginTime : time items:_pendingList]; + + // lock + OSSpinLockLock(&_lock); + + // clear list and observer + _pendingList.clear(); + [self _clearPendingListObserver]; + + // unlock + OSSpinLockUnlock(&_lock); +} + +- (void)_clearPendingListObserver +{ + if (_pendingListObserver) { + CFRunLoopRemoveObserver(CFRunLoopGetMain(), _pendingListObserver, kCFRunLoopCommonModes); + CFRelease(_pendingListObserver); + _pendingListObserver = NULL; + } +} + +- (void)_scheduleProcessPendingList +{ + // see WebKit for magic numbers, eg http://trac.webkit.org/changeset/166540 + static const CFIndex CATransactionCommitRunLoopOrder = 2000000; + static const CFIndex POPAnimationApplyRunLoopOrder = CATransactionCommitRunLoopOrder - 1; + + // lock + OSSpinLockLock(&_lock); + + if (!_pendingListObserver) { + __weak POPAnimator *weakSelf = self; + + _pendingListObserver = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopBeforeWaiting | kCFRunLoopExit, false, POPAnimationApplyRunLoopOrder, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) { + [weakSelf _processPendingList]; + }); + + if (_pendingListObserver) { + CFRunLoopAddObserver(CFRunLoopGetMain(), _pendingListObserver, kCFRunLoopCommonModes); + } + } + + // unlock + OSSpinLockUnlock(&_lock); +} + +- (void)_renderTime:(CFTimeInterval)time items:(std::list)items +{ + // begin transaction with actions disabled + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + + // notify delegate + __strong __typeof__(_delegate) delegate = _delegate; + [delegate animatorWillAnimate:self]; + + // lock + OSSpinLockLock(&_lock); + + // count active animations + const NSUInteger count = items.size(); + if (0 == count) { + // unlock + OSSpinLockUnlock(&_lock); + } else { + // copy list into vector + std::vector vector{ items.begin(), items.end() }; + + // unlock + OSSpinLockUnlock(&_lock); + + for (auto item : vector) { + [self _renderTime:time item:item]; + } + } + + // notify observers + for (id observer in self.observers) { + [observer animatorDidAnimate:(id)self]; + } + + // lock + OSSpinLockLock(&_lock); + + // update display link + updateDisplayLink(self); + + // unlock + OSSpinLockUnlock(&_lock); + + // notify delegate and commit + [delegate animatorDidAnimate:self]; + [CATransaction commit]; +} + +- (void)_renderTime:(CFTimeInterval)time item:(POPAnimatorItemRef)item +{ + id obj = item->object; + POPAnimation *anim = item->animation; + POPAnimationState *state = POPAnimationGetState(anim); + + if (nil == obj) { + // object exists not; stop animating + NSAssert(item->unretainedObject, @"object should exist"); + stopAndCleanup(self, item, true, false); + } else { + + // start if needed + state->startIfNeeded(obj, time, _slowMotionAccumulator); + + // only run active, not paused animations + if (state->active && !state->paused) { + // object exists; animate + applyAnimationTime(obj, state, time); + + FBLogAnimDebug(@"time:%f running:%@", time, item->animation); + if (state->isDone()) { + // set end value + applyAnimationToValue(obj, state); + + state->repeatCount--; + if (state->repeatForever || state->repeatCount > 0) { + if ([anim isKindOfClass:[POPPropertyAnimation class]]) { + POPPropertyAnimation *propAnim = (POPPropertyAnimation *)anim; + id oldFromValue = propAnim.fromValue; + propAnim.fromValue = propAnim.toValue; + + if (state->autoreverses) { + if (state->tracing) { + [state->tracer autoreversed]; + } + + if (state->type == kPOPAnimationDecay) { + POPDecayAnimation *decayAnimation = (POPDecayAnimation *)propAnim; + decayAnimation.velocity = [decayAnimation reversedVelocity]; + } else { + propAnim.toValue = oldFromValue; + } + } else { + if (state->type == kPOPAnimationDecay) { + POPDecayAnimation *decayAnimation = (POPDecayAnimation *)propAnim; + id originalVelocity = decayAnimation.originalVelocity; + decayAnimation.velocity = originalVelocity; + } else { + propAnim.fromValue = oldFromValue; + } + } + } + + state->stop(NO, NO); + state->reset(true); + + state->startIfNeeded(obj, time, _slowMotionAccumulator); + } else { + stopAndCleanup(self, item, state->removedOnCompletion, YES); + } + } + } + } +} + +#pragma mark - API + +- (NSArray *)observers +{ + // lock + OSSpinLockLock(&_lock); + + // get observers + NSArray *observers = 0 != _observers.count ? [_observers copy] : nil; + + // unlock + OSSpinLockUnlock(&_lock); + return observers; +} + +- (void)addAnimation:(POPAnimation *)anim forObject:(id)obj key:(NSString *)key +{ + if (!anim || !obj) { + return; + } + + // support arbitrarily many nil keys + if (!key) { + key = [[NSUUID UUID] UUIDString]; + } + + // lock + OSSpinLockLock(&_lock); + + // get key, animation dict associated with object + NSMutableDictionary *keyAnimationDict = (__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj); + + // update associated animation state + if (nil == keyAnimationDict) { + keyAnimationDict = [NSMutableDictionary dictionary]; + CFDictionarySetValue(_dict, (__bridge void *)obj, (__bridge void *)keyAnimationDict); + } else { + // if the animation instance already exists, avoid cancelling only to restart + POPAnimation *existingAnim = keyAnimationDict[key]; + if (existingAnim) { + // unlock + OSSpinLockUnlock(&_lock); + + if (existingAnim == anim) { + return; + } + [self removeAnimationForObject:obj key:key cleanupDict:NO]; + + // lock + OSSpinLockLock(&_lock); + } + } + keyAnimationDict[key] = anim; + + // create entry after potential removal + POPAnimatorItemRef item(new POPAnimatorItem(obj, key, anim)); + + // add to list and pending list + _list.push_back(item); + _pendingList.push_back(item); + + // support animation re-use, reset all animation state + POPAnimationGetState(anim)->reset(true); + + // update display link + updateDisplayLink(self); + + // unlock + OSSpinLockUnlock(&_lock); + + // schedule runloop processing of pending animations + [self _scheduleProcessPendingList]; +} + +- (void)removeAllAnimationsForObject:(id)obj +{ + // lock + OSSpinLockLock(&_lock); + + NSArray *animations = [(__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj) allValues]; + CFDictionaryRemoveValue(_dict, (__bridge void *)obj); + + // unlock + OSSpinLockUnlock(&_lock); + + if (0 == animations.count) { + return; + } + + NSHashTable *animationSet = [[NSHashTable alloc] initWithOptions:NSHashTableObjectPointerPersonality capacity:animations.count]; + for (id animation in animations) { + [animationSet addObject:animation]; + } + + // lock + OSSpinLockLock(&_lock); + + POPAnimatorItemRef item; + for (auto iter = _list.begin(); iter != _list.end();) { + item = *iter; + if(![animationSet containsObject:item->animation]) { + iter++; + } else { + iter = _list.erase(iter); + } + } + + // unlock + OSSpinLockUnlock(&_lock); + + for (POPAnimation *anim in animations) { + POPAnimationState *state = POPAnimationGetState(anim); + state->stop(true, !state->active); + } +} + +- (void)removeAnimationForObject:(id)obj key:(NSString *)key cleanupDict:(BOOL)cleanupDict +{ + POPAnimation *anim = deleteDictEntry(self, obj, key, cleanupDict); + if (nil == anim) { + return; + } + + // lock + OSSpinLockLock(&_lock); + + // remove from list + POPAnimatorItemRef item; + for (auto iter = _list.begin(); iter != _list.end();) { + item = *iter; + if(anim == item->animation) { + _list.erase(iter); + break; + } else { + iter++; + } + } + + // remove from pending list + for (auto iter = _pendingList.begin(); iter != _pendingList.end();) { + item = *iter; + if(anim == item->animation) { + _pendingList.erase(iter); + break; + } else { + iter++; + } + } + + // unlock + OSSpinLockUnlock(&_lock); + + // stop animation and callout + POPAnimationState *state = POPAnimationGetState(anim); + state->stop(true, (!state->active && !state->paused)); +} + +- (void)removeAnimationForObject:(id)obj key:(NSString *)key +{ + [self removeAnimationForObject:obj key:key cleanupDict:YES]; +} + +- (NSArray *)animationKeysForObject:(id)obj +{ + // lock + OSSpinLockLock(&_lock); + + // get keys + NSArray *keys = [(__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj) allKeys]; + + // unlock + OSSpinLockUnlock(&_lock); + return keys; +} + +- (id)animationForObject:(id)obj key:(NSString *)key +{ + // lock + OSSpinLockLock(&_lock); + + // lookup animation + NSDictionary *keyAnimationsDict = (__bridge id)CFDictionaryGetValue(_dict, (__bridge void *)obj); + POPAnimation *animation = keyAnimationsDict[key]; + + // unlock + OSSpinLockUnlock(&_lock); + return animation; +} + +- (CFTimeInterval)_currentRenderTime +{ + CFTimeInterval time = CACurrentMediaTime(); + +#if TARGET_IPHONE_SIMULATOR + // support slow-motion animations + time += _slowMotionAccumulator; + float f = POPAnimationDragCoefficient(); + + if (f > 1.0) { + if (!_slowMotionStartTime) { + _slowMotionStartTime = time; + } else { + time = (time - _slowMotionStartTime) / f + _slowMotionStartTime; + _slowMotionLastTime = time; + } + } else if (_slowMotionStartTime) { + CFTimeInterval dt = (_slowMotionLastTime - time); + time += dt; + _slowMotionAccumulator += dt; + _slowMotionStartTime = 0; + } +#endif + + return time; +} + +- (void)render +{ + CFTimeInterval time = [self _currentRenderTime]; + [self renderTime:time]; +} + +- (void)renderTime:(CFTimeInterval)time +{ + [self _renderTime:time items:_list]; +} + +- (void)addObserver:(id)observer +{ + NSAssert(nil != observer, @"attempting to add nil %@ observer", self); + if (nil == observer) { + return; + } + + // lock + OSSpinLockLock(&_lock); + + if (!_observers) { + // use ordered collection for deterministic callout + _observers = [[NSMutableArray alloc] initWithCapacity:1]; + } + + [_observers addObject:observer]; + updateDisplayLink(self); + + // unlock + OSSpinLockUnlock(&_lock); +} + +- (void)removeObserver:(id)observer +{ + NSAssert(nil != observer, @"attempting to remove nil %@ observer", self); + if (nil == observer) { + return; + } + + // lock + OSSpinLockLock(&_lock); + + [_observers removeObject:observer]; + updateDisplayLink(self); + + // unlock + OSSpinLockUnlock(&_lock); +} + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPAnimatorPrivate.h b/TalkinToTheNet/Pods/pop/pop/POPAnimatorPrivate.h new file mode 100644 index 0000000..5fba912 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPAnimatorPrivate.h @@ -0,0 +1,68 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +@class POPAnimation; + +@protocol POPAnimatorObserving +@required + +/** + @abstract Called on each observer after animator has advanced. Core Animation actions are disabled by default. + */ +- (void)animatorDidAnimate:(POPAnimator *)animator; + +@end + +@interface POPAnimator () + +#if !TARGET_OS_IPHONE +/** + Determines whether or not to use a high priority background thread for animation updates. Using a background thread can result in faster, more responsive updates, but may be less compatible. Defaults to YES. + */ ++ (BOOL)disableBackgroundThread; ++ (void)setDisableBackgroundThread:(BOOL)flag; +#endif + +/** + Used for externally driven animator instances. + */ +@property (assign, nonatomic) BOOL disableDisplayLink; + +/** + Time used when starting animations. Defaults to 0 meaning current media time is used. Exposed for unit testing. + */ +@property (assign, nonatomic) CFTimeInterval beginTime; + +/** + Exposed for unit testing. + */ +- (void)renderTime:(CFTimeInterval)time; + +/** + Funnel methods for category additions. + */ +- (void)addAnimation:(POPAnimation *)anim forObject:(id)obj key:(NSString *)key; +- (void)removeAllAnimationsForObject:(id)obj; +- (void)removeAnimationForObject:(id)obj key:(NSString *)key; +- (NSArray *)animationKeysForObject:(id)obj; +- (POPAnimation *)animationForObject:(id)obj key:(NSString *)key; + +/** + @abstract Add an animator observer. Observer will be notified of each subsequent animator advance until removal. + */ +- (void)addObserver:(id)observer; + +/** + @abstract Remove an animator observer. + */ +- (void)removeObserver:(id)observer; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPBasicAnimation.h b/TalkinToTheNet/Pods/pop/pop/POPBasicAnimation.h new file mode 100644 index 0000000..ce2e23a --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPBasicAnimation.h @@ -0,0 +1,71 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +/** + @abstract A concrete basic animation class. + @discussion Animation is achieved through interpolation. + */ +@interface POPBasicAnimation : POPPropertyAnimation + +/** + @abstract The designated initializer. + @returns An instance of a basic animation. + */ ++ (instancetype)animation; + +/** + @abstract Convenience initializer that returns an animation with animatable property of name. + @param name The name of the animatable property. + @returns An instance of a basic animation configured with specified animatable property. + */ ++ (instancetype)animationWithPropertyNamed:(NSString *)name; + +/** + @abstract Convenience constructor. + @returns Returns a basic animation with kCAMediaTimingFunctionDefault timing function. + */ ++ (instancetype)defaultAnimation; + +/** + @abstract Convenience constructor. + @returns Returns a basic animation with kCAMediaTimingFunctionLinear timing function. + */ ++ (instancetype)linearAnimation; + +/** + @abstract Convenience constructor. + @returns Returns a basic animation with kCAMediaTimingFunctionEaseIn timing function. + */ ++ (instancetype)easeInAnimation; + +/** + @abstract Convenience constructor. + @returns Returns a basic animation with kCAMediaTimingFunctionEaseOut timing function. + */ ++ (instancetype)easeOutAnimation; + +/** + @abstract Convenience constructor. + @returns Returns a basic animation with kCAMediaTimingFunctionEaseInEaseOut timing function. + */ ++ (instancetype)easeInEaseOutAnimation; + +/** + @abstract The duration in seconds. Defaults to 0.4. + */ +@property (assign, nonatomic) CFTimeInterval duration; + +/** + @abstract A timing function defining the pacing of the animation. Defaults to nil indicating pacing according to kCAMediaTimingFunctionDefault. + */ +@property (strong, nonatomic) CAMediaTimingFunction *timingFunction; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPBasicAnimation.mm b/TalkinToTheNet/Pods/pop/pop/POPBasicAnimation.mm new file mode 100644 index 0000000..2843c99 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPBasicAnimation.mm @@ -0,0 +1,106 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPBasicAnimationInternal.h" + +@implementation POPBasicAnimation + +#undef __state +#define __state ((POPBasicAnimationState *)_state) + +#pragma mark - Lifecycle + ++ (instancetype)animation +{ + return [[self alloc] init]; +} + ++ (instancetype)animationWithPropertyNamed:(NSString *)aName +{ + POPBasicAnimation *anim = [self animation]; + anim.property = [POPAnimatableProperty propertyWithName:aName]; + return anim; +} + +- (void)_initState +{ + _state = new POPBasicAnimationState(self); +} + ++ (instancetype)linearAnimation +{ + POPBasicAnimation *anim = [self animation]; + anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; + return anim; +} + ++ (instancetype)easeInAnimation +{ + POPBasicAnimation *anim = [self animation]; + anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; + return anim; +} + ++ (instancetype)easeOutAnimation +{ + POPBasicAnimation *anim = [self animation]; + anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; + return anim; +} + ++ (instancetype)easeInEaseOutAnimation +{ + POPBasicAnimation *anim = [self animation]; + anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + return anim; +} + ++ (instancetype)defaultAnimation +{ + POPBasicAnimation *anim = [self animation]; + anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]; + return anim; +} + +- (id)init +{ + return [self _init]; +} + +#pragma mark - Properties + +DEFINE_RW_PROPERTY(POPBasicAnimationState, duration, setDuration:, CFTimeInterval); +DEFINE_RW_PROPERTY_OBJ(POPBasicAnimationState, timingFunction, setTimingFunction:, CAMediaTimingFunction*, __state->updatedTimingFunction();); + +#pragma mark - Utility + +- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug +{ + [super _appendDescription:s debug:debug]; + if (__state->duration) + [s appendFormat:@"; duration = %f", __state->duration]; +} + +@end + +@implementation POPBasicAnimation (NSCopying) + +- (instancetype)copyWithZone:(NSZone *)zone { + + POPBasicAnimation *copy = [super copyWithZone:zone]; + + if (copy) { + copy.duration = self.duration; + copy.timingFunction = self.timingFunction; // not a 'copy', but timing functions are publicly immutable. + } + + return copy; +} + +@end \ No newline at end of file diff --git a/TalkinToTheNet/Pods/pop/pop/POPBasicAnimationInternal.h b/TalkinToTheNet/Pods/pop/pop/POPBasicAnimationInternal.h new file mode 100644 index 0000000..1027670 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPBasicAnimationInternal.h @@ -0,0 +1,97 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPBasicAnimation.h" + +#import "POPPropertyAnimationInternal.h" + +// default animation duration +static CGFloat const kPOPAnimationDurationDefault = 0.4; + +// progress threshold for computing done +static CGFloat const kPOPProgressThreshold = 1e-6; + +static void interpolate(POPValueType valueType, NSUInteger count, const CGFloat *fromVec, const CGFloat *toVec, CGFloat *outVec, CGFloat p) +{ + switch (valueType) { + case kPOPValueInteger: + case kPOPValueFloat: + case kPOPValuePoint: + case kPOPValueSize: + case kPOPValueRect: + case kPOPValueEdgeInsets: + case kPOPValueColor: + POPInterpolateVector(count, outVec, fromVec, toVec, p); + break; + default: + NSCAssert(false, @"unhandled type %d", valueType); + break; + } +} + +struct _POPBasicAnimationState : _POPPropertyAnimationState +{ + CAMediaTimingFunction *timingFunction; + double timingControlPoints[4]; + CFTimeInterval duration; + CFTimeInterval timeProgress; + + _POPBasicAnimationState(id __unsafe_unretained anim) : _POPPropertyAnimationState(anim), + timingFunction(nil), + timingControlPoints{0.}, + duration(kPOPAnimationDurationDefault), + timeProgress(0.) + { + type = kPOPAnimationBasic; + } + + bool isDone() { + if (_POPPropertyAnimationState::isDone()) { + return true; + } + return timeProgress + kPOPProgressThreshold >= 1.; + } + + void updatedTimingFunction() + { + float vec[4] = {0.}; + [timingFunction getControlPointAtIndex:1 values:&vec[0]]; + [timingFunction getControlPointAtIndex:2 values:&vec[2]]; + for (NSUInteger idx = 0; idx < POP_ARRAY_COUNT(vec); idx++) { + timingControlPoints[idx] = vec[idx]; + } + } + + bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) { + // default timing function + if (!timingFunction) { + ((POPBasicAnimation *)self).timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]; + } + + // solve for normalized time, aka progresss [0, 1] + CGFloat p = 1.0f; + if (duration > 0.0f) { + // cap local time to duration + CFTimeInterval t = MIN(time - startTime, duration) / duration; + p = POPTimingFunctionSolve(timingControlPoints, t, SOLVE_EPS(duration)); + timeProgress = t; + } else { + timeProgress = 1.; + } + + // interpolate and advance + interpolate(valueType, valueCount, fromVec->data(), toVec->data(), currentVec->data(), p); + progress = p; + clampCurrentValue(); + + return true; + } +}; + +typedef struct _POPBasicAnimationState POPBasicAnimationState; diff --git a/TalkinToTheNet/Pods/pop/pop/POPCGUtils.h b/TalkinToTheNet/Pods/pop/pop/POPCGUtils.h new file mode 100644 index 0000000..c843947 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPCGUtils.h @@ -0,0 +1,152 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#if TARGET_OS_IPHONE +#import +#else +#import +#endif + +#import "POPDefines.h" + +#if SCENEKIT_SDK_AVAILABLE +#import +#endif + +POP_EXTERN_C_BEGIN + +NS_INLINE CGPoint values_to_point(const CGFloat values[]) +{ + return CGPointMake(values[0], values[1]); +} + +NS_INLINE CGSize values_to_size(const CGFloat values[]) +{ + return CGSizeMake(values[0], values[1]); +} + +NS_INLINE CGRect values_to_rect(const CGFloat values[]) +{ + return CGRectMake(values[0], values[1], values[2], values[3]); +} + +#if SCENEKIT_SDK_AVAILABLE +NS_INLINE SCNVector3 values_to_vec3(const CGFloat values[]) +{ + return SCNVector3Make(values[0], values[1], values[2]); +} + +NS_INLINE SCNVector4 values_to_vec4(const CGFloat values[]) +{ + return SCNVector4Make(values[0], values[1], values[2], values[3]); +} +#endif + +#if TARGET_OS_IPHONE + +NS_INLINE UIEdgeInsets values_to_edge_insets(const CGFloat values[]) +{ + return UIEdgeInsetsMake(values[0], values[1], values[2], values[3]); +} + +#endif + +NS_INLINE void values_from_point(CGFloat values[], CGPoint p) +{ + values[0] = p.x; + values[1] = p.y; +} + +NS_INLINE void values_from_size(CGFloat values[], CGSize s) +{ + values[0] = s.width; + values[1] = s.height; +} + +NS_INLINE void values_from_rect(CGFloat values[], CGRect r) +{ + values[0] = r.origin.x; + values[1] = r.origin.y; + values[2] = r.size.width; + values[3] = r.size.height; +} + +#if SCENEKIT_SDK_AVAILABLE +NS_INLINE void values_from_vec3(CGFloat values[], SCNVector3 v) +{ + values[0] = v.x; + values[1] = v.y; + values[2] = v.z; +} + +NS_INLINE void values_from_vec4(CGFloat values[], SCNVector4 v) +{ + values[0] = v.x; + values[1] = v.y; + values[2] = v.z; + values[3] = v.w; +} +#endif + +#if TARGET_OS_IPHONE + +NS_INLINE void values_from_edge_insets(CGFloat values[], UIEdgeInsets i) +{ + values[0] = i.top; + values[1] = i.left; + values[2] = i.bottom; + values[3] = i.right; +} + +#endif + +/** + Takes a CGColorRef and converts it into RGBA components, if necessary. + */ +extern void POPCGColorGetRGBAComponents(CGColorRef color, CGFloat components[]); + +/** + Takes RGBA components and returns a CGColorRef. + */ +extern CGColorRef POPCGColorRGBACreate(const CGFloat components[]) CF_RETURNS_RETAINED; + +/** + Takes a color reference and returns a CGColor. + */ +extern CGColorRef POPCGColorWithColor(id color) CF_RETURNS_NOT_RETAINED; + +#if TARGET_OS_IPHONE + +/** + Takes a UIColor and converts it into RGBA components, if necessary. + */ +extern void POPUIColorGetRGBAComponents(UIColor *color, CGFloat components[]); + +/** + Takes RGBA components and returns a UIColor. + */ +extern UIColor *POPUIColorRGBACreate(const CGFloat components[]) NS_RETURNS_RETAINED; + +#else + +/** + Takes a NSColor and converts it into RGBA components, if necessary. + */ +extern void POPNSColorGetRGBAComponents(NSColor *color, CGFloat components[]); + +/** + Takes RGBA components and returns a NSColor. + */ +extern NSColor *POPNSColorRGBACreate(const CGFloat components[]) NS_RETURNS_RETAINED; + +#endif + +POP_EXTERN_C_END diff --git a/TalkinToTheNet/Pods/pop/pop/POPCGUtils.mm b/TalkinToTheNet/Pods/pop/pop/POPCGUtils.mm new file mode 100644 index 0000000..72a2d36 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPCGUtils.mm @@ -0,0 +1,150 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPCGUtils.h" + +#import + +void POPCGColorGetRGBAComponents(CGColorRef color, CGFloat components[]) +{ + if (color) { + const CGFloat *colors = CGColorGetComponents(color); + size_t count = CGColorGetNumberOfComponents(color); + + if (4 == count) { + // RGB colorspace + components[0] = colors[0]; + components[1] = colors[1]; + components[2] = colors[2]; + components[3] = colors[3]; + } else if (2 == count) { + // Grey colorspace + components[0] = components[1] = components[2] = colors[0]; + components[3] = colors[1]; + } else { + // Use CI to convert + CIColor *ciColor = [CIColor colorWithCGColor:color]; + components[0] = ciColor.red; + components[1] = ciColor.green; + components[2] = ciColor.blue; + components[3] = ciColor.alpha; + } + } else { + memset(components, 0, 4 * sizeof(components[0])); + } +} + +CGColorRef POPCGColorRGBACreate(const CGFloat components[]) +{ +#if TARGET_OS_IPHONE + CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); + CGColorRef color = CGColorCreate(space, components); + CGColorSpaceRelease(space); + return color; +#else + return CGColorCreateGenericRGB(components[0], components[1], components[2], components[3]); +#endif +} + +CGColorRef POPCGColorWithColor(id color) +{ + if (CFGetTypeID((__bridge CFTypeRef)color) == CGColorGetTypeID()) { + return ((__bridge CGColorRef)color); + } +#if TARGET_OS_IPHONE + else if ([color isKindOfClass:[UIColor class]]) { + return [color CGColor]; + } +#else + else if ([color isKindOfClass:[NSColor class]]) { + // -[NSColor CGColor] is only supported since OSX 10.8+ + if ([color respondsToSelector:@selector(CGColor)]) { + return [color CGColor]; + } + + /* + * Otherwise create a CGColorRef manually. + * + * The original accessor is (or would be) declared as: + * @property(readonly) CGColorRef CGColor; + * - (CGColorRef)CGColor NS_RETURNS_INNER_POINTER CF_RETURNS_NOT_RETAINED; + * + * (Please note that OSX' accessor is atomic, while iOS' isn't.) + * + * The access to the NSColor object must thus be synchronized + * and the CGColorRef be stored as an associated object, + * to return a reference which doesn't need to be released manually. + */ + @synchronized(color) { + static const void* key = &key; + + CGColorRef colorRef = (__bridge CGColorRef)objc_getAssociatedObject(color, key); + + if (!colorRef) { + size_t numberOfComponents = [color numberOfComponents]; + CGFloat components[numberOfComponents]; + CGColorSpaceRef colorSpace = [[color colorSpace] CGColorSpace]; + + [color getComponents:components]; + + colorRef = CGColorCreate(colorSpace, components); + + objc_setAssociatedObject(color, key, (__bridge id)colorRef, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + CGColorRelease(colorRef); + } + + return colorRef; + } + } +#endif + return nil; +} + +#if TARGET_OS_IPHONE + +void POPUIColorGetRGBAComponents(UIColor *color, CGFloat components[]) +{ + return POPCGColorGetRGBAComponents(POPCGColorWithColor(color), components); +} + +UIColor *POPUIColorRGBACreate(const CGFloat components[]) +{ + CGColorRef colorRef = POPCGColorRGBACreate(components); + UIColor *color = [[UIColor alloc] initWithCGColor:colorRef]; + CGColorRelease(colorRef); + return color; +} + +#else + +void POPNSColorGetRGBAComponents(NSColor *color, CGFloat components[]) +{ + return POPCGColorGetRGBAComponents(POPCGColorWithColor(color), components); +} + +NSColor *POPNSColorRGBACreate(const CGFloat components[]) +{ + CGColorRef colorRef = POPCGColorRGBACreate(components); + NSColor *color = nil; + + if (colorRef) { + if ([NSColor respondsToSelector:@selector(colorWithCGColor:)]) { + color = [NSColor colorWithCGColor:colorRef]; + } else { + color = [NSColor colorWithCIColor:[CIColor colorWithCGColor:colorRef]]; + } + + CGColorRelease(colorRef); + } + + return color; +} + +#endif + diff --git a/TalkinToTheNet/Pods/pop/pop/POPCustomAnimation.h b/TalkinToTheNet/Pods/pop/pop/POPCustomAnimation.h new file mode 100644 index 0000000..501a755 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPCustomAnimation.h @@ -0,0 +1,46 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +@class POPCustomAnimation; + +/** + @abstract POPCustomAnimationBlock is the callback block of a custom animation. + @discussion This block will be executed for each animation frame and should update the property or properties being animated based on current timing. + @param target The object being animated. Reference the passed in target to help avoid retain loops. + @param animation The custom animation instance. Use to determine the current and elapsed time since last callback. Reference the passed in animation to help avoid retain loops. + @return Flag indicating whether the animation should continue animating. Return NO to indicate animation is done. + */ +typedef BOOL (^POPCustomAnimationBlock)(id target, POPCustomAnimation *animation); + +/** + @abstract POPCustomAnimation is a concrete animation subclass for custom animations. + */ +@interface POPCustomAnimation : POPAnimation + +/** +@abstract Creates and returns an initialized custom animation instance. +@discussion This is the designated initializer. +@param block The custom animation callback block. See {@ref POPCustomAnimationBlock}. +@return The initialized custom animation instance. +*/ ++ (instancetype)animationWithBlock:(POPCustomAnimationBlock)block; + +/** + @abstract The current animation time at time of callback. + */ +@property (readonly, nonatomic) CFTimeInterval currentTime; + +/** + @abstract The elapsed animation time since last callback. + */ +@property (readonly, nonatomic) CFTimeInterval elapsedTime; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPCustomAnimation.mm b/TalkinToTheNet/Pods/pop/pop/POPCustomAnimation.mm new file mode 100644 index 0000000..8cb7913 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPCustomAnimation.mm @@ -0,0 +1,75 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimationInternal.h" + +#import "POPCustomAnimation.h" + +@interface POPCustomAnimation () +@property (nonatomic, copy) POPCustomAnimationBlock animate; +@end + +@implementation POPCustomAnimation +@synthesize currentTime = _currentTime; +@synthesize elapsedTime = _elapsedTime; +@synthesize animate = _animate; + ++ (instancetype)animationWithBlock:(BOOL(^)(id target, POPCustomAnimation *))block +{ + POPCustomAnimation *b = [[self alloc] _init]; + b.animate = block; + return b; +} + +- (id)_init +{ + self = [super _init]; + if (nil != self) { + _state->type = kPOPAnimationCustom; + } + return self; +} + +- (CFTimeInterval)beginTime +{ + POPAnimationState *s = POPAnimationGetState(self); + return s->startTime > 0 ? s->startTime : s->beginTime; +} + +- (BOOL)_advance:(id)object currentTime:(CFTimeInterval)currentTime elapsedTime:(CFTimeInterval)elapsedTime +{ + _currentTime = currentTime; + _elapsedTime = elapsedTime; + return _animate(object, self); +} + +- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug +{ + [s appendFormat:@"; elapsedTime = %f; currentTime = %f;", _elapsedTime, _currentTime]; +} + +@end + +/** + * Note that only the animate block is copied, but not the current/elapsed times + */ +@implementation POPCustomAnimation (NSCopying) + +- (instancetype)copyWithZone:(NSZone *)zone { + + POPCustomAnimation *copy = [super copyWithZone:zone]; + + if (copy) { + copy.animate = self.animate; + } + + return copy; +} + +@end \ No newline at end of file diff --git a/TalkinToTheNet/Pods/pop/pop/POPDecayAnimation.h b/TalkinToTheNet/Pods/pop/pop/POPDecayAnimation.h new file mode 100644 index 0000000..92c6b60 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPDecayAnimation.h @@ -0,0 +1,66 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +/** + @abstract A concrete decay animation class. + @discussion Animation is achieved through gradual decay of animation value. + */ +@interface POPDecayAnimation : POPPropertyAnimation + +/** + @abstract The designated initializer. + @returns An instance of a decay animation. + */ ++ (instancetype)animation; + +/** + @abstract Convenience initializer that returns an animation with animatable property of name. + @param name The name of the animatable property. + @returns An instance of a decay animation configured with specified animatable property. + */ ++ (instancetype)animationWithPropertyNamed:(NSString *)name; + +/** + @abstract The current velocity value. + @discussion Set before animation start to account for initial velocity. Expressed in change of value units per second. The only POPValueTypes supported for velocity are: kPOPValuePoint, kPOPValueInteger, kPOPValueFloat, kPOPValueRect, and kPOPValueSize. + */ +@property (copy, nonatomic) id velocity; + +/** + @abstract The original velocity value. + @discussion Since the velocity property is modified as the animation progresses, this property stores the original, passed in velocity to support autoreverse and repeatCount. + */ +@property (copy, nonatomic, readonly) id originalVelocity; + +/** + @abstract The deceleration factor. + @discussion Values specifies should be in the range [0, 1]. Lower values results in faster deceleration. Defaults to 0.998. + */ +@property (assign, nonatomic) CGFloat deceleration; + +/** + @abstract The expected duration. + @discussion Derived based on input velocity and deceleration values. + */ +@property (readonly, assign, nonatomic) CFTimeInterval duration; + +/** + The to value is derived based on input velocity and deceleration. + */ +- (void)setToValue:(id)toValue NS_UNAVAILABLE; + +/** + @abstract The reversed velocity. + @discussion The reversed velocity based on the originalVelocity when the animation was set up. + */ +- (id)reversedVelocity; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPDecayAnimation.mm b/TalkinToTheNet/Pods/pop/pop/POPDecayAnimation.mm new file mode 100644 index 0000000..4698fd0 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPDecayAnimation.mm @@ -0,0 +1,203 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPDecayAnimationInternal.h" + +#if TARGET_OS_IPHONE +#import +#endif + +const POPValueType supportedVelocityTypes[6] = { kPOPValuePoint, kPOPValueInteger, kPOPValueFloat, kPOPValueRect, kPOPValueSize, kPOPValueEdgeInsets }; + +@implementation POPDecayAnimation + +#pragma mark - Lifecycle + +#undef __state +#define __state ((POPDecayAnimationState *)_state) + ++ (instancetype)animation +{ + return [[self alloc] init]; +} + ++ (instancetype)animationWithPropertyNamed:(NSString *)aName +{ + POPDecayAnimation *anim = [self animation]; + anim.property = [POPAnimatableProperty propertyWithName:aName]; + return anim; +} + +- (id)init +{ + return [self _init]; +} + +- (void)_initState +{ + _state = new POPDecayAnimationState(self); +} + +#pragma mark - Properties + +DEFINE_RW_PROPERTY(POPDecayAnimationState, deceleration, setDeceleration:, CGFloat, __state->toVec = NULL;); + +@dynamic velocity; + +- (id)toValue +{ + [self _ensureComputedProperties]; + return POPBox(__state->toVec, __state->valueType); +} + +- (CFTimeInterval)duration +{ + [self _ensureComputedProperties]; + return __state->duration; +} + +- (void)setFromValue:(id)fromValue +{ + super.fromValue = fromValue; + [self _invalidateComputedProperties]; +} + +- (void)setToValue:(id)aValue +{ + // no-op + NSLog(@"ignoring to value on decay animation %@", self); +} + +- (id)reversedVelocity +{ + id reversedVelocity = nil; + + POPValueType velocityType = POPSelectValueType(self.originalVelocity, supportedVelocityTypes, POP_ARRAY_COUNT(supportedVelocityTypes)); + if (velocityType == kPOPValueFloat) { +#if CGFLOAT_IS_DOUBLE + CGFloat originalVelocityFloat = [(NSNumber *)self.originalVelocity doubleValue]; +#else + CGFloat originalVelocityFloat = [(NSNumber *)self.originalVelocity floatValue]; +#endif + NSNumber *negativeOriginalVelocityNumber = @(-originalVelocityFloat); + reversedVelocity = negativeOriginalVelocityNumber; + } else if (velocityType == kPOPValueInteger) { + NSInteger originalVelocityInteger = [(NSNumber *)self.originalVelocity integerValue]; + NSNumber *negativeOriginalVelocityNumber = @(-originalVelocityInteger); + reversedVelocity = negativeOriginalVelocityNumber; + } else if (velocityType == kPOPValuePoint) { + CGPoint originalVelocityPoint = [self.originalVelocity CGPointValue]; + CGPoint negativeOriginalVelocityPoint = CGPointMake(-originalVelocityPoint.x, -originalVelocityPoint.y); + reversedVelocity = [NSValue valueWithCGPoint:negativeOriginalVelocityPoint]; + } else if (velocityType == kPOPValueRect) { + CGRect originalVelocityRect = [self.originalVelocity CGRectValue]; + CGRect negativeOriginalVelocityRect = CGRectMake(-originalVelocityRect.origin.x, -originalVelocityRect.origin.y, -originalVelocityRect.size.width, -originalVelocityRect.size.height); + reversedVelocity = [NSValue valueWithCGRect:negativeOriginalVelocityRect]; + } else if (velocityType == kPOPValueSize) { + CGSize originalVelocitySize = [self.originalVelocity CGSizeValue]; + CGSize negativeOriginalVelocitySize = CGSizeMake(-originalVelocitySize.width, -originalVelocitySize.height); + reversedVelocity = [NSValue valueWithCGSize:negativeOriginalVelocitySize]; + } else if (velocityType == kPOPValueEdgeInsets) { +#if TARGET_OS_IPHONE + UIEdgeInsets originalVelocityInsets = [self.originalVelocity UIEdgeInsetsValue]; + UIEdgeInsets negativeOriginalVelocityInsets = UIEdgeInsetsMake(-originalVelocityInsets.top, -originalVelocityInsets.left, -originalVelocityInsets.bottom, -originalVelocityInsets.right); + reversedVelocity = [NSValue valueWithUIEdgeInsets:negativeOriginalVelocityInsets]; +#endif + } + + return reversedVelocity; +} + +- (id)originalVelocity +{ + return POPBox(__state->originalVelocityVec, __state->valueType); +} + +- (id)velocity +{ + return POPBox(__state->velocityVec, __state->valueType); +} + +- (void)setVelocity:(id)aValue +{ + POPValueType valueType = POPSelectValueType(aValue, supportedVelocityTypes, POP_ARRAY_COUNT(supportedVelocityTypes)); + if (valueType != kPOPValueUnknown) { + VectorRef vec = POPUnbox(aValue, __state->valueType, __state->valueCount, YES); + VectorRef origVec = POPUnbox(aValue, __state->valueType, __state->valueCount, YES); + + if (!vec_equal(vec, __state->velocityVec)) { + __state->velocityVec = vec; + __state->originalVelocityVec = origVec; + + if (__state->tracing) { + [__state->tracer updateVelocity:aValue]; + } + + [self _invalidateComputedProperties]; + + // automatically unpause active animations + if (__state->active && __state->paused) { + __state->fromVec = NULL; + __state->setPaused(false); + } + } + } else { + __state->velocityVec = NULL; + NSLog(@"Invalid velocity value for the decayAnimation: %@", aValue); + } +} + +#pragma mark - Utility + +- (void)_ensureComputedProperties +{ + if (NULL == __state->toVec) { + __state->computeDuration(); + __state->computeToValue(); + } +} + +- (void)_invalidateComputedProperties +{ + __state->toVec = NULL; + __state->duration = 0; +} + +- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug +{ + [super _appendDescription:s debug:debug]; + + if (0 != self.duration) { + [s appendFormat:@"; duration = %f", self.duration]; + } + + if (__state->deceleration) { + [s appendFormat:@"; deceleration = %f", __state->deceleration]; + } +} + +@end + +@implementation POPDecayAnimation (NSCopying) + +- (instancetype)copyWithZone:(NSZone *)zone { + + POPDecayAnimation *copy = [super copyWithZone:zone]; + + if (copy) { + // Set the velocity to the animation's original velocity, not its current. + copy.velocity = self.originalVelocity; + copy.deceleration = self.deceleration; + + } + + return copy; +} + +@end \ No newline at end of file diff --git a/TalkinToTheNet/Pods/pop/pop/POPDecayAnimationInternal.h b/TalkinToTheNet/Pods/pop/pop/POPDecayAnimationInternal.h new file mode 100644 index 0000000..c101761 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPDecayAnimationInternal.h @@ -0,0 +1,127 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPDecayAnimation.h" + +#import + +#import "POPPropertyAnimationInternal.h" + +// minimal velocity factor before decay animation is considered complete, in units / s +static CGFloat kPOPAnimationDecayMinimalVelocityFactor = 5.; + +// default decay animation deceleration +static CGFloat kPOPAnimationDecayDecelerationDefault = 0.998; + +static void decay_position(CGFloat *x, CGFloat *v, NSUInteger count, CFTimeInterval dt, CGFloat deceleration) +{ + dt *= 1000; + + // v0 = v / 1000 + // v = v0 * powf(deceleration, dt); + // v = v * 1000; + + // x0 = x; + // x = x0 + v0 * deceleration * (1 - powf(deceleration, dt)) / (1 - deceleration) + float v0[count]; + float kv = powf(deceleration, dt); + float kx = deceleration * (1 - kv) / (1 - deceleration); + + for (NSUInteger idx = 0; idx < count; idx++) { + v0[idx] = v[idx] / 1000.; + v[idx] = v0[idx] * kv * 1000.; + x[idx] = x[idx] + v0[idx] * kx; + } +} + +struct _POPDecayAnimationState : _POPPropertyAnimationState +{ + double deceleration; + CFTimeInterval duration; + + _POPDecayAnimationState(id __unsafe_unretained anim) : + _POPPropertyAnimationState(anim), + deceleration(kPOPAnimationDecayDecelerationDefault), + duration(0) + { + type = kPOPAnimationDecay; + } + + bool isDone() { + if (_POPPropertyAnimationState::isDone()) { + return true; + } + + CGFloat f = dynamicsThreshold * kPOPAnimationDecayMinimalVelocityFactor; + const CGFloat *velocityValues = vec_data(velocityVec); + for (NSUInteger idx = 0; idx < valueCount; idx++) { + if (std::abs((velocityValues[idx])) >= f) + return false; + } + return true; + + } + + void computeDuration() { + + // compute duration till threshold velocity + Vector4r scaledVelocity = vector4(velocityVec) / 1000.; + + double k = dynamicsThreshold * kPOPAnimationDecayMinimalVelocityFactor / 1000.; + double vx = k / scaledVelocity.x; + double vy = k / scaledVelocity.y; + double vz = k / scaledVelocity.z; + double vw = k / scaledVelocity.w; + double d = log(deceleration) * 1000.; + duration = MAX(MAX(MAX(log(fabs(vx)) / d, log(fabs(vy)) / d), log(fabs(vz)) / d), log(fabs(vw)) / d); + + // ensure velocity threshold is exceeded + if (std::isnan(duration) || duration < 0) { + duration = 0; + } + } + + void computeToValue() { + // to value assuming final velocity as a factor of dynamics threshold + // derived from v' = v * d^dt used in decay_position + // to compute the to value with maximal dt, p' = p + (v * d) / (1 - d) + VectorRef fromValue = NULL != currentVec ? currentVec : fromVec; + if (!fromValue) { + return; + } + + // ensure duration is computed + if (0 == duration) { + computeDuration(); + } + + // compute to value + VectorRef toValue(Vector::new_vector(fromValue.get())); + Vector4r velocity = velocityVec->vector4r(); + decay_position(toValue->data(), velocity.data(), valueCount, duration, deceleration); + toVec = toValue; + } + + bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) { + // advance past not yet initialized animations + if (NULL == currentVec) { + return false; + } + + decay_position(currentVec->data(), velocityVec->data(), valueCount, dt, deceleration); + + // clamp to compute end value; avoid possibility of decaying past + clampCurrentValue(kPOPAnimationClampEnd | clampMode); + + return true; + } + +}; + +typedef struct _POPDecayAnimationState POPDecayAnimationState; diff --git a/TalkinToTheNet/Pods/pop/pop/POPDefines.h b/TalkinToTheNet/Pods/pop/pop/POPDefines.h new file mode 100644 index 0000000..eb28781 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPDefines.h @@ -0,0 +1,37 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#ifndef POP_POPDefines_h +#define POP_POPDefines_h + +#import + +#ifdef __cplusplus +# define POP_EXTERN_C_BEGIN extern "C" { +# define POP_EXTERN_C_END } +#else +# define POP_EXTERN_C_BEGIN +# define POP_EXTERN_C_END +#endif + +#define POP_ARRAY_COUNT(x) sizeof(x) / sizeof(x[0]) + +#if defined (__cplusplus) && defined (__GNUC__) +# define POP_NOTHROW __attribute__ ((nothrow)) +#else +# define POP_NOTHROW +#endif + +#if TARGET_OS_MAC + #define SCENEKIT_SDK_AVAILABLE defined(POP_USE_SCENEKIT) +#elif TARGET_OS_IPHONE + #define SCENEKIT_SDK_AVAILABLE defined(POP_USE_SCENEKIT) +#endif + +#endif diff --git a/TalkinToTheNet/Pods/pop/pop/POPGeometry.h b/TalkinToTheNet/Pods/pop/pop/POPGeometry.h new file mode 100644 index 0000000..8ba07e3 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPGeometry.h @@ -0,0 +1,73 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#if TARGET_OS_IPHONE +#import +#endif + +#if !TARGET_OS_IPHONE + +/** NSValue extensions to support animatable types. */ +@interface NSValue (POP) + +/** + @abstract Creates an NSValue given a CGPoint. + */ ++ (NSValue *)valueWithCGPoint:(CGPoint)point; + +/** + @abstract Creates an NSValue given a CGSize. + */ ++ (NSValue *)valueWithCGSize:(CGSize)size; + +/** + @abstract Creates an NSValue given a CGRect. + */ ++ (NSValue *)valueWithCGRect:(CGRect)rect; + +/** + @abstract Creates an NSValue given a CFRange. + */ ++ (NSValue *)valueWithCFRange:(CFRange)range; + +/** + @abstract Creates an NSValue given a CGAffineTransform. + */ ++ (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform; + +/** + @abstract Returns the underlying CGPoint value. + */ +- (CGPoint)CGPointValue; + +/** + @abstract Returns the underlying CGSize value. + */ +- (CGSize)CGSizeValue; + +/** + @abstract Returns the underlying CGRect value. + */ +- (CGRect)CGRectValue; + +/** + @abstract Returns the underlying CFRange value. + */ +- (CFRange)CFRangeValue; + +/** + @abstract Returns the underlying CGAffineTransform value. + */ +- (CGAffineTransform)CGAffineTransformValue; + +@end + +#endif diff --git a/TalkinToTheNet/Pods/pop/pop/POPGeometry.mm b/TalkinToTheNet/Pods/pop/pop/POPGeometry.mm new file mode 100644 index 0000000..41998b1 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPGeometry.mm @@ -0,0 +1,94 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPGeometry.h" + +#if !TARGET_OS_IPHONE +@implementation NSValue (POP) + ++ (NSValue *)valueWithCGPoint:(CGPoint)point { + return [NSValue valueWithBytes:&point objCType:@encode(CGPoint)]; +} + ++ (NSValue *)valueWithCGSize:(CGSize)size { + return [NSValue valueWithBytes:&size objCType:@encode(CGSize)]; +} + ++ (NSValue *)valueWithCGRect:(CGRect)rect { + return [NSValue valueWithBytes:&rect objCType:@encode(CGRect)]; +} + ++ (NSValue *)valueWithCFRange:(CFRange)range { + return [NSValue valueWithBytes:&range objCType:@encode(CFRange)]; +} + ++ (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform +{ + return [NSValue valueWithBytes:&transform objCType:@encode(CGAffineTransform)]; +} + +- (CGPoint)CGPointValue { + CGPoint result; + [self getValue:&result]; + return result; +} + +- (CGSize)CGSizeValue { + CGSize result; + [self getValue:&result]; + return result; +} + +- (CGRect)CGRectValue { + CGRect result; + [self getValue:&result]; + return result; +} + +- (CFRange)CFRangeValue { + CFRange result; + [self getValue:&result]; + return result; +} + +- (CGAffineTransform)CGAffineTransformValue { + CGAffineTransform result; + [self getValue:&result]; + return result; +} +@end + +#endif + +#if TARGET_OS_IPHONE +#import "POPDefines.h" + +#if SCENEKIT_SDK_AVAILABLE +#import + +/** + Dirty hacks because iOS is weird and decided to define both SCNVector3's and SCNVector4's objCType as "t". However @encode(SCNVector3) and @encode(SCNVector4) both return the proper definition ("{SCNVector3=fff}" and "{SCNVector4=ffff}" respectively) + + [[NSValue valueWithSCNVector3:SCNVector3Make(0.0, 0.0, 0.0)] objcType] returns "t", whereas it should return "{SCNVector3=fff}". + + *flips table* + */ +@implementation NSValue (SceneKitFixes) + ++ (NSValue *)valueWithSCNVector3:(SCNVector3)vec3 { + return [NSValue valueWithBytes:&vec3 objCType:@encode(SCNVector3)]; +} + ++ (NSValue *)valueWithSCNVector4:(SCNVector4)vec4 { + return [NSValue valueWithBytes:&vec4 objCType:@encode(SCNVector4)]; +} + +@end +#endif +#endif diff --git a/TalkinToTheNet/Pods/pop/pop/POPLayerExtras.h b/TalkinToTheNet/Pods/pop/pop/POPLayerExtras.h new file mode 100644 index 0000000..ec4c29a --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPLayerExtras.h @@ -0,0 +1,196 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import + +POP_EXTERN_C_BEGIN + +#pragma mark - Scale + +/** + @abstract Returns layer scale factor for the x axis. + */ +extern CGFloat POPLayerGetScaleX(CALayer *l); + +/** + @abstract Set layer scale factor for the x axis. + */ +extern void POPLayerSetScaleX(CALayer *l, CGFloat f); + +/** + @abstract Returns layer scale factor for the y axis. + */ +extern CGFloat POPLayerGetScaleY(CALayer *l); + +/** + @abstract Set layer scale factor for the y axis. + */ +extern void POPLayerSetScaleY(CALayer *l, CGFloat f); + +/** + @abstract Returns layer scale factor for the z axis. + */ +extern CGFloat POPLayerGetScaleZ(CALayer *l); + +/** + @abstract Set layer scale factor for the z axis. + */ +extern void POPLayerSetScaleZ(CALayer *l, CGFloat f); + +/** + @abstract Returns layer scale factors for x and y access as point. + */ +extern CGPoint POPLayerGetScaleXY(CALayer *l); + +/** + @abstract Sets layer x and y scale factors given point. + */ +extern void POPLayerSetScaleXY(CALayer *l, CGPoint p); + +#pragma mark - Translation + +/** + @abstract Returns layer translation factor for the x axis. + */ +extern CGFloat POPLayerGetTranslationX(CALayer *l); + +/** + @abstract Set layer translation factor for the x axis. + */ +extern void POPLayerSetTranslationX(CALayer *l, CGFloat f); + +/** + @abstract Returns layer translation factor for the y axis. + */ +extern CGFloat POPLayerGetTranslationY(CALayer *l); + +/** + @abstract Set layer translation factor for the y axis. + */ +extern void POPLayerSetTranslationY(CALayer *l, CGFloat f); + +/** + @abstract Returns layer translation factor for the z axis. + */ +extern CGFloat POPLayerGetTranslationZ(CALayer *l); + +/** + @abstract Set layer translation factor for the z axis. + */ +extern void POPLayerSetTranslationZ(CALayer *l, CGFloat f); + +/** + @abstract Returns layer translation factors for x and y access as point. + */ +extern CGPoint POPLayerGetTranslationXY(CALayer *l); + +/** + @abstract Sets layer x and y translation factors given point. + */ +extern void POPLayerSetTranslationXY(CALayer *l, CGPoint p); + +#pragma mark - Rotation + +/** + @abstract Returns layer rotation, in radians, in the X axis. + */ +extern CGFloat POPLayerGetRotationX(CALayer *l); + +/** + @abstract Sets layer rotation, in radians, in the X axis. + */ +extern void POPLayerSetRotationX(CALayer *l, CGFloat f); + +/** + @abstract Returns layer rotation, in radians, in the Y axis. + */ +extern CGFloat POPLayerGetRotationY(CALayer *l); + +/** + @abstract Sets layer rotation, in radians, in the Y axis. + */ +extern void POPLayerSetRotationY(CALayer *l, CGFloat f); + +/** + @abstract Returns layer rotation, in radians, in the Z axis. + */ +extern CGFloat POPLayerGetRotationZ(CALayer *l); + +/** + @abstract Sets layer rotation, in radians, in the Z axis. + */ +extern void POPLayerSetRotationZ(CALayer *l, CGFloat f); + +/** + @abstract Returns layer rotation, in radians, in the Z axis. + */ +extern CGFloat POPLayerGetRotation(CALayer *l); + +/** + @abstract Sets layer rotation, in radians, in the Z axis. + */ +extern void POPLayerSetRotation(CALayer *l, CGFloat f); + +#pragma mark - Sublayer Scale + +/** + @abstract Returns sublayer scale factors for x and y access as point. + */ +extern CGPoint POPLayerGetSubScaleXY(CALayer *l); + +/** + @abstract Sets sublayer x and y scale factors given point. + */ +extern void POPLayerSetSubScaleXY(CALayer *l, CGPoint p); + +#pragma mark - Sublayer Translation + +/** + @abstract Returns sublayer translation factor for the x axis. + */ +extern CGFloat POPLayerGetSubTranslationX(CALayer *l); + +/** + @abstract Set sublayer translation factor for the x axis. + */ +extern void POPLayerSetSubTranslationX(CALayer *l, CGFloat f); + +/** + @abstract Returns sublayer translation factor for the y axis. + */ +extern CGFloat POPLayerGetSubTranslationY(CALayer *l); + +/** + @abstract Set sublayer translation factor for the y axis. + */ +extern void POPLayerSetSubTranslationY(CALayer *l, CGFloat f); + +/** + @abstract Returns sublayer translation factor for the z axis. + */ +extern CGFloat POPLayerGetSubTranslationZ(CALayer *l); + +/** + @abstract Set sublayer translation factor for the z axis. + */ +extern void POPLayerSetSubTranslationZ(CALayer *l, CGFloat f); + +/** + @abstract Returns sublayer translation factors for x and y access as point. + */ +extern CGPoint POPLayerGetSubTranslationXY(CALayer *l); + +/** + @abstract Sets sublayer x and y translation factors given point. + */ +extern void POPLayerSetSubTranslationXY(CALayer *l, CGPoint p); + +POP_EXTERN_C_END diff --git a/TalkinToTheNet/Pods/pop/pop/POPLayerExtras.mm b/TalkinToTheNet/Pods/pop/pop/POPLayerExtras.mm new file mode 100644 index 0000000..c8ad7f9 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPLayerExtras.mm @@ -0,0 +1,288 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPLayerExtras.h" + +#include "TransformationMatrix.h" + +using namespace WebCore; + +#define DECOMPOSE_TRANSFORM(L) \ + TransformationMatrix _m(L.transform); \ + TransformationMatrix::DecomposedType _d; \ + _m.decompose(_d); + +#define RECOMPOSE_TRANSFORM(L) \ + _m.recompose(_d); \ + L.transform = _m.transform3d(); + +#define RECOMPOSE_ROT_TRANSFORM(L) \ + _m.recompose(_d, true); \ + L.transform = _m.transform3d(); + +#define DECOMPOSE_SUBLAYER_TRANSFORM(L) \ + TransformationMatrix _m(L.sublayerTransform); \ + TransformationMatrix::DecomposedType _d; \ + _m.decompose(_d); + +#define RECOMPOSE_SUBLAYER_TRANSFORM(L) \ + _m.recompose(_d); \ + L.sublayerTransform = _m.transform3d(); + +#pragma mark - Scale + +NS_INLINE void ensureNonZeroValue(CGFloat &f) +{ + if (f == 0) { + f = 1e-6; + } +} + +NS_INLINE void ensureNonZeroValue(CGPoint &p) +{ + if (p.x == 0 && p.y == 0) { + p.x = 1e-6; + p.y = 1e-6; + } +} + +CGFloat POPLayerGetScaleX(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return _d.scaleX; +} + +void POPLayerSetScaleX(CALayer *l, CGFloat f) +{ + ensureNonZeroValue(f); + DECOMPOSE_TRANSFORM(l); + _d.scaleX = f; + RECOMPOSE_TRANSFORM(l); +} + +CGFloat POPLayerGetScaleY(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return _d.scaleY; +} + +void POPLayerSetScaleY(CALayer *l, CGFloat f) +{ + ensureNonZeroValue(f); + DECOMPOSE_TRANSFORM(l); + _d.scaleY = f; + RECOMPOSE_TRANSFORM(l); +} + +CGFloat POPLayerGetScaleZ(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return _d.scaleZ; +} + +void POPLayerSetScaleZ(CALayer *l, CGFloat f) +{ + ensureNonZeroValue(f); + DECOMPOSE_TRANSFORM(l); + _d.scaleZ = f; + RECOMPOSE_TRANSFORM(l); +} + +CGPoint POPLayerGetScaleXY(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return CGPointMake(_d.scaleX, _d.scaleY); +} + +void POPLayerSetScaleXY(CALayer *l, CGPoint p) +{ + ensureNonZeroValue(p); + DECOMPOSE_TRANSFORM(l); + _d.scaleX = p.x; + _d.scaleY = p.y; + RECOMPOSE_TRANSFORM(l); +} + +#pragma mark - Translation + +CGFloat POPLayerGetTranslationX(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return _d.translateX; +} + +void POPLayerSetTranslationX(CALayer *l, CGFloat f) +{ + DECOMPOSE_TRANSFORM(l); + _d.translateX = f; + RECOMPOSE_TRANSFORM(l); +} + +CGFloat POPLayerGetTranslationY(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return _d.translateY; +} + +void POPLayerSetTranslationY(CALayer *l, CGFloat f) +{ + DECOMPOSE_TRANSFORM(l); + _d.translateY = f; + RECOMPOSE_TRANSFORM(l); +} + +CGFloat POPLayerGetTranslationZ(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return _d.translateZ; +} + +void POPLayerSetTranslationZ(CALayer *l, CGFloat f) +{ + DECOMPOSE_TRANSFORM(l); + _d.translateZ = f; + RECOMPOSE_TRANSFORM(l); +} + +CGPoint POPLayerGetTranslationXY(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return CGPointMake(_d.translateX, _d.translateY); +} + +void POPLayerSetTranslationXY(CALayer *l, CGPoint p) +{ + DECOMPOSE_TRANSFORM(l); + _d.translateX = p.x; + _d.translateY = p.y; + RECOMPOSE_TRANSFORM(l); +} + +#pragma mark - Rotation + +CGFloat POPLayerGetRotationX(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return _d.rotateX; +} + +void POPLayerSetRotationX(CALayer *l, CGFloat f) +{ + DECOMPOSE_TRANSFORM(l); + _d.rotateX = f; + RECOMPOSE_ROT_TRANSFORM(l); +} + +CGFloat POPLayerGetRotationY(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return _d.rotateY; +} + +void POPLayerSetRotationY(CALayer *l, CGFloat f) +{ + DECOMPOSE_TRANSFORM(l); + _d.rotateY = f; + RECOMPOSE_ROT_TRANSFORM(l); +} + +CGFloat POPLayerGetRotationZ(CALayer *l) +{ + DECOMPOSE_TRANSFORM(l); + return _d.rotateZ; +} + +void POPLayerSetRotationZ(CALayer *l, CGFloat f) +{ + DECOMPOSE_TRANSFORM(l); + _d.rotateZ = f; + RECOMPOSE_ROT_TRANSFORM(l); +} + +CGFloat POPLayerGetRotation(CALayer *l) +{ + return POPLayerGetRotationZ(l); +} + +void POPLayerSetRotation(CALayer *l, CGFloat f) +{ + POPLayerSetRotationZ(l, f); +} + +#pragma mark - Sublayer Scale + +CGPoint POPLayerGetSubScaleXY(CALayer *l) +{ + DECOMPOSE_SUBLAYER_TRANSFORM(l); + return CGPointMake(_d.scaleX, _d.scaleY); +} + +void POPLayerSetSubScaleXY(CALayer *l, CGPoint p) +{ + ensureNonZeroValue(p); + DECOMPOSE_SUBLAYER_TRANSFORM(l); + _d.scaleX = p.x; + _d.scaleY = p.y; + RECOMPOSE_SUBLAYER_TRANSFORM(l); +} + +#pragma mark - Sublayer Translation + +extern CGFloat POPLayerGetSubTranslationX(CALayer *l) +{ + DECOMPOSE_SUBLAYER_TRANSFORM(l); + return _d.translateX; +} + +extern void POPLayerSetSubTranslationX(CALayer *l, CGFloat f) +{ + DECOMPOSE_SUBLAYER_TRANSFORM(l); + _d.translateX = f; + RECOMPOSE_SUBLAYER_TRANSFORM(l); +} + +extern CGFloat POPLayerGetSubTranslationY(CALayer *l) +{ + DECOMPOSE_SUBLAYER_TRANSFORM(l); + return _d.translateY; +} + +extern void POPLayerSetSubTranslationY(CALayer *l, CGFloat f) +{ + DECOMPOSE_SUBLAYER_TRANSFORM(l); + _d.translateY = f; + RECOMPOSE_SUBLAYER_TRANSFORM(l); +} + +extern CGFloat POPLayerGetSubTranslationZ(CALayer *l) +{ + DECOMPOSE_SUBLAYER_TRANSFORM(l); + return _d.translateZ; +} + +extern void POPLayerSetSubTranslationZ(CALayer *l, CGFloat f) +{ + DECOMPOSE_SUBLAYER_TRANSFORM(l); + _d.translateZ = f; + RECOMPOSE_SUBLAYER_TRANSFORM(l); +} + +extern CGPoint POPLayerGetSubTranslationXY(CALayer *l) +{ + DECOMPOSE_SUBLAYER_TRANSFORM(l); + return CGPointMake(_d.translateX, _d.translateY); +} + +extern void POPLayerSetSubTranslationXY(CALayer *l, CGPoint p) +{ + DECOMPOSE_SUBLAYER_TRANSFORM(l); + _d.translateX = p.x; + _d.translateY = p.y; + RECOMPOSE_SUBLAYER_TRANSFORM(l); +} diff --git a/TalkinToTheNet/Pods/pop/pop/POPMath.h b/TalkinToTheNet/Pods/pop/pop/POPMath.h new file mode 100644 index 0000000..0c6f5e2 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPMath.h @@ -0,0 +1,56 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import + +#import "POPDefines.h" +#import "POPVector.h" + +NS_INLINE CGFloat sqrtr(CGFloat f) +{ +#if CGFLOAT_IS_DOUBLE + return sqrt(f); +#else + return sqrtf(f); +#endif +} + +// round to nearest sub; pass 2.0 to round to every 0.5 (eg: retina pixels) +NS_INLINE CGFloat POPSubRound(CGFloat f, CGFloat sub) +{ + return round(f * sub) / sub; +} + +#define MIX(a, b, f) ((a) + (f) * ((b) - (a))) + +// the longer the duration, the higher the necessary precision +#define SOLVE_EPS(dur) (1. / (1000. * (dur))) + +#define _EQLF_(x, y, epsilon) (fabsf ((x) - (y)) < epsilon) + +extern void POPInterpolateVector(NSUInteger count, CGFloat *dst, const CGFloat *from, const CGFloat *to, CGFloat f); + +extern double POPTimingFunctionSolve(const double vec[4], double t, double eps); + +// quadratic mapping of t [0, 1] to [start, end] +extern double POPQuadraticOutInterpolation(double t, double start, double end); + +// normalize value to [0, 1] based on its range [startValue, endValue] +extern double POPNormalize(double value, double startValue, double endValue); + +// project a normalized value [0, 1] to a given range [start, end] +extern double POPProjectNormal(double n, double start, double end); + +// solve a quadratic equation of the form a * x^2 + b * x + c = 0 +extern void POPQuadraticSolve(CGFloat a, CGFloat b, CGFloat c, CGFloat &x1, CGFloat &x2); + +// for a given tension return the bouncy 3 friction that produces no bounce +extern double POPBouncy3NoBounce(double tension); diff --git a/TalkinToTheNet/Pods/pop/pop/POPMath.mm b/TalkinToTheNet/Pods/pop/pop/POPMath.mm new file mode 100644 index 0000000..69a506a --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPMath.mm @@ -0,0 +1,83 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPMath.h" + +#import "POPAnimationPrivate.h" +#import "UnitBezier.h" + +void POPInterpolateVector(NSUInteger count, CGFloat *dst, const CGFloat *from, const CGFloat *to, CGFloat f) +{ + for (NSUInteger idx = 0; idx < count; idx++) { + dst[idx] = MIX(from[idx], to[idx], f); + } +} + +double POPTimingFunctionSolve(const double vec[4], double t, double eps) +{ + WebCore::UnitBezier bezier(vec[0], vec[1], vec[2], vec[3]); + return bezier.solve(t, eps); +} + +double POPNormalize(double value, double startValue, double endValue) +{ + return (value - startValue) / (endValue - startValue); +} + +double POPProjectNormal(double n, double start, double end) +{ + return start + (n * (end - start)); +} + +static double linear_interpolation(double t, double start, double end) +{ + return t * end + (1.f - t) * start; +} + +double POPQuadraticOutInterpolation(double t, double start, double end) +{ + return linear_interpolation(2*t - t*t, start, end); +} + +static double b3_friction1(double x) +{ + return (0.0007 * pow(x, 3)) - (0.031 * pow(x, 2)) + 0.64 * x + 1.28; +} + +static double b3_friction2(double x) +{ + return (0.000044 * pow(x, 3)) - (0.006 * pow(x, 2)) + 0.36 * x + 2.; +} + +static double b3_friction3(double x) +{ + return (0.00000045 * pow(x, 3)) - (0.000332 * pow(x, 2)) + 0.1078 * x + 5.84; +} + +double POPBouncy3NoBounce(double tension) +{ + double friction = 0; + if (tension <= 18.) { + friction = b3_friction1(tension); + } else if (tension > 18 && tension <= 44) { + friction = b3_friction2(tension); + } else if (tension > 44) { + friction = b3_friction3(tension); + } else { + assert(false); + } + return friction; +} + +void POPQuadraticSolve(CGFloat a, CGFloat b, CGFloat c, CGFloat &x1, CGFloat &x2) +{ + CGFloat discriminant = sqrt(b * b - 4 * a * c); + x1 = (-b + discriminant) / (2 * a); + x2 = (-b - discriminant) / (2 * a); +} diff --git a/TalkinToTheNet/Pods/pop/pop/POPPropertyAnimation.h b/TalkinToTheNet/Pods/pop/pop/POPPropertyAnimation.h new file mode 100644 index 0000000..2861665 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPPropertyAnimation.h @@ -0,0 +1,65 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import +#import + +/** + @abstract Flags for clamping animation values. + @discussion Animation values can optionally be clamped to avoid overshoot. kPOPAnimationClampStart ensures values are more than fromValue and kPOPAnimationClampEnd ensures values are less than toValue. + */ +typedef NS_OPTIONS(NSUInteger, POPAnimationClampFlags) +{ + kPOPAnimationClampNone = 0, + kPOPAnimationClampStart = 1UL << 0, + kPOPAnimationClampEnd = 1UL << 1, + kPOPAnimationClampBoth = kPOPAnimationClampStart | kPOPAnimationClampEnd, +}; + +/** + @abstract The semi-concrete property animation subclass. + */ +@interface POPPropertyAnimation : POPAnimation + +/** + @abstract The property to animate. + */ +@property (strong, nonatomic) POPAnimatableProperty *property; + +/** + @abstract The value to animate from. + @discussion The value type should match the property. If unspecified, the value is initialized to the object's current value on animation start. + */ +@property (copy, nonatomic) id fromValue; + +/** + @abstract The value to animate to. + @discussion The value type should match the property. If unspecified, the value is initialized to the object's current value on animation start. + */ +@property (copy, nonatomic) id toValue; + +/** + @abstract The rounding factor applied to the current animated value. + @discussion Specify 1.0 to animate between integral values. Defaults to 0 meaning no rounding. + */ +@property (assign, nonatomic) CGFloat roundingFactor; + +/** + @abstract The clamp mode applied to the current animated value. + @discussion See {@ref POPAnimationClampFlags} for possible values. Defaults to kPOPAnimationClampNone. + */ +@property (assign, nonatomic) NSUInteger clampMode; + +/** + @abstract The flag indicating whether values should be "added" each frame, rather than set. + @discussion Addition may be type dependent. Defaults to NO. + */ +@property (assign, nonatomic, getter = isAdditive) BOOL additive; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPPropertyAnimation.mm b/TalkinToTheNet/Pods/pop/pop/POPPropertyAnimation.mm new file mode 100644 index 0000000..56a9e5c --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPPropertyAnimation.mm @@ -0,0 +1,125 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPPropertyAnimationInternal.h" + +@implementation POPPropertyAnimation + +#pragma mark - Lifecycle + +#undef __state +#define __state ((POPPropertyAnimationState *)_state) + +- (void)_initState +{ + _state = new POPPropertyAnimationState(self); +} + +#pragma mark - Properties + +DEFINE_RW_FLAG(POPPropertyAnimationState, additive, isAdditive, setAdditive:); +DEFINE_RW_PROPERTY(POPPropertyAnimationState, roundingFactor, setRoundingFactor:, CGFloat); +DEFINE_RW_PROPERTY(POPPropertyAnimationState, clampMode, setClampMode:, NSUInteger); +DEFINE_RW_PROPERTY_OBJ(POPPropertyAnimationState, property, setProperty:, POPAnimatableProperty*, ((POPPropertyAnimationState*)_state)->updatedDynamicsThreshold();); +DEFINE_RW_PROPERTY_OBJ_COPY(POPPropertyAnimationState, progressMarkers, setProgressMarkers:, NSArray*, ((POPPropertyAnimationState*)_state)->updatedProgressMarkers();); + +- (id)fromValue +{ + return POPBox(__state->fromVec, __state->valueType); +} + +- (void)setFromValue:(id)aValue +{ + POPPropertyAnimationState *s = __state; + VectorRef vec = POPUnbox(aValue, s->valueType, s->valueCount, YES); + if (!vec_equal(vec, s->fromVec)) { + s->fromVec = vec; + + if (s->tracing) { + [s->tracer updateFromValue:aValue]; + } + } +} + +- (id)toValue +{ + return POPBox(__state->toVec, __state->valueType); +} + +- (void)setToValue:(id)aValue +{ + POPPropertyAnimationState *s = __state; + VectorRef vec = POPUnbox(aValue, s->valueType, s->valueCount, YES); + + if (!vec_equal(vec, s->toVec)) { + s->toVec = vec; + + // invalidate to dependent state + s->didReachToValue = false; + s->distanceVec = NULL; + + if (s->tracing) { + [s->tracer updateToValue:aValue]; + } + + // automatically unpause active animations + if (s->active && s->paused) { + s->setPaused(false); + } + } +} + +- (id)currentValue +{ + return POPBox(__state->currentValue(), __state->valueType); +} + +#pragma mark - Utility + +- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug +{ + [s appendFormat:@"; from = %@; to = %@", describe(__state->fromVec), describe(__state->toVec)]; + + if (_state->active) + [s appendFormat:@"; currentValue = %@", describe(__state->currentValue())]; + + if (__state->velocityVec && 0 != __state->velocityVec->norm()) + [s appendFormat:@"; velocity = %@", describe(__state->velocityVec)]; + + if (!self.removedOnCompletion) + [s appendFormat:@"; removedOnCompletion = %@", POPStringFromBOOL(self.removedOnCompletion)]; + + if (__state->progressMarkers) + [s appendFormat:@"; progressMarkers = [%@]", [__state->progressMarkers componentsJoinedByString:@", "]]; + + if (_state->active) + [s appendFormat:@"; progress = %f", __state->progress]; +} + +@end + +@implementation POPPropertyAnimation (NSCopying) + +- (instancetype)copyWithZone:(NSZone *)zone { + + POPPropertyAnimation *copy = [super copyWithZone:zone]; + + if (copy) { + copy.property = [self.property copyWithZone:zone]; + copy.fromValue = self.fromValue; + copy.toValue = self.toValue; + copy.roundingFactor = self.roundingFactor; + copy.clampMode = self.clampMode; + copy.additive = self.additive; + } + + return copy; +} + +@end \ No newline at end of file diff --git a/TalkinToTheNet/Pods/pop/pop/POPPropertyAnimationInternal.h b/TalkinToTheNet/Pods/pop/pop/POPPropertyAnimationInternal.h new file mode 100644 index 0000000..9f2aee4 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPPropertyAnimationInternal.h @@ -0,0 +1,359 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPAnimationInternal.h" +#import "POPPropertyAnimation.h" + +static void clampValue(CGFloat &value, CGFloat fromValue, CGFloat toValue, NSUInteger clamp) +{ + BOOL increasing = (toValue > fromValue); + + // Clamp start of animation. + if ((kPOPAnimationClampStart & clamp) && + ((increasing && (value < fromValue)) || (!increasing && (value > fromValue)))) { + value = fromValue; + } + + // Clamp end of animation. + if ((kPOPAnimationClampEnd & clamp) && + ((increasing && (value > toValue)) || (!increasing && (value < toValue)))) { + value = toValue; + } +} + +struct _POPPropertyAnimationState : _POPAnimationState +{ + POPAnimatableProperty *property; + POPValueType valueType; + NSUInteger valueCount; + VectorRef fromVec; + VectorRef toVec; + VectorRef currentVec; + VectorRef previousVec; + VectorRef previous2Vec; + VectorRef velocityVec; + VectorRef originalVelocityVec; + VectorRef distanceVec; + CGFloat roundingFactor; + NSUInteger clampMode; + NSArray *progressMarkers; + POPProgressMarker *progressMarkerState; + NSUInteger progressMarkerCount; + NSUInteger nextProgressMarkerIdx; + CGFloat dynamicsThreshold; + + _POPPropertyAnimationState(id __unsafe_unretained anim) : _POPAnimationState(anim), + property(nil), + valueType((POPValueType)0), + valueCount(0), + fromVec(nullptr), + toVec(nullptr), + currentVec(nullptr), + previousVec(nullptr), + previous2Vec(nullptr), + velocityVec(nullptr), + originalVelocityVec(nullptr), + distanceVec(nullptr), + roundingFactor(0), + clampMode(0), + progressMarkers(nil), + progressMarkerState(nil), + progressMarkerCount(0), + nextProgressMarkerIdx(0), + dynamicsThreshold(0) + { + type = kPOPAnimationBasic; + } + + ~_POPPropertyAnimationState() + { + if (progressMarkerState) { + free(progressMarkerState); + progressMarkerState = NULL; + } + } + + bool canProgress() { + return hasValue(); + } + + bool shouldRound() { + return 0 != roundingFactor; + } + + bool hasValue() { + return 0 != valueCount; + } + + bool isDone() { + // inherit done + if (_POPAnimationState::isDone()) { + return true; + } + + // consider an animation with no values done + if (!hasValue() && !isCustom()) { + return true; + } + + return false; + } + + // returns a copy of the currentVec, rounding if needed + VectorRef currentValue() { + VectorRef vec = VectorRef(Vector::new_vector(currentVec.get())); + if (shouldRound()) { + vec->subRound(1 / roundingFactor); + } + return vec; + } + + void resetProgressMarkerState() + { + for (NSUInteger idx = 0; idx < progressMarkerCount; idx++) + progressMarkerState[idx].reached = false; + + nextProgressMarkerIdx = 0; + } + + void updatedProgressMarkers() + { + if (progressMarkerState) { + free(progressMarkerState); + progressMarkerState = NULL; + } + + progressMarkerCount = progressMarkers.count; + + if (0 != progressMarkerCount) { + progressMarkerState = (POPProgressMarker *)malloc(progressMarkerCount * sizeof(POPProgressMarker)); + [progressMarkers enumerateObjectsUsingBlock:^(NSNumber *progressMarker, NSUInteger idx, BOOL *stop) { + progressMarkerState[idx].reached = false; + progressMarkerState[idx].progress = [progressMarker floatValue]; + }]; + } + + nextProgressMarkerIdx = 0; + } + + virtual void updatedDynamicsThreshold() + { + dynamicsThreshold = property.threshold; + } + + void finalizeProgress() + { + progress = 1.0; + NSUInteger count = valueCount; + VectorRef outVec(Vector::new_vector(count, NULL)); + + if (outVec && toVec) { + *outVec = *toVec; + } + + currentVec = outVec; + clampCurrentValue(); + delegateProgress(); + } + + void computeProgress() { + if (!canProgress()) { + return; + } + + static ComputeProgressFunctor func; + Vector4r v = vector4(currentVec); + Vector4r f = vector4(fromVec); + Vector4r t = vector4(toVec); + progress = func(v, f, t); + } + + void delegateProgress() { + if (!canProgress()) { + return; + } + + if (delegateDidProgress && progressMarkerState) { + + while (nextProgressMarkerIdx < progressMarkerCount) { + if (progress < progressMarkerState[nextProgressMarkerIdx].progress) + break; + + if (!progressMarkerState[nextProgressMarkerIdx].reached) { + ActionEnabler enabler; + [delegate pop_animation:self didReachProgress:progressMarkerState[nextProgressMarkerIdx].progress]; + progressMarkerState[nextProgressMarkerIdx].reached = true; + } + + nextProgressMarkerIdx++; + } + } + + if (!didReachToValue) { + bool didReachToValue = false; + if (0 == valueCount) { + didReachToValue = true; + } else { + Vector4r distance = toVec->vector4r(); + distance -= currentVec->vector4r(); + + if (0 == distance.squaredNorm()) { + didReachToValue = true; + } else { + // components + if (distanceVec) { + didReachToValue = true; + const CGFloat *distanceValues = distanceVec->data(); + for (NSUInteger idx = 0; idx < valueCount; idx++) { + didReachToValue &= (signbit(distance[idx]) != signbit(distanceValues[idx])); + } + } + } + } + + if (didReachToValue) { + handleDidReachToValue(); + } + } + } + + void handleDidReachToValue() { + didReachToValue = true; + + if (delegateDidReachToValue) { + ActionEnabler enabler; + [delegate pop_animationDidReachToValue:self]; + } + + POPAnimationDidReachToValueBlock block = animationDidReachToValueBlock; + if (block != NULL) { + ActionEnabler enabler; + block(self); + } + + if (tracing) { + [tracer didReachToValue:POPBox(currentValue(), valueType, true)]; + } + } + + void readObjectValue(VectorRef *ptrVec, id obj) + { + // use current object value as from value + pop_animatable_read_block read = property.readBlock; + if (NULL != read) { + + Vector4r vec = read_values(read, obj, valueCount); + *ptrVec = VectorRef(Vector::new_vector(valueCount, vec)); + + if (tracing) { + [tracer readPropertyValue:POPBox(*ptrVec, valueType, true)]; + } + } + } + + virtual void willRun(bool started, id obj) { + // ensure from value initialized + if (NULL == fromVec) { + readObjectValue(&fromVec, obj); + } + + // ensure to value initialized + if (NULL == toVec) { + // compute decay to value + if (kPOPAnimationDecay == type) { + [self toValue]; + } else { + // read to value + readObjectValue(&toVec, obj); + } + } + + // handle one time value initialization on start + if (started) { + + // initialize current vec + if (!currentVec) { + currentVec = VectorRef(Vector::new_vector(valueCount, NULL)); + + // initialize current value with from value + // only do this on initial creation to avoid overwriting current value + // on paused animation continuation + if (currentVec && fromVec) { + *currentVec = *fromVec; + } + } + + // ensure velocity values + if (!velocityVec) { + velocityVec = VectorRef(Vector::new_vector(valueCount, NULL)); + } + if (!originalVelocityVec) { + originalVelocityVec = VectorRef(Vector::new_vector(valueCount, NULL)); + } + } + + // ensure distance value initialized + // depends on current value set on one time start + if (NULL == distanceVec) { + + // not yet started animations may not have current value + VectorRef fromVec2 = NULL != currentVec ? currentVec : fromVec; + + if (fromVec2 && toVec) { + Vector4r distance = toVec->vector4r(); + distance -= fromVec2->vector4r(); + + if (0 != distance.squaredNorm()) { + distanceVec = VectorRef(Vector::new_vector(valueCount, distance)); + } + } + } + } + + virtual void reset(bool all) { + _POPAnimationState::reset(all); + + if (all) { + currentVec = NULL; + previousVec = NULL; + previous2Vec = NULL; + } + progress = 0; + resetProgressMarkerState(); + didReachToValue = false; + distanceVec = NULL; + } + + void clampCurrentValue(NSUInteger clamp) + { + if (kPOPAnimationClampNone == clamp) + return; + + // Clamp all vector values + CGFloat *currentValues = currentVec->data(); + const CGFloat *fromValues = fromVec->data(); + const CGFloat *toValues = toVec->data(); + + for (NSUInteger idx = 0; idx < valueCount; idx++) { + clampValue(currentValues[idx], fromValues[idx], toValues[idx], clamp); + } + } + + void clampCurrentValue() + { + clampCurrentValue(clampMode); + } +}; + +typedef struct _POPPropertyAnimationState POPPropertyAnimationState; + +@interface POPPropertyAnimation () + +@end + diff --git a/TalkinToTheNet/Pods/pop/pop/POPSpringAnimation.h b/TalkinToTheNet/Pods/pop/pop/POPSpringAnimation.h new file mode 100644 index 0000000..a22cd5b --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPSpringAnimation.h @@ -0,0 +1,67 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +/** + @abstract A concrete spring animation class. + @discussion Animation is achieved through modeling spring dynamics. + */ +@interface POPSpringAnimation : POPPropertyAnimation + +/** + @abstract The designated initializer. + @returns An instance of a spring animation. + */ ++ (instancetype)animation; + +/** + @abstract Convenience initializer that returns an animation with animatable property of name. + @param name The name of the animatable property. + @returns An instance of a spring animation configured with specified animatable property. + */ ++ (instancetype)animationWithPropertyNamed:(NSString *)name; + +/** + @abstract The current velocity value. + @discussion Set before animation start to account for initial velocity. Expressed in change of value units per second. + */ +@property (copy, nonatomic) id velocity; + +/** + @abstract The effective bounciness. + @discussion Use in conjunction with 'springSpeed' to change animation effect. Values are converted into corresponding dynamics constants. Higher values increase spring movement range resulting in more oscillations and springiness. Defined as a value in the range [0, 20]. Defaults to 4. + */ +@property (assign, nonatomic) CGFloat springBounciness; + +/** + @abstract The effective speed. + @discussion Use in conjunction with 'springBounciness' to change animation effect. Values are converted into corresponding dynamics constants. Higher values increase the dampening power of the spring resulting in a faster initial velocity and more rapid bounce slowdown. Defined as a value in the range [0, 20]. Defaults to 12. + */ +@property (assign, nonatomic) CGFloat springSpeed; + +/** + @abstract The tension used in the dynamics simulation. + @discussion Can be used over bounciness and speed for finer grain tweaking of animation effect. + */ +@property (assign, nonatomic) CGFloat dynamicsTension; + +/** + @abstract The friction used in the dynamics simulation. + @discussion Can be used over bounciness and speed for finer grain tweaking of animation effect. + */ +@property (assign, nonatomic) CGFloat dynamicsFriction; + +/** + @abstract The mass used in the dynamics simulation. + @discussion Can be used over bounciness and speed for finer grain tweaking of animation effect. + */ +@property (assign, nonatomic) CGFloat dynamicsMass; + +@end diff --git a/TalkinToTheNet/Pods/pop/pop/POPSpringAnimation.mm b/TalkinToTheNet/Pods/pop/pop/POPSpringAnimation.mm new file mode 100644 index 0000000..d299770 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPSpringAnimation.mm @@ -0,0 +1,192 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPSpringAnimationInternal.h" + +@implementation POPSpringAnimation + +#pragma mark - Lifecycle + +#undef __state +#define __state ((POPSpringAnimationState *)_state) + ++ (instancetype)animation +{ + return [[self alloc] init]; +} + ++ (instancetype)animationWithPropertyNamed:(NSString *)aName +{ + POPSpringAnimation *anim = [self animation]; + anim.property = [POPAnimatableProperty propertyWithName:aName]; + return anim; +} + +- (void)_initState +{ + _state = new POPSpringAnimationState(self); +} + +- (id)init +{ + self = [super _init]; + if (nil != self) { + __state->solver = new SpringSolver4d(1, 1, 1); + __state->updatedDynamicsThreshold(); + __state->updatedBouncinessAndSpeed(); + } + return self; +} + +- (void)dealloc +{ + if (__state) { + delete __state->solver; + __state->solver = NULL; + } +} + +#pragma mark - Properties + +- (id)velocity +{ + return POPBox(__state->velocityVec, __state->valueType); +} + +- (void)setVelocity:(id)aValue +{ + POPPropertyAnimationState *s = __state; + VectorRef vec = POPUnbox(aValue, s->valueType, s->valueCount, YES); + VectorRef origVec = POPUnbox(aValue, s->valueType, s->valueCount, YES); + if (!vec_equal(vec, s->velocityVec)) { + s->velocityVec = vec; + s->originalVelocityVec = origVec; + + if (s->tracing) { + [s->tracer updateVelocity:aValue]; + } + } +} + +DEFINE_RW_PROPERTY(POPSpringAnimationState, dynamicsTension, setDynamicsTension:, CGFloat, [self _updatedDynamicsTension];); +DEFINE_RW_PROPERTY(POPSpringAnimationState, dynamicsFriction, setDynamicsFriction:, CGFloat, [self _updatedDynamicsFriction];); +DEFINE_RW_PROPERTY(POPSpringAnimationState, dynamicsMass, setDynamicsMass:, CGFloat, [self _updatedDynamicsMass];); + +FB_PROPERTY_GET(POPSpringAnimationState, springSpeed, CGFloat); +- (void)setSpringSpeed:(CGFloat)aFloat +{ + POPSpringAnimationState *s = __state; + if (s->userSpecifiedDynamics || aFloat != s->springSpeed) { + s->springSpeed = aFloat; + s->userSpecifiedDynamics = false; + s->updatedBouncinessAndSpeed(); + if (s->tracing) { + [s->tracer updateSpeed:aFloat]; + } + } +} + +FB_PROPERTY_GET(POPSpringAnimationState, springBounciness, CGFloat); +- (void)setSpringBounciness:(CGFloat)aFloat +{ + POPSpringAnimationState *s = __state; + if (s->userSpecifiedDynamics || aFloat != s->springBounciness) { + s->springBounciness = aFloat; + s->userSpecifiedDynamics = false; + s->updatedBouncinessAndSpeed(); + if (s->tracing) { + [s->tracer updateBounciness:aFloat]; + } + } +} + +- (SpringSolver4d *)solver +{ + return __state->solver; +} + +- (void)setSolver:(SpringSolver4d *)aSolver +{ + if (aSolver != __state->solver) { + if (__state->solver) { + delete(__state->solver); + } + __state->solver = aSolver; + } +} + +#pragma mark - Utility + +- (void)_updatedDynamicsTension +{ + __state->userSpecifiedDynamics = true; + if(__state->tracing) { + [__state->tracer updateTension:__state->dynamicsTension]; + } + __state->updatedDynamics(); +} + +- (void)_updatedDynamicsFriction +{ + __state->userSpecifiedDynamics = true; + if(__state->tracing) { + [__state->tracer updateFriction:__state->dynamicsFriction]; + } + __state->updatedDynamics(); +} + +- (void)_updatedDynamicsMass +{ + __state->userSpecifiedDynamics = true; + if(__state->tracing) { + [__state->tracer updateMass:__state->dynamicsMass]; + } + __state->updatedDynamics(); +} + +- (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug +{ + [super _appendDescription:s debug:debug]; + + if (debug) { + if (_state->userSpecifiedDynamics) { + [s appendFormat:@"; dynamics = (tension:%f, friction:%f, mass:%f)", __state->dynamicsTension, __state->dynamicsFriction, __state->dynamicsMass]; + } else { + [s appendFormat:@"; bounciness = %f; speed = %f", __state->springBounciness, __state->springSpeed]; + } + } +} + +@end + +@implementation POPSpringAnimation (NSCopying) + +- (instancetype)copyWithZone:(NSZone *)zone { + + POPSpringAnimation *copy = [super copyWithZone:zone]; + + if (copy) { + id velocity = POPBox(__state->originalVelocityVec, __state->valueType); + + // If velocity never gets set, then POPBox will return nil, messing up __state->valueCount. + if (velocity) { + copy.velocity = velocity; + } + + copy.springBounciness = self.springBounciness; + copy.springSpeed = self.springSpeed; + copy.dynamicsTension = self.dynamicsTension; + copy.dynamicsFriction = self.dynamicsFriction; + copy.dynamicsMass = self.dynamicsMass; + } + + return copy; +} + +@end \ No newline at end of file diff --git a/TalkinToTheNet/Pods/pop/pop/POPSpringAnimationInternal.h b/TalkinToTheNet/Pods/pop/pop/POPSpringAnimationInternal.h new file mode 100644 index 0000000..6a72a43 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPSpringAnimationInternal.h @@ -0,0 +1,132 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import "POPAnimationExtras.h" +#import "POPPropertyAnimationInternal.h" + +struct _POPSpringAnimationState : _POPPropertyAnimationState +{ + SpringSolver4d *solver; + CGFloat springSpeed; + CGFloat springBounciness; // normalized springiness + CGFloat dynamicsTension; // tension + CGFloat dynamicsFriction; // friction + CGFloat dynamicsMass; // mass + + _POPSpringAnimationState(id __unsafe_unretained anim) : _POPPropertyAnimationState(anim), + solver(nullptr), + springSpeed(12.), + springBounciness(4.), + dynamicsTension(0), + dynamicsFriction(0), + dynamicsMass(0) + { + type = kPOPAnimationSpring; + } + + bool hasConverged() + { + NSUInteger count = valueCount; + if (shouldRound()) { + return vec_equal(previous2Vec, previousVec) && vec_equal(previousVec, toVec); + } else { + if (!previousVec || !previous2Vec) + return false; + + CGFloat t = dynamicsThreshold / 5; + + const CGFloat *toValues = toVec->data(); + const CGFloat *previousValues = previousVec->data(); + const CGFloat *previous2Values = previous2Vec->data(); + + for (NSUInteger idx = 0; idx < count; idx++) { + if ((std::abs(toValues[idx] - previousValues[idx]) >= t) || (std::abs(previous2Values[idx] - previousValues[idx]) >= t)) { + return false; + } + } + return true; + } + } + + bool isDone() { + if (_POPPropertyAnimationState::isDone()) { + return true; + } + return solver->started() && (hasConverged() || solver->hasConverged()); + } + + void updatedDynamics() + { + if (NULL != solver) { + solver->setConstants(dynamicsTension, dynamicsFriction, dynamicsMass); + } + } + + void updatedDynamicsThreshold() + { + _POPPropertyAnimationState::updatedDynamicsThreshold(); + if (NULL != solver) { + solver->setThreshold(dynamicsThreshold); + } + } + + void updatedBouncinessAndSpeed() { + [POPSpringAnimation convertBounciness:springBounciness speed:springSpeed toTension:&dynamicsTension friction:&dynamicsFriction mass:&dynamicsMass]; + updatedDynamics(); + } + + bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) { + // advance past not yet initialized animations + if (NULL == currentVec) { + return false; + } + + CFTimeInterval localTime = time - startTime; + + Vector4d value = vector4d(currentVec); + Vector4d toValue = vector4d(toVec); + Vector4d velocity = vector4d(velocityVec); + + SSState4d state; + state.p = toValue - value; + + // the solver assumes a spring of size zero + // flip the velocity from user perspective to solver perspective + state.v = velocity * -1; + + solver->advance(state, localTime, dt); + value = toValue - state.p; + + // flip velocity back to user perspective + velocity = state.v * -1; + + *currentVec = value; + + if (velocityVec) { + *velocityVec = velocity; + } + + clampCurrentValue(); + + return true; + } + + virtual void reset(bool all) { + _POPPropertyAnimationState::reset(all); + + if (solver) { + solver->setConstants(dynamicsTension, dynamicsFriction, dynamicsMass); + solver->reset(); + } + } +}; + +typedef struct _POPSpringAnimationState POPSpringAnimationState; diff --git a/TalkinToTheNet/Pods/pop/pop/POPSpringSolver.h b/TalkinToTheNet/Pods/pop/pop/POPSpringSolver.h new file mode 100644 index 0000000..df485bf --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPSpringSolver.h @@ -0,0 +1,190 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import "POPVector.h" + +namespace POP { + + template + struct SSState + { + T p; + T v; + }; + + template + struct SSDerivative + { + T dp; + T dv; + }; + + typedef SSState SSState4d; + typedef SSDerivative SSDerivative4d; + + const CFTimeInterval solverDt = 0.001f; + const CFTimeInterval maxSolverDt = 30.0f; + + /** + Templated spring solver class. + */ + template + class SpringSolver + { + double _k; // stiffness + double _b; // dampening + double _m; // mass + + double _tp; // threshold + double _tv; // threshold velocity + double _ta; // threshold acceleration + + CFTimeInterval _accumulatedTime; + SSState _lastState; + T _lastDv; + bool _started; + + public: + SpringSolver(double k, double b, double m = 1) : _k(k), _b(b), _m(m), _started(false) + { + _accumulatedTime = 0; + _lastState.p = T::Zero(); + _lastState.v = T::Zero(); + _lastDv = T::Zero(); + setThreshold(1.); + } + + ~SpringSolver() + { + } + + bool started() + { + return _started; + } + + void setConstants(double k, double b, double m) + { + _k = k; + _b = b; + _m = m; + } + + void setThreshold(double t) + { + _tp = t / 2; // half a unit + _tv = 25.0 * t; // 5 units per second, squared for comparison + _ta = 625.0 * t * t; // 5 units per second squared, squared for comparison + } + + T acceleration(const SSState &state, double t) + { + return state.p*(-_k/_m) - state.v*(_b/_m); + } + + SSDerivative evaluate(const SSState &initial, double t) + { + SSDerivative output; + output.dp = initial.v; + output.dv = acceleration(initial, t); + return output; + } + + SSDerivative evaluate(const SSState &initial, double t, double dt, const SSDerivative &d) + { + SSState state; + state.p = initial.p + d.dp*dt; + state.v = initial.v + d.dv*dt; + SSDerivative output; + output.dp = state.v; + output.dv = acceleration(state, t+dt); + return output; + } + + void integrate(SSState &state, double t, double dt) + { + SSDerivative a = evaluate(state, t); + SSDerivative b = evaluate(state, t, dt*0.5, a); + SSDerivative c = evaluate(state, t, dt*0.5, b); + SSDerivative d = evaluate(state, t, dt, c); + + T dpdt = (a.dp + (b.dp + c.dp)*2.0 + d.dp) * (1.0/6.0); + T dvdt = (a.dv + (b.dv + c.dv)*2.0 + d.dv) * (1.0/6.0); + + state.p = state.p + dpdt*dt; + state.v = state.v + dvdt*dt; + + _lastDv = dvdt; + } + + SSState interpolate(const SSState &previous, const SSState ¤t, double alpha) + { + SSState state; + state.p = current.p*alpha + previous.p*(1-alpha); + state.v = current.v*alpha + previous.v*(1-alpha); + return state; + } + + void advance(SSState &state, double t, double dt) + { + _started = true; + + if (dt > maxSolverDt) { + // excessive time step, force shut down + _lastDv = _lastState.v = _lastState.p = T::Zero(); + } else { + _accumulatedTime += dt; + + SSState previousState = state, currentState = state; + while (_accumulatedTime >= solverDt) { + previousState = currentState; + this->integrate(currentState, t, solverDt); + t += solverDt; + _accumulatedTime -= solverDt; + } + CFTimeInterval alpha = _accumulatedTime / solverDt; + _lastState = state = this->interpolate(previousState, currentState, alpha); + } + } + + bool hasConverged() + { + if (!_started) { + return false; + } + + for (size_t idx = 0; idx < _lastState.p.size(); idx++) { + if (fabs(_lastState.p(idx)) >= _tp) { + return false; + } + } + + return (_lastState.v.squaredNorm() < _tv) && (_lastDv.squaredNorm() < _ta); + } + + void reset() + { + _accumulatedTime = 0; + _lastState.p = T::Zero(); + _lastState.v = T::Zero(); + _lastDv = T::Zero(); + _started = false; + } + }; + + /** + Convenience spring solver type definitions. + */ + typedef SpringSolver SpringSolver2d; + typedef SpringSolver SpringSolver3d; + typedef SpringSolver SpringSolver4d; +} + diff --git a/TalkinToTheNet/Pods/pop/pop/POPVector.h b/TalkinToTheNet/Pods/pop/pop/POPVector.h new file mode 100644 index 0000000..44d4e9f --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPVector.h @@ -0,0 +1,394 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#ifndef __POP__FBVector__ +#define __POP__FBVector__ + +#include +#include + +#import + +#import + +#import "POPDefines.h" + +#if SCENEKIT_SDK_AVAILABLE +#import +#endif + +#if TARGET_OS_IPHONE +#import +#endif + +#import "POPMath.h" + +namespace POP { + + /** Fixed two-size vector class */ + template + struct Vector2 + { + private: + typedef T Vector2::* const _data[2]; + static const _data _v; + + public: + T x; + T y; + + // Zero vector + static const Vector2 Zero() { return Vector2(0); } + + // Constructors + Vector2() {} + explicit Vector2(T v) { x = v; y = v; }; + explicit Vector2(T x0, T y0) : x(x0), y(y0) {}; + explicit Vector2(const CGPoint &p) : x(p.x), y (p.y) {} + explicit Vector2(const CGSize &s) : x(s.width), y (s.height) {} + + // Copy constructor + template explicit Vector2(const Vector2 &v) : x(v.x), y(v.y) {} + + // Index operators + const T& operator[](size_t i) const { return this->*_v[i]; } + T& operator[](size_t i) { return this->*_v[i]; } + const T& operator()(size_t i) const { return this->*_v[i]; } + T& operator()(size_t i) { return this->*_v[i]; } + + // Backing data + T * data() { return &(this->*_v[0]); } + const T * data() const { return &(this->*_v[0]); } + + // Size + inline size_t size() const { return 2; } + + // Assignment + Vector2 &operator= (T v) { x = v; y = v; return *this;} + template Vector2 &operator= (const Vector2 &v) { x = v.x; y = v.y; return *this;} + + // Negation + Vector2 operator- (void) const { return Vector2(-x, -y); } + + // Equality + bool operator== (T v) const { return (x == v && y == v); } + bool operator== (const Vector2 &v) const { return (x == v.x && y == v.y); } + + // Inequality + bool operator!= (T v) const {return (x != v || y != v); } + bool operator!= (const Vector2 &v) const { return (x != v.x || y != v.y); } + + // Scalar Math + Vector2 operator+ (T v) const { return Vector2(x + v, y + v); } + Vector2 operator- (T v) const { return Vector2(x - v, y - v); } + Vector2 operator* (T v) const { return Vector2(x * v, y * v); } + Vector2 operator/ (T v) const { return Vector2(x / v, y / v); } + Vector2 &operator+= (T v) { x += v; y += v; return *this; }; + Vector2 &operator-= (T v) { x -= v; y -= v; return *this; }; + Vector2 &operator*= (T v) { x *= v; y *= v; return *this; }; + Vector2 &operator/= (T v) { x /= v; y /= v; return *this; }; + + // Vector Math + Vector2 operator+ (const Vector2 &v) const { return Vector2(x + v.x, y + v.y); } + Vector2 operator- (const Vector2 &v) const { return Vector2(x - v.x, y - v.y); } + Vector2 &operator+= (const Vector2 &v) { x += v.x; y += v.y; return *this; }; + Vector2 &operator-= (const Vector2 &v) { x -= v.x; y -= v.y; return *this; }; + + // Norms + CGFloat norm() const { return sqrtr(squaredNorm()); } + CGFloat squaredNorm() const { return x * x + y * y; } + + // Cast + template Vector2 cast() const { return Vector2(x, y); } + CGPoint cg_point() const { return CGPointMake(x, y); }; + }; + + template + const typename Vector2::_data Vector2::_v = { &Vector2::x, &Vector2::y }; + + /** Fixed three-size vector class */ + template + struct Vector3 + { + private: + typedef T Vector3::* const _data[3]; + static const _data _v; + + public: + T x; + T y; + T z; + + // Zero vector + static const Vector3 Zero() { return Vector3(0); }; + + // Constructors + Vector3() {} + explicit Vector3(T v) : x(v), y(v), z(v) {}; + explicit Vector3(T x0, T y0, T z0) : x(x0), y(y0), z(z0) {}; + + // Copy constructor + template explicit Vector3(const Vector3 &v) : x(v.x), y(v.y), z(v.z) {} + + // Index operators + const T& operator[](size_t i) const { return this->*_v[i]; } + T& operator[](size_t i) { return this->*_v[i]; } + const T& operator()(size_t i) const { return this->*_v[i]; } + T& operator()(size_t i) { return this->*_v[i]; } + + // Backing data + T * data() { return &(this->*_v[0]); } + const T * data() const { return &(this->*_v[0]); } + + // Size + inline size_t size() const { return 3; } + + // Assignment + Vector3 &operator= (T v) { x = v; y = v; z = v; return *this;} + template Vector3 &operator= (const Vector3 &v) { x = v.x; y = v.y; z = v.z; return *this;} + + // Negation + Vector3 operator- (void) const { return Vector3(-x, -y, -z); } + + // Equality + bool operator== (T v) const { return (x == v && y == v && z = v); } + bool operator== (const Vector3 &v) const { return (x == v.x && y == v.y && z == v.z); } + + // Inequality + bool operator!= (T v) const {return (x != v || y != v || z != v); } + bool operator!= (const Vector3 &v) const { return (x != v.x || y != v.y || z != v.z); } + + // Scalar Math + Vector3 operator+ (T v) const { return Vector3(x + v, y + v, z + v); } + Vector3 operator- (T v) const { return Vector3(x - v, y - v, z - v); } + Vector3 operator* (T v) const { return Vector3(x * v, y * v, z * v); } + Vector3 operator/ (T v) const { return Vector3(x / v, y / v, z / v); } + Vector3 &operator+= (T v) { x += v; y += v; z += v; return *this; }; + Vector3 &operator-= (T v) { x -= v; y -= v; z -= v; return *this; }; + Vector3 &operator*= (T v) { x *= v; y *= v; z *= v; return *this; }; + Vector3 &operator/= (T v) { x /= v; y /= v; z /= v; return *this; }; + + // Vector Math + Vector3 operator+ (const Vector3 &v) const { return Vector3(x + v.x, y + v.y, z + v.z); } + Vector3 operator- (const Vector3 &v) const { return Vector3(x - v.x, y - v.y, z - v.z); } + Vector3 &operator+= (const Vector3 &v) { x += v.x; y += v.y; z += v.z; return *this; }; + Vector3 &operator-= (const Vector3 &v) { x -= v.x; y -= v.y; z -= v.z; return *this; }; + + // Norms + CGFloat norm() const { return sqrtr(squaredNorm()); } + CGFloat squaredNorm() const { return x * x + y * y + z * z; } + + // Cast + template Vector3 cast() const { return Vector3(x, y, z); } + }; + + template + const typename Vector3::_data Vector3::_v = { &Vector3::x, &Vector3::y, &Vector3::z }; + + /** Fixed four-size vector class */ + template + struct Vector4 + { + private: + typedef T Vector4::* const _data[4]; + static const _data _v; + + public: + T x; + T y; + T z; + T w; + + // Zero vector + static const Vector4 Zero() { return Vector4(0); }; + + // Constructors + Vector4() {} + explicit Vector4(T v) : x(v), y(v), z(v), w(v) {}; + explicit Vector4(T x0, T y0, T z0, T w0) : x(x0), y(y0), z(z0), w(w0) {}; + + // Copy constructor + template explicit Vector4(const Vector4 &v) : x(v.x), y(v.y), z(v.z), w(v.w) {} + + // Index operators + const T& operator[](size_t i) const { return this->*_v[i]; } + T& operator[](size_t i) { return this->*_v[i]; } + const T& operator()(size_t i) const { return this->*_v[i]; } + T& operator()(size_t i) { return this->*_v[i]; } + + // Backing data + T * data() { return &(this->*_v[0]); } + const T * data() const { return &(this->*_v[0]); } + + // Size + inline size_t size() const { return 4; } + + // Assignment + Vector4 &operator= (T v) { x = v; y = v; z = v; w = v; return *this;} + template Vector4 &operator= (const Vector4 &v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this;} + + // Negation + Vector4 operator- (void) const { return Vector4(-x, -y, -z, -w); } + + // Equality + bool operator== (T v) const { return (x == v && y == v && z = v, w = v); } + bool operator== (const Vector4 &v) const { return (x == v.x && y == v.y && z == v.z && w == v.w); } + + // Inequality + bool operator!= (T v) const {return (x != v || y != v || z != v || w != v); } + bool operator!= (const Vector4 &v) const { return (x != v.x || y != v.y || z != v.z || w != v.w); } + + // Scalar Math + Vector4 operator+ (T v) const { return Vector4(x + v, y + v, z + v, w + v); } + Vector4 operator- (T v) const { return Vector4(x - v, y - v, z - v, w - v); } + Vector4 operator* (T v) const { return Vector4(x * v, y * v, z * v, w * v); } + Vector4 operator/ (T v) const { return Vector4(x / v, y / v, z / v, w / v); } + Vector4 &operator+= (T v) { x += v; y += v; z += v; w += v; return *this; }; + Vector4 &operator-= (T v) { x -= v; y -= v; z -= v; w -= v; return *this; }; + Vector4 &operator*= (T v) { x *= v; y *= v; z *= v; w *= v; return *this; }; + Vector4 &operator/= (T v) { x /= v; y /= v; z /= v; w /= v; return *this; }; + + // Vector Math + Vector4 operator+ (const Vector4 &v) const { return Vector4(x + v.x, y + v.y, z + v.z, w + v.w); } + Vector4 operator- (const Vector4 &v) const { return Vector4(x - v.x, y - v.y, z - v.z, w - v.w); } + Vector4 &operator+= (const Vector4 &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; }; + Vector4 &operator-= (const Vector4 &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; }; + + // Norms + CGFloat norm() const { return sqrtr(squaredNorm()); } + CGFloat squaredNorm() const { return x * x + y * y + z * z + w * w; } + + // Cast + template Vector4 cast() const { return Vector4(x, y, z, w); } + }; + + template + const typename Vector4::_data Vector4::_v = { &Vector4::x, &Vector4::y, &Vector4::z, &Vector4::w }; + + /** Convenience typedefs */ + typedef Vector2 Vector2f; + typedef Vector2 Vector2d; + typedef Vector2 Vector2r; + typedef Vector3 Vector3f; + typedef Vector3 Vector3d; + typedef Vector3 Vector3r; + typedef Vector4 Vector4f; + typedef Vector4 Vector4d; + typedef Vector4 Vector4r; + + /** Variable-sized vector class */ + class Vector + { + size_t _count; + CGFloat *_values; + + private: + Vector(size_t); + Vector(const Vector& other); + + public: + ~Vector(); + + // Creates a new vector instance of count with values. Initializing a vector of size 0 returns NULL. + static Vector *new_vector(NSUInteger count, const CGFloat *values); + + // Creates a new vector given a pointer to another. Can return NULL. + static Vector *new_vector(const Vector * const other); + + // Creates a variable size vector given a static vector and count. + static Vector *new_vector(NSUInteger count, Vector4r vec); + + // Size of vector + NSUInteger size() const { return _count; } + + // Returns array of values + CGFloat *data () { return _values; } + const CGFloat *data () const { return _values; }; + + // Vector2r support + Vector2r vector2r() const; + + // Vector4r support + Vector4r vector4r() const; + + // CGFloat support + static Vector *new_cg_float(CGFloat f); + + // CGPoint support + CGPoint cg_point() const; + static Vector *new_cg_point(const CGPoint &p); + + // CGSize support + CGSize cg_size() const; + static Vector *new_cg_size(const CGSize &s); + + // CGRect support + CGRect cg_rect() const; + static Vector *new_cg_rect(const CGRect &r); + +#if TARGET_OS_IPHONE + // UIEdgeInsets support + UIEdgeInsets ui_edge_insets() const; + static Vector *new_ui_edge_insets(const UIEdgeInsets &i); +#endif + + // CGAffineTransform support + CGAffineTransform cg_affine_transform() const; + static Vector *new_cg_affine_transform(const CGAffineTransform &t); + + // CGColorRef support + CGColorRef cg_color() const CF_RETURNS_RETAINED; + static Vector *new_cg_color(CGColorRef color); + +#if SCENEKIT_SDK_AVAILABLE + // SCNVector3 support + SCNVector3 scn_vector3() const; + static Vector *new_scn_vector3(const SCNVector3 &vec3); + + // SCNVector4 support + SCNVector4 scn_vector4() const; + static Vector *new_scn_vector4(const SCNVector4 &vec4); +#endif + + // operator overloads + CGFloat &operator[](size_t i) const { + NSCAssert(size() > i, @"unexpected vector size:%lu", (unsigned long)size()); + return _values[i]; + } + + // Returns the mathematical length + CGFloat norm() const; + CGFloat squaredNorm() const; + + // Round to nearest sub + void subRound(CGFloat sub); + + // Returns string description + NSString * toString() const; + + // Operator overloads + template Vector& operator= (const Vector4& other) { + size_t count = MIN(_count, other.size()); + for (size_t i = 0; i < count; i++) { + _values[i] = other[i]; + } + return *this; + } + Vector& operator= (const Vector& other); + void swap(Vector &first, Vector &second); + bool operator==(const Vector &other) const; + bool operator!=(const Vector &other) const; + }; + + /** Convenience typedefs */ + typedef std::shared_ptr VectorRef; + typedef std::shared_ptr VectorConstRef; + +} +#endif /* defined(__POP__FBVector__) */ diff --git a/TalkinToTheNet/Pods/pop/pop/POPVector.mm b/TalkinToTheNet/Pods/pop/pop/POPVector.mm new file mode 100644 index 0000000..96cee24 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/POPVector.mm @@ -0,0 +1,334 @@ +/** + Copyright (c) 2014-present, Facebook, Inc. + All rights reserved. + + This source code is licensed under the BSD-style license found in the + LICENSE file in the root directory of this source tree. An additional grant + of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "POPVector.h" + +#import "POPDefines.h" +#import "POPCGUtils.h" + +namespace POP +{ + + Vector::Vector(const size_t count) + { + _count = count; + _values = 0 != count ? (CGFloat *)calloc(count, sizeof(CGFloat)) : NULL; + } + + Vector::Vector(const Vector& other) + { + _count = other.size(); + _values = 0 != _count ? (CGFloat *)calloc(_count, sizeof(CGFloat)) : NULL; + if (0 != _count) { + memcpy(_values, other.data(), _count * sizeof(CGFloat)); + } + } + + Vector::~Vector() + { + if (NULL != _values) { + free(_values); + _values = NULL; + } + _count = 0; + } + + void Vector::swap(Vector &first, Vector &second) + { + using std::swap; + swap(first._count, second._count); + swap(first._values, second._values); + } + + Vector& Vector::operator=(const Vector& other) + { + Vector temp(other); + swap(*this, temp); + return *this; + } + + bool Vector::operator==(const Vector &other) const { + if (_count != other.size()) { + return false; + } + + const CGFloat * const values = other.data(); + + for (NSUInteger idx = 0; idx < _count; idx++) { + if (_values[idx] != values[idx]) { + return false; + } + } + + return true; + } + + bool Vector::operator!=(const Vector &other) const { + if (_count == other.size()) { + return false; + } + + const CGFloat * const values = other.data(); + + for (NSUInteger idx = 0; idx < _count; idx++) { + if (_values[idx] != values[idx]) { + return false; + } + } + + return true; + } + + Vector *Vector::new_vector(NSUInteger count, const CGFloat *values) + { + if (0 == count) { + return NULL; + } + + Vector *v = new Vector(count); + if (NULL != values) { + memcpy(v->_values, values, count * sizeof(CGFloat)); + } + return v; + } + + Vector *Vector::new_vector(const Vector * const other) + { + if (NULL == other) { + return NULL; + } + + return Vector::new_vector(other->size(), other->data()); + } + + Vector *Vector::new_vector(NSUInteger count, Vector4r vec) + { + if (0 == count) { + return NULL; + } + + Vector *v = new Vector(count); + + NSCAssert(count <= 4, @"unexpected count %lu", (unsigned long)count); + for (NSUInteger i = 0; i < MIN(count, (NSUInteger)4); i++) { + v->_values[i] = vec[i]; + } + + return v; + } + + Vector4r Vector::vector4r() const + { + Vector4r v = Vector4r::Zero(); + for (size_t i = 0; i < _count; i++) { + v(i) = _values[i]; + } + return v; + } + + Vector2r Vector::vector2r() const + { + Vector2r v = Vector2r::Zero(); + if (_count > 0) v(0) = _values[0]; + if (_count > 1) v(1) = _values[1]; + return v; + } + + Vector *Vector::new_cg_float(CGFloat f) + { + Vector *v = new Vector(1); + v->_values[0] = f; + return v; + } + + CGPoint Vector::cg_point () const + { + Vector2r v = vector2r(); + return CGPointMake(v(0), v(1)); + } + + Vector *Vector::new_cg_point(const CGPoint &p) + { + Vector *v = new Vector(2); + v->_values[0] = p.x; + v->_values[1] = p.y; + return v; + } + + CGSize Vector::cg_size () const + { + Vector2r v = vector2r(); + return CGSizeMake(v(0), v(1)); + } + + Vector *Vector::new_cg_size(const CGSize &s) + { + Vector *v = new Vector(2); + v->_values[0] = s.width; + v->_values[1] = s.height; + return v; + } + + CGRect Vector::cg_rect() const + { + return _count < 4 ? CGRectZero : CGRectMake(_values[0], _values[1], _values[2], _values[3]); + } + + Vector *Vector::new_cg_rect(const CGRect &r) + { + Vector *v = new Vector(4); + v->_values[0] = r.origin.x; + v->_values[1] = r.origin.y; + v->_values[2] = r.size.width; + v->_values[3] = r.size.height; + return v; + } + +#if TARGET_OS_IPHONE + + UIEdgeInsets Vector::ui_edge_insets() const + { + return _count < 4 ? UIEdgeInsetsZero : UIEdgeInsetsMake(_values[0], _values[1], _values[2], _values[3]); + } + + Vector *Vector::new_ui_edge_insets(const UIEdgeInsets &i) + { + Vector *v = new Vector(4); + v->_values[0] = i.top; + v->_values[1] = i.left; + v->_values[2] = i.bottom; + v->_values[3] = i.right; + return v; + } + +#endif + + CGAffineTransform Vector::cg_affine_transform() const + { + if (_count < 6) { + return CGAffineTransformIdentity; + } + + NSCAssert(size() >= 6, @"unexpected vector size:%lu", (unsigned long)size()); + CGAffineTransform t; + t.a = _values[0]; + t.b = _values[1]; + t.c = _values[2]; + t.d = _values[3]; + t.tx = _values[4]; + t.ty = _values[5]; + return t; + } + + Vector *Vector::new_cg_affine_transform(const CGAffineTransform &t) + { + Vector *v = new Vector(6); + v->_values[0] = t.a; + v->_values[1] = t.b; + v->_values[2] = t.c; + v->_values[3] = t.d; + v->_values[4] = t.tx; + v->_values[5] = t.ty; + return v; + } + + CGColorRef Vector::cg_color() const + { + if (_count < 4) { + return NULL; + } + return POPCGColorRGBACreate(_values); + } + + Vector *Vector::new_cg_color(CGColorRef color) + { + CGFloat rgba[4]; + POPCGColorGetRGBAComponents(color, rgba); + return new_vector(4, rgba); + } + +#if SCENEKIT_SDK_AVAILABLE + SCNVector3 Vector::scn_vector3() const + { + return _count < 3 ? SCNVector3Make(0.0, 0.0, 0.0) : SCNVector3Make(_values[0], _values[1], _values[2]); + } + + Vector *Vector::new_scn_vector3(const SCNVector3 &vec3) + { + Vector *v = new Vector(3); + v->_values[0] = vec3.x; + v->_values[1] = vec3.y; + v->_values[2] = vec3.z; + return v; + } + + SCNVector4 Vector::scn_vector4() const + { + return _count < 4 ? SCNVector4Make(0.0, 0.0, 0.0, 0.0) : SCNVector4Make(_values[0], _values[1], _values[2], _values[3]); + } + + Vector *Vector::new_scn_vector4(const SCNVector4 &vec4) + { + Vector *v = new Vector(4); + v->_values[0] = vec4.x; + v->_values[1] = vec4.y; + v->_values[2] = vec4.z; + v->_values[3] = vec4.w; + return v; + } +#endif + + void Vector::subRound(CGFloat sub) + { + for (NSUInteger idx = 0; idx < _count; idx++) { + _values[idx] = POPSubRound(_values[idx], sub); + } + } + + CGFloat Vector::norm() const + { + return sqrtr(squaredNorm()); + } + + CGFloat Vector::squaredNorm() const + { + CGFloat d = 0; + for (NSUInteger idx = 0; idx < _count; idx++) { + d += (_values[idx] * _values[idx]); + } + return d; + } + + NSString * Vector::toString() const + { + if (0 == _count) + return @"()"; + + if (1 == _count) + return [NSString stringWithFormat:@"%f", _values[0]]; + + if (2 == _count) + return [NSString stringWithFormat:@"(%.3f, %.3f)", _values[0], _values[1]]; + + NSMutableString *s = [NSMutableString stringWithCapacity:10]; + + for (NSUInteger idx = 0; idx < _count; idx++) { + if (0 == idx) { + [s appendFormat:@"[%.3f", _values[idx]]; + } else if (idx == _count - 1) { + [s appendFormat:@", %.3f]", _values[idx]]; + } else { + [s appendFormat:@", %.3f", _values[idx]]; + } + } + + return s; + + } +} diff --git a/TalkinToTheNet/Pods/pop/pop/WebCore/FloatConversion.h b/TalkinToTheNet/Pods/pop/pop/WebCore/FloatConversion.h new file mode 100644 index 0000000..4a16166 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/WebCore/FloatConversion.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2007 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef FloatConversion_h +#define FloatConversion_h + +#include + +namespace WebCore { + + template + float narrowPrecisionToFloat(T); + + template<> + inline float narrowPrecisionToFloat(double number) + { + return static_cast(number); + } + + template + CGFloat narrowPrecisionToCGFloat(T); + + template<> + inline CGFloat narrowPrecisionToCGFloat(double number) + { + return static_cast(number); + } + +} // namespace WebCore + +#endif // FloatConversion_h diff --git a/TalkinToTheNet/Pods/pop/pop/WebCore/TransformationMatrix.cpp b/TalkinToTheNet/Pods/pop/pop/WebCore/TransformationMatrix.cpp new file mode 100644 index 0000000..7264ab5 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/WebCore/TransformationMatrix.cpp @@ -0,0 +1,1074 @@ +/* + * Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2009 Torch Mobile, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "TransformationMatrix.h" + +#include + +#include "FloatConversion.h" + +inline double deg2rad(double d) { return d * M_PI / 180.0; } +inline double rad2deg(double r) { return r * 180.0 / M_PI; } +inline double deg2grad(double d) { return d * 400.0 / 360.0; } +inline double grad2deg(double g) { return g * 360.0 / 400.0; } +inline double turn2deg(double t) { return t * 360.0; } +inline double deg2turn(double d) { return d / 360.0; } +inline double rad2grad(double r) { return r * 200.0 / M_PI; } +inline double grad2rad(double g) { return g * M_PI / 200.0; } + +//using namespace std; + +namespace WebCore { + + // + // Supporting Math Functions + // + // This is a set of function from various places (attributed inline) to do things like + // inversion and decomposition of a 4x4 matrix. They are used throughout the code + // + + // + // Adapted from Matrix Inversion by Richard Carling, Graphics Gems . + + // EULA: The Graphics Gems code is copyright-protected. In other words, you cannot claim the text of the code + // as your own and resell it. Using the code is permitted in any program, product, or library, non-commercial + // or commercial. Giving credit is not required, though is a nice gesture. The code comes as-is, and if there + // are any flaws or problems with any Gems code, nobody involved with Gems - authors, editors, publishers, or + // webmasters - are to be held responsible. Basically, don't be a jerk, and remember that anything free comes + // with no guarantee. + + // A clarification about the storage of matrix elements + // + // This class uses a 2 dimensional array internally to store the elements of the matrix. The first index into + // the array refers to the column that the element lies in; the second index refers to the row. + // + // In other words, this is the layout of the matrix: + // + // | m_matrix[0][0] m_matrix[1][0] m_matrix[2][0] m_matrix[3][0] | + // | m_matrix[0][1] m_matrix[1][1] m_matrix[2][1] m_matrix[3][1] | + // | m_matrix[0][2] m_matrix[1][2] m_matrix[2][2] m_matrix[3][2] | + // | m_matrix[0][3] m_matrix[1][3] m_matrix[2][3] m_matrix[3][3] | + + typedef double Vector4[4]; + typedef double Vector3[3]; + + const double SMALL_NUMBER = 1.e-8; + + // inverse(original_matrix, inverse_matrix) + // + // calculate the inverse of a 4x4 matrix + // + // -1 + // A = ___1__ adjoint A + // det A + + // double = determinant2x2(double a, double b, double c, double d) + // + // calculate the determinant of a 2x2 matrix. + + static double determinant2x2(double a, double b, double c, double d) + { + return a * d - b * c; + } + + // double = determinant3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3) + // + // Calculate the determinant of a 3x3 matrix + // in the form + // + // | a1, b1, c1 | + // | a2, b2, c2 | + // | a3, b3, c3 | + + static double determinant3x3(double a1, double a2, double a3, double b1, double b2, double b3, double c1, double c2, double c3) + { + return a1 * determinant2x2(b2, b3, c2, c3) + - b1 * determinant2x2(a2, a3, c2, c3) + + c1 * determinant2x2(a2, a3, b2, b3); + } + + // double = determinant4x4(matrix) + // + // calculate the determinant of a 4x4 matrix. + + static double determinant4x4(const TransformationMatrix::Matrix4& m) + { + // Assign to individual variable names to aid selecting + // correct elements + + double a1 = m[0][0]; + double b1 = m[0][1]; + double c1 = m[0][2]; + double d1 = m[0][3]; + + double a2 = m[1][0]; + double b2 = m[1][1]; + double c2 = m[1][2]; + double d2 = m[1][3]; + + double a3 = m[2][0]; + double b3 = m[2][1]; + double c3 = m[2][2]; + double d3 = m[2][3]; + + double a4 = m[3][0]; + double b4 = m[3][1]; + double c4 = m[3][2]; + double d4 = m[3][3]; + + return a1 * determinant3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4) + - b1 * determinant3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4) + + c1 * determinant3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4) + - d1 * determinant3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4); + } + + // adjoint( original_matrix, inverse_matrix ) + // + // calculate the adjoint of a 4x4 matrix + // + // Let a denote the minor determinant of matrix A obtained by + // ij + // + // deleting the ith row and jth column from A. + // + // i+j + // Let b = (-1) a + // ij ji + // + // The matrix B = (b ) is the adjoint of A + // ij + + static void adjoint(const TransformationMatrix::Matrix4& matrix, TransformationMatrix::Matrix4& result) + { + // Assign to individual variable names to aid + // selecting correct values + double a1 = matrix[0][0]; + double b1 = matrix[0][1]; + double c1 = matrix[0][2]; + double d1 = matrix[0][3]; + + double a2 = matrix[1][0]; + double b2 = matrix[1][1]; + double c2 = matrix[1][2]; + double d2 = matrix[1][3]; + + double a3 = matrix[2][0]; + double b3 = matrix[2][1]; + double c3 = matrix[2][2]; + double d3 = matrix[2][3]; + + double a4 = matrix[3][0]; + double b4 = matrix[3][1]; + double c4 = matrix[3][2]; + double d4 = matrix[3][3]; + + // Row column labeling reversed since we transpose rows & columns + result[0][0] = determinant3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4); + result[1][0] = - determinant3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4); + result[2][0] = determinant3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4); + result[3][0] = - determinant3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4); + + result[0][1] = - determinant3x3(b1, b3, b4, c1, c3, c4, d1, d3, d4); + result[1][1] = determinant3x3(a1, a3, a4, c1, c3, c4, d1, d3, d4); + result[2][1] = - determinant3x3(a1, a3, a4, b1, b3, b4, d1, d3, d4); + result[3][1] = determinant3x3(a1, a3, a4, b1, b3, b4, c1, c3, c4); + + result[0][2] = determinant3x3(b1, b2, b4, c1, c2, c4, d1, d2, d4); + result[1][2] = - determinant3x3(a1, a2, a4, c1, c2, c4, d1, d2, d4); + result[2][2] = determinant3x3(a1, a2, a4, b1, b2, b4, d1, d2, d4); + result[3][2] = - determinant3x3(a1, a2, a4, b1, b2, b4, c1, c2, c4); + + result[0][3] = - determinant3x3(b1, b2, b3, c1, c2, c3, d1, d2, d3); + result[1][3] = determinant3x3(a1, a2, a3, c1, c2, c3, d1, d2, d3); + result[2][3] = - determinant3x3(a1, a2, a3, b1, b2, b3, d1, d2, d3); + result[3][3] = determinant3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3); + } + + // Returns false if the matrix is not invertible + static bool inverse(const TransformationMatrix::Matrix4& matrix, TransformationMatrix::Matrix4& result) + { + // Calculate the adjoint matrix + adjoint(matrix, result); + + // Calculate the 4x4 determinant + // If the determinant is zero, + // then the inverse matrix is not unique. + double det = determinant4x4(matrix); + + if (fabs(det) < SMALL_NUMBER) + return false; + + // Scale the adjoint matrix to get the inverse + + for (int i = 0; i < 4; i++) + for (int j = 0; j < 4; j++) + result[i][j] = result[i][j] / det; + + return true; + } + + // End of code adapted from Matrix Inversion by Richard Carling + + // Perform a decomposition on the passed matrix, return false if unsuccessful + // From Graphics Gems: unmatrix.c + + // Transpose rotation portion of matrix a, return b + static void transposeMatrix4(const TransformationMatrix::Matrix4& a, TransformationMatrix::Matrix4& b) + { + for (int i = 0; i < 4; i++) + for (int j = 0; j < 4; j++) + b[i][j] = a[j][i]; + } + + // Multiply a homogeneous point by a matrix and return the transformed point + static void v4MulPointByMatrix(const Vector4 p, const TransformationMatrix::Matrix4& m, Vector4 result) + { + result[0] = (p[0] * m[0][0]) + (p[1] * m[1][0]) + + (p[2] * m[2][0]) + (p[3] * m[3][0]); + result[1] = (p[0] * m[0][1]) + (p[1] * m[1][1]) + + (p[2] * m[2][1]) + (p[3] * m[3][1]); + result[2] = (p[0] * m[0][2]) + (p[1] * m[1][2]) + + (p[2] * m[2][2]) + (p[3] * m[3][2]); + result[3] = (p[0] * m[0][3]) + (p[1] * m[1][3]) + + (p[2] * m[2][3]) + (p[3] * m[3][3]); + } + + static double v3Length(Vector3 a) + { + return sqrt((a[0] * a[0]) + (a[1] * a[1]) + (a[2] * a[2])); + } + + static void v3Scale(Vector3 v, double desiredLength) + { + double len = v3Length(v); + if (len != 0) { + double l = desiredLength / len; + v[0] *= l; + v[1] *= l; + v[2] *= l; + } + } + + static double v3Dot(const Vector3 a, const Vector3 b) + { + return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]); + } + + // Make a linear combination of two vectors and return the result. + // result = (a * ascl) + (b * bscl) + static void v3Combine(const Vector3 a, const Vector3 b, Vector3 result, double ascl, double bscl) + { + result[0] = (ascl * a[0]) + (bscl * b[0]); + result[1] = (ascl * a[1]) + (bscl * b[1]); + result[2] = (ascl * a[2]) + (bscl * b[2]); + } + + // Return the cross product result = a cross b */ + static void v3Cross(const Vector3 a, const Vector3 b, Vector3 result) + { + result[0] = (a[1] * b[2]) - (a[2] * b[1]); + result[1] = (a[2] * b[0]) - (a[0] * b[2]); + result[2] = (a[0] * b[1]) - (a[1] * b[0]); + } + + static bool decompose(const TransformationMatrix::Matrix4& mat, TransformationMatrix::DecomposedType& result) + { + TransformationMatrix::Matrix4 localMatrix; + memcpy(localMatrix, mat, sizeof(TransformationMatrix::Matrix4)); + + // Normalize the matrix. + if (localMatrix[3][3] == 0) + return false; + + int i, j; + for (i = 0; i < 4; i++) + for (j = 0; j < 4; j++) + localMatrix[i][j] /= localMatrix[3][3]; + + // perspectiveMatrix is used to solve for perspective, but it also provides + // an easy way to test for singularity of the upper 3x3 component. + TransformationMatrix::Matrix4 perspectiveMatrix; + memcpy(perspectiveMatrix, localMatrix, sizeof(TransformationMatrix::Matrix4)); + for (i = 0; i < 3; i++) + perspectiveMatrix[i][3] = 0; + perspectiveMatrix[3][3] = 1; + + if (determinant4x4(perspectiveMatrix) == 0) + return false; + + // First, isolate perspective. This is the messiest. + if (localMatrix[0][3] != 0 || localMatrix[1][3] != 0 || localMatrix[2][3] != 0) { + // rightHandSide is the right hand side of the equation. + Vector4 rightHandSide; + rightHandSide[0] = localMatrix[0][3]; + rightHandSide[1] = localMatrix[1][3]; + rightHandSide[2] = localMatrix[2][3]; + rightHandSide[3] = localMatrix[3][3]; + + // Solve the equation by inverting perspectiveMatrix and multiplying + // rightHandSide by the inverse. (This is the easiest way, not + // necessarily the best.) + TransformationMatrix::Matrix4 inversePerspectiveMatrix, transposedInversePerspectiveMatrix; + inverse(perspectiveMatrix, inversePerspectiveMatrix); + transposeMatrix4(inversePerspectiveMatrix, transposedInversePerspectiveMatrix); + + Vector4 perspectivePoint; + v4MulPointByMatrix(rightHandSide, transposedInversePerspectiveMatrix, perspectivePoint); + + result.perspectiveX = perspectivePoint[0]; + result.perspectiveY = perspectivePoint[1]; + result.perspectiveZ = perspectivePoint[2]; + result.perspectiveW = perspectivePoint[3]; + + // Clear the perspective partition + localMatrix[0][3] = localMatrix[1][3] = localMatrix[2][3] = 0; + localMatrix[3][3] = 1; + } else { + // No perspective. + result.perspectiveX = result.perspectiveY = result.perspectiveZ = 0; + result.perspectiveW = 1; + } + + // Next take care of translation (easy). + result.translateX = localMatrix[3][0]; + localMatrix[3][0] = 0; + result.translateY = localMatrix[3][1]; + localMatrix[3][1] = 0; + result.translateZ = localMatrix[3][2]; + localMatrix[3][2] = 0; + + // Vector4 type and functions need to be added to the common set. + Vector3 row[3], pdum3; + + // Now get scale and shear. + for (i = 0; i < 3; i++) { + row[i][0] = localMatrix[i][0]; + row[i][1] = localMatrix[i][1]; + row[i][2] = localMatrix[i][2]; + } + + // Compute X scale factor and normalize first row. + result.scaleX = v3Length(row[0]); + v3Scale(row[0], 1.0); + + // Compute XY shear factor and make 2nd row orthogonal to 1st. + result.skewXY = v3Dot(row[0], row[1]); + v3Combine(row[1], row[0], row[1], 1.0, -result.skewXY); + + // Now, compute Y scale and normalize 2nd row. + result.scaleY = v3Length(row[1]); + v3Scale(row[1], 1.0); + result.skewXY /= result.scaleY; + + // Compute XZ and YZ shears, orthogonalize 3rd row. + result.skewXZ = v3Dot(row[0], row[2]); + v3Combine(row[2], row[0], row[2], 1.0, -result.skewXZ); + result.skewYZ = v3Dot(row[1], row[2]); + v3Combine(row[2], row[1], row[2], 1.0, -result.skewYZ); + + // Next, get Z scale and normalize 3rd row. + result.scaleZ = v3Length(row[2]); + v3Scale(row[2], 1.0); + result.skewXZ /= result.scaleZ; + result.skewYZ /= result.scaleZ; + + // At this point, the matrix (in rows[]) is orthonormal. + // Check for a coordinate system flip. If the determinant + // is -1, then negate the matrix and the scaling factors. + v3Cross(row[1], row[2], pdum3); + if (v3Dot(row[0], pdum3) < 0) { + + result.scaleX *= -1; + result.scaleY *= -1; + result.scaleZ *= -1; + + for (i = 0; i < 3; i++) { + row[i][0] *= -1; + row[i][1] *= -1; + row[i][2] *= -1; + } + } + + // Now, get the rotations out, as described in the gem. + + result.rotateY = asin(-row[0][2]); + if (cos(result.rotateY) != 0) { + result.rotateX = atan2(row[1][2], row[2][2]); + result.rotateZ = atan2(row[0][1], row[0][0]); + } else { + result.rotateX = atan2(-row[2][0], row[1][1]); + result.rotateZ = 0; + } + + double s, t, x, y, z, w; + + t = row[0][0] + row[1][1] + row[2][2] + 1.0; + + if (t > 1e-4) { + s = 0.5 / sqrt(t); + w = 0.25 / s; + x = (row[2][1] - row[1][2]) * s; + y = (row[0][2] - row[2][0]) * s; + z = (row[1][0] - row[0][1]) * s; + } else if (row[0][0] > row[1][1] && row[0][0] > row[2][2]) { + s = sqrt (1.0 + row[0][0] - row[1][1] - row[2][2]) * 2.0; // S=4*qx + x = 0.25 * s; + y = (row[0][1] + row[1][0]) / s; + z = (row[0][2] + row[2][0]) / s; + w = (row[2][1] - row[1][2]) / s; + } else if (row[1][1] > row[2][2]) { + s = sqrt (1.0 + row[1][1] - row[0][0] - row[2][2]) * 2.0; // S=4*qy + x = (row[0][1] + row[1][0]) / s; + y = 0.25 * s; + z = (row[1][2] + row[2][1]) / s; + w = (row[0][2] - row[2][0]) / s; + } else { + s = sqrt(1.0 + row[2][2] - row[0][0] - row[1][1]) * 2.0; // S=4*qz + x = (row[0][2] + row[2][0]) / s; + y = (row[1][2] + row[2][1]) / s; + z = 0.25 * s; + w = (row[1][0] - row[0][1]) / s; + } + + result.quaternionX = x; + result.quaternionY = y; + result.quaternionZ = z; + result.quaternionW = w; + + return true; + } + + // Perform a spherical linear interpolation between the two + // passed quaternions with 0 <= t <= 1 + static void slerp(double qa[4], const double qb[4], double t) + { + double ax, ay, az, aw; + double bx, by, bz, bw; + double cx, cy, cz, cw; + double angle; + double th, invth, scale, invscale; + + ax = qa[0]; ay = qa[1]; az = qa[2]; aw = qa[3]; + bx = qb[0]; by = qb[1]; bz = qb[2]; bw = qb[3]; + + angle = ax * bx + ay * by + az * bz + aw * bw; + + if (angle < 0.0) { + ax = -ax; ay = -ay; + az = -az; aw = -aw; + angle = -angle; + } + + if (angle + 1.0 > .05) { + if (1.0 - angle >= .05) { + th = acos (angle); + invth = 1.0 / sin (th); + scale = sin (th * (1.0 - t)) * invth; + invscale = sin (th * t) * invth; + } else { + scale = 1.0 - t; + invscale = t; + } + } else { + bx = -ay; + by = ax; + bz = -aw; + bw = az; + scale = sin(M_PI * (.5 - t)); + invscale = sin (M_PI * t); + } + + cx = ax * scale + bx * invscale; + cy = ay * scale + by * invscale; + cz = az * scale + bz * invscale; + cw = aw * scale + bw * invscale; + + qa[0] = cx; qa[1] = cy; qa[2] = cz; qa[3] = cw; + } + + // End of Supporting Math Functions + + TransformationMatrix::TransformationMatrix(const CGAffineTransform& t) + { + setMatrix(t.a, t.b, t.c, t.d, t.tx, t.ty); + } + + TransformationMatrix::TransformationMatrix(const CATransform3D& t) + { + setMatrix( + t.m11, t.m12, t.m13, t.m14, + t.m21, t.m22, t.m23, t.m24, + t.m31, t.m32, t.m33, t.m34, + t.m41, t.m42, t.m43, t.m44); + } + + CATransform3D TransformationMatrix::transform3d() const + { + CATransform3D t; + t.m11 = narrowPrecisionToFloat(m11()); + t.m12 = narrowPrecisionToFloat(m12()); + t.m13 = narrowPrecisionToFloat(m13()); + t.m14 = narrowPrecisionToFloat(m14()); + t.m21 = narrowPrecisionToFloat(m21()); + t.m22 = narrowPrecisionToFloat(m22()); + t.m23 = narrowPrecisionToFloat(m23()); + t.m24 = narrowPrecisionToFloat(m24()); + t.m31 = narrowPrecisionToFloat(m31()); + t.m32 = narrowPrecisionToFloat(m32()); + t.m33 = narrowPrecisionToFloat(m33()); + t.m34 = narrowPrecisionToFloat(m34()); + t.m41 = narrowPrecisionToFloat(m41()); + t.m42 = narrowPrecisionToFloat(m42()); + t.m43 = narrowPrecisionToFloat(m43()); + t.m44 = narrowPrecisionToFloat(m44()); + return t; + } + + CGAffineTransform TransformationMatrix::affineTransform () const + { + CGAffineTransform t; + t.a = narrowPrecisionToFloat(m11()); + t.b = narrowPrecisionToFloat(m12()); + t.c = narrowPrecisionToFloat(m21()); + t.d = narrowPrecisionToFloat(m22()); + t.tx = narrowPrecisionToFloat(m41()); + t.ty = narrowPrecisionToFloat(m42()); + return t; + } + + TransformationMatrix::operator CATransform3D() const + { + return transform3d(); + } + + TransformationMatrix& TransformationMatrix::scale(double s) + { + return scaleNonUniform(s, s); + } + + TransformationMatrix& TransformationMatrix::rotateFromVector(double x, double y) + { + return rotate(rad2deg(atan2(y, x))); + } + + TransformationMatrix& TransformationMatrix::flipX() + { + return scaleNonUniform(-1.0, 1.0); + } + + TransformationMatrix& TransformationMatrix::flipY() + { + return scaleNonUniform(1.0, -1.0); + } + + TransformationMatrix& TransformationMatrix::scaleNonUniform(double sx, double sy) + { + m_matrix[0][0] *= sx; + m_matrix[0][1] *= sx; + m_matrix[0][2] *= sx; + m_matrix[0][3] *= sx; + + m_matrix[1][0] *= sy; + m_matrix[1][1] *= sy; + m_matrix[1][2] *= sy; + m_matrix[1][3] *= sy; + return *this; + } + + TransformationMatrix& TransformationMatrix::scale3d(double sx, double sy, double sz) + { + scaleNonUniform(sx, sy); + + m_matrix[2][0] *= sz; + m_matrix[2][1] *= sz; + m_matrix[2][2] *= sz; + m_matrix[2][3] *= sz; + return *this; + } + + TransformationMatrix& TransformationMatrix::rotate3d(double x, double y, double z, double angle) + { + // Normalize the axis of rotation + double length = sqrt(x * x + y * y + z * z); + if (length == 0) { + // A direction vector that cannot be normalized, such as [0, 0, 0], will cause the rotation to not be applied. + return *this; + } else if (length != 1) { + x /= length; + y /= length; + z /= length; + } + + // Angles are in degrees. Switch to radians. + angle = deg2rad(angle); + + double sinTheta = sin(angle); + double cosTheta = cos(angle); + + TransformationMatrix mat; + + // Optimize cases where the axis is along a major axis + if (x == 1.0 && y == 0.0 && z == 0.0) { + mat.m_matrix[0][0] = 1.0; + mat.m_matrix[0][1] = 0.0; + mat.m_matrix[0][2] = 0.0; + mat.m_matrix[1][0] = 0.0; + mat.m_matrix[1][1] = cosTheta; + mat.m_matrix[1][2] = sinTheta; + mat.m_matrix[2][0] = 0.0; + mat.m_matrix[2][1] = -sinTheta; + mat.m_matrix[2][2] = cosTheta; + mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0; + mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0; + mat.m_matrix[3][3] = 1.0; + } else if (x == 0.0 && y == 1.0 && z == 0.0) { + mat.m_matrix[0][0] = cosTheta; + mat.m_matrix[0][1] = 0.0; + mat.m_matrix[0][2] = -sinTheta; + mat.m_matrix[1][0] = 0.0; + mat.m_matrix[1][1] = 1.0; + mat.m_matrix[1][2] = 0.0; + mat.m_matrix[2][0] = sinTheta; + mat.m_matrix[2][1] = 0.0; + mat.m_matrix[2][2] = cosTheta; + mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0; + mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0; + mat.m_matrix[3][3] = 1.0; + } else if (x == 0.0 && y == 0.0 && z == 1.0) { + mat.m_matrix[0][0] = cosTheta; + mat.m_matrix[0][1] = sinTheta; + mat.m_matrix[0][2] = 0.0; + mat.m_matrix[1][0] = -sinTheta; + mat.m_matrix[1][1] = cosTheta; + mat.m_matrix[1][2] = 0.0; + mat.m_matrix[2][0] = 0.0; + mat.m_matrix[2][1] = 0.0; + mat.m_matrix[2][2] = 1.0; + mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0; + mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0; + mat.m_matrix[3][3] = 1.0; + } else { + // This case is the rotation about an arbitrary unit vector. + // + // Formula is adapted from Wikipedia article on Rotation matrix, + // http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle + // + // An alternate resource with the same matrix: http://www.fastgraph.com/makegames/3drotation/ + // + double oneMinusCosTheta = 1 - cosTheta; + mat.m_matrix[0][0] = cosTheta + x * x * oneMinusCosTheta; + mat.m_matrix[0][1] = y * x * oneMinusCosTheta + z * sinTheta; + mat.m_matrix[0][2] = z * x * oneMinusCosTheta - y * sinTheta; + mat.m_matrix[1][0] = x * y * oneMinusCosTheta - z * sinTheta; + mat.m_matrix[1][1] = cosTheta + y * y * oneMinusCosTheta; + mat.m_matrix[1][2] = z * y * oneMinusCosTheta + x * sinTheta; + mat.m_matrix[2][0] = x * z * oneMinusCosTheta + y * sinTheta; + mat.m_matrix[2][1] = y * z * oneMinusCosTheta - x * sinTheta; + mat.m_matrix[2][2] = cosTheta + z * z * oneMinusCosTheta; + mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0; + mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0; + mat.m_matrix[3][3] = 1.0; + } + multiply(mat); + return *this; + } + + TransformationMatrix& TransformationMatrix::rotate3d(double rx, double ry, double rz) + { + // Angles are in degrees. Switch to radians. + rx = deg2rad(rx); + ry = deg2rad(ry); + rz = deg2rad(rz); + + TransformationMatrix mat; + + double sinTheta = sin(rz); + double cosTheta = cos(rz); + + mat.m_matrix[0][0] = cosTheta; + mat.m_matrix[0][1] = sinTheta; + mat.m_matrix[0][2] = 0.0; + mat.m_matrix[1][0] = -sinTheta; + mat.m_matrix[1][1] = cosTheta; + mat.m_matrix[1][2] = 0.0; + mat.m_matrix[2][0] = 0.0; + mat.m_matrix[2][1] = 0.0; + mat.m_matrix[2][2] = 1.0; + mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0; + mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0; + mat.m_matrix[3][3] = 1.0; + + TransformationMatrix rmat(mat); + + sinTheta = sin(ry); + cosTheta = cos(ry); + + mat.m_matrix[0][0] = cosTheta; + mat.m_matrix[0][1] = 0.0; + mat.m_matrix[0][2] = -sinTheta; + mat.m_matrix[1][0] = 0.0; + mat.m_matrix[1][1] = 1.0; + mat.m_matrix[1][2] = 0.0; + mat.m_matrix[2][0] = sinTheta; + mat.m_matrix[2][1] = 0.0; + mat.m_matrix[2][2] = cosTheta; + mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0; + mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0; + mat.m_matrix[3][3] = 1.0; + + rmat.multiply(mat); + + sinTheta = sin(rx); + cosTheta = cos(rx); + + mat.m_matrix[0][0] = 1.0; + mat.m_matrix[0][1] = 0.0; + mat.m_matrix[0][2] = 0.0; + mat.m_matrix[1][0] = 0.0; + mat.m_matrix[1][1] = cosTheta; + mat.m_matrix[1][2] = sinTheta; + mat.m_matrix[2][0] = 0.0; + mat.m_matrix[2][1] = -sinTheta; + mat.m_matrix[2][2] = cosTheta; + mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0; + mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0; + mat.m_matrix[3][3] = 1.0; + + rmat.multiply(mat); + + multiply(rmat); + return *this; + } + + TransformationMatrix& TransformationMatrix::translate(double tx, double ty) + { + m_matrix[3][0] += tx * m_matrix[0][0] + ty * m_matrix[1][0]; + m_matrix[3][1] += tx * m_matrix[0][1] + ty * m_matrix[1][1]; + m_matrix[3][2] += tx * m_matrix[0][2] + ty * m_matrix[1][2]; + m_matrix[3][3] += tx * m_matrix[0][3] + ty * m_matrix[1][3]; + return *this; + } + + TransformationMatrix& TransformationMatrix::translate3d(double tx, double ty, double tz) + { + m_matrix[3][0] += tx * m_matrix[0][0] + ty * m_matrix[1][0] + tz * m_matrix[2][0]; + m_matrix[3][1] += tx * m_matrix[0][1] + ty * m_matrix[1][1] + tz * m_matrix[2][1]; + m_matrix[3][2] += tx * m_matrix[0][2] + ty * m_matrix[1][2] + tz * m_matrix[2][2]; + m_matrix[3][3] += tx * m_matrix[0][3] + ty * m_matrix[1][3] + tz * m_matrix[2][3]; + return *this; + } + + TransformationMatrix& TransformationMatrix::translateRight(double tx, double ty) + { + if (tx != 0) { + m_matrix[0][0] += m_matrix[0][3] * tx; + m_matrix[1][0] += m_matrix[1][3] * tx; + m_matrix[2][0] += m_matrix[2][3] * tx; + m_matrix[3][0] += m_matrix[3][3] * tx; + } + + if (ty != 0) { + m_matrix[0][1] += m_matrix[0][3] * ty; + m_matrix[1][1] += m_matrix[1][3] * ty; + m_matrix[2][1] += m_matrix[2][3] * ty; + m_matrix[3][1] += m_matrix[3][3] * ty; + } + + return *this; + } + + TransformationMatrix& TransformationMatrix::translateRight3d(double tx, double ty, double tz) + { + translateRight(tx, ty); + if (tz != 0) { + m_matrix[0][2] += m_matrix[0][3] * tz; + m_matrix[1][2] += m_matrix[1][3] * tz; + m_matrix[2][2] += m_matrix[2][3] * tz; + m_matrix[3][2] += m_matrix[3][3] * tz; + } + + return *this; + } + + TransformationMatrix& TransformationMatrix::skew(double sx, double sy) + { + // angles are in degrees. Switch to radians + sx = deg2rad(sx); + sy = deg2rad(sy); + + TransformationMatrix mat; + mat.m_matrix[0][1] = tan(sy); // note that the y shear goes in the first row + mat.m_matrix[1][0] = tan(sx); // and the x shear in the second row + + multiply(mat); + return *this; + } + + TransformationMatrix& TransformationMatrix::applyPerspective(double p) + { + TransformationMatrix mat; + if (p != 0) + mat.m_matrix[2][3] = -1/p; + + multiply(mat); + return *this; + } + + // this = mat * this. + TransformationMatrix& TransformationMatrix::multiply(const TransformationMatrix& mat) + { + Matrix4 tmp; + + tmp[0][0] = (mat.m_matrix[0][0] * m_matrix[0][0] + mat.m_matrix[0][1] * m_matrix[1][0] + + mat.m_matrix[0][2] * m_matrix[2][0] + mat.m_matrix[0][3] * m_matrix[3][0]); + tmp[0][1] = (mat.m_matrix[0][0] * m_matrix[0][1] + mat.m_matrix[0][1] * m_matrix[1][1] + + mat.m_matrix[0][2] * m_matrix[2][1] + mat.m_matrix[0][3] * m_matrix[3][1]); + tmp[0][2] = (mat.m_matrix[0][0] * m_matrix[0][2] + mat.m_matrix[0][1] * m_matrix[1][2] + + mat.m_matrix[0][2] * m_matrix[2][2] + mat.m_matrix[0][3] * m_matrix[3][2]); + tmp[0][3] = (mat.m_matrix[0][0] * m_matrix[0][3] + mat.m_matrix[0][1] * m_matrix[1][3] + + mat.m_matrix[0][2] * m_matrix[2][3] + mat.m_matrix[0][3] * m_matrix[3][3]); + + tmp[1][0] = (mat.m_matrix[1][0] * m_matrix[0][0] + mat.m_matrix[1][1] * m_matrix[1][0] + + mat.m_matrix[1][2] * m_matrix[2][0] + mat.m_matrix[1][3] * m_matrix[3][0]); + tmp[1][1] = (mat.m_matrix[1][0] * m_matrix[0][1] + mat.m_matrix[1][1] * m_matrix[1][1] + + mat.m_matrix[1][2] * m_matrix[2][1] + mat.m_matrix[1][3] * m_matrix[3][1]); + tmp[1][2] = (mat.m_matrix[1][0] * m_matrix[0][2] + mat.m_matrix[1][1] * m_matrix[1][2] + + mat.m_matrix[1][2] * m_matrix[2][2] + mat.m_matrix[1][3] * m_matrix[3][2]); + tmp[1][3] = (mat.m_matrix[1][0] * m_matrix[0][3] + mat.m_matrix[1][1] * m_matrix[1][3] + + mat.m_matrix[1][2] * m_matrix[2][3] + mat.m_matrix[1][3] * m_matrix[3][3]); + + tmp[2][0] = (mat.m_matrix[2][0] * m_matrix[0][0] + mat.m_matrix[2][1] * m_matrix[1][0] + + mat.m_matrix[2][2] * m_matrix[2][0] + mat.m_matrix[2][3] * m_matrix[3][0]); + tmp[2][1] = (mat.m_matrix[2][0] * m_matrix[0][1] + mat.m_matrix[2][1] * m_matrix[1][1] + + mat.m_matrix[2][2] * m_matrix[2][1] + mat.m_matrix[2][3] * m_matrix[3][1]); + tmp[2][2] = (mat.m_matrix[2][0] * m_matrix[0][2] + mat.m_matrix[2][1] * m_matrix[1][2] + + mat.m_matrix[2][2] * m_matrix[2][2] + mat.m_matrix[2][3] * m_matrix[3][2]); + tmp[2][3] = (mat.m_matrix[2][0] * m_matrix[0][3] + mat.m_matrix[2][1] * m_matrix[1][3] + + mat.m_matrix[2][2] * m_matrix[2][3] + mat.m_matrix[2][3] * m_matrix[3][3]); + + tmp[3][0] = (mat.m_matrix[3][0] * m_matrix[0][0] + mat.m_matrix[3][1] * m_matrix[1][0] + + mat.m_matrix[3][2] * m_matrix[2][0] + mat.m_matrix[3][3] * m_matrix[3][0]); + tmp[3][1] = (mat.m_matrix[3][0] * m_matrix[0][1] + mat.m_matrix[3][1] * m_matrix[1][1] + + mat.m_matrix[3][2] * m_matrix[2][1] + mat.m_matrix[3][3] * m_matrix[3][1]); + tmp[3][2] = (mat.m_matrix[3][0] * m_matrix[0][2] + mat.m_matrix[3][1] * m_matrix[1][2] + + mat.m_matrix[3][2] * m_matrix[2][2] + mat.m_matrix[3][3] * m_matrix[3][2]); + tmp[3][3] = (mat.m_matrix[3][0] * m_matrix[0][3] + mat.m_matrix[3][1] * m_matrix[1][3] + + mat.m_matrix[3][2] * m_matrix[2][3] + mat.m_matrix[3][3] * m_matrix[3][3]); + + setMatrix(tmp); + return *this; + } + + void TransformationMatrix::multVecMatrix(double x, double y, double& resultX, double& resultY) const + { + resultX = m_matrix[3][0] + x * m_matrix[0][0] + y * m_matrix[1][0]; + resultY = m_matrix[3][1] + x * m_matrix[0][1] + y * m_matrix[1][1]; + double w = m_matrix[3][3] + x * m_matrix[0][3] + y * m_matrix[1][3]; + if (w != 1 && w != 0) { + resultX /= w; + resultY /= w; + } + } + + void TransformationMatrix::multVecMatrix(double x, double y, double z, double& resultX, double& resultY, double& resultZ) const + { + resultX = m_matrix[3][0] + x * m_matrix[0][0] + y * m_matrix[1][0] + z * m_matrix[2][0]; + resultY = m_matrix[3][1] + x * m_matrix[0][1] + y * m_matrix[1][1] + z * m_matrix[2][1]; + resultZ = m_matrix[3][2] + x * m_matrix[0][2] + y * m_matrix[1][2] + z * m_matrix[2][2]; + double w = m_matrix[3][3] + x * m_matrix[0][3] + y * m_matrix[1][3] + z * m_matrix[2][3]; + if (w != 1 && w != 0) { + resultX /= w; + resultY /= w; + resultZ /= w; + } + } + + bool TransformationMatrix::isInvertible() const + { + if (isIdentityOrTranslation()) + return true; + + double det = WebCore::determinant4x4(m_matrix); + + if (fabs(det) < SMALL_NUMBER) + return false; + + return true; + } + + TransformationMatrix TransformationMatrix::inverse() const + { + if (isIdentityOrTranslation()) { + // identity matrix + if (m_matrix[3][0] == 0 && m_matrix[3][1] == 0 && m_matrix[3][2] == 0) + return TransformationMatrix(); + + // translation + return TransformationMatrix(1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + -m_matrix[3][0], -m_matrix[3][1], -m_matrix[3][2], 1); + } + + TransformationMatrix invMat; + bool inverted = WebCore::inverse(m_matrix, invMat.m_matrix); + if (!inverted) + return TransformationMatrix(); + + return invMat; + } + + void TransformationMatrix::makeAffine() + { + m_matrix[0][2] = 0; + m_matrix[0][3] = 0; + + m_matrix[1][2] = 0; + m_matrix[1][3] = 0; + + m_matrix[2][0] = 0; + m_matrix[2][1] = 0; + m_matrix[2][2] = 1; + m_matrix[2][3] = 0; + + m_matrix[3][2] = 0; + m_matrix[3][3] = 1; + } + + static inline void blendFloat(double& from, double to, double progress) + { + if (from != to) + from = from + (to - from) * progress; + } + + void TransformationMatrix::blend(const TransformationMatrix& from, double progress) + { + if (from.isIdentity() && isIdentity()) + return; + + // decompose + DecomposedType fromDecomp; + DecomposedType toDecomp; + from.decompose(fromDecomp); + decompose(toDecomp); + + // interpolate + blendFloat(fromDecomp.scaleX, toDecomp.scaleX, progress); + blendFloat(fromDecomp.scaleY, toDecomp.scaleY, progress); + blendFloat(fromDecomp.scaleZ, toDecomp.scaleZ, progress); + blendFloat(fromDecomp.skewXY, toDecomp.skewXY, progress); + blendFloat(fromDecomp.skewXZ, toDecomp.skewXZ, progress); + blendFloat(fromDecomp.skewYZ, toDecomp.skewYZ, progress); + blendFloat(fromDecomp.translateX, toDecomp.translateX, progress); + blendFloat(fromDecomp.translateY, toDecomp.translateY, progress); + blendFloat(fromDecomp.translateZ, toDecomp.translateZ, progress); + blendFloat(fromDecomp.perspectiveX, toDecomp.perspectiveX, progress); + blendFloat(fromDecomp.perspectiveY, toDecomp.perspectiveY, progress); + blendFloat(fromDecomp.perspectiveZ, toDecomp.perspectiveZ, progress); + blendFloat(fromDecomp.perspectiveW, toDecomp.perspectiveW, progress); + + slerp(&fromDecomp.quaternionX, &toDecomp.quaternionX, progress); + + // recompose + recompose(fromDecomp); + } + + bool TransformationMatrix::decompose(DecomposedType& decomp) const + { + if (isIdentity()) { + memset(&decomp, 0, sizeof(decomp)); + decomp.perspectiveW = 1; + decomp.scaleX = 1; + decomp.scaleY = 1; + decomp.scaleZ = 1; + } + + if (!WebCore::decompose(m_matrix, decomp)) + return false; + return true; + } + + void TransformationMatrix::recompose(const DecomposedType& decomp, bool useEulerAngle) + { + makeIdentity(); + + // first apply perspective + m_matrix[0][3] = decomp.perspectiveX; + m_matrix[1][3] = decomp.perspectiveY; + m_matrix[2][3] = decomp.perspectiveZ; + m_matrix[3][3] = decomp.perspectiveW; + + // now translate + translate3d(decomp.translateX, decomp.translateY, decomp.translateZ); + + if (!useEulerAngle) { + // apply rotation + double xx = decomp.quaternionX * decomp.quaternionX; + double xy = decomp.quaternionX * decomp.quaternionY; + double xz = decomp.quaternionX * decomp.quaternionZ; + double xw = decomp.quaternionX * decomp.quaternionW; + double yy = decomp.quaternionY * decomp.quaternionY; + double yz = decomp.quaternionY * decomp.quaternionZ; + double yw = decomp.quaternionY * decomp.quaternionW; + double zz = decomp.quaternionZ * decomp.quaternionZ; + double zw = decomp.quaternionZ * decomp.quaternionW; + + // Construct a composite rotation matrix from the quaternion values + TransformationMatrix rotationMatrix(1 - 2 * (yy + zz), 2 * (xy - zw), 2 * (xz + yw), 0, + 2 * (xy + zw), 1 - 2 * (xx + zz), 2 * (yz - xw), 0, + 2 * (xz - yw), 2 * (yz + xw), 1 - 2 * (xx + yy), 0, + 0, 0, 0, 1); + + multiply(rotationMatrix); + } else { + rotate3d(1.0, 0.0, 0.0, rad2deg(decomp.rotateX)); + rotate3d(0.0, 1.0, 0.0, rad2deg(decomp.rotateY)); + rotate3d(0.0, 0.0, 1.0, rad2deg(decomp.rotateZ)); + } + + // now apply skew + if (decomp.skewYZ) { + TransformationMatrix tmp; + tmp.setM32(decomp.skewYZ); + multiply(tmp); + } + + if (decomp.skewXZ) { + TransformationMatrix tmp; + tmp.setM31(decomp.skewXZ); + multiply(tmp); + } + + if (decomp.skewXY) { + TransformationMatrix tmp; + tmp.setM21(decomp.skewXY); + multiply(tmp); + } + + // finally, apply scale + scale3d(decomp.scaleX, decomp.scaleY, decomp.scaleZ); + } +} \ No newline at end of file diff --git a/TalkinToTheNet/Pods/pop/pop/WebCore/TransformationMatrix.h b/TalkinToTheNet/Pods/pop/pop/WebCore/TransformationMatrix.h new file mode 100644 index 0000000..b99ae89 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/WebCore/TransformationMatrix.h @@ -0,0 +1,279 @@ +/* + * Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef TransformationMatrix_h +#define TransformationMatrix_h + +#include //for memcpy + +#include + +#include + +namespace WebCore { + + class TransformationMatrix { + public: + + typedef double Matrix4[4][4]; + + TransformationMatrix() { makeIdentity(); } + TransformationMatrix(const TransformationMatrix& t) { *this = t; } + TransformationMatrix(double a, double b, double c, double d, double e, double f) { setMatrix(a, b, c, d, e, f); } + TransformationMatrix(double m11, double m12, double m13, double m14, + double m21, double m22, double m23, double m24, + double m31, double m32, double m33, double m34, + double m41, double m42, double m43, double m44) + { + setMatrix(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44); + } + + void setMatrix(double a, double b, double c, double d, double e, double f) + { + m_matrix[0][0] = a; m_matrix[0][1] = b; m_matrix[0][2] = 0; m_matrix[0][3] = 0; + m_matrix[1][0] = c; m_matrix[1][1] = d; m_matrix[1][2] = 0; m_matrix[1][3] = 0; + m_matrix[2][0] = 0; m_matrix[2][1] = 0; m_matrix[2][2] = 1; m_matrix[2][3] = 0; + m_matrix[3][0] = e; m_matrix[3][1] = f; m_matrix[3][2] = 0; m_matrix[3][3] = 1; + } + + void setMatrix(double m11, double m12, double m13, double m14, + double m21, double m22, double m23, double m24, + double m31, double m32, double m33, double m34, + double m41, double m42, double m43, double m44) + { + m_matrix[0][0] = m11; m_matrix[0][1] = m12; m_matrix[0][2] = m13; m_matrix[0][3] = m14; + m_matrix[1][0] = m21; m_matrix[1][1] = m22; m_matrix[1][2] = m23; m_matrix[1][3] = m24; + m_matrix[2][0] = m31; m_matrix[2][1] = m32; m_matrix[2][2] = m33; m_matrix[2][3] = m34; + m_matrix[3][0] = m41; m_matrix[3][1] = m42; m_matrix[3][2] = m43; m_matrix[3][3] = m44; + } + + TransformationMatrix& operator =(const TransformationMatrix &t) + { + setMatrix(t.m_matrix); + return *this; + } + + TransformationMatrix& makeIdentity() + { + setMatrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return *this; + } + + bool isIdentity() const + { + return m_matrix[0][0] == 1 && m_matrix[0][1] == 0 && m_matrix[0][2] == 0 && m_matrix[0][3] == 0 && + m_matrix[1][0] == 0 && m_matrix[1][1] == 1 && m_matrix[1][2] == 0 && m_matrix[1][3] == 0 && + m_matrix[2][0] == 0 && m_matrix[2][1] == 0 && m_matrix[2][2] == 1 && m_matrix[2][3] == 0 && + m_matrix[3][0] == 0 && m_matrix[3][1] == 0 && m_matrix[3][2] == 0 && m_matrix[3][3] == 1; + } + + // This form preserves the double math from input to output + void map(double x, double y, double& x2, double& y2) const { multVecMatrix(x, y, x2, y2); } + + double m11() const { return m_matrix[0][0]; } + void setM11(double f) { m_matrix[0][0] = f; } + double m12() const { return m_matrix[0][1]; } + void setM12(double f) { m_matrix[0][1] = f; } + double m13() const { return m_matrix[0][2]; } + void setM13(double f) { m_matrix[0][2] = f; } + double m14() const { return m_matrix[0][3]; } + void setM14(double f) { m_matrix[0][3] = f; } + double m21() const { return m_matrix[1][0]; } + void setM21(double f) { m_matrix[1][0] = f; } + double m22() const { return m_matrix[1][1]; } + void setM22(double f) { m_matrix[1][1] = f; } + double m23() const { return m_matrix[1][2]; } + void setM23(double f) { m_matrix[1][2] = f; } + double m24() const { return m_matrix[1][3]; } + void setM24(double f) { m_matrix[1][3] = f; } + double m31() const { return m_matrix[2][0]; } + void setM31(double f) { m_matrix[2][0] = f; } + double m32() const { return m_matrix[2][1]; } + void setM32(double f) { m_matrix[2][1] = f; } + double m33() const { return m_matrix[2][2]; } + void setM33(double f) { m_matrix[2][2] = f; } + double m34() const { return m_matrix[2][3]; } + void setM34(double f) { m_matrix[2][3] = f; } + double m41() const { return m_matrix[3][0]; } + void setM41(double f) { m_matrix[3][0] = f; } + double m42() const { return m_matrix[3][1]; } + void setM42(double f) { m_matrix[3][1] = f; } + double m43() const { return m_matrix[3][2]; } + void setM43(double f) { m_matrix[3][2] = f; } + double m44() const { return m_matrix[3][3]; } + void setM44(double f) { m_matrix[3][3] = f; } + + double a() const { return m_matrix[0][0]; } + void setA(double a) { m_matrix[0][0] = a; } + + double b() const { return m_matrix[0][1]; } + void setB(double b) { m_matrix[0][1] = b; } + + double c() const { return m_matrix[1][0]; } + void setC(double c) { m_matrix[1][0] = c; } + + double d() const { return m_matrix[1][1]; } + void setD(double d) { m_matrix[1][1] = d; } + + double e() const { return m_matrix[3][0]; } + void setE(double e) { m_matrix[3][0] = e; } + + double f() const { return m_matrix[3][1]; } + void setF(double f) { m_matrix[3][1] = f; } + + // this = this * mat + TransformationMatrix& multiply(const TransformationMatrix&); + + TransformationMatrix& scale(double); + TransformationMatrix& scaleNonUniform(double sx, double sy); + TransformationMatrix& scale3d(double sx, double sy, double sz); + + TransformationMatrix& rotate(double d) { return rotate3d(0, 0, d); } + TransformationMatrix& rotateFromVector(double x, double y); + TransformationMatrix& rotate3d(double rx, double ry, double rz); + + // The vector (x,y,z) is normalized if it's not already. A vector of + // (0,0,0) uses a vector of (0,0,1). + TransformationMatrix& rotate3d(double x, double y, double z, double angle); + + TransformationMatrix& translate(double tx, double ty); + TransformationMatrix& translate3d(double tx, double ty, double tz); + + // translation added with a post-multiply + TransformationMatrix& translateRight(double tx, double ty); + TransformationMatrix& translateRight3d(double tx, double ty, double tz); + + TransformationMatrix& flipX(); + TransformationMatrix& flipY(); + TransformationMatrix& skew(double angleX, double angleY); + TransformationMatrix& skewX(double angle) { return skew(angle, 0); } + TransformationMatrix& skewY(double angle) { return skew(0, angle); } + + TransformationMatrix& applyPerspective(double p); + bool hasPerspective() const { return m_matrix[2][3] != 0.0f; } + + bool isInvertible() const; + + // This method returns the identity matrix if it is not invertible. + // Use isInvertible() before calling this if you need to know. + TransformationMatrix inverse() const; + + // decompose the matrix into its component parts + typedef struct { + double scaleX, scaleY, scaleZ; + double skewXY, skewXZ, skewYZ; + double rotateX, rotateY, rotateZ; + double quaternionX, quaternionY, quaternionZ, quaternionW; + double translateX, translateY, translateZ; + double perspectiveX, perspectiveY, perspectiveZ, perspectiveW; + } DecomposedType; + + bool decompose(DecomposedType& decomp) const; + void recompose(const DecomposedType& decomp, bool useEulerAngle = false); + + void blend(const TransformationMatrix& from, double progress); + + bool isAffine() const + { + return (m13() == 0 && m14() == 0 && m23() == 0 && m24() == 0 && + m31() == 0 && m32() == 0 && m33() == 1 && m34() == 0 && m43() == 0 && m44() == 1); + } + + // Throw away the non-affine parts of the matrix (lossy!) + void makeAffine(); + + bool operator==(const TransformationMatrix& m2) const + { + return (m_matrix[0][0] == m2.m_matrix[0][0] && + m_matrix[0][1] == m2.m_matrix[0][1] && + m_matrix[0][2] == m2.m_matrix[0][2] && + m_matrix[0][3] == m2.m_matrix[0][3] && + m_matrix[1][0] == m2.m_matrix[1][0] && + m_matrix[1][1] == m2.m_matrix[1][1] && + m_matrix[1][2] == m2.m_matrix[1][2] && + m_matrix[1][3] == m2.m_matrix[1][3] && + m_matrix[2][0] == m2.m_matrix[2][0] && + m_matrix[2][1] == m2.m_matrix[2][1] && + m_matrix[2][2] == m2.m_matrix[2][2] && + m_matrix[2][3] == m2.m_matrix[2][3] && + m_matrix[3][0] == m2.m_matrix[3][0] && + m_matrix[3][1] == m2.m_matrix[3][1] && + m_matrix[3][2] == m2.m_matrix[3][2] && + m_matrix[3][3] == m2.m_matrix[3][3]); + } + + bool operator!=(const TransformationMatrix& other) const { return !(*this == other); } + + // *this = *this * t (i.e., a multRight) + TransformationMatrix& operator*=(const TransformationMatrix& t) + { + return multiply(t); + } + + // result = *this * t (i.e., a multRight) + TransformationMatrix operator*(const TransformationMatrix& t) + { + TransformationMatrix result = *this; + result.multiply(t); + return result; + } + + CATransform3D transform3d () const; + CGAffineTransform affineTransform () const; + + TransformationMatrix(const CATransform3D&); + operator CATransform3D() const; + + TransformationMatrix(const CGAffineTransform&); + operator CGAffineTransform() const; + + private: + + // multiply passed 2D point by matrix (assume z=0) + void multVecMatrix(double x, double y, double& dstX, double& dstY) const; + + // multiply passed 3D point by matrix + void multVecMatrix(double x, double y, double z, double& dstX, double& dstY, double& dstZ) const; + + void setMatrix(const Matrix4 m) + { + if (m && m != m_matrix) + memcpy(m_matrix, m, sizeof(Matrix4)); + } + + bool isIdentityOrTranslation() const + { + return m_matrix[0][0] == 1 && m_matrix[0][1] == 0 && m_matrix[0][2] == 0 && m_matrix[0][3] == 0 && + m_matrix[1][0] == 0 && m_matrix[1][1] == 1 && m_matrix[1][2] == 0 && m_matrix[1][3] == 0 && + m_matrix[2][0] == 0 && m_matrix[2][1] == 0 && m_matrix[2][2] == 1 && m_matrix[2][3] == 0 && + m_matrix[3][3] == 1; + } + + Matrix4 m_matrix; + }; + +} // namespace WebCore + +#endif // TransformationMatrix_h diff --git a/TalkinToTheNet/Pods/pop/pop/WebCore/UnitBezier.h b/TalkinToTheNet/Pods/pop/pop/WebCore/UnitBezier.h new file mode 100644 index 0000000..0f847a0 --- /dev/null +++ b/TalkinToTheNet/Pods/pop/pop/WebCore/UnitBezier.h @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef UnitBezier_h +#define UnitBezier_h + +#include + +namespace WebCore { + + struct UnitBezier { + UnitBezier(double p1x, double p1y, double p2x, double p2y) + { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + cx = 3.0 * p1x; + bx = 3.0 * (p2x - p1x) - cx; + ax = 1.0 - cx -bx; + + cy = 3.0 * p1y; + by = 3.0 * (p2y - p1y) - cy; + ay = 1.0 - cy - by; + } + + double sampleCurveX(double t) + { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((ax * t + bx) * t + cx) * t; + } + + double sampleCurveY(double t) + { + return ((ay * t + by) * t + cy) * t; + } + + double sampleCurveDerivativeX(double t) + { + return (3.0 * ax * t + 2.0 * bx) * t + cx; + } + + // Given an x value, find a parametric value it came from. + double solveCurveX(double x, double epsilon) + { + double t0; + double t1; + double t2; + double x2; + double d2; + int i; + + // First try a few iterations of Newton's method -- normally very fast. + for (t2 = x, i = 0; i < 8; i++) { + x2 = sampleCurveX(t2) - x; + if (fabs (x2) < epsilon) + return t2; + d2 = sampleCurveDerivativeX(t2); + if (fabs(d2) < 1e-6) + break; + t2 = t2 - x2 / d2; + } + + // Fall back to the bisection method for reliability. + t0 = 0.0; + t1 = 1.0; + t2 = x; + + if (t2 < t0) + return t0; + if (t2 > t1) + return t1; + + while (t0 < t1) { + x2 = sampleCurveX(t2); + if (fabs(x2 - x) < epsilon) + return t2; + if (x > x2) + t0 = t2; + else + t1 = t2; + t2 = (t1 - t0) * .5 + t0; + } + + // Failure. + return t2; + } + + double solve(double x, double epsilon) + { + return sampleCurveY(solveCurveX(x, epsilon)); + } + + private: + double ax; + double bx; + double cx; + + double ay; + double by; + double cy; + }; +} +#endif diff --git a/TalkinToTheNet/TalkinToTheNet.xcodeproj/project.pbxproj b/TalkinToTheNet/TalkinToTheNet.xcodeproj/project.pbxproj index ee35a70..c3a9ed4 100644 --- a/TalkinToTheNet/TalkinToTheNet.xcodeproj/project.pbxproj +++ b/TalkinToTheNet/TalkinToTheNet.xcodeproj/project.pbxproj @@ -7,25 +7,115 @@ objects = { /* Begin PBXBuildFile section */ + 6B7481131BBCCC92000F5F7A /* InstaPostHeaderView.m in Sources */ = {isa = PBXBuildFile; fileRef = 6B74810E1BBCCC92000F5F7A /* InstaPostHeaderView.m */; settings = {ASSET_TAGS = (); }; }; + 6B7481141BBCCC92000F5F7A /* InstaPostHeaderView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 6B74810F1BBCCC92000F5F7A /* InstaPostHeaderView.xib */; settings = {ASSET_TAGS = (); }; }; + 6B7481151BBCCC92000F5F7A /* InstaPostTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = 6B7481111BBCCC92000F5F7A /* InstaPostTableViewCell.m */; settings = {ASSET_TAGS = (); }; }; + 6B7481161BBCCC92000F5F7A /* InstaPostTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 6B7481121BBCCC92000F5F7A /* InstaPostTableViewCell.xib */; settings = {ASSET_TAGS = (); }; }; + 6B7BFDE71BB5E83C0014B24E /* InstaPost.m in Sources */ = {isa = PBXBuildFile; fileRef = 6B7BFDE61BB5E83C0014B24E /* InstaPost.m */; settings = {ASSET_TAGS = (); }; }; + 6B7BFDEA1BB5E8A30014B24E /* InstagramDetailViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 6B7BFDE91BB5E8A30014B24E /* InstagramDetailViewController.m */; settings = {ASSET_TAGS = (); }; }; + 6B7E7DBA1BBA23C000EDA881 /* MapKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B7E7DB91BBA23C000EDA881 /* MapKit.framework */; }; + 6BA440E91BB0DB5700BEC68E /* APIManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BA440E81BB0DB5700BEC68E /* APIManager.m */; settings = {ASSET_TAGS = (); }; }; + 6BA440EC1BB0DBA700BEC68E /* vegaNomViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BA440EB1BB0DBA700BEC68E /* vegaNomViewController.m */; settings = {ASSET_TAGS = (); }; }; + 6BA440F21BB0DF3900BEC68E /* VegaNomSearchResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BA440F11BB0DF3900BEC68E /* VegaNomSearchResult.m */; settings = {ASSET_TAGS = (); }; }; + 6BA4F96C1BB6DE7300497B07 /* DistProTh.otf in Resources */ = {isa = PBXBuildFile; fileRef = 6BA4F96A1BB6DCFA00497B07 /* DistProTh.otf */; }; + 6BA4F96D1BB6DE7B00497B07 /* FreightSansCmpPro-Light.otf in Resources */ = {isa = PBXBuildFile; fileRef = 6BA4F96B1BB6DD1200497B07 /* FreightSansCmpPro-Light.otf */; }; + 6BC1C0C81BB37D8A00442479 /* NSURLRequest+OAuth.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C09C1BB37D8A00442479 /* NSURLRequest+OAuth.m */; settings = {ASSET_TAGS = (); }; }; + 6BC1C0C91BB37D8A00442479 /* NSMutableURLRequest+Parameters.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0A01BB37D8A00442479 /* NSMutableURLRequest+Parameters.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0CA1BB37D8A00442479 /* NSString+URLEncoding.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0A21BB37D8A00442479 /* NSString+URLEncoding.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0CB1BB37D8A00442479 /* NSURL+Base.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0A41BB37D8A00442479 /* NSURL+Base.m */; settings = {ASSET_TAGS = (); }; }; + 6BC1C0CC1BB37D8A00442479 /* Base64Transcoder.c in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0A61BB37D8A00442479 /* Base64Transcoder.c */; settings = {ASSET_TAGS = (); }; }; + 6BC1C0CD1BB37D8A00442479 /* hmac.c in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0A81BB37D8A00442479 /* hmac.c */; settings = {ASSET_TAGS = (); }; }; + 6BC1C0CE1BB37D8A00442479 /* sha1.c in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0AA1BB37D8A00442479 /* sha1.c */; settings = {ASSET_TAGS = (); }; }; + 6BC1C0CF1BB37D8A00442479 /* OACall.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0AD1BB37D8A00442479 /* OACall.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D01BB37D8A00442479 /* OAConsumer.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0AF1BB37D8A00442479 /* OAConsumer.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D11BB37D8A00442479 /* OADataFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0B11BB37D8A00442479 /* OADataFetcher.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D21BB37D8A00442479 /* OAHMAC_SHA1SignatureProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0B31BB37D8A00442479 /* OAHMAC_SHA1SignatureProvider.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D31BB37D8A00442479 /* OAMutableURLRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0B51BB37D8A00442479 /* OAMutableURLRequest.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D41BB37D8A00442479 /* OAPlaintextSignatureProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0B71BB37D8A00442479 /* OAPlaintextSignatureProvider.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D51BB37D8A00442479 /* OAProblem.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0B91BB37D8A00442479 /* OAProblem.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D61BB37D8A00442479 /* OARequestParameter.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0BB1BB37D8A00442479 /* OARequestParameter.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D71BB37D8A00442479 /* OAServiceTicket.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0BD1BB37D8A00442479 /* OAServiceTicket.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D81BB37D8A00442479 /* OAToken.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0C01BB37D8A00442479 /* OAToken.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0D91BB37D8A00442479 /* OATokenManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 6BC1C0C21BB37D8A00442479 /* OATokenManager.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6BC1C0DC1BB391B500442479 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6BC1C0DB1BB391B500442479 /* Foundation.framework */; }; 8D7DCD4B1BAF859400A92AD2 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D7DCD4A1BAF859400A92AD2 /* main.m */; }; 8D7DCD4E1BAF859400A92AD2 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D7DCD4D1BAF859400A92AD2 /* AppDelegate.m */; }; - 8D7DCD511BAF859400A92AD2 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D7DCD501BAF859400A92AD2 /* ViewController.m */; }; 8D7DCD541BAF859400A92AD2 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8D7DCD521BAF859400A92AD2 /* Main.storyboard */; }; 8D7DCD561BAF859400A92AD2 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8D7DCD551BAF859400A92AD2 /* Assets.xcassets */; }; 8D7DCD591BAF859400A92AD2 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8D7DCD571BAF859400A92AD2 /* LaunchScreen.storyboard */; }; + C51F779A9241E4AC3CA413F5 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = F48C98293323B9B3B5699C62 /* libPods.a */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 6B74810D1BBCCC92000F5F7A /* InstaPostHeaderView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InstaPostHeaderView.h; sourceTree = ""; }; + 6B74810E1BBCCC92000F5F7A /* InstaPostHeaderView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = InstaPostHeaderView.m; sourceTree = ""; }; + 6B74810F1BBCCC92000F5F7A /* InstaPostHeaderView.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = InstaPostHeaderView.xib; sourceTree = ""; }; + 6B7481101BBCCC92000F5F7A /* InstaPostTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InstaPostTableViewCell.h; sourceTree = ""; }; + 6B7481111BBCCC92000F5F7A /* InstaPostTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = InstaPostTableViewCell.m; sourceTree = ""; }; + 6B7481121BBCCC92000F5F7A /* InstaPostTableViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = InstaPostTableViewCell.xib; sourceTree = ""; }; + 6B7BFDE51BB5E83C0014B24E /* InstaPost.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InstaPost.h; sourceTree = ""; }; + 6B7BFDE61BB5E83C0014B24E /* InstaPost.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = InstaPost.m; sourceTree = ""; }; + 6B7BFDE81BB5E8A30014B24E /* InstagramDetailViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InstagramDetailViewController.h; sourceTree = ""; }; + 6B7BFDE91BB5E8A30014B24E /* InstagramDetailViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = InstagramDetailViewController.m; sourceTree = ""; }; + 6B7E7DB91BBA23C000EDA881 /* MapKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MapKit.framework; path = System/Library/Frameworks/MapKit.framework; sourceTree = SDKROOT; }; + 6BA440E71BB0DB5700BEC68E /* APIManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APIManager.h; sourceTree = ""; }; + 6BA440E81BB0DB5700BEC68E /* APIManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = APIManager.m; sourceTree = ""; }; + 6BA440EA1BB0DBA700BEC68E /* vegaNomViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vegaNomViewController.h; sourceTree = ""; }; + 6BA440EB1BB0DBA700BEC68E /* vegaNomViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = vegaNomViewController.m; sourceTree = ""; }; + 6BA440F01BB0DF3900BEC68E /* VegaNomSearchResult.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = VegaNomSearchResult.h; sourceTree = ""; }; + 6BA440F11BB0DF3900BEC68E /* VegaNomSearchResult.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = VegaNomSearchResult.m; sourceTree = ""; }; + 6BA4F96A1BB6DCFA00497B07 /* DistProTh.otf */ = {isa = PBXFileReference; lastKnownFileType = file; path = DistProTh.otf; sourceTree = ""; }; + 6BA4F96B1BB6DD1200497B07 /* FreightSansCmpPro-Light.otf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "FreightSansCmpPro-Light.otf"; sourceTree = ""; }; + 6BC1C09B1BB37D8A00442479 /* NSURLRequest+OAuth.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSURLRequest+OAuth.h"; sourceTree = ""; }; + 6BC1C09C1BB37D8A00442479 /* NSURLRequest+OAuth.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSURLRequest+OAuth.m"; sourceTree = ""; }; + 6BC1C09F1BB37D8A00442479 /* NSMutableURLRequest+Parameters.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSMutableURLRequest+Parameters.h"; sourceTree = ""; }; + 6BC1C0A01BB37D8A00442479 /* NSMutableURLRequest+Parameters.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSMutableURLRequest+Parameters.m"; sourceTree = ""; }; + 6BC1C0A11BB37D8A00442479 /* NSString+URLEncoding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+URLEncoding.h"; sourceTree = ""; }; + 6BC1C0A21BB37D8A00442479 /* NSString+URLEncoding.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+URLEncoding.m"; sourceTree = ""; }; + 6BC1C0A31BB37D8A00442479 /* NSURL+Base.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSURL+Base.h"; sourceTree = ""; }; + 6BC1C0A41BB37D8A00442479 /* NSURL+Base.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSURL+Base.m"; sourceTree = ""; }; + 6BC1C0A61BB37D8A00442479 /* Base64Transcoder.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = Base64Transcoder.c; sourceTree = ""; }; + 6BC1C0A71BB37D8A00442479 /* Base64Transcoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Base64Transcoder.h; sourceTree = ""; }; + 6BC1C0A81BB37D8A00442479 /* hmac.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = hmac.c; sourceTree = ""; }; + 6BC1C0A91BB37D8A00442479 /* hmac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = hmac.h; sourceTree = ""; }; + 6BC1C0AA1BB37D8A00442479 /* sha1.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sha1.c; sourceTree = ""; }; + 6BC1C0AB1BB37D8A00442479 /* sha1.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sha1.h; sourceTree = ""; }; + 6BC1C0AC1BB37D8A00442479 /* OACall.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OACall.h; sourceTree = ""; }; + 6BC1C0AD1BB37D8A00442479 /* OACall.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OACall.m; sourceTree = ""; }; + 6BC1C0AE1BB37D8A00442479 /* OAConsumer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OAConsumer.h; sourceTree = ""; }; + 6BC1C0AF1BB37D8A00442479 /* OAConsumer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OAConsumer.m; sourceTree = ""; }; + 6BC1C0B01BB37D8A00442479 /* OADataFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OADataFetcher.h; sourceTree = ""; }; + 6BC1C0B11BB37D8A00442479 /* OADataFetcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OADataFetcher.m; sourceTree = ""; }; + 6BC1C0B21BB37D8A00442479 /* OAHMAC_SHA1SignatureProvider.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OAHMAC_SHA1SignatureProvider.h; sourceTree = ""; }; + 6BC1C0B31BB37D8A00442479 /* OAHMAC_SHA1SignatureProvider.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OAHMAC_SHA1SignatureProvider.m; sourceTree = ""; }; + 6BC1C0B41BB37D8A00442479 /* OAMutableURLRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OAMutableURLRequest.h; sourceTree = ""; }; + 6BC1C0B51BB37D8A00442479 /* OAMutableURLRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OAMutableURLRequest.m; sourceTree = ""; }; + 6BC1C0B61BB37D8A00442479 /* OAPlaintextSignatureProvider.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OAPlaintextSignatureProvider.h; sourceTree = ""; }; + 6BC1C0B71BB37D8A00442479 /* OAPlaintextSignatureProvider.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OAPlaintextSignatureProvider.m; sourceTree = ""; }; + 6BC1C0B81BB37D8A00442479 /* OAProblem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OAProblem.h; sourceTree = ""; }; + 6BC1C0B91BB37D8A00442479 /* OAProblem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OAProblem.m; sourceTree = ""; }; + 6BC1C0BA1BB37D8A00442479 /* OARequestParameter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OARequestParameter.h; sourceTree = ""; }; + 6BC1C0BB1BB37D8A00442479 /* OARequestParameter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OARequestParameter.m; sourceTree = ""; }; + 6BC1C0BC1BB37D8A00442479 /* OAServiceTicket.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OAServiceTicket.h; sourceTree = ""; }; + 6BC1C0BD1BB37D8A00442479 /* OAServiceTicket.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OAServiceTicket.m; sourceTree = ""; }; + 6BC1C0BE1BB37D8A00442479 /* OASignatureProviding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OASignatureProviding.h; sourceTree = ""; }; + 6BC1C0BF1BB37D8A00442479 /* OAToken.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OAToken.h; sourceTree = ""; }; + 6BC1C0C01BB37D8A00442479 /* OAToken.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OAToken.m; sourceTree = ""; }; + 6BC1C0C11BB37D8A00442479 /* OATokenManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OATokenManager.h; sourceTree = ""; }; + 6BC1C0C21BB37D8A00442479 /* OATokenManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OATokenManager.m; sourceTree = ""; }; + 6BC1C0C31BB37D8A00442479 /* OAuthConsumer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OAuthConsumer.h; sourceTree = ""; }; + 6BC1C0DB1BB391B500442479 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 84DF4379842B073C781E2728 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; 8D7DCD461BAF859400A92AD2 /* TalkinToTheNet.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TalkinToTheNet.app; sourceTree = BUILT_PRODUCTS_DIR; }; 8D7DCD4A1BAF859400A92AD2 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 8D7DCD4C1BAF859400A92AD2 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 8D7DCD4D1BAF859400A92AD2 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - 8D7DCD4F1BAF859400A92AD2 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; - 8D7DCD501BAF859400A92AD2 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 8D7DCD531BAF859400A92AD2 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 8D7DCD551BAF859400A92AD2 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 8D7DCD581BAF859400A92AD2 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 8D7DCD5A1BAF859400A92AD2 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + B286D212E1CC2549FC8F0B0F /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; + F48C98293323B9B3B5699C62 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -33,17 +123,94 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 6B7E7DBA1BBA23C000EDA881 /* MapKit.framework in Frameworks */, + 6BC1C0DC1BB391B500442479 /* Foundation.framework in Frameworks */, + C51F779A9241E4AC3CA413F5 /* libPods.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 6BC1C0991BB37D8A00442479 /* YelpAPI+OAuth */ = { + isa = PBXGroup; + children = ( + 6BC1C09B1BB37D8A00442479 /* NSURLRequest+OAuth.h */, + 6BC1C09C1BB37D8A00442479 /* NSURLRequest+OAuth.m */, + 6BC1C09D1BB37D8A00442479 /* OAuthConsumer */, + ); + name = "YelpAPI+OAuth"; + path = YelpAPISample; + sourceTree = ""; + }; + 6BC1C09D1BB37D8A00442479 /* OAuthConsumer */ = { + isa = PBXGroup; + children = ( + 6BC1C09E1BB37D8A00442479 /* Categories */, + 6BC1C0A51BB37D8A00442479 /* Crytpo */, + 6BC1C0AC1BB37D8A00442479 /* OACall.h */, + 6BC1C0AD1BB37D8A00442479 /* OACall.m */, + 6BC1C0AE1BB37D8A00442479 /* OAConsumer.h */, + 6BC1C0AF1BB37D8A00442479 /* OAConsumer.m */, + 6BC1C0B01BB37D8A00442479 /* OADataFetcher.h */, + 6BC1C0B11BB37D8A00442479 /* OADataFetcher.m */, + 6BC1C0B21BB37D8A00442479 /* OAHMAC_SHA1SignatureProvider.h */, + 6BC1C0B31BB37D8A00442479 /* OAHMAC_SHA1SignatureProvider.m */, + 6BC1C0B41BB37D8A00442479 /* OAMutableURLRequest.h */, + 6BC1C0B51BB37D8A00442479 /* OAMutableURLRequest.m */, + 6BC1C0B61BB37D8A00442479 /* OAPlaintextSignatureProvider.h */, + 6BC1C0B71BB37D8A00442479 /* OAPlaintextSignatureProvider.m */, + 6BC1C0B81BB37D8A00442479 /* OAProblem.h */, + 6BC1C0B91BB37D8A00442479 /* OAProblem.m */, + 6BC1C0BA1BB37D8A00442479 /* OARequestParameter.h */, + 6BC1C0BB1BB37D8A00442479 /* OARequestParameter.m */, + 6BC1C0BC1BB37D8A00442479 /* OAServiceTicket.h */, + 6BC1C0BD1BB37D8A00442479 /* OAServiceTicket.m */, + 6BC1C0BE1BB37D8A00442479 /* OASignatureProviding.h */, + 6BC1C0BF1BB37D8A00442479 /* OAToken.h */, + 6BC1C0C01BB37D8A00442479 /* OAToken.m */, + 6BC1C0C11BB37D8A00442479 /* OATokenManager.h */, + 6BC1C0C21BB37D8A00442479 /* OATokenManager.m */, + 6BC1C0C31BB37D8A00442479 /* OAuthConsumer.h */, + ); + path = OAuthConsumer; + sourceTree = ""; + }; + 6BC1C09E1BB37D8A00442479 /* Categories */ = { + isa = PBXGroup; + children = ( + 6BC1C09F1BB37D8A00442479 /* NSMutableURLRequest+Parameters.h */, + 6BC1C0A01BB37D8A00442479 /* NSMutableURLRequest+Parameters.m */, + 6BC1C0A11BB37D8A00442479 /* NSString+URLEncoding.h */, + 6BC1C0A21BB37D8A00442479 /* NSString+URLEncoding.m */, + 6BC1C0A31BB37D8A00442479 /* NSURL+Base.h */, + 6BC1C0A41BB37D8A00442479 /* NSURL+Base.m */, + ); + path = Categories; + sourceTree = ""; + }; + 6BC1C0A51BB37D8A00442479 /* Crytpo */ = { + isa = PBXGroup; + children = ( + 6BC1C0A61BB37D8A00442479 /* Base64Transcoder.c */, + 6BC1C0A71BB37D8A00442479 /* Base64Transcoder.h */, + 6BC1C0A81BB37D8A00442479 /* hmac.c */, + 6BC1C0A91BB37D8A00442479 /* hmac.h */, + 6BC1C0AA1BB37D8A00442479 /* sha1.c */, + 6BC1C0AB1BB37D8A00442479 /* sha1.h */, + ); + path = Crytpo; + sourceTree = ""; + }; 8D7DCD3D1BAF859400A92AD2 = { isa = PBXGroup; children = ( + 6B7E7DB91BBA23C000EDA881 /* MapKit.framework */, + 6BC1C0DB1BB391B500442479 /* Foundation.framework */, 8D7DCD481BAF859400A92AD2 /* TalkinToTheNet */, 8D7DCD471BAF859400A92AD2 /* Products */, + FDA4082E47CE2F16EEFC77B0 /* Pods */, + CF6ECB3821B0D015564C7F09 /* Frameworks */, ); sourceTree = ""; }; @@ -58,10 +225,25 @@ 8D7DCD481BAF859400A92AD2 /* TalkinToTheNet */ = { isa = PBXGroup; children = ( + 6BC1C0991BB37D8A00442479 /* YelpAPI+OAuth */, 8D7DCD4C1BAF859400A92AD2 /* AppDelegate.h */, 8D7DCD4D1BAF859400A92AD2 /* AppDelegate.m */, - 8D7DCD4F1BAF859400A92AD2 /* ViewController.h */, - 8D7DCD501BAF859400A92AD2 /* ViewController.m */, + 6B74810D1BBCCC92000F5F7A /* InstaPostHeaderView.h */, + 6B74810E1BBCCC92000F5F7A /* InstaPostHeaderView.m */, + 6B74810F1BBCCC92000F5F7A /* InstaPostHeaderView.xib */, + 6B7481101BBCCC92000F5F7A /* InstaPostTableViewCell.h */, + 6B7481111BBCCC92000F5F7A /* InstaPostTableViewCell.m */, + 6B7481121BBCCC92000F5F7A /* InstaPostTableViewCell.xib */, + 6B7BFDE51BB5E83C0014B24E /* InstaPost.h */, + 6B7BFDE61BB5E83C0014B24E /* InstaPost.m */, + 6B7BFDE81BB5E8A30014B24E /* InstagramDetailViewController.h */, + 6B7BFDE91BB5E8A30014B24E /* InstagramDetailViewController.m */, + 6BA440F01BB0DF3900BEC68E /* VegaNomSearchResult.h */, + 6BA440F11BB0DF3900BEC68E /* VegaNomSearchResult.m */, + 6BA440E71BB0DB5700BEC68E /* APIManager.h */, + 6BA440E81BB0DB5700BEC68E /* APIManager.m */, + 6BA440EA1BB0DBA700BEC68E /* vegaNomViewController.h */, + 6BA440EB1BB0DBA700BEC68E /* vegaNomViewController.m */, 8D7DCD521BAF859400A92AD2 /* Main.storyboard */, 8D7DCD551BAF859400A92AD2 /* Assets.xcassets */, 8D7DCD571BAF859400A92AD2 /* LaunchScreen.storyboard */, @@ -74,11 +256,30 @@ 8D7DCD491BAF859400A92AD2 /* Supporting Files */ = { isa = PBXGroup; children = ( + 6BA4F96A1BB6DCFA00497B07 /* DistProTh.otf */, + 6BA4F96B1BB6DD1200497B07 /* FreightSansCmpPro-Light.otf */, 8D7DCD4A1BAF859400A92AD2 /* main.m */, ); name = "Supporting Files"; sourceTree = ""; }; + CF6ECB3821B0D015564C7F09 /* Frameworks */ = { + isa = PBXGroup; + children = ( + F48C98293323B9B3B5699C62 /* libPods.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + FDA4082E47CE2F16EEFC77B0 /* Pods */ = { + isa = PBXGroup; + children = ( + 84DF4379842B073C781E2728 /* Pods.debug.xcconfig */, + B286D212E1CC2549FC8F0B0F /* Pods.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -86,9 +287,11 @@ isa = PBXNativeTarget; buildConfigurationList = 8D7DCD5D1BAF859400A92AD2 /* Build configuration list for PBXNativeTarget "TalkinToTheNet" */; buildPhases = ( + 4264621E69995B05959F1BD6 /* Check Pods Manifest.lock */, 8D7DCD421BAF859400A92AD2 /* Sources */, 8D7DCD431BAF859400A92AD2 /* Frameworks */, 8D7DCD441BAF859400A92AD2 /* Resources */, + 422F40BFC46F56525AD257C2 /* Copy Pods Resources */, ); buildRules = ( ); @@ -110,6 +313,7 @@ TargetAttributes = { 8D7DCD451BAF859400A92AD2 = { CreatedOnToolsVersion = 7.0; + DevelopmentTeam = BA3X38Y2VZ; }; }; }; @@ -136,22 +340,83 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 6BA4F96D1BB6DE7B00497B07 /* FreightSansCmpPro-Light.otf in Resources */, + 6B7481161BBCCC92000F5F7A /* InstaPostTableViewCell.xib in Resources */, + 6BA4F96C1BB6DE7300497B07 /* DistProTh.otf in Resources */, 8D7DCD591BAF859400A92AD2 /* LaunchScreen.storyboard in Resources */, 8D7DCD561BAF859400A92AD2 /* Assets.xcassets in Resources */, 8D7DCD541BAF859400A92AD2 /* Main.storyboard in Resources */, + 6B7481141BBCCC92000F5F7A /* InstaPostHeaderView.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 422F40BFC46F56525AD257C2 /* Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + 4264621E69995B05959F1BD6 /* Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 8D7DCD421BAF859400A92AD2 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 8D7DCD511BAF859400A92AD2 /* ViewController.m in Sources */, + 6BC1C0D31BB37D8A00442479 /* OAMutableURLRequest.m in Sources */, + 6BC1C0D81BB37D8A00442479 /* OAToken.m in Sources */, + 6BC1C0CE1BB37D8A00442479 /* sha1.c in Sources */, + 6B7BFDEA1BB5E8A30014B24E /* InstagramDetailViewController.m in Sources */, + 6BC1C0D41BB37D8A00442479 /* OAPlaintextSignatureProvider.m in Sources */, + 6BC1C0CD1BB37D8A00442479 /* hmac.c in Sources */, + 6BC1C0CA1BB37D8A00442479 /* NSString+URLEncoding.m in Sources */, + 6B7481151BBCCC92000F5F7A /* InstaPostTableViewCell.m in Sources */, + 6BC1C0D71BB37D8A00442479 /* OAServiceTicket.m in Sources */, + 6BC1C0CF1BB37D8A00442479 /* OACall.m in Sources */, + 6BA440F21BB0DF3900BEC68E /* VegaNomSearchResult.m in Sources */, + 6BC1C0D61BB37D8A00442479 /* OARequestParameter.m in Sources */, + 6BC1C0D51BB37D8A00442479 /* OAProblem.m in Sources */, + 6BC1C0D11BB37D8A00442479 /* OADataFetcher.m in Sources */, 8D7DCD4E1BAF859400A92AD2 /* AppDelegate.m in Sources */, + 6B7481131BBCCC92000F5F7A /* InstaPostHeaderView.m in Sources */, + 6BC1C0C91BB37D8A00442479 /* NSMutableURLRequest+Parameters.m in Sources */, + 6BC1C0D21BB37D8A00442479 /* OAHMAC_SHA1SignatureProvider.m in Sources */, + 6BC1C0D91BB37D8A00442479 /* OATokenManager.m in Sources */, 8D7DCD4B1BAF859400A92AD2 /* main.m in Sources */, + 6BA440EC1BB0DBA700BEC68E /* vegaNomViewController.m in Sources */, + 6BC1C0CC1BB37D8A00442479 /* Base64Transcoder.c in Sources */, + 6B7BFDE71BB5E83C0014B24E /* InstaPost.m in Sources */, + 6BA440E91BB0DB5700BEC68E /* APIManager.m in Sources */, + 6BC1C0D01BB37D8A00442479 /* OAConsumer.m in Sources */, + 6BC1C0C81BB37D8A00442479 /* NSURLRequest+OAuth.m in Sources */, + 6BC1C0CB1BB37D8A00442479 /* NSURL+Base.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -259,25 +524,33 @@ }; 8D7DCD5E1BAF859400A92AD2 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 84DF4379842B073C781E2728 /* Pods.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; INFOPLIST_FILE = TalkinToTheNet/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 8.4; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = com.mikekavouras.TalkinToTheNet; + PRODUCT_BUNDLE_IDENTIFIER = com.gartnerjustine.TalkinToTheNet; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; }; name = Debug; }; 8D7DCD5F1BAF859400A92AD2 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = B286D212E1CC2549FC8F0B0F /* Pods.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; INFOPLIST_FILE = TalkinToTheNet/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 8.4; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = com.mikekavouras.TalkinToTheNet; + PRODUCT_BUNDLE_IDENTIFIER = com.gartnerjustine.TalkinToTheNet; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; }; name = Release; }; @@ -300,6 +573,7 @@ 8D7DCD5F1BAF859400A92AD2 /* Release */, ); defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; diff --git a/TalkinToTheNet/TalkinToTheNet.xcworkspace/contents.xcworkspacedata b/TalkinToTheNet/TalkinToTheNet.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1ecaee8 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/TalkinToTheNet/TalkinToTheNet/APIManager.h b/TalkinToTheNet/TalkinToTheNet/APIManager.h new file mode 100644 index 0000000..462ac73 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/APIManager.h @@ -0,0 +1,27 @@ +// +// APIManager.h +// API-Practice +// +// Created by Justine Gartner on 9/20/15. +// Copyright © 2015 Justine Gartner. All rights reserved. +// + +#import +#import + +@interface APIManager : NSObject + ++ (void)getYelpAPIRequestForTerm:(NSString *)term location:(NSString *)location completionHandler:(void (^)(NSArray *businesses, NSError *error))completionHandler; + ++ (NSURLRequest *)_searchRequestWithTerm:(NSString *)term location:(NSString *)location; + ++ (void)GetInstagramAPIRequestWithURL: (NSURL *)url + completionHandler: (void(^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler; + ++ (UIImage *)createImageFromString:(NSString *)urlString; + ++ (NSString *)createAddressFromArray: (NSArray *)addressArray; + ++ (NSString *)createTagFromVenueName: (NSString *)venueName; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/APIManager.m b/TalkinToTheNet/TalkinToTheNet/APIManager.m new file mode 100644 index 0000000..8934384 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/APIManager.m @@ -0,0 +1,133 @@ +// +// APIManager.m +// API-Practice +// +// Created by Justine Gartner on 9/20/15. +// Copyright © 2015 Justine Gartner. All rights reserved. +// + +#import "APIManager.h" +#import "NSURLRequest+OAuth.h" + +/** + Default paths and search terms used in this example + */ +static NSString * const kAPIHost = @"api.yelp.com"; +static NSString * const kSearchPath = @"/v2/search/"; +static NSString * const kBusinessPath = @"/v2/business/"; +static NSString * const kSearchLimit = @"20"; + +@implementation APIManager + +#pragma mark - Yelp API Request Public + ++ (void)getYelpAPIRequestForTerm:(NSString *)term location:(NSString *)location completionHandler:(void (^)(NSArray *businesses, NSError *error))completionHandler { + + NSLog(@"Querying the Search API with term \'%@\' and location \'%@'", term, location); + + //Make a first request to get the search results with the passed term and location + NSURLRequest *searchRequest = [self _searchRequestWithTerm:term location:location]; + + NSURLSession *session = [NSURLSession sharedSession]; + [[session dataTaskWithRequest:searchRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; + + if (!error && httpResponse.statusCode == 200) { + + NSDictionary *searchResponseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; + NSArray *businessArray = searchResponseJSON[@"businesses"]; + + if ([businessArray count] > 0) { + NSDictionary *firstBusiness = [businessArray firstObject]; + NSString *firstBusinessID = firstBusiness[@"id"]; + NSLog(@"%lu businesses found, querying business info for the top result: %@", (unsigned long)[businessArray count], firstBusinessID); + + dispatch_async(dispatch_get_main_queue(), ^{ + completionHandler(businessArray, nil); + }); + + } else { + completionHandler(nil, error); // No business was found + } + } else { + completionHandler(nil, error); // An error happened or the HTTP response is not a 200 OK + } + }] resume]; +} + + +#pragma mark - Yelp API Request Builders + +/** + Builds a request to hit the search endpoint with the given parameters. + + @param term The term of the search, e.g: dinner + @param location The location request, e.g: San Francisco, CA + + @return The NSURLRequest needed to perform the search + */ ++ (NSURLRequest *)_searchRequestWithTerm:(NSString *)term location:(NSString *)location { + NSDictionary *params = @{ + @"term": term, + @"location": location, + @"limit": kSearchLimit + }; + + return [NSURLRequest requestWithHost:kAPIHost path:kSearchPath params:params]; +} + +#pragma mark - data conversion methods + + ++ (UIImage *)createImageFromString:(NSString *)urlString{ + + NSURL *url = [NSURL URLWithString:urlString]; + + NSData *imageData = [NSData dataWithContentsOfURL:url]; + + UIImage *image = [UIImage imageWithData:imageData]; + + return image; + +} + ++ (NSString *)createAddressFromArray: (NSArray *)addressArray{ + + NSString *venueAddress; + + if (addressArray.count == 3) { + + venueAddress = [NSString stringWithFormat:@"%@ %@ %@", addressArray[0], addressArray[1], addressArray[2]]; + + }else if (addressArray.count == 2){ + + venueAddress = [NSString stringWithFormat:@"%@ %@", addressArray[0], addressArray[1]]; + }else{ + + venueAddress = addressArray[0]; + + } + + return venueAddress; +} + ++ (NSString *)createTagFromVenueName: (NSString *)venueName{ + + NSString *vNameApostrophe = [venueName stringByReplacingOccurrencesOfString:@"'" withString:@""]; + NSString *vNameAmpersand = [vNameApostrophe stringByReplacingOccurrencesOfString:@"&" withString:@"and"]; + NSString *vNameDash = [vNameAmpersand stringByReplacingOccurrencesOfString:@"-" withString:@""]; + NSString *vNameE = [vNameDash stringByReplacingOccurrencesOfString:@"é" withString:@"e"]; + NSString *vNameSpaces = [vNameE stringByReplacingOccurrencesOfString:@" " withString:@""]; + NSString *vNameBabyCakesBakery = [vNameSpaces stringByReplacingOccurrencesOfString:@"ErinMcKennasBabyCakes" withString:@"erinmckennasbakery"]; + NSString *vNameExclamation = [vNameBabyCakesBakery stringByReplacingOccurrencesOfString:@"!" withString:@""]; + NSString *vNameI = [vNameExclamation stringByReplacingOccurrencesOfString:@"í" withString:@"i"]; + NSString *vNamePeriod = [vNameI stringByReplacingOccurrencesOfString:@"." withString:@""]; + + NSString *venueTag = [vNamePeriod lowercaseString]; + + return venueTag; +} + + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/AppDelegate.m b/TalkinToTheNet/TalkinToTheNet/AppDelegate.m index d99b336..4adca28 100644 --- a/TalkinToTheNet/TalkinToTheNet/AppDelegate.m +++ b/TalkinToTheNet/TalkinToTheNet/AppDelegate.m @@ -14,11 +14,25 @@ @interface AppDelegate () @implementation AppDelegate - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - // Override point for customization after application launch. +//Fonts added to project +//DistrictPro-Thin +//FreightSansCmpPro-Light + +//To find the font family names +/*- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + + for (NSString* family in [UIFont familyNames]) + { + NSLog(@"%@", family); + + for (NSString* name in [UIFont fontNamesForFamilyName: family]) + { + NSLog(@" %@", name); + } + } + return YES; -} +}*/ - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. diff --git a/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Contents.json b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram.imageset/Contents.json b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram.imageset/Contents.json new file mode 100644 index 0000000..b814470 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "Instagram.jpg", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram.imageset/Instagram.jpg b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram.imageset/Instagram.jpg new file mode 100644 index 0000000..bbaca48 Binary files /dev/null and b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram.imageset/Instagram.jpg differ diff --git a/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram_logo.imageset/Contents.json b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram_logo.imageset/Contents.json new file mode 100644 index 0000000..20ceefb --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram_logo.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "Instagram_logo.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram_logo.imageset/Instagram_logo.png b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram_logo.imageset/Instagram_logo.png new file mode 100644 index 0000000..9916b60 Binary files /dev/null and b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/Instagram_logo.imageset/Instagram_logo.png differ diff --git a/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/instagram_wordmark_detail.dataset/Contents.json b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/instagram_wordmark_detail.dataset/Contents.json new file mode 100644 index 0000000..18b623f --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/instagram_wordmark_detail.dataset/Contents.json @@ -0,0 +1,12 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + }, + "data" : [ + { + "idiom" : "universal", + "filename" : "instagram_wordmark_detail.gif" + } + ] +} \ No newline at end of file diff --git a/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/instagram_wordmark_detail.dataset/instagram_wordmark_detail.gif b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/instagram_wordmark_detail.dataset/instagram_wordmark_detail.gif new file mode 100644 index 0000000..0337c7a Binary files /dev/null and b/TalkinToTheNet/TalkinToTheNet/Assets.xcassets/instagram_wordmark_detail.dataset/instagram_wordmark_detail.gif differ diff --git a/TalkinToTheNet/TalkinToTheNet/Base.lproj/LaunchScreen.storyboard b/TalkinToTheNet/TalkinToTheNet/Base.lproj/LaunchScreen.storyboard index 2e721e1..aa08113 100644 --- a/TalkinToTheNet/TalkinToTheNet/Base.lproj/LaunchScreen.storyboard +++ b/TalkinToTheNet/TalkinToTheNet/Base.lproj/LaunchScreen.storyboard @@ -1,7 +1,8 @@ - + - + + diff --git a/TalkinToTheNet/TalkinToTheNet/Base.lproj/Main.storyboard b/TalkinToTheNet/TalkinToTheNet/Base.lproj/Main.storyboard index f56d2f3..ad55837 100644 --- a/TalkinToTheNet/TalkinToTheNet/Base.lproj/Main.storyboard +++ b/TalkinToTheNet/TalkinToTheNet/Base.lproj/Main.storyboard @@ -1,13 +1,24 @@ - + - + + + + + DistrictPro-Thin + + + FreightSansCmpPro-Light + FreightSansCmpPro-Light + FreightSansCmpPro-Light + + - + - + @@ -15,11 +26,223 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TalkinToTheNet/TalkinToTheNet/DistProTh.otf b/TalkinToTheNet/TalkinToTheNet/DistProTh.otf new file mode 100644 index 0000000..1512dcc Binary files /dev/null and b/TalkinToTheNet/TalkinToTheNet/DistProTh.otf differ diff --git a/TalkinToTheNet/TalkinToTheNet/FreightSansCmpPro-Light.otf b/TalkinToTheNet/TalkinToTheNet/FreightSansCmpPro-Light.otf new file mode 100644 index 0000000..607aee6 Binary files /dev/null and b/TalkinToTheNet/TalkinToTheNet/FreightSansCmpPro-Light.otf differ diff --git a/TalkinToTheNet/TalkinToTheNet/Info.plist b/TalkinToTheNet/TalkinToTheNet/Info.plist index 6905cc6..ffae031 100644 --- a/TalkinToTheNet/TalkinToTheNet/Info.plist +++ b/TalkinToTheNet/TalkinToTheNet/Info.plist @@ -22,6 +22,18 @@ 1 LSRequiresIPhoneOS + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + NSLocationWhenInUseUsageDescription + + UIAppFonts + + DistProTH.otf + FreightSansCmpPro-Light.otf + UILaunchStoryboardName LaunchScreen UIMainStoryboardFile diff --git a/TalkinToTheNet/TalkinToTheNet/InstaPost.h b/TalkinToTheNet/TalkinToTheNet/InstaPost.h new file mode 100644 index 0000000..515fa78 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstaPost.h @@ -0,0 +1,25 @@ +// +// InstaPost.h +// CustomTableViewCells +// +// Created by Justine Gartner on 9/24/15. +// Copyright © 2015 Justine Gartner. All rights reserved. +// + +#import +#import + +@interface InstaPost : NSObject + +@property (nonatomic) NSArray *tags; +@property (nonatomic) NSInteger commentCount; +@property (nonatomic) NSInteger likeCount; +@property (nonatomic) NSString *username; +@property (nonatomic) NSString *fullName; +@property (nonatomic) NSDictionary *caption; +@property (nonatomic) NSString *instaImage; +@property (nonatomic) NSString *avatarImageURL; + +-(instancetype)initWithJSON: (NSDictionary *)json; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/InstaPost.m b/TalkinToTheNet/TalkinToTheNet/InstaPost.m new file mode 100644 index 0000000..876c698 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstaPost.m @@ -0,0 +1,40 @@ +// +// InstaPost.m +// CustomTableViewCells +// +// Created by Justine Gartner on 9/24/15. +// Copyright © 2015 Justine Gartner. All rights reserved. +// + +#import "InstaPost.h" +#import "APIManager.h" + +@implementation InstaPost + +-(instancetype)initWithJSON: (NSDictionary *)json{ + + //call super init, return self + + if (self = [super init]){ + + self.tags = [json objectForKey:@"tags"]; + self.commentCount = [json[@"comments"][@"count"]integerValue]; + self.likeCount = [json[@"likes"][@"count"]integerValue]; + + self.username = json[@"user"][@"username"]; + self.fullName = json[@"user"][@"full_name"]; + self.caption = json[@"caption"]; + + self.instaImage = json[@"images"][@"standard_resolution"][@"url"]; + + self.avatarImageURL = json[@"user"][@"profile_picture"]; + + return self; + + } + + return nil; + +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/InstaPostHeaderView.h b/TalkinToTheNet/TalkinToTheNet/InstaPostHeaderView.h new file mode 100644 index 0000000..b5d5afc --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstaPostHeaderView.h @@ -0,0 +1,18 @@ +// +// InstaPostHeaderView.h +// CustomTableViewCells +// +// Created by Justine Gartner on 9/26/15. +// Copyright © 2015 Justine Gartner. All rights reserved. +// + +#import + +@interface InstaPostHeaderView : UITableViewHeaderFooterView + +@property (weak, nonatomic) IBOutlet UIImageView *imageView; +@property (weak, nonatomic) IBOutlet UILabel *fullNameLabel; +@property (weak, nonatomic) IBOutlet UILabel *usernameLabel; +@property (weak, nonatomic) IBOutlet UILabel *dateStampLabel; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/InstaPostHeaderView.m b/TalkinToTheNet/TalkinToTheNet/InstaPostHeaderView.m new file mode 100644 index 0000000..ac2277c --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstaPostHeaderView.m @@ -0,0 +1,21 @@ +// +// InstaPostHeaderView.m +// CustomTableViewCells +// +// Created by Justine Gartner on 9/26/15. +// Copyright © 2015 Justine Gartner. All rights reserved. +// + +#import "InstaPostHeaderView.h" + +@implementation InstaPostHeaderView + +/* +// Only override drawRect: if you perform custom drawing. +// An empty implementation adversely affects performance during animation. +- (void)drawRect:(CGRect)rect { + // Drawing code +} +*/ + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/InstaPostHeaderView.xib b/TalkinToTheNet/TalkinToTheNet/InstaPostHeaderView.xib new file mode 100644 index 0000000..5fe2f58 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstaPostHeaderView.xib @@ -0,0 +1,70 @@ + + + + + + + + + + FreightSansCmpPro-Light + FreightSansCmpPro-Light + FreightSansCmpPro-Light + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TalkinToTheNet/TalkinToTheNet/InstaPostTableViewCell.h b/TalkinToTheNet/TalkinToTheNet/InstaPostTableViewCell.h new file mode 100644 index 0000000..9f95f46 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstaPostTableViewCell.h @@ -0,0 +1,19 @@ +// +// InstaPostTableViewCell.h +// CustomTableViewCells +// +// Created by Justine Gartner on 9/24/15. +// Copyright © 2015 Justine Gartner. All rights reserved. +// + +#import + +@interface InstaPostTableViewCell : UITableViewCell +@property (weak, nonatomic) IBOutlet UILabel *usernameLabel; +@property (weak, nonatomic) IBOutlet UILabel *likesLabel; +@property (weak, nonatomic) IBOutlet UILabel *tagsLabel; +@property (weak, nonatomic) IBOutlet UILabel *captionLabel; +@property (weak, nonatomic) IBOutlet UILabel *fullName; +@property (weak, nonatomic) IBOutlet UIImageView *userMediaImageView; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/InstaPostTableViewCell.m b/TalkinToTheNet/TalkinToTheNet/InstaPostTableViewCell.m new file mode 100644 index 0000000..2ccf6e4 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstaPostTableViewCell.m @@ -0,0 +1,23 @@ +// +// InstaPostTableViewCell.m +// CustomTableViewCells +// +// Created by Justine Gartner on 9/24/15. +// Copyright © 2015 Justine Gartner. All rights reserved. +// + +#import "InstaPostTableViewCell.h" + +@implementation InstaPostTableViewCell + +- (void)awakeFromNib { + // Initialization code +} + +- (void)setSelected:(BOOL)selected animated:(BOOL)animated { + [super setSelected:selected animated:animated]; + + // Configure the view for the selected state +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/InstaPostTableViewCell.xib b/TalkinToTheNet/TalkinToTheNet/InstaPostTableViewCell.xib new file mode 100644 index 0000000..d3900bd --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstaPostTableViewCell.xib @@ -0,0 +1,83 @@ + + + + + + + + + + FreightSansCmpPro-Light + FreightSansCmpPro-Light + FreightSansCmpPro-Light + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TalkinToTheNet/TalkinToTheNet/InstagramDetailViewController.h b/TalkinToTheNet/TalkinToTheNet/InstagramDetailViewController.h new file mode 100644 index 0000000..4ed6bae --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstagramDetailViewController.h @@ -0,0 +1,16 @@ +// +// InstagramDetailViewController.h +// TalkinToTheNet +// +// Created by Justine Gartner on 9/25/15. +// Copyright © 2015 Mike Kavouras. All rights reserved. +// + +#import +#import "InstaPost.h" + +@interface InstagramDetailViewController : UIViewController + +@property (nonatomic) NSString *venueNameTag; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/InstagramDetailViewController.m b/TalkinToTheNet/TalkinToTheNet/InstagramDetailViewController.m new file mode 100644 index 0000000..f6c809b --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/InstagramDetailViewController.m @@ -0,0 +1,145 @@ +// +// InstagramDetailViewController.m +// TalkinToTheNet +// +// Created by Justine Gartner on 9/25/15. +// Copyright © 2015 Mike Kavouras. All rights reserved. +// + +#import "InstagramDetailViewController.h" +#import "APIManager.h" +#import "InstaPostTableViewCell.h" +#import "InstaPostHeaderView.h" +#import +#import + + +@interface InstagramDetailViewController () + +@property (weak, nonatomic) IBOutlet UILabel *tagLabel; +@property (weak, nonatomic) IBOutlet UITableView *tableView; +@property (weak, nonatomic) IBOutlet UIView *instagramLogoImageView; + +@property (nonatomic) NSMutableArray *searchResults; + +@end + +@implementation InstagramDetailViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + + self.tableView.delegate = self; + self.tableView.dataSource = self; + + self.tagLabel.text = [NSString stringWithFormat:@"#%@", self.venueNameTag]; + + [self fetchInstagramData]; + + //tell the table view to auto adjust the height of each cell + self.tableView.rowHeight = UITableViewAutomaticDimension; + self.tableView.estimatedRowHeight = 44; + + //grab the nib from the main bundle + UINib *nib = [UINib nibWithNibName:@"InstaPostTableViewCell" bundle:nil]; + + //register the nib for the cell identifier + [self.tableView registerNib:nib forCellReuseIdentifier:@"InstaPostCellIdentifier"]; + + //do the same thing here in one line: + [self.tableView registerNib:[UINib nibWithNibName:@"InstaPostHeaderView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"InstaPostHeaderIdentifier"]; + +} + +-(void)fetchInstagramData{ + + NSString *venueNameTagURL = [NSString stringWithFormat:@"https://api.instagram.com/v1/tags/%@/media/recent?client_id=ac0ee52ebb154199bfabfb15b498c067", self.venueNameTag]; + + AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; + + [manager GET:venueNameTagURL parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) { + + NSArray *results = responseObject[@"data"]; + + self.searchResults = [[NSMutableArray alloc] init]; + + for (NSDictionary *result in results){ + + InstaPost *post = [[InstaPost alloc] initWithJSON:result]; + + [self.searchResults addObject:post]; + } + + [self.tableView reloadData]; + + } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) { + + NSLog(@"%@", error); + + }]; + +} + +#pragma mark - Table view data source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { + + return self.searchResults.count; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + + return 1; +} + + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + + InstaPostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InstaPostCellIdentifier" forIndexPath:indexPath]; + + InstaPost *post = self.searchResults[indexPath.section]; + + cell.usernameLabel.text = [NSString stringWithFormat:@"@%@", post.username]; + cell.likesLabel.text = [NSString stringWithFormat:@"Likes: %ld",post.likeCount]; + cell.captionLabel.text = post.caption[@"text"]; + + NSURL *instagramImage = [NSURL URLWithString:post.instaImage]; + + [cell.userMediaImageView sd_setImageWithURL:instagramImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + + cell.userMediaImageView.image = image; + }]; + + return cell; +} + +-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ + + InstaPostHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"InstaPostHeaderIdentifier"]; + + InstaPost *post = self.searchResults[section]; + + headerView.usernameLabel.text = post.username; + headerView.fullNameLabel.text = post.fullName; + + headerView.backgroundView = [[UIView alloc] initWithFrame:headerView.bounds]; + headerView.backgroundView.backgroundColor = [UIColor whiteColor]; + + + NSURL *avatarURL = [NSURL URLWithString:post.instaImage]; + + [headerView.imageView sd_setImageWithURL:avatarURL completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { + headerView.imageView.image = image; + }]; + + return headerView; +} + +-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ + + return 60.0; +} + + + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/VegaNomSearchResult.h b/TalkinToTheNet/TalkinToTheNet/VegaNomSearchResult.h new file mode 100644 index 0000000..9d2a6dc --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/VegaNomSearchResult.h @@ -0,0 +1,20 @@ +// +// VegaNomSearchResult.h +// TalkinToTheNet +// +// Created by Justine Gartner on 9/21/15. +// Copyright © 2015 Mike Kavouras. All rights reserved. +// + +#import +#import + +@interface VegaNomSearchResult : NSObject + +@property (nonatomic) NSString *venueName; +@property (nonatomic) NSString *venueAvatar; +@property (nonatomic) NSMutableArray *venueAddress; + +-(instancetype)initWithAPIResponse: (NSDictionary *)business; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/VegaNomSearchResult.m b/TalkinToTheNet/TalkinToTheNet/VegaNomSearchResult.m new file mode 100644 index 0000000..0038b0e --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/VegaNomSearchResult.m @@ -0,0 +1,29 @@ +// +// VegaNomSearchResult.m +// TalkinToTheNet +// +// Created by Justine Gartner on 9/21/15. +// Copyright © 2015 Mike Kavouras. All rights reserved. +// + +#import "VegaNomSearchResult.h" + +@implementation VegaNomSearchResult + +-(instancetype)initWithAPIResponse: (NSDictionary *)business{ + + if (self = [super init]){ + + self.venueName = business[@"name"]; + + self.venueAddress = business[@"location"][@"display_address"]; + + self.venueAvatar = business[@"image_url"]; + + return self; + } + + return nil; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/ViewController.h b/TalkinToTheNet/TalkinToTheNet/ViewController.h deleted file mode 100644 index 8113a85..0000000 --- a/TalkinToTheNet/TalkinToTheNet/ViewController.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// ViewController.h -// TalkinToTheNet -// -// Created by Michael Kavouras on 9/20/15. -// Copyright © 2015 Mike Kavouras. All rights reserved. -// - -#import - -@interface ViewController : UIViewController - - -@end - diff --git a/TalkinToTheNet/TalkinToTheNet/ViewController.m b/TalkinToTheNet/TalkinToTheNet/ViewController.m deleted file mode 100644 index cbefa29..0000000 --- a/TalkinToTheNet/TalkinToTheNet/ViewController.m +++ /dev/null @@ -1,27 +0,0 @@ -// -// ViewController.m -// TalkinToTheNet -// -// Created by Michael Kavouras on 9/20/15. -// Copyright © 2015 Mike Kavouras. All rights reserved. -// - -#import "ViewController.h" - -@interface ViewController () - -@end - -@implementation ViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - // Do any additional setup after loading the view, typically from a nib. -} - -- (void)didReceiveMemoryWarning { - [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. -} - -@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/NSURLRequest+OAuth.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/NSURLRequest+OAuth.h new file mode 100644 index 0000000..38d1b58 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/NSURLRequest+OAuth.h @@ -0,0 +1,28 @@ +// +// NSURLRequest+OAuth.h +// YelpAPISample +// +// Created by Thibaud Robelain on 7/2/14. +// Copyright (c) 2014 Yelp Inc. All rights reserved. +// + +#import + +@interface NSURLRequest (OAuth) + +/** + @param host The domain host + @param path The path on the domain host + @return Builds a NSURLRequest with all the OAuth headers field set with the host and path given to it. + */ ++ (NSURLRequest *)requestWithHost:(NSString *)host path:(NSString *)path; + +/** + @param host The domain host + @param path The path on the domain host + @param params The query parameters + @return Builds a NSURLRequest with all the OAuth headers field set with the host, path, and query parameters given to it. + */ ++ (NSURLRequest *)requestWithHost:(NSString *)host path:(NSString *)path params:(NSDictionary *)params; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/NSURLRequest+OAuth.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/NSURLRequest+OAuth.m new file mode 100644 index 0000000..9bd61bb --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/NSURLRequest+OAuth.m @@ -0,0 +1,73 @@ +// +// NSURLRequest+OAuth.m +// YelpAPISample +// +// Created by Thibaud Robelain on 7/2/14. +// Copyright (c) 2014 Yelp Inc. All rights reserved. +// + +#import "NSURLRequest+OAuth.h" +#import "OAMutableURLRequest.h" + +/** + OAuth credential placeholders that must be filled by each user in regards to + http://www.yelp.com/developers/getting_started/api_access + */ +#warning Fill in the API keys below with your developer v2 keys. +static NSString * const kConsumerKey = @"E55XCmJCbSrhJ-BtforP4w"; +static NSString * const kConsumerSecret = @"EJrszNNmY8-4t1diOu4FeRu6IyI"; +static NSString * const kToken = @"SV1k-ha9h09pTelPdD9iCtu-0iYp-PEB"; +static NSString * const kTokenSecret = @"cAGd1Lt0bVs7XbTay7X3vsAPCKU"; + +@implementation NSURLRequest (OAuth) + ++ (NSURLRequest *)requestWithHost:(NSString *)host path:(NSString *)path { + return [self requestWithHost:host path:path params:nil]; +} + ++ (NSURLRequest *)requestWithHost:(NSString *)host path:(NSString *)path params:(NSDictionary *)params { + NSURL *URL = [self _URLWithHost:host path:path queryParameters:params]; + + if ([kConsumerKey length] == 0 || [kConsumerSecret length] == 0 || [kToken length] == 0 || [kTokenSecret length] == 0) { + NSLog(@"WARNING: Please enter your api v2 credentials before attempting any API request. You can do so in NSURLRequest+OAuth.m"); + } + + OAConsumer *consumer = [[OAConsumer alloc] initWithKey:kConsumerKey secret:kConsumerSecret]; + OAToken *token = [[OAToken alloc] initWithKey:kToken secret:kTokenSecret]; + + //The signature provider is HMAC-SHA1 by default and the nonce and timestamp are generated in the method + OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:URL consumer:consumer token:token realm:nil signatureProvider:nil]; + [request setHTTPMethod:@"GET"]; + [request prepare]; // Attaches our consumer and token credentials to the request + + return request; +} + +#pragma mark - URL Builder Helper + +/** + Builds an NSURL given a host, path and a number of queryParameters + + @param host The domain host of the API + @param path The path of the API after the domain + @param params The query parameters + @return An NSURL built with the specified parameters +*/ ++ (NSURL *)_URLWithHost:(NSString *)host path:(NSString *)path queryParameters:(NSDictionary *)queryParameters { + + NSMutableArray *queryParts = [[NSMutableArray alloc] init]; + for (NSString *key in [queryParameters allKeys]) { + NSString *queryPart = [NSString stringWithFormat:@"%@=%@", key, queryParameters[key]]; + [queryParts addObject:queryPart]; + } + + NSURLComponents *components = [[NSURLComponents alloc] init]; + components.scheme = @"http"; + components.host = host; + components.path = path; + components.query = [queryParts componentsJoinedByString:@"&"]; + + return [components URL]; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSMutableURLRequest+Parameters.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSMutableURLRequest+Parameters.h new file mode 100644 index 0000000..41eb090 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSMutableURLRequest+Parameters.h @@ -0,0 +1,37 @@ +// +// NSMutableURLRequest+Parameters.h +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 +#import "OARequestParameter.h" +#import "NSURL+Base.h" + + +@interface NSMutableURLRequest (OAParameterAdditions) + +@property(nonatomic, retain) NSArray *parameters; + +- (void)setHTTPBodyWithString:(NSString *)body; +- (void)attachFileWithName:(NSString *)name filename:(NSString*)filename contentType:(NSString *)contentType data:(NSData*)data; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSMutableURLRequest+Parameters.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSMutableURLRequest+Parameters.m new file mode 100644 index 0000000..2e2fe53 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSMutableURLRequest+Parameters.m @@ -0,0 +1,113 @@ +// +// NSMutableURLRequest+Parameters.m +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "NSMutableURLRequest+Parameters.h" + +static NSString *Boundary = @"-----------------------------------0xCoCoaouTHeBouNDaRy"; + +@implementation NSMutableURLRequest (OAParameterAdditions) + +- (BOOL)isMultipart { + return [[self valueForHTTPHeaderField:@"Content-Type"] hasPrefix:@"multipart/form-data"]; +} + +- (NSArray *)parameters { + NSString *encodedParameters = nil; + + if (![self isMultipart]) { + if ([[self HTTPMethod] isEqualToString:@"GET"] || [[self HTTPMethod] isEqualToString:@"DELETE"]) { + encodedParameters = [[self URL] query]; + } else { + encodedParameters = [[[NSString alloc] initWithData:[self HTTPBody] encoding:NSASCIIStringEncoding] autorelease]; + } + } + + if (encodedParameters == nil || [encodedParameters isEqualToString:@""]) { + return nil; + } +// NSLog(@"raw parameters %@", encodedParameters); + NSArray *encodedParameterPairs = [encodedParameters componentsSeparatedByString:@"&"]; + NSMutableArray *requestParameters = [NSMutableArray arrayWithCapacity:[encodedParameterPairs count]]; + + for (NSString *encodedPair in encodedParameterPairs) { + NSArray *encodedPairElements = [encodedPair componentsSeparatedByString:@"="]; + OARequestParameter *parameter = [[OARequestParameter alloc] initWithName:[[encodedPairElements objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] + value:[[encodedPairElements objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + [requestParameters addObject:parameter]; + [parameter release]; + } + + return requestParameters; +} + +- (void)setParameters:(NSArray *)parameters +{ + NSMutableArray *pairs = [[[NSMutableArray alloc] initWithCapacity:[parameters count]] autorelease]; + for (OARequestParameter *requestParameter in parameters) { + [pairs addObject:[requestParameter URLEncodedNameValuePair]]; + } + + NSString *encodedParameterPairs = [pairs componentsJoinedByString:@"&"]; + + if ([[self HTTPMethod] isEqualToString:@"GET"] || [[self HTTPMethod] isEqualToString:@"DELETE"]) { + [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", [[self URL] URLStringWithoutQuery], encodedParameterPairs]]]; + } else { + // POST, PUT + [self setHTTPBodyWithString:encodedParameterPairs]; + [self setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + } +} + +- (void)setHTTPBodyWithString:(NSString *)body { + NSData *bodyData = [body dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; + [self setValue:[NSString stringWithFormat:@"%d", [bodyData length]] forHTTPHeaderField:@"Content-Length"]; + [self setHTTPBody:bodyData]; +} + +- (void)attachFileWithName:(NSString *)name filename:(NSString*)filename contentType:(NSString *)contentType data:(NSData*)data { + + NSArray *parameters = [self parameters]; + [self setValue:[@"multipart/form-data; boundary=" stringByAppendingString:Boundary] forHTTPHeaderField:@"Content-type"]; + + NSMutableData *bodyData = [NSMutableData new]; + for (OARequestParameter *parameter in parameters) { + NSString *param = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n", + Boundary, [parameter URLEncodedName], [parameter value]]; + + [bodyData appendData:[param dataUsingEncoding:NSUTF8StringEncoding]]; + } + + NSString *filePrefix = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\nContent-Type: %@\r\n\r\n", + Boundary, name, filename, contentType]; + [bodyData appendData:[filePrefix dataUsingEncoding:NSUTF8StringEncoding]]; + [bodyData appendData:data]; + + [bodyData appendData:[[[@"--" stringByAppendingString:Boundary] stringByAppendingString:@"--"] dataUsingEncoding:NSUTF8StringEncoding]]; + [self setValue:[NSString stringWithFormat:@"%d", [bodyData length]] forHTTPHeaderField:@"Content-Length"]; + [self setHTTPBody:bodyData]; + [bodyData release]; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSString+URLEncoding.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSString+URLEncoding.h new file mode 100644 index 0000000..01931ed --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSString+URLEncoding.h @@ -0,0 +1,35 @@ +// +// NSString+URLEncoding.h +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 + + +@interface NSString (OAURLEncodingAdditions) + +- (NSString *)encodedURLString; +- (NSString *)encodedURLParameterString; +- (NSString *)decodedURLString; +- (NSString *)removeQuotes; +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSString+URLEncoding.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSString+URLEncoding.m new file mode 100644 index 0000000..7b9880d --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSString+URLEncoding.m @@ -0,0 +1,73 @@ +// +// NSString+URLEncoding.m +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "NSString+URLEncoding.h" + + +@implementation NSString (OAURLEncodingAdditions) + +- (NSString *)encodedURLString { + NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, + (CFStringRef)self, + NULL, // characters to leave unescaped (NULL = all escaped sequences are replaced) + CFSTR("?=&+"), // legal URL characters to be escaped (NULL = all legal characters are replaced) + kCFStringEncodingUTF8); // encoding + return [result autorelease]; +} + +- (NSString *)encodedURLParameterString { + NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, + (CFStringRef)self, + NULL, + CFSTR(":/=,!$&'()*+;[]@#?"), + kCFStringEncodingUTF8); + return [result autorelease]; +} + +- (NSString *)decodedURLString { + NSString *result = (NSString*)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, + (CFStringRef)self, + CFSTR(""), + kCFStringEncodingUTF8); + + return [result autorelease]; + +} + +-(NSString *)removeQuotes +{ + NSUInteger length = [self length]; + NSString *ret = self; + if ([self characterAtIndex:0] == '"') { + ret = [ret substringFromIndex:1]; + } + if ([self characterAtIndex:length - 1] == '"') { + ret = [ret substringToIndex:length - 2]; + } + + return ret; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSURL+Base.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSURL+Base.h new file mode 100644 index 0000000..5d12b69 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSURL+Base.h @@ -0,0 +1,34 @@ +// +// NSURL+Base.h +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 + + +@interface NSURL (OABaseAdditions) + +- (NSString *)URLStringWithoutQuery; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSURL+Base.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSURL+Base.m new file mode 100644 index 0000000..3ebe2c6 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Categories/NSURL+Base.m @@ -0,0 +1,37 @@ +// +// NSURL+Base.m +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "NSURL+Base.h" + + +@implementation NSURL (OABaseAdditions) + +- (NSString *)URLStringWithoutQuery { + NSArray *parts = [[self absoluteString] componentsSeparatedByString:@"?"]; + return [parts objectAtIndex:0]; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/Base64Transcoder.c b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/Base64Transcoder.c new file mode 100644 index 0000000..a655581 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/Base64Transcoder.c @@ -0,0 +1,230 @@ +/* + * Base64Transcoder.c + * Base64Test + * + * Created by Jonathan Wight on Tue Mar 18 2003. + * Copyright (c) 2003 Toxic Software. All rights reserved. + * + * 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. + * + */ + +#include "Base64Transcoder.h" + +#include +#include + +const u_int8_t kBase64EncodeTable[64] = { + /* 0 */ 'A', /* 1 */ 'B', /* 2 */ 'C', /* 3 */ 'D', + /* 4 */ 'E', /* 5 */ 'F', /* 6 */ 'G', /* 7 */ 'H', + /* 8 */ 'I', /* 9 */ 'J', /* 10 */ 'K', /* 11 */ 'L', + /* 12 */ 'M', /* 13 */ 'N', /* 14 */ 'O', /* 15 */ 'P', + /* 16 */ 'Q', /* 17 */ 'R', /* 18 */ 'S', /* 19 */ 'T', + /* 20 */ 'U', /* 21 */ 'V', /* 22 */ 'W', /* 23 */ 'X', + /* 24 */ 'Y', /* 25 */ 'Z', /* 26 */ 'a', /* 27 */ 'b', + /* 28 */ 'c', /* 29 */ 'd', /* 30 */ 'e', /* 31 */ 'f', + /* 32 */ 'g', /* 33 */ 'h', /* 34 */ 'i', /* 35 */ 'j', + /* 36 */ 'k', /* 37 */ 'l', /* 38 */ 'm', /* 39 */ 'n', + /* 40 */ 'o', /* 41 */ 'p', /* 42 */ 'q', /* 43 */ 'r', + /* 44 */ 's', /* 45 */ 't', /* 46 */ 'u', /* 47 */ 'v', + /* 48 */ 'w', /* 49 */ 'x', /* 50 */ 'y', /* 51 */ 'z', + /* 52 */ '0', /* 53 */ '1', /* 54 */ '2', /* 55 */ '3', + /* 56 */ '4', /* 57 */ '5', /* 58 */ '6', /* 59 */ '7', + /* 60 */ '8', /* 61 */ '9', /* 62 */ '+', /* 63 */ '/' +}; + +/* +-1 = Base64 end of data marker. +-2 = White space (tabs, cr, lf, space) +-3 = Noise (all non whitespace, non-base64 characters) +-4 = Dangerous noise +-5 = Illegal noise (null byte) +*/ + +const int8_t kBase64DecodeTable[128] = { + /* 0x00 */ -5, /* 0x01 */ -3, /* 0x02 */ -3, /* 0x03 */ -3, + /* 0x04 */ -3, /* 0x05 */ -3, /* 0x06 */ -3, /* 0x07 */ -3, + /* 0x08 */ -3, /* 0x09 */ -2, /* 0x0a */ -2, /* 0x0b */ -2, + /* 0x0c */ -2, /* 0x0d */ -2, /* 0x0e */ -3, /* 0x0f */ -3, + /* 0x10 */ -3, /* 0x11 */ -3, /* 0x12 */ -3, /* 0x13 */ -3, + /* 0x14 */ -3, /* 0x15 */ -3, /* 0x16 */ -3, /* 0x17 */ -3, + /* 0x18 */ -3, /* 0x19 */ -3, /* 0x1a */ -3, /* 0x1b */ -3, + /* 0x1c */ -3, /* 0x1d */ -3, /* 0x1e */ -3, /* 0x1f */ -3, + /* ' ' */ -2, /* '!' */ -3, /* '"' */ -3, /* '#' */ -3, + /* '$' */ -3, /* '%' */ -3, /* '&' */ -3, /* ''' */ -3, + /* '(' */ -3, /* ')' */ -3, /* '*' */ -3, /* '+' */ 62, + /* ',' */ -3, /* '-' */ -3, /* '.' */ -3, /* '/' */ 63, + /* '0' */ 52, /* '1' */ 53, /* '2' */ 54, /* '3' */ 55, + /* '4' */ 56, /* '5' */ 57, /* '6' */ 58, /* '7' */ 59, + /* '8' */ 60, /* '9' */ 61, /* ':' */ -3, /* ';' */ -3, + /* '<' */ -3, /* '=' */ -1, /* '>' */ -3, /* '?' */ -3, + /* '@' */ -3, /* 'A' */ 0, /* 'B' */ 1, /* 'C' */ 2, + /* 'D' */ 3, /* 'E' */ 4, /* 'F' */ 5, /* 'G' */ 6, + /* 'H' */ 7, /* 'I' */ 8, /* 'J' */ 9, /* 'K' */ 10, + /* 'L' */ 11, /* 'M' */ 12, /* 'N' */ 13, /* 'O' */ 14, + /* 'P' */ 15, /* 'Q' */ 16, /* 'R' */ 17, /* 'S' */ 18, + /* 'T' */ 19, /* 'U' */ 20, /* 'V' */ 21, /* 'W' */ 22, + /* 'X' */ 23, /* 'Y' */ 24, /* 'Z' */ 25, /* '[' */ -3, + /* '\' */ -3, /* ']' */ -3, /* '^' */ -3, /* '_' */ -3, + /* '`' */ -3, /* 'a' */ 26, /* 'b' */ 27, /* 'c' */ 28, + /* 'd' */ 29, /* 'e' */ 30, /* 'f' */ 31, /* 'g' */ 32, + /* 'h' */ 33, /* 'i' */ 34, /* 'j' */ 35, /* 'k' */ 36, + /* 'l' */ 37, /* 'm' */ 38, /* 'n' */ 39, /* 'o' */ 40, + /* 'p' */ 41, /* 'q' */ 42, /* 'r' */ 43, /* 's' */ 44, + /* 't' */ 45, /* 'u' */ 46, /* 'v' */ 47, /* 'w' */ 48, + /* 'x' */ 49, /* 'y' */ 50, /* 'z' */ 51, /* '{' */ -3, + /* '|' */ -3, /* '}' */ -3, /* '~' */ -3, /* 0x7f */ -3 +}; + +const u_int8_t kBits_00000011 = 0x03; +const u_int8_t kBits_00001111 = 0x0F; +const u_int8_t kBits_00110000 = 0x30; +const u_int8_t kBits_00111100 = 0x3C; +const u_int8_t kBits_00111111 = 0x3F; +const u_int8_t kBits_11000000 = 0xC0; +const u_int8_t kBits_11110000 = 0xF0; +const u_int8_t kBits_11111100 = 0xFC; + +size_t EstimateBas64EncodedDataSize(size_t inDataSize) +{ +size_t theEncodedDataSize = (int)ceil(inDataSize / 3.0) * 4; +theEncodedDataSize = theEncodedDataSize / 72 * 74 + theEncodedDataSize % 72; +return(theEncodedDataSize); +} + +size_t EstimateBas64DecodedDataSize(size_t inDataSize) +{ +size_t theDecodedDataSize = (int)ceil(inDataSize / 4.0) * 3; +//theDecodedDataSize = theDecodedDataSize / 72 * 74 + theDecodedDataSize % 72; +return(theDecodedDataSize); +} + +bool Base64EncodeData(const void *inInputData, size_t inInputDataSize, char *outOutputData, size_t *ioOutputDataSize) +{ +size_t theEncodedDataSize = EstimateBas64EncodedDataSize(inInputDataSize); +if (*ioOutputDataSize < theEncodedDataSize) + return(false); +*ioOutputDataSize = theEncodedDataSize; +const u_int8_t *theInPtr = (const u_int8_t *)inInputData; +u_int32_t theInIndex = 0, theOutIndex = 0; +for (; theInIndex < (inInputDataSize / 3) * 3; theInIndex += 3) + { + outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_11111100) >> 2]; + outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_00000011) << 4 | (theInPtr[theInIndex + 1] & kBits_11110000) >> 4]; + outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex + 1] & kBits_00001111) << 2 | (theInPtr[theInIndex + 2] & kBits_11000000) >> 6]; + outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex + 2] & kBits_00111111) >> 0]; + if (theOutIndex % 74 == 72) + { + outOutputData[theOutIndex++] = '\r'; + outOutputData[theOutIndex++] = '\n'; + } + } +const size_t theRemainingBytes = inInputDataSize - theInIndex; +if (theRemainingBytes == 1) + { + outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_11111100) >> 2]; + outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_00000011) << 4 | (0 & kBits_11110000) >> 4]; + outOutputData[theOutIndex++] = '='; + outOutputData[theOutIndex++] = '='; + if (theOutIndex % 74 == 72) + { + outOutputData[theOutIndex++] = '\r'; + outOutputData[theOutIndex++] = '\n'; + } + } +else if (theRemainingBytes == 2) + { + outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_11111100) >> 2]; + outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_00000011) << 4 | (theInPtr[theInIndex + 1] & kBits_11110000) >> 4]; + outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex + 1] & kBits_00001111) << 2 | (0 & kBits_11000000) >> 6]; + outOutputData[theOutIndex++] = '='; + if (theOutIndex % 74 == 72) + { + outOutputData[theOutIndex++] = '\r'; + outOutputData[theOutIndex++] = '\n'; + } + } +return(true); +} + +bool Base64DecodeData(const void *inInputData, size_t inInputDataSize, void *ioOutputData, size_t *ioOutputDataSize) +{ +memset(ioOutputData, '.', *ioOutputDataSize); + +size_t theDecodedDataSize = EstimateBas64DecodedDataSize(inInputDataSize); +if (*ioOutputDataSize < theDecodedDataSize) + return(false); +*ioOutputDataSize = 0; +const u_int8_t *theInPtr = (const u_int8_t *)inInputData; +u_int8_t *theOutPtr = (u_int8_t *)ioOutputData; +size_t theInIndex = 0, theOutIndex = 0; +u_int8_t theOutputOctet; +size_t theSequence = 0; +for (; theInIndex < inInputDataSize; ) + { + int8_t theSextet = 0; + + int8_t theCurrentInputOctet = theInPtr[theInIndex]; + theSextet = kBase64DecodeTable[theCurrentInputOctet]; + if (theSextet == -1) + break; + while (theSextet == -2) + { + theCurrentInputOctet = theInPtr[++theInIndex]; + theSextet = kBase64DecodeTable[theCurrentInputOctet]; + } + while (theSextet == -3) + { + theCurrentInputOctet = theInPtr[++theInIndex]; + theSextet = kBase64DecodeTable[theCurrentInputOctet]; + } + if (theSequence == 0) + { + theOutputOctet = (theSextet >= 0 ? theSextet : 0) << 2 & kBits_11111100; + } + else if (theSequence == 1) + { + theOutputOctet |= (theSextet >- 0 ? theSextet : 0) >> 4 & kBits_00000011; + theOutPtr[theOutIndex++] = theOutputOctet; + } + else if (theSequence == 2) + { + theOutputOctet = (theSextet >= 0 ? theSextet : 0) << 4 & kBits_11110000; + } + else if (theSequence == 3) + { + theOutputOctet |= (theSextet >= 0 ? theSextet : 0) >> 2 & kBits_00001111; + theOutPtr[theOutIndex++] = theOutputOctet; + } + else if (theSequence == 4) + { + theOutputOctet = (theSextet >= 0 ? theSextet : 0) << 6 & kBits_11000000; + } + else if (theSequence == 5) + { + theOutputOctet |= (theSextet >= 0 ? theSextet : 0) >> 0 & kBits_00111111; + theOutPtr[theOutIndex++] = theOutputOctet; + } + theSequence = (theSequence + 1) % 6; + if (theSequence != 2 && theSequence != 4) + theInIndex++; + } +*ioOutputDataSize = theOutIndex; +return(true); +} diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/Base64Transcoder.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/Base64Transcoder.h new file mode 100644 index 0000000..8752098 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/Base64Transcoder.h @@ -0,0 +1,36 @@ +/* + * Base64Transcoder.h + * Base64Test + * + * Created by Jonathan Wight on Tue Mar 18 2003. + * Copyright (c) 2003 Toxic Software. All rights reserved. + * + * 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. + * + */ + +#include +#include + +extern size_t EstimateBas64EncodedDataSize(size_t inDataSize); +extern size_t EstimateBas64DecodedDataSize(size_t inDataSize); + +extern bool Base64EncodeData(const void *inInputData, size_t inInputDataSize, char *outOutputData, size_t *ioOutputDataSize); +extern bool Base64DecodeData(const void *inInputData, size_t inInputDataSize, void *ioOutputData, size_t *ioOutputDataSize); + diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/hmac.c b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/hmac.c new file mode 100644 index 0000000..ea511b2 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/hmac.c @@ -0,0 +1,86 @@ +// +// hmac.c +// OAuthConsumer +// +// Created by Jonathan Wight on 4/8/8. +// Copyright 2008 Jonathan Wight. All rights reserved. +// +// 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. + +/* + * Implementation of HMAC-SHA1. Adapted from example at http://tools.ietf.org/html/rfc2104 + + */ + +#include "sha1.h" + +#include +#include + +void hmac_sha1(const u_int8_t *inText, size_t inTextLength, u_int8_t* inKey, size_t inKeyLength, u_int8_t *outDigest) +{ +#define B 64 +#define L 20 + +SHA1_CTX theSHA1Context; +u_int8_t k_ipad[B + 1]; /* inner padding - key XORd with ipad */ +u_int8_t k_opad[B + 1]; /* outer padding - key XORd with opad */ + +/* if key is longer than 64 bytes reset it to key=SHA1 (key) */ +if (inKeyLength > B) + { + SHA1Init(&theSHA1Context); + SHA1Update(&theSHA1Context, inKey, inKeyLength); + SHA1Final(inKey, &theSHA1Context); + inKeyLength = L; + } + +/* start out by storing key in pads */ +memset(k_ipad, 0, sizeof k_ipad); +memset(k_opad, 0, sizeof k_opad); +memcpy(k_ipad, inKey, inKeyLength); +memcpy(k_opad, inKey, inKeyLength); + +/* XOR key with ipad and opad values */ +int i; +for (i = 0; i < B; i++) + { + k_ipad[i] ^= 0x36; + k_opad[i] ^= 0x5c; + } + +/* +* perform inner SHA1 +*/ +SHA1Init(&theSHA1Context); /* init context for 1st pass */ +SHA1Update(&theSHA1Context, k_ipad, B); /* start with inner pad */ +SHA1Update(&theSHA1Context, (u_int8_t *)inText, inTextLength); /* then text of datagram */ +SHA1Final((u_int8_t *)outDigest, &theSHA1Context); /* finish up 1st pass */ + +/* +* perform outer SHA1 +*/ +SHA1Init(&theSHA1Context); /* init context for 2nd +* pass */ +SHA1Update(&theSHA1Context, k_opad, B); /* start with outer pad */ +SHA1Update(&theSHA1Context, (u_int8_t *)outDigest, L); /* then results of 1st +* hash */ +SHA1Final((u_int8_t *)outDigest, &theSHA1Context); /* finish up 2nd pass */ + +} \ No newline at end of file diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/hmac.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/hmac.h new file mode 100644 index 0000000..67530ba --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/hmac.h @@ -0,0 +1,31 @@ +// +// hmac.h +// OAuthConsumer +// +// Created by Jonathan Wight on 4/8/8. +// Copyright 2008 Jonathan Wight. All rights reserved. +// +// 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. + +#ifndef HMAC_H +#define HMAC_H 1 + +extern void hmac_sha1(const u_int8_t *inText, size_t inTextLength, u_int8_t* inKey, const size_t inKeyLength, u_int8_t *outDigest); + +#endif /* HMAC_H */ \ No newline at end of file diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/sha1.c b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/sha1.c new file mode 100644 index 0000000..54dd2fa --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/sha1.c @@ -0,0 +1,169 @@ +/* +SHA-1 in C +By Steve Reid +100% Public Domain + +Test Vectors (from FIPS PUB 180-1) +"abc" + A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D +"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" + 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 +A million repetitions of "a" + 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F +*/ + +/* #define LITTLE_ENDIAN * This should be #define'd if true. */ +#if __LITTLE_ENDIAN__ +#define LITTLE_ENDIAN +#endif +/* #define SHA1HANDSOFF * Copies data before messing with it. */ + +#include +#include + +#include "sha1.h" + +void SHA1Transform(u_int32_t state[5], u_int8_t buffer[64]); + +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) + +/* blk0() and blk() perform the initial expand. */ +/* I got the idea of expanding during the round function from SSLeay */ +#ifdef LITTLE_ENDIAN +#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ + |(rol(block->l[i],8)&0x00FF00FF)) +#else +#define blk0(i) block->l[i] +#endif +#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ + ^block->l[(i+2)&15]^block->l[i&15],1)) + +/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ +#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); +#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); +#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); + + +/* Hash a single 512-bit block. This is the core of the algorithm. */ + +void SHA1Transform(u_int32_t state[5], u_int8_t buffer[64]) +{ +u_int32_t a, b, c, d, e; +typedef union { + u_int8_t c[64]; + u_int32_t l[16]; +} CHAR64LONG16; +CHAR64LONG16* block; +#ifdef SHA1HANDSOFF +static u_int8_t workspace[64]; + block = (CHAR64LONG16*)workspace; + memcpy(block, buffer, 64); +#else + block = (CHAR64LONG16*)buffer; +#endif + /* Copy context->state[] to working vars */ + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + /* 4 rounds of 20 operations each. Loop unrolled. */ + R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); + R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); + R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); + R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); + R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); + R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); + R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); + R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); + R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); + R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); + R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); + R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); + R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); + R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); + R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); + R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); + R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); + R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); + R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); + R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); + /* Add the working vars back into context.state[] */ + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + /* Wipe variables */ + a = b = c = d = e = 0; +} + + +/* SHA1Init - Initialize new context */ + +void SHA1Init(SHA1_CTX* context) +{ + /* SHA1 initialization constants */ + context->state[0] = 0x67452301; + context->state[1] = 0xEFCDAB89; + context->state[2] = 0x98BADCFE; + context->state[3] = 0x10325476; + context->state[4] = 0xC3D2E1F0; + context->count[0] = context->count[1] = 0; +} + + +/* Run your data through this. */ + +void SHA1Update(SHA1_CTX* context, u_int8_t* data, unsigned int len) +{ +unsigned int i, j; + + j = (context->count[0] >> 3) & 63; + if ((context->count[0] += len << 3) < (len << 3)) context->count[1]++; + context->count[1] += (len >> 29); + if ((j + len) > 63) { + memcpy(&context->buffer[j], data, (i = 64-j)); + SHA1Transform(context->state, context->buffer); + for ( ; i + 63 < len; i += 64) { + SHA1Transform(context->state, &data[i]); + } + j = 0; + } + else i = 0; + memcpy(&context->buffer[j], &data[i], len - i); +} + + +/* Add padding and return the message digest. */ + +void SHA1Final(u_int8_t digest[20], SHA1_CTX* context) +{ +u_int32_t i, j; +u_int8_t finalcount[8]; + + for (i = 0; i < 8; i++) { + finalcount[i] = (u_int8_t)((context->count[(i >= 4 ? 0 : 1)] + >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ + } + SHA1Update(context, (u_int8_t *)"\200", 1); + while ((context->count[0] & 504) != 448) { + SHA1Update(context, (u_int8_t *)"\0", 1); + } + SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ + for (i = 0; i < 20; i++) { + digest[i] = (u_int8_t) + ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); + } + /* Wipe variables */ + i = j = 0; + memset(context->buffer, 0, 64); + memset(context->state, 0, 20); + memset(context->count, 0, 8); + memset(&finalcount, 0, 8); +#ifdef SHA1HANDSOFF /* make SHA1Transform overwrite it's own static vars */ + SHA1Transform(context->state, context->buffer); +#endif +} diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/sha1.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/sha1.h new file mode 100644 index 0000000..76f7051 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/Crytpo/sha1.h @@ -0,0 +1,14 @@ + +// From http://www.mirrors.wiretapped.net/security/cryptography/hashes/sha1/sha1.c + +#include + +typedef struct { + u_int32_t state[5]; + u_int32_t count[2]; + u_int8_t buffer[64]; +} SHA1_CTX; + +extern void SHA1Init(SHA1_CTX* context); +extern void SHA1Update(SHA1_CTX* context, u_int8_t* data, u_int32_t len); +extern void SHA1Final(u_int8_t digest[20], SHA1_CTX* context); diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OACall.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OACall.h new file mode 100644 index 0000000..92c6ffa --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OACall.h @@ -0,0 +1,63 @@ +// +// OACall.h +// OAuthConsumer +// +// Created by Alberto García Hierro on 04/09/08. +// Copyright 2008 Alberto García Hierro. All rights reserved. +// bynotes.com + +#import + +@class OAProblem; +@class OACall; + +@protocol OACallDelegate + +- (void)call:(OACall *)call failedWithError:(NSError *)error; +- (void)call:(OACall *)call failedWithProblem:(OAProblem *)problem; + +@end + +@class OAConsumer; +@class OAToken; +@class OADataFetcher; +@class OAMutableURLRequest; +@class OAServiceTicket; + +@interface OACall : NSObject { + NSURL *url; + NSString *method; + NSArray *parameters; + NSDictionary *files; + NSObject *delegate; + SEL finishedSelector; + OADataFetcher *fetcher; + OAMutableURLRequest *request; + OAServiceTicket *ticket; +} + +@property(readonly) NSURL *url; +@property(readonly) NSString *method; +@property(readonly) NSArray *parameters; +@property(readonly) NSDictionary *files; +@property(nonatomic, retain) OAServiceTicket *ticket; + +- (id)init; +- (id)initWithURL:(NSURL *)aURL; +- (id)initWithURL:(NSURL *)aURL method:(NSString *)aMethod; +- (id)initWithURL:(NSURL *)aURL parameters:(NSArray *)theParameters; +- (id)initWithURL:(NSURL *)aURL method:(NSString *)aMethod parameters:(NSArray *)theParameters; +- (id)initWithURL:(NSURL *)aURL parameters:(NSArray *)theParameters files:(NSDictionary*)theFiles; + +- (id)initWithURL:(NSURL *)aURL + method:(NSString *)aMethod + parameters:(NSArray *)theParameters + files:(NSDictionary*)theFiles; + +- (void)perform:(OAConsumer *)consumer + token:(OAToken *)token + realm:(NSString *)realm + delegate:(NSObject *)aDelegate + didFinish:(SEL)finished; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OACall.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OACall.m new file mode 100644 index 0000000..dcc88b9 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OACall.m @@ -0,0 +1,168 @@ +// +// OACall.m +// OAuthConsumer +// +// Created by Alberto García Hierro on 04/09/08. +// Copyright 2008 Alberto García Hierro. All rights reserved. +// bynotes.com + +#import "OAConsumer.h" +#import "OAToken.h" +#import "OAProblem.h" +#import "OADataFetcher.h" +#import "OAServiceTicket.h" +#import "OAMutableURLRequest.h" +#import "OACall.h" + +@interface OACall (Private) + +- (void)callFinished:(OAServiceTicket *)ticket withData:(NSData *)data; +- (void)callFailed:(OAServiceTicket *)ticket withError:(NSError *)error; + +@end + +@implementation OACall + +@synthesize url, method, parameters, files, ticket; + +- (id)init { + return [self initWithURL:nil + method:nil + parameters:nil + files:nil]; +} + +- (id)initWithURL:(NSURL *)aURL { + return [self initWithURL:aURL + method:nil + parameters:nil + files:nil]; +} + +- (id)initWithURL:(NSURL *)aURL method:(NSString *)aMethod { + return [self initWithURL:aURL + method:aMethod + parameters:nil + files:nil]; +} + +- (id)initWithURL:(NSURL *)aURL parameters:(NSArray *)theParameters { + return [self initWithURL:aURL + method:nil + parameters:theParameters]; +} + +- (id)initWithURL:(NSURL *)aURL method:(NSString *)aMethod parameters:(NSArray *)theParameters { + return [self initWithURL:aURL + method:aMethod + parameters:theParameters + files:nil]; +} + +- (id)initWithURL:(NSURL *)aURL parameters:(NSArray *)theParameters files:(NSDictionary*)theFiles { + return [self initWithURL:aURL + method:@"POST" + parameters:theParameters + files:theFiles]; +} + +- (id)initWithURL:(NSURL *)aURL + method:(NSString *)aMethod + parameters:(NSArray *)theParameters + files:(NSDictionary*)theFiles { + url = [aURL retain]; + method = [aMethod retain]; + parameters = [theParameters retain]; + files = [theFiles retain]; + fetcher = nil; + request = nil; + + return self; +} + +- (void)dealloc { + [url release]; + [method release]; + [parameters release]; + [files release]; + [fetcher release]; + [request release]; + [ticket release]; + [super dealloc]; +} + +- (void)callFailed:(OAServiceTicket *)aTicket withError:(NSError *)error { + NSLog(@"error body: %@", aTicket.body); + self.ticket = aTicket; + [aTicket release]; + OAProblem *problem = [OAProblem problemWithResponseBody:ticket.body]; + if (problem) { + [delegate call:self failedWithProblem:problem]; + } else { + [delegate call:self failedWithError:error]; + } +} + +- (void)callFinished:(OAServiceTicket *)aTicket withData:(NSData *)data { + self.ticket = aTicket; + [aTicket release]; + if (ticket.didSucceed) { +// NSLog(@"Call body: %@", ticket.body); + [delegate performSelector:finishedSelector withObject:self withObject:ticket.body]; + } else { +// NSLog(@"Failed call body: %@", ticket.body); + [self callFailed:[ticket retain] withError:nil]; + } +} + +- (void)perform:(OAConsumer *)consumer + token:(OAToken *)token + realm:(NSString *)realm + delegate:(NSObject *)aDelegate + didFinish:(SEL)finished + +{ + delegate = aDelegate; + finishedSelector = finished; + + request = [[OAMutableURLRequest alloc] initWithURL:url + consumer:consumer + token:token + realm:realm + signatureProvider:nil]; + if(method) { + [request setHTTPMethod:method]; + } + + if (self.parameters) { + [request setParameters:self.parameters]; + } + if (self.files) { + for (NSString *key in self.files) { + [request attachFileWithName:@"file" filename:NSLocalizedString(@"Photo.jpg", @"") data:[self.files objectForKey:key]]; + } + } + fetcher = [[OADataFetcher alloc] init]; + [fetcher fetchDataWithRequest:request + delegate:self + didFinishSelector:@selector(callFinished:withData:) + didFailSelector:@selector(callFailed:withError:)]; +} + +/*- (BOOL)isEqual:(id)object { + if ([object isKindOfClass:[self class]]) { + return [self isEqualToCall:(OACall *)object]; + } + return NO; +} + +- (BOOL)isEqualToCall:(OACall *)aCall { + return (delegate == aCall->delegate + && finishedSelector == aCall->finishedSelector + && [url isEqualTo:aCall.url] + && [method isEqualToString:aCall.method] + && [parameters isEqualToArray:aCall.parameters] + && [files isEqualToDictionary:aCall.files]); +}*/ + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAConsumer.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAConsumer.h new file mode 100644 index 0000000..5990028 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAConsumer.h @@ -0,0 +1,42 @@ +// +// OAConsumer.h +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 + + +@interface OAConsumer : NSObject { +@protected + NSString *key; + NSString *secret; +} +@property(copy, readwrite) NSString *key; +@property(copy, readwrite) NSString *secret; + +- (id)initWithKey:(const NSString *)aKey secret:(const NSString *)aSecret; + +- (BOOL)isEqualToConsumer:(OAConsumer *)aConsumer; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAConsumer.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAConsumer.m new file mode 100644 index 0000000..1545c95 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAConsumer.m @@ -0,0 +1,53 @@ +// +// OAConsumer.m +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "OAConsumer.h" + + +@implementation OAConsumer +@synthesize key, secret; + +#pragma mark init + +- (id)initWithKey:(const NSString *)aKey secret:(const NSString *)aSecret { + [super init]; + self.key = [aKey retain]; + self.secret = [aSecret retain]; + return self; +} + +- (BOOL)isEqual:(id)object { + if ([object isKindOfClass:[self class]]) { + return [self isEqualToConsumer:(OAConsumer*)object]; + } + return NO; +} + +- (BOOL)isEqualToConsumer:(OAConsumer *)aConsumer { + return ([self.key isEqualToString:aConsumer.key] && + [self.secret isEqualToString:aConsumer.secret]); +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OADataFetcher.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OADataFetcher.h new file mode 100644 index 0000000..8afeb33 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OADataFetcher.h @@ -0,0 +1,44 @@ +// +// OADataFetcher.h +// OAuthConsumer +// +// Created by Jon Crosby on 11/5/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 +#import "OAMutableURLRequest.h" +#import "OAServiceTicket.h" + + +@interface OADataFetcher : NSObject { +@private + OAMutableURLRequest *request; + NSURLResponse *response; + NSURLConnection *connection; + NSMutableData *responseData; + id delegate; + SEL didFinishSelector; + SEL didFailSelector; +} + +- (void)fetchDataWithRequest:(OAMutableURLRequest *)aRequest delegate:(id)aDelegate didFinishSelector:(SEL)finishSelector didFailSelector:(SEL)failSelector; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OADataFetcher.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OADataFetcher.m new file mode 100644 index 0000000..08cf295 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OADataFetcher.m @@ -0,0 +1,89 @@ +// +// OADataFetcher.m +// OAuthConsumer +// +// Created by Jon Crosby on 11/5/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "OADataFetcher.h" + + +@implementation OADataFetcher + +- (id)init { + [super init]; + responseData = [[NSMutableData alloc] init]; + return self; +} + +- (void)dealloc { + [connection release]; + [response release]; + [responseData release]; + [request release]; + [super dealloc]; +} + +/* Protocol for async URL loading */ +- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)aResponse { + [response release]; + response = [aResponse retain]; + [responseData setLength:0]; +} + +- (void)connection:(NSURLConnection *)aConnection didFailWithError:(NSError *)error { + OAServiceTicket *ticket = [[OAServiceTicket alloc] initWithRequest:request + response:response + data:responseData + didSucceed:NO]; + + [delegate performSelector:didFailSelector withObject:ticket withObject:error]; + [ticket release]; +} + +- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { + [responseData appendData:data]; +} + +- (void)connectionDidFinishLoading:(NSURLConnection *)connection { + OAServiceTicket *ticket = [[OAServiceTicket alloc] initWithRequest:request + response:response + data:responseData + didSucceed:[(NSHTTPURLResponse *)response statusCode] < 400]; + + [delegate performSelector:didFinishSelector withObject:ticket withObject:responseData]; + [ticket release]; +} + +- (void)fetchDataWithRequest:(OAMutableURLRequest *)aRequest delegate:(id)aDelegate didFinishSelector:(SEL)finishSelector didFailSelector:(SEL)failSelector { + [request release]; + request = [aRequest retain]; + delegate = aDelegate; + didFinishSelector = finishSelector; + didFailSelector = failSelector; + + [request prepare]; + + connection = [[NSURLConnection alloc] initWithRequest:aRequest delegate:self]; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAHMAC_SHA1SignatureProvider.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAHMAC_SHA1SignatureProvider.h new file mode 100644 index 0000000..d259c4e --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAHMAC_SHA1SignatureProvider.h @@ -0,0 +1,32 @@ +// +// OAHMAC_SHA1SignatureProvider.h +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 +#import "OASignatureProviding.h" + + +@interface OAHMAC_SHA1SignatureProvider : NSObject +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAHMAC_SHA1SignatureProvider.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAHMAC_SHA1SignatureProvider.m new file mode 100644 index 0000000..63bb7ea --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAHMAC_SHA1SignatureProvider.m @@ -0,0 +1,58 @@ +// +// OAHMAC_SHA1SignatureProvider.m +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "OAHMAC_SHA1SignatureProvider.h" + +#include "hmac.h" +#include "Base64Transcoder.h" + +@implementation OAHMAC_SHA1SignatureProvider + +- (NSString *)name { + return @"HMAC-SHA1"; +} + +- (NSString *)signClearText:(NSString *)text withSecret:(NSString *)secret { + NSData *secretData = [[secret dataUsingEncoding:NSUTF8StringEncoding] retain]; + NSData *clearTextData = [[text dataUsingEncoding:NSUTF8StringEncoding] retain]; + unsigned char result[20]; + hmac_sha1((unsigned char *)[clearTextData bytes], [clearTextData length], (unsigned char *)[secretData bytes], [secretData length], result); + [secretData release]; + [clearTextData release]; + + //Base64 Encoding + + char base64Result[32]; + size_t theResultLength = 32; + Base64EncodeData(result, 20, base64Result, &theResultLength); + NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength]; + + NSString *base64EncodedResult = [[[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding] autorelease]; + + return base64EncodedResult; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAMutableURLRequest.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAMutableURLRequest.h new file mode 100644 index 0000000..c080bd1 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAMutableURLRequest.h @@ -0,0 +1,67 @@ +// +// OAMutableURLRequest.h +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 +#import "OAConsumer.h" +#import "OAToken.h" +#import "OAHMAC_SHA1SignatureProvider.h" +#import "OASignatureProviding.h" +#import "NSMutableURLRequest+Parameters.h" +#import "NSURL+Base.h" + + +@interface OAMutableURLRequest : NSMutableURLRequest { +@protected + OAConsumer *consumer; + OAToken *token; + NSString *realm; + NSString *signature; + id signatureProvider; + NSString *nonce; + NSString *timestamp; +} +@property(readonly) NSString *signature; +@property(readonly) NSString *nonce; + +- (id)initWithURL:(NSURL *)aUrl + consumer:(OAConsumer *)aConsumer + token:(OAToken *)aToken + realm:(NSString *)aRealm +signatureProvider:(id)aProvider; + +- (id)initWithURL:(NSURL *)aUrl + consumer:(OAConsumer *)aConsumer + token:(OAToken *)aToken + realm:(NSString *)aRealm +signatureProvider:(id)aProvider + nonce:(NSString *)aNonce + timestamp:(NSString *)aTimestamp; + +- (void)prepare; + +- (NSString *)signatureBaseString; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAMutableURLRequest.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAMutableURLRequest.m new file mode 100644 index 0000000..24ae11e --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAMutableURLRequest.m @@ -0,0 +1,199 @@ +// +// OAMutableURLRequest.m +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "OAMutableURLRequest.h" + + +@interface OAMutableURLRequest (Private) +- (void)_generateTimestamp; +- (void)_generateNonce; +@end + +@implementation OAMutableURLRequest +@synthesize signature, nonce; + +#pragma mark init + +- (id)initWithURL:(NSURL *)aUrl + consumer:(OAConsumer *)aConsumer + token:(OAToken *)aToken + realm:(NSString *)aRealm +signatureProvider:(id)aProvider { + [super initWithURL:aUrl + cachePolicy:NSURLRequestReloadIgnoringCacheData + timeoutInterval:10.0]; + + consumer = aConsumer; + + // empty token for Unauthorized Request Token transaction + if (aToken == nil) { + token = [[OAToken alloc] init]; + } else { + token = [aToken retain]; + } + + if (aRealm == nil) { + realm = @""; + } else { + realm = [aRealm copy]; + } + + // default to HMAC-SHA1 + if (aProvider == nil) { + signatureProvider = [[OAHMAC_SHA1SignatureProvider alloc] init]; + } else { + signatureProvider = [aProvider retain]; + } + + [self _generateTimestamp]; + [self _generateNonce]; + + return self; +} + +// Setting a timestamp and nonce to known +// values can be helpful for testing +- (id)initWithURL:(NSURL *)aUrl + consumer:(OAConsumer *)aConsumer + token:(OAToken *)aToken + realm:(NSString *)aRealm +signatureProvider:(id)aProvider + nonce:(NSString *)aNonce + timestamp:(NSString *)aTimestamp { + [self initWithURL:aUrl + consumer:aConsumer + token:aToken + realm:aRealm + signatureProvider:aProvider]; + + nonce = [aNonce copy]; + timestamp = [aTimestamp copy]; + + return self; +} + +- (void)prepare { + // sign +// NSLog(@"Base string is: %@", [self _signatureBaseString]); + signature = [signatureProvider signClearText:[self signatureBaseString] + withSecret:[NSString stringWithFormat:@"%@&%@", + [consumer.secret encodedURLParameterString], + token.secret ? [token.secret encodedURLParameterString] : @""]]; + + // set OAuth headers + NSMutableArray *chunks = [[NSMutableArray alloc] init]; + [chunks addObject:[NSString stringWithFormat:@"realm=\"%@\"", [realm encodedURLParameterString]]]; + [chunks addObject:[NSString stringWithFormat:@"oauth_consumer_key=\"%@\"", [consumer.key encodedURLParameterString]]]; + + NSDictionary *tokenParameters = [token parameters]; + for (NSString *k in tokenParameters) { + [chunks addObject:[NSString stringWithFormat:@"%@=\"%@\"", k, [[tokenParameters objectForKey:k] encodedURLParameterString]]]; + } + + [chunks addObject:[NSString stringWithFormat:@"oauth_signature_method=\"%@\"", [[signatureProvider name] encodedURLParameterString]]]; + [chunks addObject:[NSString stringWithFormat:@"oauth_signature=\"%@\"", [signature encodedURLParameterString]]]; + [chunks addObject:[NSString stringWithFormat:@"oauth_timestamp=\"%@\"", timestamp]]; + [chunks addObject:[NSString stringWithFormat:@"oauth_nonce=\"%@\"", nonce]]; + [chunks addObject:@"oauth_version=\"1.0\""]; + + NSString *oauthHeader = [NSString stringWithFormat:@"OAuth %@", [chunks componentsJoinedByString:@", "]]; + [chunks release]; + + [self setValue:oauthHeader forHTTPHeaderField:@"Authorization"]; +} + +- (void)_generateTimestamp { + [timestamp release]; + timestamp = [[NSString alloc]initWithFormat:@"%d", time(NULL)]; +} + +- (void)_generateNonce { + CFUUIDRef theUUID = CFUUIDCreate(NULL); + CFStringRef string = CFUUIDCreateString(NULL, theUUID); + NSMakeCollectable(theUUID); + if (nonce) { + CFRelease(nonce); + } + nonce = (NSString *)string; +} + +- (NSString *)signatureBaseString { + // OAuth Spec, Section 9.1.1 "Normalize Request Parameters" + // build a sorted array of both request parameters and OAuth header parameters + NSDictionary *tokenParameters = [token parameters]; + // 6 being the number of OAuth params in the Signature Base String + NSArray *parameters = [self parameters]; + NSMutableArray *parameterPairs = [[NSMutableArray alloc] initWithCapacity:(5 + [parameters count] + [tokenParameters count])]; + + OARequestParameter *parameter; + parameter = [[OARequestParameter alloc] initWithName:@"oauth_consumer_key" value:consumer.key]; + + [parameterPairs addObject:[parameter URLEncodedNameValuePair]]; + [parameter release]; + parameter = [[OARequestParameter alloc] initWithName:@"oauth_signature_method" value:[signatureProvider name]]; + [parameterPairs addObject:[parameter URLEncodedNameValuePair]]; + [parameter release]; + parameter = [[OARequestParameter alloc] initWithName:@"oauth_timestamp" value:timestamp]; + [parameterPairs addObject:[parameter URLEncodedNameValuePair]]; + [parameter release]; + parameter = [[OARequestParameter alloc] initWithName:@"oauth_nonce" value:nonce]; + [parameterPairs addObject:[parameter URLEncodedNameValuePair]]; + [parameter release]; + parameter = [[OARequestParameter alloc] initWithName:@"oauth_version" value:@"1.0"] ; + [parameterPairs addObject:[parameter URLEncodedNameValuePair]]; + [parameter release]; + + for(NSString *k in tokenParameters) { + [parameterPairs addObject:[[OARequestParameter requestParameter:k value:[tokenParameters objectForKey:k]] URLEncodedNameValuePair]]; + } + + if (![[self valueForHTTPHeaderField:@"Content-Type"] hasPrefix:@"multipart/form-data"]) { + for (OARequestParameter *param in parameters) { + [parameterPairs addObject:[param URLEncodedNameValuePair]]; + } + } + + NSArray *sortedPairs = [parameterPairs sortedArrayUsingSelector:@selector(compare:)]; + NSString *normalizedRequestParameters = [sortedPairs componentsJoinedByString:@"&"]; + [parameterPairs release]; + // NSLog(@"Normalized: %@", normalizedRequestParameters); + // OAuth Spec, Section 9.1.2 "Concatenate Request Elements" + return [NSString stringWithFormat:@"%@&%@&%@", + [self HTTPMethod], + [[[self URL] URLStringWithoutQuery] encodedURLParameterString], + [normalizedRequestParameters encodedURLString]]; +} + +- (void) dealloc +{ + [token release]; + [(NSObject*)signatureProvider release]; + [timestamp release]; + CFRelease(nonce); + [super dealloc]; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAPlaintextSignatureProvider.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAPlaintextSignatureProvider.h new file mode 100644 index 0000000..96bb2f2 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAPlaintextSignatureProvider.h @@ -0,0 +1,31 @@ +// +// OAPlaintextSignatureProvider.h +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 +#import "OASignatureProviding.h" + +@interface OAPlaintextSignatureProvider : NSObject +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAPlaintextSignatureProvider.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAPlaintextSignatureProvider.m new file mode 100644 index 0000000..9cc4d63 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAPlaintextSignatureProvider.m @@ -0,0 +1,40 @@ +// +// OAPlaintextSignatureProvider.m +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "OAPlaintextSignatureProvider.h" + + +@implementation OAPlaintextSignatureProvider + +- (NSString *)name { + return @"PLAINTEXT"; +} + +- (NSString *)signClearText:(NSString *)text withSecret:(NSString *)secret { + return secret; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAProblem.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAProblem.h new file mode 100644 index 0000000..fe64c70 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAProblem.h @@ -0,0 +1,53 @@ +// +// OAProblem.h +// OAuthConsumer +// +// Created by Alberto García Hierro on 03/09/08. +// Copyright 2008 Alberto García Hierro. All rights reserved. +// bynotes.com + +#import + +enum { + kOAProblemSignatureMethodRejected = 0, + kOAProblemParameterAbsent, + kOAProblemVersionRejected, + kOAProblemConsumerKeyUnknown, + kOAProblemTokenRejected, + kOAProblemSignatureInvalid, + kOAProblemNonceUsed, + kOAProblemTimestampRefused, + kOAProblemTokenExpired, + kOAProblemTokenNotRenewable +}; + +@interface OAProblem : NSObject { + const NSString *problem; +} + +@property (readonly) const NSString *problem; + +- (id)initWithProblem:(const NSString *)aProblem; +- (id)initWithResponseBody:(const NSString *)response; + +- (BOOL)isEqualToProblem:(OAProblem *)aProblem; +- (BOOL)isEqualToString:(const NSString *)aProblem; +- (BOOL)isEqualTo:(id)aProblem; +- (int)code; + ++ (OAProblem *)problemWithResponseBody:(const NSString *)response; + ++ (const NSArray *)validProblems; + ++ (OAProblem *)SignatureMethodRejected; ++ (OAProblem *)ParameterAbsent; ++ (OAProblem *)VersionRejected; ++ (OAProblem *)ConsumerKeyUnknown; ++ (OAProblem *)TokenRejected; ++ (OAProblem *)SignatureInvalid; ++ (OAProblem *)NonceUsed; ++ (OAProblem *)TimestampRefused; ++ (OAProblem *)TokenExpired; ++ (OAProblem *)TokenNotRenewable; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAProblem.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAProblem.m new file mode 100644 index 0000000..7a885a3 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAProblem.m @@ -0,0 +1,165 @@ +// +// OAProblem.m +// OAuthConsumer +// +// Created by Alberto García Hierro on 03/09/08. +// Copyright 2008 Alberto García Hierro. All rights reserved. +// bynotes.com + +#import "OAProblem.h" + +const NSString *signature_method_rejected = @"signature_method_rejected"; +const NSString *parameter_absent = @"parameter_absent"; +const NSString *version_rejected = @"version_rejected"; +const NSString *consumer_key_unknown = @"consumer_key_unknown"; +const NSString *token_rejected = @"token_rejected"; +const NSString *signature_invalid = @"signature_invalid"; +const NSString *nonce_used = @"nonce_used"; +const NSString *timestamp_refused = @"timestamp_refused"; +const NSString *token_expired = @"token_expired"; +const NSString *token_not_renewable = @"token_not_renewable"; + +@implementation OAProblem + +@synthesize problem; + +- (id)initWithPointer:(const NSString *) aPointer +{ + [super init]; + problem = aPointer; + return self; +} + +- (id)initWithProblem:(const NSString *) aProblem +{ + NSUInteger idx = [[OAProblem validProblems] indexOfObject:aProblem]; + if (idx == NSNotFound) { + return nil; + } + + return [self initWithPointer: [[OAProblem validProblems] objectAtIndex:idx]]; +} + +- (id)initWithResponseBody:(const NSString *) response +{ + NSArray *fields = [response componentsSeparatedByString:@"&"]; + for (NSString *field in fields) { + if ([field hasPrefix:@"oauth_problem="]) { + NSString *value = [[field componentsSeparatedByString:@"="] objectAtIndex:1]; + return [self initWithProblem:value]; + } + } + + return nil; +} + ++ (OAProblem *)problemWithResponseBody:(const NSString *) response +{ + return [[[OAProblem alloc] initWithResponseBody:response] autorelease]; +} + ++ (const NSArray *)validProblems +{ + static NSArray *array; + if (!array) { + array = [[NSArray alloc] initWithObjects:signature_method_rejected, + parameter_absent, + version_rejected, + consumer_key_unknown, + token_rejected, + signature_invalid, + nonce_used, + timestamp_refused, + token_expired, + token_not_renewable, + nil]; + } + + return array; +} + +- (BOOL)isEqualToProblem:(OAProblem *) aProblem +{ + return [problem isEqualToString:(NSString *)aProblem->problem]; +} + +- (BOOL)isEqualToString:(const NSString *) aProblem +{ + return [problem isEqualToString:(NSString *)aProblem]; +} + +- (BOOL)isEqualTo:(id) aProblem +{ + if ([aProblem isKindOfClass:[NSString class]]) { + return [self isEqualToString:aProblem]; + } + + if ([aProblem isKindOfClass:[OAProblem class]]) { + return [self isEqualToProblem:aProblem]; + } + + return NO; +} + +- (int)code { + return [[[self class] validProblems] indexOfObject:problem]; +} + +- (NSString *)description +{ + return [NSString stringWithFormat:@"OAuth Problem: %@", (NSString *)problem]; +} + +#pragma mark class_methods + ++ (OAProblem *)SignatureMethodRejected +{ + return [[[OAProblem alloc] initWithPointer:signature_method_rejected] autorelease]; +} + ++ (OAProblem *)ParameterAbsent +{ + return [[[OAProblem alloc] initWithPointer:parameter_absent] autorelease]; +} + ++ (OAProblem *)VersionRejected +{ + return [[[OAProblem alloc] initWithPointer:version_rejected] autorelease]; +} + ++ (OAProblem *)ConsumerKeyUnknown +{ + return [[[OAProblem alloc] initWithPointer:consumer_key_unknown] autorelease]; +} + ++ (OAProblem *)TokenRejected +{ + return [[[OAProblem alloc] initWithPointer:token_rejected] autorelease]; +} + ++ (OAProblem *)SignatureInvalid +{ + return [[[OAProblem alloc] initWithPointer:signature_invalid] autorelease]; +} + ++ (OAProblem *)NonceUsed +{ + return [[[OAProblem alloc] initWithPointer:nonce_used] autorelease]; +} + ++ (OAProblem *)TimestampRefused +{ + return [[[OAProblem alloc] initWithPointer:timestamp_refused] autorelease]; +} + ++ (OAProblem *)TokenExpired +{ + return [[[OAProblem alloc] initWithPointer:token_expired] autorelease]; +} + ++ (OAProblem *)TokenNotRenewable +{ + return [[[OAProblem alloc] initWithPointer:token_not_renewable] autorelease]; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OARequestParameter.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OARequestParameter.h new file mode 100644 index 0000000..de73ea8 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OARequestParameter.h @@ -0,0 +1,48 @@ +// +// OARequestParameter.h +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 +#import "NSString+URLEncoding.h" + + +@interface OARequestParameter : NSObject { +@protected + NSString *name; + NSString *value; +} +@property(copy, readwrite) NSString *name; +@property(copy, readwrite) NSString *value; + +- (id)initWithName:(NSString *)aName value:(NSString *)aValue; +- (NSString *)URLEncodedName; +- (NSString *)URLEncodedValue; +- (NSString *)URLEncodedNameValuePair; + +- (BOOL)isEqualToRequestParameter:(OARequestParameter *)parameter; + ++ (id)requestParameter:(NSString *)aName value:(NSString *)aValue; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OARequestParameter.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OARequestParameter.m new file mode 100644 index 0000000..236b03a --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OARequestParameter.m @@ -0,0 +1,72 @@ +// +// OARequestParameter.m +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "OARequestParameter.h" + + +@implementation OARequestParameter +@synthesize name, value; + +- (id)initWithName:(NSString *)aName value:(NSString *)aValue { + [super init]; + self.name = aName; + self.value = aValue; + return self; +} + +- (NSString *)URLEncodedName { + return self.name; +// return [self.name encodedURLParameterString]; +} + +- (NSString *)URLEncodedValue { + return [self.value encodedURLParameterString]; +} + +- (NSString *)URLEncodedNameValuePair { + return [NSString stringWithFormat:@"%@=%@", [self URLEncodedName], [self URLEncodedValue]]; +} + +- (BOOL)isEqual:(id)object { + if ([object isKindOfClass:[self class]]) { + return [self isEqualToRequestParameter:(OARequestParameter *)object]; + } + + return NO; +} + +- (BOOL)isEqualToRequestParameter:(OARequestParameter *)parameter { + return ([self.name isEqualToString:parameter.name] && + [self.value isEqualToString:parameter.value]); +} + + ++ (id)requestParameter:(NSString *)aName value:(NSString *)aValue +{ + return [[[self alloc] initWithName:aName value:aValue] autorelease]; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAServiceTicket.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAServiceTicket.h new file mode 100644 index 0000000..63852b9 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAServiceTicket.h @@ -0,0 +1,46 @@ +// +// OAServiceTicket.h +// OAuthConsumer +// +// Created by Jon Crosby on 11/5/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 +#import "OAMutableURLRequest.h" + + +@interface OAServiceTicket : NSObject { +@private + OAMutableURLRequest *request; + NSURLResponse *response; + NSData *data; + BOOL didSucceed; +} +@property(readonly) OAMutableURLRequest *request; +@property(readonly) NSURLResponse *response; +@property(readonly) NSData *data; +@property(readonly) BOOL didSucceed; +@property(readonly) NSString *body; + +- (id)initWithRequest:(OAMutableURLRequest *)aRequest response:(NSURLResponse *)aResponse data:(NSData *)aData didSucceed:(BOOL)success; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAServiceTicket.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAServiceTicket.m new file mode 100644 index 0000000..0dbe90c --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAServiceTicket.m @@ -0,0 +1,51 @@ +// +// OAServiceTicket.m +// OAuthConsumer +// +// Created by Jon Crosby on 11/5/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "OAServiceTicket.h" + + +@implementation OAServiceTicket +@synthesize request, response, data, didSucceed; + +- (id)initWithRequest:(OAMutableURLRequest *)aRequest response:(NSURLResponse *)aResponse data:(NSData *)aData didSucceed:(BOOL)success { + [super init]; + request = aRequest; + response = aResponse; + data = aData; + didSucceed = success; + return self; +} + +- (NSString *)body +{ + if (!data) { + return nil; + } + + return [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OASignatureProviding.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OASignatureProviding.h new file mode 100644 index 0000000..6fc5f98 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OASignatureProviding.h @@ -0,0 +1,34 @@ +// +// OASignatureProviding.h +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 + + +@protocol OASignatureProviding + +- (NSString *)name; +- (NSString *)signClearText:(NSString *)text withSecret:(NSString *)secret; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAToken.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAToken.h new file mode 100644 index 0000000..eb2c2bf --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAToken.h @@ -0,0 +1,72 @@ +// +// OAToken.h +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 + +@interface OAToken : NSObject { +@protected + NSString *key; + NSString *secret; + NSString *session; + NSNumber *duration; + NSMutableDictionary *attributes; + NSDate *created; + BOOL renewable; + BOOL forRenewal; +} +@property(retain, readwrite) NSString *key; +@property(retain, readwrite) NSString *secret; +@property(retain, readwrite) NSString *session; +@property(retain, readwrite) NSNumber *duration; +@property(retain, readwrite) NSMutableDictionary *attributes; +@property(readwrite, getter=isForRenewal) BOOL forRenewal; + +- (id)initWithKey:(NSString *)aKey secret:(NSString *)aSecret; +- (id)initWithKey:(NSString *)aKey secret:(NSString *)aSecret session:(NSString *)aSession + duration:(NSNumber *)aDuration attributes:(NSDictionary *)theAttributes created:(NSDate *)creation + renewable:(BOOL)renew; +- (id)initWithHTTPResponseBody:(NSString *)body; + +- (id)initWithUserDefaultsUsingServiceProviderName:(NSString *)provider prefix:(NSString *)prefix; +- (int)storeInUserDefaultsWithServiceProviderName:(NSString *)provider prefix:(NSString *)prefix; + +- (BOOL)isValid; + +- (void)setAttribute:(NSString *)aKey value:(NSString *)aValue; +- (NSString *)attribute:(NSString *)aKey; +- (void)setAttributesWithString:(NSString *)aAttributes; +- (NSString *)attributeString; + +- (BOOL)hasExpired; +- (BOOL)isRenewable; +- (void)setDurationWithString:(NSString *)aDuration; +- (BOOL)hasAttributes; +- (NSDictionary *)parameters; + +- (BOOL)isEqualToToken:(OAToken *)aToken; + ++ (void)removeFromUserDefaultsWithServiceProviderName:(const NSString *)provider prefix:(const NSString *)prefix; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAToken.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAToken.m new file mode 100644 index 0000000..a2ab54a --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAToken.m @@ -0,0 +1,328 @@ +// +// OAToken.m +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 "NSString+URLEncoding.h" +#import "OAToken.h" + +@interface OAToken (Private) + ++ (NSString *)settingsKey:(const NSString *)name provider:(const NSString *)provider prefix:(const NSString *)prefix; ++ (id)loadSetting:(const NSString *)name provider:(const NSString *)provider prefix:(const NSString *)prefix; ++ (void)saveSetting:(NSString *)name object:(id)object provider:(const NSString *)provider prefix:(const NSString *)prefix; ++ (NSNumber *)durationWithString:(NSString *)aDuration; ++ (NSDictionary *)attributesWithString:(NSString *)theAttributes; + +@end + +@implementation OAToken + +@synthesize key, secret, session, duration, attributes, forRenewal; + +#pragma mark init + +- (id)init { + return [self initWithKey:nil secret:nil]; +} + +- (id)initWithKey:(NSString *)aKey secret:(NSString *)aSecret { + return [self initWithKey:aKey secret:aSecret session:nil duration:nil + attributes:nil created:nil renewable:NO]; +} + +- (id)initWithKey:(NSString *)aKey secret:(NSString *)aSecret session:(NSString *)aSession + duration:(NSNumber *)aDuration attributes:(NSDictionary *)theAttributes created:(NSDate *)creation + renewable:(BOOL)renew { + [super init]; + self.key = aKey; + self.secret = aSecret; + self.session = aSession; + self.duration = aDuration; + self.attributes = theAttributes; + created = [creation retain]; + renewable = renew; + forRenewal = NO; + + return self; +} + +- (id)initWithHTTPResponseBody:(const NSString *)body { + NSString *aKey = nil; + NSString *aSecret = nil; + NSString *aSession = nil; + NSNumber *aDuration = nil; + NSDate *creationDate = nil; + NSDictionary *attrs = nil; + BOOL renew = NO; + NSArray *pairs = [body componentsSeparatedByString:@"&"]; + + for (NSString *pair in pairs) { + NSArray *elements = [pair componentsSeparatedByString:@"="]; + if ([[elements objectAtIndex:0] isEqualToString:@"oauth_token"]) { + aKey = [elements objectAtIndex:1]; + } else if ([[elements objectAtIndex:0] isEqualToString:@"oauth_token_secret"]) { + aSecret = [elements objectAtIndex:1]; + } else if ([[elements objectAtIndex:0] isEqualToString:@"oauth_session_handle"]) { + aSession = [elements objectAtIndex:1]; + } else if ([[elements objectAtIndex:0] isEqualToString:@"oauth_token_duration"]) { + aDuration = [[self class] durationWithString:[elements objectAtIndex:1]]; + creationDate = [NSDate date]; + } else if ([[elements objectAtIndex:0] isEqualToString:@"oauth_token_attributes"]) { + attrs = [[self class] attributesWithString:[[elements objectAtIndex:1] decodedURLString]]; + } else if ([[elements objectAtIndex:0] isEqualToString:@"oauth_token_renewable"]) { + NSString *lowerCase = [[elements objectAtIndex:1] lowercaseString]; + if ([lowerCase isEqualToString:@"true"] || [lowerCase isEqualToString:@"t"]) { + renew = YES; + } + } + } + + return [self initWithKey:aKey secret:aSecret session:aSession duration:aDuration + attributes:attrs created:creationDate renewable:renew]; +} + +- (id)initWithUserDefaultsUsingServiceProviderName:(const NSString *)provider prefix:(const NSString *)prefix { + [super init]; + self.key = [OAToken loadSetting:@"key" provider:provider prefix:prefix]; + self.secret = [OAToken loadSetting:@"secret" provider:provider prefix:prefix]; + self.session = [OAToken loadSetting:@"session" provider:provider prefix:prefix]; + self.duration = [OAToken loadSetting:@"duration" provider:provider prefix:prefix]; + self.attributes = [OAToken loadSetting:@"attributes" provider:provider prefix:prefix]; + created = [OAToken loadSetting:@"created" provider:provider prefix:prefix]; + renewable = [[OAToken loadSetting:@"renewable" provider:provider prefix:prefix] boolValue]; + + if (![self isValid]) { + [self autorelease]; + return nil; + } + + return self; +} + +#pragma mark dealloc + +- (void)dealloc { + self.key = nil; + self.secret = nil; + self.duration = nil; + self.attributes = nil; + [super dealloc]; +} + +#pragma mark settings + +- (BOOL)isValid { + return (key != nil && ![key isEqualToString:@""] && secret != nil && ![secret isEqualToString:@""]); +} + +- (int)storeInUserDefaultsWithServiceProviderName:(const NSString *)provider prefix:(const NSString *)prefix { + [OAToken saveSetting:@"key" object:key provider:provider prefix:prefix]; + [OAToken saveSetting:@"secret" object:secret provider:provider prefix:prefix]; + [OAToken saveSetting:@"created" object:created provider:provider prefix:prefix]; + [OAToken saveSetting:@"duration" object:duration provider:provider prefix:prefix]; + [OAToken saveSetting:@"session" object:session provider:provider prefix:prefix]; + [OAToken saveSetting:@"attributes" object:attributes provider:provider prefix:prefix]; + [OAToken saveSetting:@"renewable" object:renewable ? @"t" : @"f" provider:provider prefix:prefix]; + + [[NSUserDefaults standardUserDefaults] synchronize]; + return(0); +} + +#pragma mark duration + +- (void)setDurationWithString:(NSString *)aDuration { + self.duration = [[self class] durationWithString:aDuration]; +} + +- (BOOL)hasExpired +{ + return created && [created timeIntervalSinceNow] > [duration intValue]; +} + +- (BOOL)isRenewable +{ + return session && renewable && created && [created timeIntervalSinceNow] < (2 * [duration intValue]); +} + + +#pragma mark attributes + +- (void)setAttribute:(const NSString *)aKey value:(const NSString *)aAttribute { + if (!attributes) { + attributes = [[NSMutableDictionary alloc] init]; + } + [attributes setObject: aAttribute forKey: aKey]; +} + +- (void)setAttributes:(NSDictionary *)theAttributes { + [attributes release]; + if (theAttributes) { + attributes = [[NSMutableDictionary alloc] initWithDictionary:theAttributes]; + }else { + attributes = nil; + } + +} + +- (BOOL)hasAttributes { + return (attributes && [attributes count] > 0); +} + +- (NSString *)attributeString { + if (![self hasAttributes]) { + return @""; + } + + NSMutableArray *chunks = [[NSMutableArray alloc] init]; + for(NSString *aKey in self->attributes) { + [chunks addObject:[NSString stringWithFormat:@"%@:%@", aKey, [attributes objectForKey:aKey]]]; + } + NSString *attrs = [chunks componentsJoinedByString:@";"]; + [chunks release]; + return attrs; +} + +- (NSString *)attribute:(NSString *)aKey +{ + return [attributes objectForKey:aKey]; +} + +- (void)setAttributesWithString:(NSString *)theAttributes +{ + self.attributes = [[self class] attributesWithString:theAttributes]; +} + +- (NSDictionary *)parameters +{ + NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease]; + + if (key) { + [params setObject:key forKey:@"oauth_token"]; + if ([self isForRenewal]) { + [params setObject:session forKey:@"oauth_session_handle"]; + } + } else { + if (duration) { + [params setObject:[duration stringValue] forKey: @"oauth_token_duration"]; + } + if ([attributes count]) { + [params setObject:[self attributeString] forKey:@"oauth_token_attributes"]; + } + } + return params; +} + +#pragma mark comparisions + +- (BOOL)isEqual:(id)object { + if([object isKindOfClass:[self class]]) { + return [self isEqualToToken:(OAToken *)object]; + } + return NO; +} + +- (BOOL)isEqualToToken:(OAToken *)aToken { + /* Since ScalableOAuth determines that the token may be + renewed using the same key and secret, we must also + check the creation date */ + if ([self.key isEqualToString:aToken.key] && + [self.secret isEqualToString:aToken.secret]) { + /* May be nil */ + if (created == aToken->created || [created isEqualToDate:aToken->created]) { + return YES; + } + } + + return NO; +} + +#pragma mark class_functions + ++ (NSString *)settingsKey:(NSString *)name provider:(NSString *)provider prefix:(NSString *)prefix { + return [NSString stringWithFormat:@"OAUTH_%@_%@_%@", provider, prefix, [name uppercaseString]]; +} + ++ (id)loadSetting:(NSString *)name provider:(NSString *)provider prefix:(NSString *)prefix { + return [[NSUserDefaults standardUserDefaults] objectForKey:[self settingsKey:name + provider:provider + prefix:prefix]]; +} + ++ (void)saveSetting:(NSString *)name object:(id)object provider:(NSString *)provider prefix:(NSString *)prefix { + [[NSUserDefaults standardUserDefaults] setObject:object forKey:[self settingsKey:name + provider:provider + prefix:prefix]]; +} + ++ (void)removeFromUserDefaultsWithServiceProviderName:(NSString *)provider prefix:(NSString *)prefix { + NSArray *keys = [NSArray arrayWithObjects:@"key", @"secret", @"created", @"duration", @"session", @"attributes", @"renewable", nil]; + for(NSString *name in keys) { + [[NSUserDefaults standardUserDefaults] removeObjectForKey:[OAToken settingsKey:name provider:provider prefix:prefix]]; + } +} + ++ (NSNumber *)durationWithString:(NSString *)aDuration { + NSUInteger length = [aDuration length]; + unichar c = toupper([aDuration characterAtIndex:length - 1]); + int mult; + if (c >= '0' && c <= '9') { + return [NSNumber numberWithInt:[aDuration intValue]]; + } + if (c == 'S') { + mult = 1; + } else if (c == 'H') { + mult = 60 * 60; + } else if (c == 'D') { + mult = 60 * 60 * 24; + } else if (c == 'W') { + mult = 60 * 60 * 24 * 7; + } else if (c == 'M') { + mult = 60 * 60 * 24 * 30; + } else if (c == 'Y') { + mult = 60 * 60 * 365; + } else { + mult = 1; + } + + return [NSNumber numberWithInt: mult * [[aDuration substringToIndex:length - 1] intValue]]; +} + ++ (NSDictionary *)attributesWithString:(NSString *)theAttributes { + NSArray *attrs = [theAttributes componentsSeparatedByString:@";"]; + NSMutableDictionary *dct = [[NSMutableDictionary alloc] init]; + for (NSString *pair in attrs) { + NSArray *elements = [pair componentsSeparatedByString:@":"]; + [dct setObject:[elements objectAtIndex:1] forKey:[elements objectAtIndex:0]]; + } + return [dct autorelease]; +} + +#pragma mark description + +- (NSString *)description { + return [NSString stringWithFormat:@"Key \"%@\" Secret:\"%@\"", key, secret]; +} + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OATokenManager.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OATokenManager.h new file mode 100644 index 0000000..bebfc80 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OATokenManager.h @@ -0,0 +1,68 @@ +// +// OATokenManager.h +// OAuthConsumer +// +// Created by Alberto García Hierro on 01/09/08. +// Copyright 2008 Alberto García Hierro. All rights reserved. +// bynotes.com + +#import + +#import "OACall.h" + +@class OATokenManager; + +@protocol OATokenManagerDelegate + +- (BOOL)tokenManager:(OATokenManager *)manager failedCall:(OACall *)call withError:(NSError *)error; +- (BOOL)tokenManager:(OATokenManager *)manager failedCall:(OACall *)call withProblem:(OAProblem *)problem; + +@optional + +- (BOOL)tokenManagerNeedsToken:(OATokenManager *)manager; + +@end + +@class OAConsumer; +@class OAToken; + +@interface OATokenManager : NSObject { + OAConsumer *consumer; + OAToken *acToken; + OAToken *reqToken; + OAToken *initialToken; + NSString *authorizedTokenKey; + NSString *oauthBase; + NSString *realm; + NSString *callback; + NSObject *delegate; + NSMutableArray *calls; + NSMutableArray *selectors; + NSMutableDictionary *delegates; + BOOL isDispatching; +} + + +- (id)init; + +- (id)initWithConsumer:(OAConsumer *)aConsumer token:(OAToken *)aToken oauthBase:(const NSString *)base + realm:(const NSString *)aRealm callback:(const NSString *)aCallback + delegate:(NSObject *)aDelegate; + +- (void)authorizedToken:(const NSString *)key; + +- (void)fetchData:(NSString *)aURL finished:(SEL)didFinish; + +- (void)fetchData:(NSString *)aURL method:(NSString *)aMethod parameters:(NSArray *)theParameters + finished:(SEL)didFinish; + +- (void)fetchData:(NSString *)aURL method:(NSString *)aMethod parameters:(NSArray *)theParameters + files:(NSDictionary *)theFiles finished:(SEL)didFinish; + +- (void)fetchData:(NSString *)aURL method:(NSString *)aMethod parameters:(NSArray *)theParameters + files:(NSDictionary *)theFiles finished:(SEL)didFinish delegate:(NSObject*)aDelegate; + +- (void)call:(OACall *)call failedWithError:(NSError *)error; +- (void)call:(OACall *)call failedWithProblem:(OAProblem *)problem; + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OATokenManager.m b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OATokenManager.m new file mode 100644 index 0000000..9de1481 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OATokenManager.m @@ -0,0 +1,400 @@ +// +// OATokenManager.m +// OAuthConsumer +// +// Created by Alberto García Hierro on 01/09/08. +// Copyright 2008 Alberto García Hierro. All rights reserved. +// bynotes.com + +#import "OAConsumer.h" +#import "OAToken.h" +#import "OAProblem.h" +#import "OACall.h" +#import "OATokenManager.h" + +@interface OATokenManager (Private) + +- (void)callProblem:(OACall *)call problem:(OAProblem *)problem; +- (void)callError:(OACall *)call error:(NSError *)error; +- (void)callFinished:(OACall *)call body:(NSString *)body; + +- (void)dispatch; +- (void)performCall:(OACall *)aCall; + +- (void)requestToken; +- (void)requestTokenReceived; +- (void)exchangeToken; +- (void)renewToken; +- (void)accessTokenReceived; +- (void)setAccessToken:(OAToken *)token; +- (void)deleteSavedRequestToken; + +- (OACall *)queue; +- (void)enqueue:(OACall *)call selector:(SEL)selector; +- (void)dequeue:(OACall *)call; +- (SEL)getSelector:(OACall *)call; + +@end + +@implementation OATokenManager + +- (id)init { + return [self initWithConsumer:nil + token:nil + oauthBase:nil + realm:nil + callback:nil + delegate:nil]; +} + +- (id)initWithConsumer:(OAConsumer *)aConsumer token:(OAToken *)aToken oauthBase:(const NSString *)base + realm:(const NSString *)aRealm callback:(const NSString *)aCallback + delegate:(NSObject *)aDelegate { + + [super init]; + consumer = [aConsumer retain]; + acToken = nil; + reqToken = nil; + initialToken = [aToken retain]; + authorizedTokenKey = nil; + oauthBase = [base copy]; + realm = [aRealm copy]; + callback = [aCallback copy]; + delegate = aDelegate; + calls = [[NSMutableArray alloc] init]; + selectors = [[NSMutableArray alloc] init]; + delegates = [[NSMutableDictionary alloc] init]; + isDispatching = NO; + + return self; +} + +- (void)dealloc { + [consumer release]; + [acToken release]; + [reqToken release]; + [initialToken release]; + [authorizedTokenKey release]; + [oauthBase release]; + [realm release]; + [callback release]; + [calls release]; + [selectors release]; + [delegates release]; + [super dealloc]; +} + +// The application got a new authorized +// request token and is notifying us +- (void)authorizedToken:(const NSString *)aKey +{ + if (reqToken && [aKey isEqualToString:reqToken.key]) { + [self exchangeToken]; + } else { + [authorizedTokenKey release]; + authorizedTokenKey = [aKey retain]; + } +} + + +// Private functions + +// Deal with problems and errors in calls + +- (void)call:(OACall *)call failedWithProblem:(OAProblem *)problem +{ + /* Always clear the saved request token, just in case */ + [self deleteSavedRequestToken]; + + if ([problem isEqualToProblem:[OAProblem TokenExpired]]) { + /* renewToken checks if it's renewable */ + [self renewToken]; + } else if ([problem isEqualToProblem:[OAProblem TokenNotRenewable]] || + [problem isEqualToProblem:[OAProblem TokenRejected]]) { + /* This token may have been revoked by the user, get a new one + after removing the stored requestToken, since the problem may be in + it */ + [self setAccessToken:nil]; + [self requestToken]; + } else if ([problem isEqualToProblem:[OAProblem NonceUsed]]) { + /* Just repeat this request */ + [self performCall:call]; + } else { + /* Non-recoverable error, tell the delegate and dequeue the call + if appropiate */ + if([delegate tokenManager:self failedCall:call withProblem:problem]) { + [self dequeue:call]; + } + @synchronized(self) { + isDispatching = NO; + } + } +} + +- (void)call:(OACall *)call failedWithError:(NSError *)error +{ + if([delegate tokenManager:self failedCall:call withError:error]) { + [self dequeue:call]; + } + @synchronized(self) { + isDispatching = NO; + } +} + +// When a call finish, notify the delegate +- (void)callFinished:(OACall *)call body:(NSString *)body +{ + SEL selector = [self getSelector:call]; + id deleg = [delegates objectForKey:[NSString stringWithFormat:@"%p", call]]; + if (deleg) { + [deleg performSelector:selector withObject:body]; + [delegates removeObjectForKey:call]; + } else { + [delegate performSelector:selector withObject:body]; + } + @synchronized(self) { + isDispatching = NO; + } + [self dequeue:call]; + [self dispatch]; +} + +- (OACall *)queue { + id obj = nil; + @synchronized(calls) { + if ([calls count]) { + obj = [calls objectAtIndex:0]; + } + } + return obj; +} + +- (void)enqueue:(OACall *)call selector:(SEL)selector { + NSUInteger idx = [calls indexOfObject:call]; + if (idx == NSNotFound) { + @synchronized(calls) { + [calls addObject:call]; + [call release]; + [selectors addObject:NSStringFromSelector(selector)]; + } + } +} + +- (void)dequeue:(OACall *)call { + NSUInteger idx = [calls indexOfObject:call]; + if (idx != NSNotFound) { + @synchronized(calls) { + [calls removeObjectAtIndex:idx]; + [selectors removeObjectAtIndex:idx]; + } + } +} + +- (SEL)getSelector:(OACall *)call +{ + NSUInteger idx = [calls indexOfObject:call]; + if (idx != NSNotFound) { + return NSSelectorFromString([selectors objectAtIndex:idx]); + } + return 0; +} + +// Token management functions + +// Requesting a new token + +// Gets a new token and opens the default +// browser for authorizing it. The application +// is expected to call authorizedToken when it +// gets the authorized token back + +- (void)requestToken +{ + /* Try to load an access token from settings */ + OAToken *atoken = [[[OAToken alloc] initWithUserDefaultsUsingServiceProviderName:oauthBase prefix:[@"access:" stringByAppendingString:realm]] autorelease]; + if (atoken && [atoken isValid]) { + [self setAccessToken:atoken]; + return; + } + /* Try to load a stored requestToken from + settings (useful for iPhone) */ + OAToken *token = [[[OAToken alloc] initWithUserDefaultsUsingServiceProviderName:oauthBase prefix:[@"request:" stringByAppendingString:realm]] autorelease]; + /* iPhone specific, the manager must have got the authorized token before reaching this point */ + NSLog(@"request token in settings %@", token); + if (token && token.key && [authorizedTokenKey isEqualToString:token.key]) { + reqToken = [token retain]; + [self exchangeToken]; + return; + } + if ([delegate respondsToSelector:@selector(tokenManagerNeedsToken:)]) { + if (![delegate tokenManagerNeedsToken:self]) { + return; + } + } + OACall *call = [[OACall alloc] initWithURL:[NSURL URLWithString:[oauthBase stringByAppendingString:@"request_token"]] method:@"POST"]; + [call perform:consumer + token:initialToken + realm:realm + delegate:self + didFinish:@selector(requestTokenReceived:body:)]; + +} + +- (void)requestTokenReceived:(OACall *)call body:(NSString *)body +{ + /* XXX: Check if token != nil */ + NSLog(@"Received request token %@", body); + OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:body] autorelease]; + if (token) { + [reqToken release]; + reqToken = [token retain]; + + [reqToken storeInUserDefaultsWithServiceProviderName:oauthBase prefix:[@"request:" stringByAppendingString:realm]]; + /* Save the token in case we exit and start again + before the token is authorized (useful for iPhone) */ + NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@authorize?oauth_token=%@&oauth_callback=%@", + oauthBase, token.key, callback]]; +// [[UIApplication sharedApplication] openURL:url]; + + } + [call release]; +} + +// Exchaing a request token for an access token + +// Exchanges the current authorized +// request token for an access token +- (void)exchangeToken +{ + if (!reqToken) { + [self requestToken]; + return; + } + NSURL *url = [NSURL URLWithString:[oauthBase stringByAppendingString:@"access_token"]]; + OACall *call = [[OACall alloc] initWithURL:url method:@"POST"]; + [call perform:consumer + token:reqToken + realm:realm + delegate:self + didFinish:@selector(accessTokenReceived:body:)]; +} + +- (void)accessTokenReceived:(OACall *)call body:(NSString *)body +{ + OAToken *token = [[OAToken alloc] initWithHTTPResponseBody:body]; + [self setAccessToken:token]; +} + +- (void)renewToken { + NSLog(@"Renewing token"); + if (!acToken || ![acToken isRenewable]) { + [self requestToken]; + return; + } + acToken.forRenewal = YES; + NSURL *url = [NSURL URLWithString:[oauthBase stringByAppendingString:@"access_token"]]; + OACall *call = [[OACall alloc] initWithURL:url method:@"POST"]; + [call perform:consumer + token:acToken + realm:realm + delegate:self + didFinish:@selector(accessTokenReceived:body:)]; +} + +- (void)setAccessToken:(OAToken *)token { + /* Remove the stored requestToken which generated + this access token */ + [self deleteSavedRequestToken]; + if (token) { + [acToken release]; + acToken = [token retain]; + [acToken storeInUserDefaultsWithServiceProviderName:oauthBase prefix:[@"access:" stringByAppendingString:realm]]; + @synchronized(self) { + isDispatching = NO; + } + [self dispatch]; + } else { + /* Clear the in-memory and saved access tokens */ + [acToken release]; + acToken = nil; + [OAToken removeFromUserDefaultsWithServiceProviderName:oauthBase prefix:[@"access:" stringByAppendingString:realm]]; + } +} + +- (void)deleteSavedRequestToken { + [OAToken removeFromUserDefaultsWithServiceProviderName:oauthBase prefix:[@"request:" stringByAppendingString:realm]]; + [reqToken release]; + reqToken = nil; +} + +- (void)performCall:(OACall *)aCall { + NSLog(@"Performing call"); + [aCall perform:consumer + token:acToken + realm:realm + delegate:self + didFinish:@selector(callFinished:body:)]; +} + +- (void)dispatch { + OACall *call = [self queue]; + if (!call) { + return; + } + @synchronized(self) { + if (isDispatching) { + return; + } + isDispatching = YES; + } + NSLog(@"Started dispatching"); + if(acToken) { + [self performCall:call]; + } else if(reqToken) { + [self exchangeToken]; + } else { + [self requestToken]; + } +} + +- (void)fetchData:(NSString *)aURL method:(NSString *)aMethod parameters:(NSArray *)theParameters + files:(NSDictionary *)theFiles finished:(SEL)didFinish delegate:(NSObject*)aDelegate { + + OACall *call = [[OACall alloc] initWithURL:[NSURL URLWithString:aURL] + method:aMethod + parameters:theParameters + files:theFiles]; + NSLog(@"Received request for: %@", aURL); + [self enqueue:call selector:didFinish]; + if (aDelegate) { + [delegates setObject:aDelegate forKey:[NSString stringWithFormat:@"%p", call]]; + } + [self dispatch]; +} + +- (void)fetchData:(NSString *)aURL method:(NSString *)aMethod parameters:(NSArray *)theParameters + files:(NSDictionary *)theFiles finished:(SEL)didFinish { + + [self fetchData:aURL method:aMethod parameters:theParameters files:theFiles + finished:didFinish delegate:nil]; +} + + +- (void)fetchData:(NSString *)aURL method:(NSString *)aMethod parameters:(NSArray *)theParameters + finished:(SEL)didFinish { + + [self fetchData:aURL method:aMethod parameters:theParameters files:nil finished:didFinish]; +} + +- (void)fetchData:(NSString *)aURL parameters:(NSArray *)theParameters files:(NSDictionary *)theFiles + finished:(SEL)didFinish { + + [self fetchData:aURL method:@"POST" parameters:theParameters files:theFiles finished:didFinish]; +} + +- (void)fetchData:(NSString *)aURL finished:(SEL)didFinish { + [self fetchData:aURL method:nil parameters:nil files:nil finished:didFinish]; +} + + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAuthConsumer.h b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAuthConsumer.h new file mode 100644 index 0000000..fc875eb --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/YelpAPISample/OAuthConsumer/OAuthConsumer.h @@ -0,0 +1,40 @@ +// +// OAuthConsumer.h +// OAuthConsumer +// +// Created by Jon Crosby on 10/19/07. +// Copyright 2007 Kaboomerang LLC. All rights reserved. +// +// 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 +#import "OAProblem.h" +#import "OAToken.h" +#import "OAConsumer.h" +#import "OAMutableURLRequest.h" +#import "NSString+URLEncoding.h" +#import "NSMutableURLRequest+Parameters.h" +#import "NSURL+Base.h" +#import "OASignatureProviding.h" +#import "OAHMAC_SHA1SignatureProvider.h" +#import "OAPlaintextSignatureProvider.h" +#import "OARequestParameter.h" +#import "OAServiceTicket.h" +#import "OADataFetcher.h" +#import "OATokenManager.h" \ No newline at end of file diff --git a/TalkinToTheNet/TalkinToTheNet/vegaNomViewController.h b/TalkinToTheNet/TalkinToTheNet/vegaNomViewController.h new file mode 100644 index 0000000..7324e57 --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/vegaNomViewController.h @@ -0,0 +1,13 @@ +// +// vegaNomViewController.h +// TalkinToTheNet +// +// Created by Justine Gartner on 9/21/15. +// Copyright © 2015 Mike Kavouras. All rights reserved. +// + +#import + +@interface vegaNomViewController : UIViewController + +@end diff --git a/TalkinToTheNet/TalkinToTheNet/vegaNomViewController.m b/TalkinToTheNet/TalkinToTheNet/vegaNomViewController.m new file mode 100644 index 0000000..2c1489e --- /dev/null +++ b/TalkinToTheNet/TalkinToTheNet/vegaNomViewController.m @@ -0,0 +1,330 @@ +// +// vegaNomViewController.m +// TalkinToTheNet +// +// Created by Justine Gartner on 9/21/15. +// Copyright © 2015 Mike Kavouras. All rights reserved. + +//CustomFont: FreightSansCmpPro-Light , FreightSansCmpPro +//CustomFont: District Pro , DistrictPro-Thin + +#import "vegaNomViewController.h" +#import "APIManager.h" +#import "VegaNomSearchResult.h" +#import "NSURLRequest+OAuth.h" +#import "InstagramDetailViewController.h" +#import "InstaPost.h" +#import +#import +#import +#import "MapKit/MapKit.h" + +#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) + +@interface vegaNomViewController () + +@property (weak, nonatomic) IBOutlet MKMapView *mapView; +@property (weak, nonatomic) IBOutlet UITableView *tableView; +@property (weak, nonatomic) IBOutlet UITextField *whatTextField; +@property (weak, nonatomic) IBOutlet UITextField *whereTextField; +@property (nonatomic) NSMutableArray *searchResults; +@property (nonatomic) NSArray *businesses; +@property (nonatomic) NSString *searchTerm; +@property (nonatomic) NSString *location; + +@property (nonatomic) CLLocationManager *locationManager; + +@end + +@implementation vegaNomViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + + self.tableView.delegate = self; + self.tableView.dataSource = self; + self.whatTextField.delegate = self; + self.whereTextField.delegate = self; + self.locationManager.delegate = self; + self.navigationItem.title = @"VegaNom"; + + //start with map centered at the following coordinates + //with a span from the center point + + //CLLocationCoordinate2D center = [self getLocation]; + + CLLocationCoordinate2D center = CLLocationCoordinate2DMake(40.7, -74); //for running in the simulator + MKCoordinateSpan span = MKCoordinateSpanMake(0.25, 0.25); + + [self.mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES]; + + self.locationManager = [[CLLocationManager alloc] init]; + + if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { + [self.locationManager requestWhenInUseAuthorization]; + }; + +} + +-(CLLocationCoordinate2D) getLocation{ + CLLocationManager *locationManager = [[CLLocationManager alloc] init]; + locationManager.delegate = self; + locationManager.desiredAccuracy = kCLLocationAccuracyBest; + locationManager.distanceFilter = kCLDistanceFilterNone; + [locationManager startUpdatingLocation]; + CLLocation *location = [locationManager location]; + CLLocationCoordinate2D coordinate = [location coordinate]; + + return coordinate; +} + + +-(void)makeNewYelpRequestWithSearchTerm: (NSString *)searchTerm andLocation: (NSString *)location callbackBlock: (void(^)())block{ + + NSString *searchTerms = [NSString stringWithFormat:@"vegan,%@", searchTerm]; + + [APIManager getYelpAPIRequestForTerm:searchTerms location:location completionHandler:^(NSArray *businesses, NSError *error) { + + if (error) { + NSLog(@"An error happened during the request: %@", error); + + [self presentAlertViewForError]; + + } else if (businesses) { + + NSLog(@"businesses: %@", businesses); + self.businesses = businesses; + + self.searchResults = [[NSMutableArray alloc] init]; + + for (NSDictionary *business in businesses) { + + VegaNomSearchResult *venue = [[VegaNomSearchResult alloc] initWithAPIResponse:business]; + + [self.searchResults addObject:venue]; + + block(); + } + + }else { + NSLog(@"No business was found"); + + [self presentAlertViewForNoBusinessesFound]; + + block (); + + + } + + }]; + +} + +#pragma mark - Alert View methods + +-(void)presentAlertViewForNoLocation{ + + NYAlertViewController *alertViewController = [[NYAlertViewController alloc] initWithNibName:nil bundle:nil]; + + [self setUpCustomAlertViewController:alertViewController + withTitle:@"Oops" + message:@"Please enter a valid address, city and/or state." + andAction:@"OK"]; + + [self presentViewController:alertViewController animated:YES completion:nil]; + +} + + +-(void)presentAlertViewForNoBusinessesFound{ + + + NYAlertViewController *alertViewController = [[NYAlertViewController alloc] initWithNibName:nil bundle:nil]; + + [self setUpCustomAlertViewController:alertViewController + withTitle:@"No businesses found." + message:@"Please try your search again" + andAction:@"OK"]; + + [self presentViewController:alertViewController animated:YES completion:nil]; + +} + +-(void)presentAlertViewForError{ + + NYAlertViewController *alertViewController = [[NYAlertViewController alloc] initWithNibName:nil bundle:nil]; + + [self setUpCustomAlertViewController:alertViewController + withTitle:@"Error" + message:@"Please try your search again" + andAction:@"OK"]; + + [self presentViewController:alertViewController animated:YES completion:nil]; +} + +-(void)setUpCustomAlertViewController: (NYAlertViewController *)alertViewController + withTitle: (NSString *)title + message: (NSString *)message + andAction: (NSString *)actionTitle{ + + // Set a title and message + alertViewController.title = title; + alertViewController.message = message; + + // Customize appearance as desired + alertViewController.buttonCornerRadius = 20.0f; + alertViewController.view.tintColor = self.view.tintColor; + + alertViewController.titleFont = [UIFont fontWithName:@"DistrictPro-Thin" size:19.0f]; + alertViewController.messageFont = [UIFont fontWithName:@"DistrictPro-Thin" size:16.0f]; + alertViewController.buttonTitleFont = [UIFont fontWithName:@"DistrictPro-Thin" size:alertViewController.buttonTitleFont.pointSize]; + alertViewController.cancelButtonTitleFont = [UIFont fontWithName:@"DistrictPro-Thin" size:alertViewController.cancelButtonTitleFont.pointSize]; + + alertViewController.swipeDismissalGestureEnabled = YES; + alertViewController.backgroundTapDismissalGestureEnabled = YES; + + // Add alert actions + [alertViewController addAction:[NYAlertAction actionWithTitle:actionTitle + style:UIAlertActionStyleCancel + handler:^(NYAlertAction *action) { + [self dismissViewControllerAnimated:YES completion:nil]; + }]]; +} + + +#pragma mark - CLLocationManagerDelegate methods + +- (void)locationManager:(CLLocationManager *)manager + didUpdateLocations:(NSArray *)locations{ + NSLog(@"did update locations"); +} + +-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ + NSLog(@"did fail with error"); +} + + +#pragma mark - tableViewDatasource methods + +-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ + + return 1; +} + +-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ + + return self.searchResults.count; +} + +-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ + + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"vegaNomCellIdentifier" forIndexPath:indexPath]; + + VegaNomSearchResult *currentResult = self.searchResults[indexPath.row]; + + cell.textLabel.text = currentResult.venueName; + + NSString *venueAddress = [APIManager createAddressFromArray:currentResult.venueAddress]; + + cell.detailTextLabel.text = venueAddress; + + UIImage *venueAvatar = [APIManager createImageFromString:currentResult.venueAvatar]; + + cell.imageView.image = venueAvatar; + + return cell; +} + +#pragma mark - textFieldDelegate methods + +-(BOOL)textFieldShouldReturn:(UITextField *)textField{ + + //dismiss keyboard + [self.view endEditing:YES]; + + self.searchTerm = self.whatTextField.text; + self.location = self.whereTextField.text; + + if ([self.location isEqualToString:@""]){ + + [self presentAlertViewForNoLocation]; + + }else{ + + [self makeNewYelpRequestWithSearchTerm:self.searchTerm andLocation: self.location callbackBlock:^{ + + [self.tableView reloadData]; + + [self updateMap]; + + self.searchTerm = nil; + self.location = nil; + }]; + } + + return YES; +} + + + +#pragma mark - Navigation + +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + + NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; + + VegaNomSearchResult *currentResult = self.searchResults [indexPath.row]; + + NSString *currentResultTagName = [APIManager createTagFromVenueName:currentResult.venueName]; + + InstagramDetailViewController *detailViewController = segue.destinationViewController; + + detailViewController.venueNameTag = currentResultTagName; + +} + +#pragma mark - map view methods + +-(void)updateMap{ + + [self.mapView removeAnnotations:self.mapView.annotations]; + + for (NSDictionary *business in self.businesses) { + [self addMapAnnotationForVenue:business]; + } +} + +-(void)addMapAnnotationForVenue: (NSDictionary *)venue{ + + MKPointAnnotation *mapPin = [[MKPointAnnotation alloc] init]; + + double lat = [venue[@"location"][@"coordinate"][@"latitude"]doubleValue]; + double lng = [venue[@"location"][@"coordinate"][@"longitude"]doubleValue]; + + CLLocationCoordinate2D latLng = CLLocationCoordinate2DMake(lat, lng); + + CLLocationCoordinate2D center = latLng; + MKCoordinateSpan span = MKCoordinateSpanMake(0.25, 0.25); + [self.mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES]; + + mapPin.coordinate = latLng; + mapPin.title = venue[@"name"]; + mapPin.subtitle = [self findIfVenueIsClosedOrOpen:venue[@"is_closed"]]; + + [self.mapView addAnnotation:mapPin]; +} + +-(NSString *)findIfVenueIsClosedOrOpen: (BOOL)isClosed{ + + NSString *openOrClosed; + + if (isClosed) { + openOrClosed = @"Currently Closed"; + }else{ + + openOrClosed = @"OPEN"; + } + return openOrClosed; +} + +@end diff --git a/podfile b/podfile new file mode 100644 index 0000000..946eb90 --- /dev/null +++ b/podfile @@ -0,0 +1 @@ +pod 'SDWebImage', '~>3.7' \ No newline at end of file