text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```objective-c // UIActivityIndicatorView+AFNetworking.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> @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:(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:(AFURLConnectionOperation *)operation; @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
468
```objective-c // UIImageView+AFNetworking.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> @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 loadiing 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 <AFImageCache>)sharedImageCache; /** Set the cache used for image loading. @param imageCache The image cache. */ + (void)setSharedImageCache:(id <AFImageCache>)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 path_to_url */ @property (nonatomic, strong) id <AFURLResponseSerialization> 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:(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 request and response parameters will be `nil`. @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. */ - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest placeholderImage:(UIImage *)placeholderImage success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; /** Cancels any executing image 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 <NSObject> /** Returns a cached image for the specififed request, if available. @param request The image request. @return The cached image. */ - (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 #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,424
```objective-c // UIProgressView+AFNetworking.m // // // 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 <objc/runtime.h> #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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,639
```objective-c // UIRefreshControl+AFNetworking.m // // // 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" #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFHTTPRequestOperation.h" #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 #import "AFURLSessionManager.h" #endif @implementation UIRefreshControl (AFNetworking) #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) { if (task.state != NSURLSessionTaskStateCompleted) { if (task.state == NSURLSessionTaskStateRunning) { [self beginRefreshing]; } else { [self endRefreshing]; } [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]; } } } #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) { if (![operation isFinished]) { if ([operation isExecuting]) { [self beginRefreshing]; } else { [self endRefreshing]; } [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingOperationDidStartNotification object:operation]; [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingOperationDidFinishNotification object:operation]; } } } #pragma mark - - (void)af_beginRefreshing { dispatch_async(dispatch_get_main_queue(), ^{ [self beginRefreshing]; }); } - (void)af_endRefreshing { dispatch_async(dispatch_get_main_queue(), ^{ [self endRefreshing]; }); } @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
737
```objective-c // UIButton+AFNetworking.m // // // 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 <objc/runtime.h> #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 const char * af_imageRequestOperationKeyForState(UIControlState state) { return [[NSString stringWithFormat:@"af_imageRequestOperationKeyForState_%lu", (unsigned long)state] cStringUsingEncoding:NSASCIIStringEncoding]; } - (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 const char * af_backgroundImageRequestOperationKeyForState(UIControlState state) { return [[NSString stringWithFormat:@"af_backgroundImageRequestOperationKeyForState_%lu", (unsigned long)state] cStringUsingEncoding:NSASCIIStringEncoding]; } - (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 <AFImageCache>)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 <AFImageCache>)imageCache { objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - - (id <AFURLResponseSerialization>)imageResponseSerializer { static id <AFURLResponseSerialization> _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 <AFURLResponseSerialization>)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.response 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]; } } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if ([[urlRequest URL] isEqual:[operation.response 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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,098
```objective-c // UIButton+AFNetworking.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> @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. */ @interface UIButton (AFNetworking) ///---------------------------- /// @name Accessing Image Cache ///---------------------------- /** The image cache used to improve image loadiing performance on scroll views. By default, `UIButton` will use the `sharedImageCache` of `UIImageView`. */ + (id <AFImageCache>)sharedImageCache; /** Set the cache used for image loading. @param imageCache The image cache. */ + (void)setSharedImageCache:(id <AFImageCache>)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 path_to_url */ @property (nonatomic, strong) id <AFURLResponseSerialization> 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:(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:(UIImage *)placeholderImage success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(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:(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:(UIImage *)placeholderImage success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(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 #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,800
```objective-c // UIActivityIndicatorView+AFNetworking.m // // // 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" #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFHTTPRequestOperation.h" #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 #import "AFURLSessionManager.h" #endif @implementation UIActivityIndicatorView (AFNetworking) #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) { if (task.state == NSURLSessionTaskStateRunning) { [self startAnimating]; } else { [self stopAnimating]; } [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]) { if ([operation isExecuting]) { [self startAnimating]; } else { [self stopAnimating]; } [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(), ^{ [self startAnimating]; }); } - (void)af_stopAnimating { dispatch_async(dispatch_get_main_queue(), ^{ [self stopAnimating]; }); } @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
737
```objective-c // UIKit+AFNetworking.h // // // 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 <UIKit/UIKit.h> #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 "UIKit+AFNetworking.h" #import "UIProgressView+AFNetworking.h" #import "UIRefreshControl+AFNetworking.h" #import "UIWebView+AFNetworking.h" #endif /* _UIKIT_AFNETWORKING_ */ ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
359
```objective-c // UIRefreshControl+AFNetworking.m // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> @class AFURLConnectionOperation; /** This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically begining 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 diabled. */ #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 #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
471
```objective-c // AFNetworkActivityIndicatorManager.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> /** `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; By setting `isNetworkActivityIndicatorVisible` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: path_to_url#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 */ @interface AFNetworkActivityIndicatorManager : NSObject /** A Boolean value indicating whether the manager is enabled. If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. */ @property (nonatomic, assign, getter = isEnabled) BOOL enabled; /** A Boolean value indicating whether the network activity indicator is currently displayed in the status bar. */ @property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible; /** Returns the shared network activity indicator manager object for the system. @return The systemwide network activity indicator manager. */ + (instancetype)sharedManager; /** Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. */ - (void)incrementActivityCount; /** Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. */ - (void)decrementActivityCount; @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
710
```objective-c // UIWebView+AFNetworking.m // // // 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 <objc/runtime.h> #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 <AFURLRequestSerialization> *)requestSerializer { static AFHTTPRequestSerializer <AFURLRequestSerialization> *_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<AFURLRequestSerialization> *)requestSerializer { objc_setAssociatedObject(self, @selector(requestSerializer), requestSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer { static AFHTTPResponseSerializer <AFURLResponseSerialization> *_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<AFURLResponseSerialization> *)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]]; #pragma clang diagnostic pop } failure:^(AFHTTPRequestOperation * __unused operation, NSError *error) { if (failure) { failure(error); } }]; [self.af_HTTPRequestOperation start]; } @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,274
```objective-c // UIAlertView+AFNetworking.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> @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:(id)delegate; #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:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION; #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:(id)delegate; /** 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:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION; @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
942
```objective-c // UIAlertView+AFNetworking.m // // // 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 { __block 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 alloc] initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil] show]; } [[NSNotificationCenter defaultCenter] removeObserver:observer name:AFNetworkingTaskDidCompleteNotification object:notification.object]; }]; } #endif #pragma mark - + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation delegate:(id)delegate { [self showAlertViewForRequestOperationWithErrorOnCompletion:operation delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlert View Cancel Button Title") otherButtonTitles:nil, nil]; } + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION { __block 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 alloc] initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil] show]; } } [[NSNotificationCenter defaultCenter] removeObserver:observer name:AFNetworkingOperationDidFinishNotification object:notification.object]; }]; } @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,037
```objective-c // UIWebView+AFNetworking.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> @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 <AFURLRequestSerialization> * 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 <AFURLResponseSerialization> * 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:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success failure:(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:(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; @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,172
```objective-c // UIProgressView+AFNetworking.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> @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 #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
653
```objective-c // UIImageView+AFNetworking.m // // // 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 <objc/runtime.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFHTTPRequestOperation.h" @interface AFImageCache : NSCache <AFImageCache> @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 <AFImageCache>)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 <AFImageCache>)imageCache { objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - - (id <AFURLResponseSerialization>)imageResponseSerializer { static id <AFURLResponseSerialization> _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 <AFURLResponseSerialization>)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(nil, 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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,577
```objective-c // AFNetworkActivityIndicatorManager.m // // // 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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,227
```objective-c // AFHTTPRequestOperation.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import "AFURLConnectionOperation.h" /** `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) 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 <AFURLResponseSerialization> * 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) 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:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFHTTPRequestOperation.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
828
```objective-c // AFSecurity.m // // // 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" // Equivalent of macro in <AssertMacros.h>, without causing compiler warning: // "'DebugAssert' is deprecated: first deprecated in OS X 10.8" #ifndef AF_Require #define AF_Require(assertion, exceptionLabel) \ do { \ if (__builtin_expect(!(assertion), 0)) { \ goto exceptionLabel; \ } \ } while (0) #endif #ifndef AF_Require_noErr #define AF_Require_noErr(errorCode, exceptionLabel) \ do { \ if (__builtin_expect(0 != (errorCode), 0)) { \ goto exceptionLabel; \ } \ } while (0) #endif #if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED) static NSData * AFSecKeyGetData(SecKeyRef key) { CFDataRef data = NULL; AF_Require_noErr(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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 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); AF_Require(allowedCertificate != NULL, _out); allowedCertificates[0] = allowedCertificate; tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); policy = SecPolicyCreateBasicX509(); AF_Require_noErr(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); AF_Require_noErr(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; AF_Require_noErr(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; AF_Require_noErr(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); SecTrustResultType result; AF_Require_noErr(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, 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.validatesDomainName = YES; [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]]; return securityPolicy; } - (id)init { self = [super init]; if (!self) { return nil; } self.validatesCertificateChain = YES; return self; } #pragma mark - - (void)setPinnedCertificates:(NSArray *)pinnedCertificates { _pinnedCertificates = pinnedCertificates; 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 { 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 (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { return NO; } NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); switch (self.SSLPinningMode) { case AFSSLPinningModeNone: return YES; 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; } if (!self.validatesCertificateChain) { return YES; } NSUInteger trustedCertificateCount = 0; for (NSData *trustChainCertificate in serverCertificates) { if ([self.pinnedCertificates containsObject:trustChainCertificate]) { trustedCertificateCount++; } } return trustedCertificateCount == [serverCertificates count]; } case AFSSLPinningModePublicKey: { NSUInteger trustedPublicKeyCount = 0; NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); if (!self.validatesCertificateChain && [publicKeys count] > 0) { publicKeys = @[[publicKeys firstObject]]; } for (id trustChainPublicKey in publicKeys) { for (id pinnedPublicKey in self.pinnedPublicKeys) { if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { trustedPublicKeyCount += 1; } } } return trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1)); } } return NO; } #pragma mark - NSKeyValueObserving + (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { return [NSSet setWithObject:@"pinnedCertificates"]; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFSecurityPolicy.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,359
```objective-c // AFURLSessionManager.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import "AFURLResponseSerialization.h" #import "AFURLRequestSerialization.h" #import "AFSecurityPolicy.h" #import "AFNetworkReachabilityManager.h" /** `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`. ## 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. */ #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) @interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying> /** 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 <AFURLResponseSerialization> 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; ///-------------------------------------- /// @name Monitoring Network Reachability ///-------------------------------------- /** The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. */ @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; ///---------------------------- /// @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. */ @property (nonatomic, strong) dispatch_queue_t completionQueue; /** The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. */ @property (nonatomic, strong) dispatch_group_t completionGroup; ///--------------------------------- /// @name 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 path_to_url */ @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:(NSURLSessionConfiguration *)configuration; /** 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:(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 * __autoreleasing *)progress completionHandler:(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:(NSData *)bodyData progress:(NSProgress * __autoreleasing *)progress completionHandler:(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 * __autoreleasing *)progress completionHandler:(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 * __autoreleasing *)progress destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(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 * __autoreleasing *)progress destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(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. */ - (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. */ - (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:(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:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *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:(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:(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:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *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:(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:(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:(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:(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:(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:(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:(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:(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:(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:(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; ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFURLSessionManager.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
5,781
```objective-c // AFSerialization.h // // // 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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) #import <Cocoa/Cocoa.h> #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 <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) { id value = [(NSDictionary *)JSONObject objectForKey:key]; if (!value || [value isEqual:[NSNull null]]) { [mutableDictionary removeObjectForKey:key]; } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { [mutableDictionary setObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions) forKey:key]; } } 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) { 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]) { 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", @"text/html", @"text/plain", 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 path_to_url 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 path_to_url 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", @"text/html", @"text/plain", 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", @"text/html", @"text/plain", 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 <CoreGraphics/CoreGraphics.h> static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { UIImage *image = [[UIImage alloc] initWithData:data]; return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; } static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { if (!data || [data length] == 0) { return nil; } 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); // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so if so, fall back to AFImageWithDataAtScale if (imageRef) { CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); 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; } size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate 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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) self.imageScale = [[UIScreen mainScreen] scale]; 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 <AFURLResponseSerialization> 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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFURLResponseSerialization.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
5,814
```objective-c // AFNetworkReachabilityManager.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <SystemConfiguration/SystemConfiguration.h> typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { AFNetworkReachabilityStatusUnknown = -1, AFNetworkReachabilityStatusNotReachable = 0, AFNetworkReachabilityStatusReachableViaWWAN = 1, AFNetworkReachabilityStatusReachableViaWiFi = 2, }; /** `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 (path_to_url @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; ///-------------------------------------------------- /// @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:(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 <SystemConfiguration/SystemConfiguration.h>` 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); ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,447
```objective-c // AFHTTPRequestOperationManager.m // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import "AFHTTPRequestOperationManager.h" #import "AFHTTPRequestOperation.h" #import <Availability.h> #import <Security/Security.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> #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 <AFURLRequestSerialization> *)requestSerializer { NSParameterAssert(requestSerializer); _requestSerializer = requestSerializer; } - (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer { NSParameterAssert(responseSerializer); _responseSerializer = responseSerializer; } #pragma mark - - (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 { NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request 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 { NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"HEAD" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) { if (success) { success(requestOperation); } } failure:failure]; [self.operationQueue addOperation:operation]; return operation; } //////////////////////////////////////////////////// - (AFHTTPRequestOperation *)POST:(NSString *)URLString sign:(NSString *)sign token:(NSString *)token parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; if (sign) { [request addValue:sign forHTTPHeaderField:@"sign"]; } [request addValue:token forHTTPHeaderField:@"TOKEN"]; // NSDictionary *phoneInfo = [CWGlobal obtainPhoneInfo]; // [request addValue:[phoneInfo objectForKey:@"device_id"] forHTTPHeaderField:@"device_id"]; // [request addValue:[phoneInfo objectForKey:@"app_version"] forHTTPHeaderField:@"app_version"]; // [request addValue:[phoneInfo objectForKey:@"app_sign"] forHTTPHeaderField:@"app_sign"];//bundle ID // [request addValue:[phoneInfo objectForKey:@"platform"] forHTTPHeaderField:@"platform"];// // [request addValue:[phoneInfo objectForKey:@"phone_model"] forHTTPHeaderField:@"phone_model"];// // [request addValue:[phoneInfo objectForKey:@"rom_info"] forHTTPHeaderField:@"rom_info"];// AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; [self.operationQueue addOperation:operation]; return operation; } // heard sign - (AFHTTPRequestOperation *)POST:(NSString *)URLString sign:(NSString *)sign parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; if (sign) { [request addValue:sign forHTTPHeaderField:@"sign"]; } AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success 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 { NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; [self.operationQueue addOperation:operation]; return operation; } - (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:nil]; AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; [self.operationQueue addOperation:operation]; return operation; } //=============== sign token ==================== - (AFHTTPRequestOperation *)POST:(NSString *)URLString sign:(NSString *)sign token:(NSString *)token parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:nil]; //-------------------------------------- if (sign) { [request addValue:sign forHTTPHeaderField:@"sign"]; } [request addValue:token forHTTPHeaderField:@"TOKEN"]; //-------------------------------------- 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 { NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PUT" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request 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 { NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PATCH" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request 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 { NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"DELETE" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request 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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,736
```objective-c // AFNetworkReachabilityManager.m // // // 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" #import <netinet/in.h> #import <netinet6/in6.h> #import <arpa/inet.h> #import <ifaddrs.h> #import <netdb.h> 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]; [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }]; }); } 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, assign) SCNetworkReachabilityRef 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 = reachability; self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; return self; } - (void)dealloc { [self stopMonitoring]; if (_networkReachability) { CFRelease(_networkReachability); _networkReachability = NULL; } } #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); } }; SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); SCNetworkReachabilityScheduleWithRunLoop(self.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(self.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(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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,061
```objective-c // AFURLConnectionOperation.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import "AFSecurityPolicy.h" /** `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"](path_to_url#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. ## App Extensions When using AFNetworking in an App Extension, `#define AF_APP_EXTENSIONS` to avoid using unavailable APIs. ## 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. */ @interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying> ///------------------------------- /// @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) NSURLResponse *response; /** The error, if any, that occurred in the lifecycle of the request. */ @property (readonly, nonatomic, strong) NSError *error; ///---------------------------- /// @name Getting Response Data ///---------------------------- /** The data received during the request. */ @property (readonly, nonatomic, strong) NSData *responseData; /** The string representation of the response data. */ @property (readonly, nonatomic, copy) 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) 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) NSOutputStream *outputStream; ///--------------------------------- /// @name Managing Callback Queues ///--------------------------------- /** The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. */ @property (nonatomic, strong) dispatch_queue_t completionQueue; /** The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. */ @property (nonatomic, strong) dispatch_group_t completionGroup; ///--------------------------------------------- /// @name Managing Request Operation Information ///--------------------------------------------- /** The user info dictionary for the receiver. */ @property (nonatomic, strong) NSDictionary *userInfo; ///------------------------------------------------------ /// @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; ///---------------------------------- /// @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 applications remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the applications suspension momentarily while the application is notified. */ #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler; #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:(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:(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:(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:(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:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; /// /** */ + (NSArray *)batchOfRequestOperations:(NSArray *)operations progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock completionBlock:(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; ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFURLConnectionOperation.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
3,202
```objective-c // AFSerialization.h // // // 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 <MobileCoreServices/MobileCoreServices.h> #else #import <CoreServices/CoreServices.h> #endif NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, NSDictionary *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]; } static NSString * const kAFCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*"; static NSString * AFPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { static NSString * const kAFCharactersToLeaveUnescapedInQueryStringPairKey = @"[]."; return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); } static NSString * AFPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); } #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 *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding; @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 *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding { if (!self.value || [self.value isEqual:[NSNull null]]) { return AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding); } else { return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), AFPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)]; } } @end #pragma mark - extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); static NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) { NSMutableArray *mutablePairs = [NSMutableArray array]; for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]]; } 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 objectForKey: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 <AFMultipartFormData> - (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 path_to_url#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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) // User-Agent Header; see path_to_url#sec14.43 userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__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 path_to_url 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 - - (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 *, NSDictionary *, 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 <AFMultipartFormData> 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 <AFMultipartFormData> 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 { if (!request.HTTPBodyStream) { return [request mutableCopy]; } 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 = AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding); 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 - (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 <NSStreamDelegate> @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 objectForKey: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 () <NSCopying> @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 objectAtIndex:0] 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 () <NSCopying> { 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]) { [self performSelectorOnMainThread:@selector(transitionToNextPhase) withObject:nil waitUntilDone:YES]; 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"]) { NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); [mutableRequest setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] 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"]) { NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); [mutableRequest setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] 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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFURLRequestSerialization.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
10,434
```objective-c // AFSerialization.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <CoreGraphics/CoreGraphics.h> /** 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 <NSObject, NSSecureCoding, NSCopying> /** 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. */ - (id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__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 <AFURLResponseSerialization> /** The string encoding used to serialize parameters. */ @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 path_to_url */ @property (nonatomic, copy) 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) 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:(NSHTTPURLResponse *)response data:(NSData *)data error:(NSError *__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 /** 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 - /** `AFXMLParserSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. By default, `AFXMLParserSerializer` 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 /** `AFXMLDocumentSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. By default, `AFXMLDocumentSerializer` 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 /** 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 - /** `AFPropertyListSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. By default, `AFPropertyListSerializer` accepts the following MIME types: - `application/x-plist` */ @interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer /** 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 - /** `AFImageSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. By default, `AFImageSerializer` 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; ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFURLResponseSerialization.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,277
```objective-c // AFURLSessionManager.m // // // 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" #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 <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate> @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; if (self.downloadFileURL) { userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; } else if (self.mutableData) { userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = [NSData dataWithData:self.mutableData]; } 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:[NSData dataWithData:self.mutableData] 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 - @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 (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]; self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; 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]; } }]; return self; } #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); [task addObserver:self forKeyPath:NSStringFromSelector(@selector(state)) options:(NSKeyValueObservingOptions)(NSKeyValueObservingOptionOld |NSKeyValueObservingOptionNew) context:AFTaskStateChangedContext]; [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; [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]; } } delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount]; delegate.progress.pausingHandler = ^{ [uploadTask suspend]; }; delegate.progress.cancellationHandler = ^{ [uploadTask cancel]; }; if (progress) { *progress = delegate.progress; } [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; } [self setDelegate:delegate forTask:downloadTask]; } - (void)removeDelegateForTask:(NSURLSessionTask *)task { NSParameterAssert(task); [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(state)) context:AFTaskStateChangedContext]; [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 <AFURLResponseSerialization>)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 - NSKeyValueObserving - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context == AFTaskStateChangedContext && [keyPath isEqualToString:@"state"]) { if (change[NSKeyValueChangeOldKey] && change[NSKeyValueChangeNewKey] && [change[NSKeyValueChangeNewKey] isEqual:change[NSKeyValueChangeOldKey]]) { return; } NSString *notificationName = nil; switch ([(NSURLSessionTask *)object state]) { case NSURLSessionTaskStateRunning: notificationName = AFNetworkingTaskDidResumeNotification; break; case NSURLSessionTaskStateSuspended: notificationName = AFNetworkingTaskDidSuspendNotification; break; case NSURLSessionTaskStateCompleted: // AFNetworkingTaskDidFinishNotification posted by task completion handlers default: break; } if (notificationName) { dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:object]; }); } } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } #pragma mark - NSURLSessionDelegate - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error { if (self.sessionDidBecomeInvalid) { self.sessionDidBecomeInvalid(session, error); } [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { NSArray *tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; for (NSURLSessionTask *task in tasks) { [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(state)) context:AFTaskStateChangedContext]; } [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 { if (self.downloadTaskDidFinishDownloading) { NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); if (fileURL) { NSError *error = nil; [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]; if (error) { [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; } return; } } AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; 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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFURLSessionManager.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
8,978
```objective-c // AFHTTPSessionManager.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <SystemConfiguration/SystemConfiguration.h> #import <Availability.h> #if __IPHONE_OS_VERSION_MIN_REQUIRED #import <MobileCoreServices/MobileCoreServices.h> #else #import <CoreServices/CoreServices.h> #endif #import "AFURLSessionManager.h" /** `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 `<AFURLRequestSerialization>`. Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>` ## 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:@"path_to_url"]; [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"path_to_url" relativeToURL:baseURL]; // path_to_url 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. */ #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) @interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying> /** 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) 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 <AFURLRequestSerialization> * 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 <AFURLResponseSerialization> * 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:(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:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration; ///--------------------------- /// @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: */ - (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(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: */ - (NSURLSessionDataTask *)HEAD:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task))success failure:(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: */ - (NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(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: */ - (NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(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: */ - (NSURLSessionDataTask *)PUT:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(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: */ - (NSURLSessionDataTask *)PATCH:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(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: */ - (NSURLSessionDataTask *)DELETE:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFHTTPSessionManager.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,822
```objective-c // AFNetworking.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Availability.h> #ifndef _AFNETWORKING_ #define _AFNETWORKING_ #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import "AFSecurityPolicy.h" #import "AFNetworkReachabilityManager.h" #import "AFURLConnectionOperation.h" #import "AFHTTPRequestOperation.h" #import "AFHTTPRequestOperationManager.h" #if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \ ( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) ) #import "AFURLSessionManager.h" #import "AFHTTPSessionManager.h" #endif #endif /* _AFNETWORKING_ */ ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFNetworking.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
402
```objective-c // AFURLConnectionOperation.m // // // 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 <UIKit/UIKit.h> #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, }; #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier; #else typedef id AFBackgroundTaskIdentifier; #endif 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); 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, assign) AFBackgroundTaskIdentifier backgroundTaskIdentifier; @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; } - (void)dealloc { if (_outputStream) { [_outputStream close]; _outputStream = nil; } #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) if (_backgroundTaskIdentifier) { [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier]; _backgroundTaskIdentifier = UIBackgroundTaskInvalid; } #endif } #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) && !defined(AF_APP_EXTENSIONS) - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { [self.lock lock]; if (!self.backgroundTaskIdentifier) { UIApplication *application = [UIApplication sharedApplication]; __weak __typeof(self)weakSelf = self; self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ __strong __typeof(weakSelf)strongSelf = weakSelf; if (handler) { handler(); } if (strongSelf) { [strongSelf cancel]; [application endBackgroundTask:strongSelf.backgroundTaskIdentifier]; strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; } }]; } [self.lock unlock]; } #endif #pragma mark - - (void)setState:(AFOperationState)state { if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) { return; } [self.lock lock]; NSString *oldStateKey = AFKeyPathFromOperationState(self.state); NSString *newStateKey = AFKeyPathFromOperationState(state); [self willChangeValueForKey:newStateKey]; [self willChangeValueForKey:oldStateKey]; _state = state; [self didChangeValueForKey:oldStateKey]; [self didChangeValueForKey:newStateKey]; [self.lock unlock]; } - (void)pause { if ([self isPaused] || [self isFinished] || [self isCancelled]) { return; } [self.lock lock]; if ([self isExecuting]) { [self 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 = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; } 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 { // Accomodate race condition where `self.connection` has not yet been set before cancellation self.error = error; [self finish]; } } } #pragma mark - + (NSArray *)batchOfRequestOperations:(NSArray *)operations progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock completionBlock:(void (^)(NSArray *operations))completionBlock { if (!operations || [operations count] == 0) { return @[[NSBlockOperation blockOperationWithBlock:^{ dispatch_async(dispatch_get_main_queue(), ^{ if (completionBlock) { completionBlock(@[]); } }); }]]; } __block dispatch_group_t group = dispatch_group_create(); NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{ dispatch_group_notify(group, dispatch_get_main_queue(), ^{ if (completionBlock) { completionBlock(operations); } }); }]; for (AFURLConnectionOperation *operation in operations) { operation.completionGroup = group; void (^originalCompletionBlock)(void) = [operation.completionBlock copy]; __weak __typeof(operation)weakOperation = operation; operation.completionBlock = ^{ __strong __typeof(weakOperation)strongOperation = weakOperation; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue(); #pragma clang diagnostic pop dispatch_group_async(group, queue, ^{ if (originalCompletionBlock) { originalCompletionBlock(); } NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) { return [op isFinished]; }] count]; if (progressBlock) { progressBlock(numberOfFinishedOperations, [operations count]); } dispatch_group_leave(group); }); }; dispatch_group_enter(group); [batchedOperation addDependency:operation]; } return [operations arrayByAddingObject:batchedOperation]; } #pragma mark - NSObject - (NSString *)description { return [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response]; } #pragma mark - 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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFURLConnectionOperation.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
5,559
```objective-c // AFSerialization.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> #endif /** 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 <NSObject, NSSecureCoding, NSCopying> /** 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. */ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(id)parameters error:(NSError * __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 <AFURLRequestSerialization> /** The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default. */ @property (nonatomic, assign) NSStringEncoding stringEncoding; /** Whether created requests can use the devices 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. */ @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:(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` */ - (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:(NSString * (^)(NSURLRequest *request, NSDictionary *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 occured while constructing the request. @return An `NSMutableURLRequest` object. */ - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters error:(NSError * __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 <AFMultipartFormData> 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 path_to_url#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 occured while constructing the request. @return An `NSMutableURLRequest` object */ - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block error:(NSError * __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. @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 path_to_url */ - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request writingStreamContentsToFile:(NSURL *)fileURL completionHandler:(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 * __autoreleasing *)error; /** Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. @param name The name to be associated with the specified data. This parameter must not be `nil`. @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. @param error If an error occurs, upon return contains an `NSError` object that describes the problem. @return `YES` if the file data was successfully appended otherwise `NO`. */ - (BOOL)appendPartWithFileURL:(NSURL *)fileURL name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType error:(NSError * __autoreleasing *)error; /** Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. @param inputStream The input stream to be appended to the form data @param name The name to be associated with the specified input stream. This parameter must not be `nil`. @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. @param length The length of the specified input stream in bytes. @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see path_to_url This parameter must not be `nil`. */ - (void)appendPartWithInputStream:(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 path_to_url 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:(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 - @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 @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 ///---------------- /// @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 AFNetworkingOperationFailingURLResponseErrorKey` ### Constants `AFNetworkingOperationFailingURLRequestErrorKey` The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `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; ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFURLRequestSerialization.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
4,185
```objective-c // AFSecurity.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <Security/Security.h> 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. */ @interface AFSecurityPolicy : NSObject /** The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. */ @property (nonatomic, assign) AFSSLPinningMode SSLPinningMode; /** Whether to evaluate an entire SSL certificate chain, or just the leaf certificate. Defaults to `YES`. */ @property (nonatomic, assign) BOOL validatesCertificateChain; /** 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. */ @property (nonatomic, strong) 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 certificates CN field. Defaults to `YES` for `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate`, otherwise `NO`. */ @property (nonatomic, assign) BOOL validatesDomainName; ///----------------------------------------- /// @name Getting Specific Security Policies ///----------------------------------------- /** Returns the shared default security policy, which does not accept invalid certificates, 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:(NSString *)domain; @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. */ ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFSecurityPolicy.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,017
```objective-c // AFHTTPRequestOperationManager.h // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <SystemConfiguration/SystemConfiguration.h> #import <Availability.h> #if __IPHONE_OS_VERSION_MIN_REQUIRED #import <MobileCoreServices/MobileCoreServices.h> #else #import <CoreServices/CoreServices.h> #endif #import "AFHTTPRequestOperation.h" #import "AFURLResponseSerialization.h" #import "AFURLRequestSerialization.h" #import "AFSecurityPolicy.h" #import "AFNetworkReachabilityManager.h" /** `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 `<AFURLRequestSerialization>`. Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>` ## 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:@"path_to_url"]; [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // path_to_url [NSURL URLWithString:@"path_to_url" relativeToURL:baseURL]; // path_to_url 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 <NSSecureCoding, NSCopying> /** 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) 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 <AFURLRequestSerialization> * 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 <AFURLResponseSerialization> * 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) 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. */ @property (nonatomic, strong) dispatch_queue_t completionQueue; /** The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used. */ @property (nonatomic, strong) dispatch_group_t completionGroup; ///--------------------------------------------- /// @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:(NSURL *)url; ///--------------------------------------- /// @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:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(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: */ - (AFHTTPRequestOperation *)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(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: */ - (AFHTTPRequestOperation *)HEAD:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation))success failure:(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: */ - (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; /** header sign,token*/ - (AFHTTPRequestOperation *)POST:(NSString *)URLString sign:(NSString *)sign token:(NSString *)token parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; /** heard sign */ - (AFHTTPRequestOperation *)POST:(NSString *)URLString sign:(NSString *)sign parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(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: */ - (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; /** header sign token **/ - (AFHTTPRequestOperation *)POST:(NSString *)URLString sign:(NSString *)sign token:(NSString *)token parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(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: */ - (AFHTTPRequestOperation *)PUT:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(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: */ - (AFHTTPRequestOperation *)PATCH:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(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: */ - (AFHTTPRequestOperation *)DELETE:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
3,701
```objective-c // AFHTTPSessionManager.m // // // 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) #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import <Availability.h> #import <Security/Security.h> #ifdef _SYSTEMCONFIGURATION_H #import <netinet/in.h> #import <netinet6/in6.h> #import <arpa/inet.h> #import <ifaddrs.h> #import <netdb.h> #endif #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> #endif @interface AFHTTPSessionManager () @property (readwrite, nonatomic, strong) NSURL *baseURL; @end @implementation AFHTTPSessionManager + (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 <AFURLRequestSerialization> *)requestSerializer { NSParameterAssert(requestSerializer); _requestSerializer = requestSerializer; } - (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)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 <AFMultipartFormData> 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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFHTTPSessionManager.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,401
```objective-c // // MASLayoutConstraint.h // Masonry // // Created by Jonas Budelmann on 3/08/13. // #import "MASUtilities.h" /** * When you are debugging or printing the constraints attached to a view this subclass * makes it easier to identify which constraints have been created via Masonry */ @interface MASLayoutConstraint : NSLayoutConstraint /** * a key to associate with this constraint */ @property (nonatomic, strong) id mas_key; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASLayoutConstraint.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
101
```objective-c // AFHTTPRequestOperation.m // // // 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 lock; - (instancetype)initWithRequest:(NSURLRequest *)urlRequest { self = [super initWithRequest:urlRequest]; if (!self) { return nil; } self.responseSerializer = [AFHTTPResponseSerializer serializer]; return self; } - (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)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 ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/AFNetworking/AFNetworking/AFHTTPRequestOperation.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,432
```objective-c // // MASCompositeConstraint.h // Masonry // // Created by Jonas Budelmann on 21/07/13. // #import "MASConstraint.h" #import "MASUtilities.h" /** * A group of MASConstraint objects */ @interface MASCompositeConstraint : MASConstraint /** * Creates a composite with a predefined array of children * * @param children child MASConstraints * * @return a composite constraint */ - (id)initWithChildren:(NSArray *)children; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASCompositeConstraint.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
106
```objective-c // // MASConstraint+Private.h // Masonry // // Created by Nick Tymchenko on 29/04/14. // #import "MASConstraint.h" @protocol MASConstraintDelegate; @interface MASConstraint () /** * Whether or not to check for an existing constraint instead of adding constraint */ @property (nonatomic, assign) BOOL updateExisting; /** * Usually MASConstraintMaker but could be a parent MASConstraint */ @property (nonatomic, weak) id<MASConstraintDelegate> delegate; /** * Based on a provided value type, is equal to calling: * NSNumber - setOffset: * NSValue with CGPoint - setPointOffset: * NSValue with CGSize - setSizeOffset: * NSValue with MASEdgeInsets - setInsets: */ - (void)setLayoutConstantWithValue:(NSValue *)value; @end @interface MASConstraint (Abstract) /** * Sets the constraint relation to given NSLayoutRelation * returns a block which accepts one of the following: * MASViewAttribute, UIView, NSValue, NSArray * see readme for more details. */ - (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation; /** * Override to set a custom chaining behaviour */ - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; @end @protocol MASConstraintDelegate <NSObject> /** * Notifies the delegate when the constraint needs to be replaced with another constraint. For example * A MASViewConstraint may turn into a MASCompositeConstraint when an array is passed to one of the equality blocks */ - (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint; - (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASConstraint+Private.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
381
```objective-c // // MASConstraint.m // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASViewConstraint.h" #import "MASConstraint+Private.h" #import "MASCompositeConstraint.h" #import "MASLayoutConstraint.h" #import "View+MASAdditions.h" #import <objc/runtime.h> @interface MAS_VIEW (MASConstraints) @property (nonatomic, readonly) NSMutableSet *mas_installedConstraints; @end @implementation MAS_VIEW (MASConstraints) static char kInstalledConstraintsKey; - (NSMutableSet *)mas_installedConstraints { NSMutableSet *constraints = objc_getAssociatedObject(self, &kInstalledConstraintsKey); if (!constraints) { constraints = [NSMutableSet set]; objc_setAssociatedObject(self, &kInstalledConstraintsKey, constraints, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } return constraints; } @end @interface MASViewConstraint () @property (nonatomic, strong, readwrite) MASViewAttribute *secondViewAttribute; @property (nonatomic, weak) MAS_VIEW *installedView; @property (nonatomic, weak) MASLayoutConstraint *layoutConstraint; @property (nonatomic, assign) NSLayoutRelation layoutRelation; @property (nonatomic, assign) MASLayoutPriority layoutPriority; @property (nonatomic, assign) CGFloat layoutMultiplier; @property (nonatomic, assign) CGFloat layoutConstant; @property (nonatomic, assign) BOOL hasLayoutRelation; @property (nonatomic, strong) id mas_key; @property (nonatomic, assign) BOOL useAnimator; @end @implementation MASViewConstraint - (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute { self = [super init]; if (!self) return nil; _firstViewAttribute = firstViewAttribute; self.layoutPriority = MASLayoutPriorityRequired; self.layoutMultiplier = 1; return self; } #pragma mark - NSCoping - (id)copyWithZone:(NSZone __unused *)zone { MASViewConstraint *constraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:self.firstViewAttribute]; constraint.layoutConstant = self.layoutConstant; constraint.layoutRelation = self.layoutRelation; constraint.layoutPriority = self.layoutPriority; constraint.layoutMultiplier = self.layoutMultiplier; constraint.delegate = self.delegate; return constraint; } #pragma mark - Public + (NSArray *)installedConstraintsForView:(MAS_VIEW *)view { return [view.mas_installedConstraints allObjects]; } #pragma mark - Private - (void)setLayoutConstant:(CGFloat)layoutConstant { _layoutConstant = layoutConstant; #if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) if (self.useAnimator) { [self.layoutConstraint.animator setConstant:layoutConstant]; } else { self.layoutConstraint.constant = layoutConstant; } #else self.layoutConstraint.constant = layoutConstant; #endif } - (void)setLayoutRelation:(NSLayoutRelation)layoutRelation { _layoutRelation = layoutRelation; self.hasLayoutRelation = YES; } - (BOOL)supportsActiveProperty { return [self.layoutConstraint respondsToSelector:@selector(isActive)]; } - (BOOL)isActive { BOOL active = YES; if ([self supportsActiveProperty]) { active = [self.layoutConstraint isActive]; } return active; } - (BOOL)hasBeenInstalled { return (self.layoutConstraint != nil) && [self isActive]; } - (void)setSecondViewAttribute:(id)secondViewAttribute { if ([secondViewAttribute isKindOfClass:NSValue.class]) { [self setLayoutConstantWithValue:secondViewAttribute]; } else if ([secondViewAttribute isKindOfClass:MAS_VIEW.class]) { _secondViewAttribute = [[MASViewAttribute alloc] initWithView:secondViewAttribute layoutAttribute:self.firstViewAttribute.layoutAttribute]; } else if ([secondViewAttribute isKindOfClass:MASViewAttribute.class]) { _secondViewAttribute = secondViewAttribute; } else { } } #pragma mark - NSLayoutConstraint multiplier proxies - (MASConstraint * (^)(CGFloat))multipliedBy { return ^id(CGFloat multiplier) { NSAssert(!self.hasBeenInstalled, @"Cannot modify constraint multiplier after it has been installed"); self.layoutMultiplier = multiplier; return self; }; } - (MASConstraint * (^)(CGFloat))dividedBy { return ^id(CGFloat divider) { NSAssert(!self.hasBeenInstalled, @"Cannot modify constraint multiplier after it has been installed"); self.layoutMultiplier = 1.0/divider; return self; }; } #pragma mark - MASLayoutPriority proxy - (MASConstraint * (^)(MASLayoutPriority))priority { return ^id(MASLayoutPriority priority) { NSAssert(!self.hasBeenInstalled, @"Cannot modify constraint priority after it has been installed"); self.layoutPriority = priority; return self; }; } #pragma mark - NSLayoutRelation proxy - (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { return ^id(id attribute, NSLayoutRelation relation) { if ([attribute isKindOfClass:NSArray.class]) { NSAssert(!self.hasLayoutRelation, @"Redefinition of constraint relation"); NSMutableArray *children = NSMutableArray.new; for (id attr in attribute) { MASViewConstraint *viewConstraint = [self copy]; viewConstraint.secondViewAttribute = attr; [children addObject:viewConstraint]; } MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; compositeConstraint.delegate = self.delegate; [self.delegate constraint:self shouldBeReplacedWithConstraint:compositeConstraint]; return compositeConstraint; } else { NSAssert(!self.hasLayoutRelation || self.layoutRelation == relation && [attribute isKindOfClass:NSValue.class], @"Redefinition of constraint relation"); self.layoutRelation = relation; self.secondViewAttribute = attribute; return self; } }; } #pragma mark - Semantic properties - (MASConstraint *)with { return self; } - (MASConstraint *)and { return self; } #pragma mark - attribute chaining - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { NSAssert(!self.hasLayoutRelation, @"Attributes should be chained before defining the constraint relation"); return [self.delegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; } #pragma mark - Animator proxy #if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) - (MASConstraint *)animator { self.useAnimator = YES; return self; } #endif #pragma mark - debug helpers - (MASConstraint * (^)(id))key { return ^id(id key) { self.mas_key = key; return self; }; } #pragma mark - NSLayoutConstraint constant setters - (void)setInsets:(MASEdgeInsets)insets { NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; switch (layoutAttribute) { case NSLayoutAttributeLeft: case NSLayoutAttributeLeading: self.layoutConstant = insets.left; break; case NSLayoutAttributeTop: self.layoutConstant = insets.top; break; case NSLayoutAttributeBottom: self.layoutConstant = -insets.bottom; break; case NSLayoutAttributeRight: case NSLayoutAttributeTrailing: self.layoutConstant = -insets.right; break; default: break; } } - (void)setOffset:(CGFloat)offset { self.layoutConstant = offset; } - (void)setSizeOffset:(CGSize)sizeOffset { NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; switch (layoutAttribute) { case NSLayoutAttributeWidth: self.layoutConstant = sizeOffset.width; break; case NSLayoutAttributeHeight: self.layoutConstant = sizeOffset.height; break; default: break; } } - (void)setCenterOffset:(CGPoint)centerOffset { NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; switch (layoutAttribute) { case NSLayoutAttributeCenterX: self.layoutConstant = centerOffset.x; break; case NSLayoutAttributeCenterY: self.layoutConstant = centerOffset.y; break; default: break; } } #pragma mark - MASConstraint - (void)activate { if ([self supportsActiveProperty] && self.layoutConstraint) { if (self.hasBeenInstalled) { return; } self.layoutConstraint.active = YES; [self.firstViewAttribute.view.mas_installedConstraints addObject:self]; } else { [self install]; } } - (void)deactivate { if ([self supportsActiveProperty]) { self.layoutConstraint.active = NO; [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; } else { [self uninstall]; } } - (void)install { if (self.hasBeenInstalled) { return; } MAS_VIEW *firstLayoutItem = self.firstViewAttribute.item; NSLayoutAttribute firstLayoutAttribute = self.firstViewAttribute.layoutAttribute; MAS_VIEW *secondLayoutItem = self.secondViewAttribute.item; NSLayoutAttribute secondLayoutAttribute = self.secondViewAttribute.layoutAttribute; // alignment attributes must have a secondViewAttribute // therefore we assume that is refering to superview // eg make.left.equalTo(@10) if (!self.firstViewAttribute.isSizeAttribute && !self.secondViewAttribute) { secondLayoutItem = self.firstViewAttribute.view.superview; secondLayoutAttribute = firstLayoutAttribute; } MASLayoutConstraint *layoutConstraint = [MASLayoutConstraint constraintWithItem:firstLayoutItem attribute:firstLayoutAttribute relatedBy:self.layoutRelation toItem:secondLayoutItem attribute:secondLayoutAttribute multiplier:self.layoutMultiplier constant:self.layoutConstant]; layoutConstraint.priority = self.layoutPriority; layoutConstraint.mas_key = self.mas_key; if (self.secondViewAttribute.view) { MAS_VIEW *closestCommonSuperview = [self.firstViewAttribute.view mas_closestCommonSuperview:self.secondViewAttribute.view]; self.installedView = closestCommonSuperview; } else if (self.firstViewAttribute.isSizeAttribute) { self.installedView = self.firstViewAttribute.view; } else { self.installedView = self.firstViewAttribute.view.superview; } MASLayoutConstraint *existingConstraint = nil; if (self.updateExisting) { existingConstraint = [self layoutConstraintSimilarTo:layoutConstraint]; } if (existingConstraint) { // just update the constant existingConstraint.constant = layoutConstraint.constant; self.layoutConstraint = existingConstraint; } else { [self.installedView addConstraint:layoutConstraint]; self.layoutConstraint = layoutConstraint; [firstLayoutItem.mas_installedConstraints addObject:self]; } } - (MASLayoutConstraint *)layoutConstraintSimilarTo:(MASLayoutConstraint *)layoutConstraint { // check if any constraints are the same apart from the only mutable property constant // go through constraints in reverse as we do not want to match auto-resizing or interface builder constraints // and they are likely to be added first. for (NSLayoutConstraint *existingConstraint in self.installedView.constraints.reverseObjectEnumerator) { if (![existingConstraint isKindOfClass:MASLayoutConstraint.class]) continue; if (existingConstraint.firstItem != layoutConstraint.firstItem) continue; if (existingConstraint.secondItem != layoutConstraint.secondItem) continue; if (existingConstraint.firstAttribute != layoutConstraint.firstAttribute) continue; if (existingConstraint.secondAttribute != layoutConstraint.secondAttribute) continue; if (existingConstraint.relation != layoutConstraint.relation) continue; if (existingConstraint.multiplier != layoutConstraint.multiplier) continue; if (existingConstraint.priority != layoutConstraint.priority) continue; return (id)existingConstraint; } return nil; } - (void)uninstall { [self.installedView removeConstraint:self.layoutConstraint]; self.layoutConstraint = nil; self.installedView = nil; [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASViewConstraint.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,535
```objective-c // // MASConstraintBuilder.m // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASConstraintMaker.h" #import "MASViewConstraint.h" #import "MASCompositeConstraint.h" #import "MASConstraint+Private.h" #import "MASViewAttribute.h" #import "View+MASAdditions.h" @interface MASConstraintMaker () <MASConstraintDelegate> @property (nonatomic, weak) MAS_VIEW *view; @property (nonatomic, strong) NSMutableArray *constraints; @end @implementation MASConstraintMaker - (id)initWithView:(MAS_VIEW *)view { self = [super init]; if (!self) return nil; self.view = view; self.constraints = NSMutableArray.new; return self; } - (NSArray *)install { if (self.removeExisting) { NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view]; for (MASConstraint *constraint in installedConstraints) { [constraint uninstall]; } } NSArray *constraints = self.constraints.copy; for (MASConstraint *constraint in constraints) { constraint.updateExisting = self.updateExisting; [constraint install]; } [self.constraints removeAllObjects]; return constraints; } #pragma mark - MASConstraintDelegate - (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { NSUInteger index = [self.constraints indexOfObject:constraint]; [self.constraints replaceObjectAtIndex:index withObject:replacementConstraint]; } - (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { MASViewAttribute *viewAttribute = [[MASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute]; MASViewConstraint *newConstraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute]; if ([constraint isKindOfClass:MASViewConstraint.class]) { //replace with composite constraint NSArray *children = @[constraint, newConstraint]; MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; compositeConstraint.delegate = self; [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint]; return compositeConstraint; } if (!constraint) { newConstraint.delegate = self; [self.constraints addObject:newConstraint]; } return newConstraint; } - (MASConstraint *)addConstraintWithAttributes:(MASAttribute)attrs { __unused MASAttribute anyAttribute = (MASAttributeLeft | MASAttributeRight | MASAttributeTop | MASAttributeBottom | MASAttributeLeading | MASAttributeTrailing | MASAttributeWidth | MASAttributeHeight | MASAttributeCenterX | MASAttributeCenterY | MASAttributeBaseline #if TARGET_OS_IPHONE || TARGET_OS_TV | MASAttributeLeftMargin | MASAttributeRightMargin | MASAttributeTopMargin | MASAttributeBottomMargin | MASAttributeLeadingMargin | MASAttributeTrailingMargin | MASAttributeCenterXWithinMargins | MASAttributeCenterYWithinMargins #endif ); NSAssert((attrs & anyAttribute) != 0, @"You didn't pass any attribute to make.attributes(...)"); NSMutableArray *attributes = [NSMutableArray array]; if (attrs & MASAttributeLeft) [attributes addObject:self.view.mas_left]; if (attrs & MASAttributeRight) [attributes addObject:self.view.mas_right]; if (attrs & MASAttributeTop) [attributes addObject:self.view.mas_top]; if (attrs & MASAttributeBottom) [attributes addObject:self.view.mas_bottom]; if (attrs & MASAttributeLeading) [attributes addObject:self.view.mas_leading]; if (attrs & MASAttributeTrailing) [attributes addObject:self.view.mas_trailing]; if (attrs & MASAttributeWidth) [attributes addObject:self.view.mas_width]; if (attrs & MASAttributeHeight) [attributes addObject:self.view.mas_height]; if (attrs & MASAttributeCenterX) [attributes addObject:self.view.mas_centerX]; if (attrs & MASAttributeCenterY) [attributes addObject:self.view.mas_centerY]; if (attrs & MASAttributeBaseline) [attributes addObject:self.view.mas_baseline]; #if TARGET_OS_IPHONE || TARGET_OS_TV if (attrs & MASAttributeLeftMargin) [attributes addObject:self.view.mas_leftMargin]; if (attrs & MASAttributeRightMargin) [attributes addObject:self.view.mas_rightMargin]; if (attrs & MASAttributeTopMargin) [attributes addObject:self.view.mas_topMargin]; if (attrs & MASAttributeBottomMargin) [attributes addObject:self.view.mas_bottomMargin]; if (attrs & MASAttributeLeadingMargin) [attributes addObject:self.view.mas_leadingMargin]; if (attrs & MASAttributeTrailingMargin) [attributes addObject:self.view.mas_trailingMargin]; if (attrs & MASAttributeCenterXWithinMargins) [attributes addObject:self.view.mas_centerXWithinMargins]; if (attrs & MASAttributeCenterYWithinMargins) [attributes addObject:self.view.mas_centerYWithinMargins]; #endif NSMutableArray *children = [NSMutableArray arrayWithCapacity:attributes.count]; for (MASViewAttribute *a in attributes) { [children addObject:[[MASViewConstraint alloc] initWithFirstViewAttribute:a]]; } MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; constraint.delegate = self; [self.constraints addObject:constraint]; return constraint; } #pragma mark - standard Attributes - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute]; } - (MASConstraint *)left { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; } - (MASConstraint *)top { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; } - (MASConstraint *)right { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; } - (MASConstraint *)bottom { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; } - (MASConstraint *)leading { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; } - (MASConstraint *)trailing { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; } - (MASConstraint *)width { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; } - (MASConstraint *)height { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; } - (MASConstraint *)centerX { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; } - (MASConstraint *)centerY { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; } - (MASConstraint *)baseline { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; } - (MASConstraint *(^)(MASAttribute))attributes { return ^(MASAttribute attrs){ return [self addConstraintWithAttributes:attrs]; }; } #if TARGET_OS_IPHONE || TARGET_OS_TV - (MASConstraint *)leftMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; } - (MASConstraint *)rightMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; } - (MASConstraint *)topMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; } - (MASConstraint *)bottomMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; } - (MASConstraint *)leadingMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; } - (MASConstraint *)trailingMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; } - (MASConstraint *)centerXWithinMargins { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; } - (MASConstraint *)centerYWithinMargins { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; } #endif #pragma mark - composite Attributes - (MASConstraint *)edges { return [self addConstraintWithAttributes:MASAttributeTop | MASAttributeLeft | MASAttributeRight | MASAttributeBottom]; } - (MASConstraint *)size { return [self addConstraintWithAttributes:MASAttributeWidth | MASAttributeHeight]; } - (MASConstraint *)center { return [self addConstraintWithAttributes:MASAttributeCenterX | MASAttributeCenterY]; } #pragma mark - grouping - (MASConstraint *(^)(dispatch_block_t group))group { return ^id(dispatch_block_t group) { NSInteger previousCount = self.constraints.count; group(); NSArray *children = [self.constraints subarrayWithRange:NSMakeRange(previousCount, self.constraints.count - previousCount)]; MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; constraint.delegate = self; return constraint; }; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASConstraintMaker.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,822
```objective-c // // MASCompositeConstraint.m // Masonry // // Created by Jonas Budelmann on 21/07/13. // #import "MASCompositeConstraint.h" #import "MASConstraint+Private.h" @interface MASCompositeConstraint () <MASConstraintDelegate> @property (nonatomic, strong) id mas_key; @property (nonatomic, strong) NSMutableArray *childConstraints; @end @implementation MASCompositeConstraint - (id)initWithChildren:(NSArray *)children { self = [super init]; if (!self) return nil; _childConstraints = [children mutableCopy]; for (MASConstraint *constraint in _childConstraints) { constraint.delegate = self; } return self; } #pragma mark - MASConstraintDelegate - (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { NSUInteger index = [self.childConstraints indexOfObject:constraint]; [self.childConstraints replaceObjectAtIndex:index withObject:replacementConstraint]; } - (MASConstraint *)constraint:(MASConstraint __unused *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { id<MASConstraintDelegate> strongDelegate = self.delegate; MASConstraint *newConstraint = [strongDelegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; newConstraint.delegate = self; [self.childConstraints addObject:newConstraint]; return newConstraint; } #pragma mark - NSLayoutConstraint multiplier proxies - (MASConstraint * (^)(CGFloat))multipliedBy { return ^id(CGFloat multiplier) { for (MASConstraint *constraint in self.childConstraints) { constraint.multipliedBy(multiplier); } return self; }; } - (MASConstraint * (^)(CGFloat))dividedBy { return ^id(CGFloat divider) { for (MASConstraint *constraint in self.childConstraints) { constraint.dividedBy(divider); } return self; }; } #pragma mark - MASLayoutPriority proxy - (MASConstraint * (^)(MASLayoutPriority))priority { return ^id(MASLayoutPriority priority) { for (MASConstraint *constraint in self.childConstraints) { constraint.priority(priority); } return self; }; } #pragma mark - NSLayoutRelation proxy - (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { return ^id(id attr, NSLayoutRelation relation) { for (MASConstraint *constraint in self.childConstraints.copy) { constraint.equalToWithRelation(attr, relation); } return self; }; } #pragma mark - attribute chaining - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { [self constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; return self; } #pragma mark - Animator proxy #if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) - (MASConstraint *)animator { for (MASConstraint *constraint in self.childConstraints) { [constraint animator]; } return self; } #endif #pragma mark - debug helpers - (MASConstraint * (^)(id))key { return ^id(id key) { self.mas_key = key; int i = 0; for (MASConstraint *constraint in self.childConstraints) { constraint.key([NSString stringWithFormat:@"%@[%d]", key, i++]); } return self; }; } #pragma mark - NSLayoutConstraint constant setters - (void)setInsets:(MASEdgeInsets)insets { for (MASConstraint *constraint in self.childConstraints) { constraint.insets = insets; } } - (void)setOffset:(CGFloat)offset { for (MASConstraint *constraint in self.childConstraints) { constraint.offset = offset; } } - (void)setSizeOffset:(CGSize)sizeOffset { for (MASConstraint *constraint in self.childConstraints) { constraint.sizeOffset = sizeOffset; } } - (void)setCenterOffset:(CGPoint)centerOffset { for (MASConstraint *constraint in self.childConstraints) { constraint.centerOffset = centerOffset; } } #pragma mark - MASConstraint - (void)activate { for (MASConstraint *constraint in self.childConstraints) { [constraint activate]; } } - (void)deactivate { for (MASConstraint *constraint in self.childConstraints) { [constraint deactivate]; } } - (void)install { for (MASConstraint *constraint in self.childConstraints) { constraint.updateExisting = self.updateExisting; [constraint install]; } } - (void)uninstall { for (MASConstraint *constraint in self.childConstraints) { [constraint uninstall]; } } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASCompositeConstraint.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
970
```objective-c // // MASLayoutConstraint.m // Masonry // // Created by Jonas Budelmann on 3/08/13. // #import "MASLayoutConstraint.h" @implementation MASLayoutConstraint @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASLayoutConstraint.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
43
```objective-c // // UIView+MASShorthandAdditions.h // Masonry // // Created by Jonas Budelmann on 22/07/13. // #import "View+MASAdditions.h" #ifdef MAS_SHORTHAND /** * Shorthand view additions without the 'mas_' prefixes, * only enabled if MAS_SHORTHAND is defined */ @interface MAS_VIEW (MASShorthandAdditions) @property (nonatomic, strong, readonly) MASViewAttribute *left; @property (nonatomic, strong, readonly) MASViewAttribute *top; @property (nonatomic, strong, readonly) MASViewAttribute *right; @property (nonatomic, strong, readonly) MASViewAttribute *bottom; @property (nonatomic, strong, readonly) MASViewAttribute *leading; @property (nonatomic, strong, readonly) MASViewAttribute *trailing; @property (nonatomic, strong, readonly) MASViewAttribute *width; @property (nonatomic, strong, readonly) MASViewAttribute *height; @property (nonatomic, strong, readonly) MASViewAttribute *centerX; @property (nonatomic, strong, readonly) MASViewAttribute *centerY; @property (nonatomic, strong, readonly) MASViewAttribute *baseline; @property (nonatomic, strong, readonly) MASViewAttribute *(^attribute)(NSLayoutAttribute attr); #if TARGET_OS_IPHONE || TARGET_OS_TV @property (nonatomic, strong, readonly) MASViewAttribute *leftMargin; @property (nonatomic, strong, readonly) MASViewAttribute *rightMargin; @property (nonatomic, strong, readonly) MASViewAttribute *topMargin; @property (nonatomic, strong, readonly) MASViewAttribute *bottomMargin; @property (nonatomic, strong, readonly) MASViewAttribute *leadingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *trailingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *centerXWithinMargins; @property (nonatomic, strong, readonly) MASViewAttribute *centerYWithinMargins; #endif - (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; @end #define MAS_ATTR_FORWARD(attr) \ - (MASViewAttribute *)attr { \ return [self mas_##attr]; \ } @implementation MAS_VIEW (MASShorthandAdditions) MAS_ATTR_FORWARD(top); MAS_ATTR_FORWARD(left); MAS_ATTR_FORWARD(bottom); MAS_ATTR_FORWARD(right); MAS_ATTR_FORWARD(leading); MAS_ATTR_FORWARD(trailing); MAS_ATTR_FORWARD(width); MAS_ATTR_FORWARD(height); MAS_ATTR_FORWARD(centerX); MAS_ATTR_FORWARD(centerY); MAS_ATTR_FORWARD(baseline); #if TARGET_OS_IPHONE || TARGET_OS_TV MAS_ATTR_FORWARD(leftMargin); MAS_ATTR_FORWARD(rightMargin); MAS_ATTR_FORWARD(topMargin); MAS_ATTR_FORWARD(bottomMargin); MAS_ATTR_FORWARD(leadingMargin); MAS_ATTR_FORWARD(trailingMargin); MAS_ATTR_FORWARD(centerXWithinMargins); MAS_ATTR_FORWARD(centerYWithinMargins); #endif - (MASViewAttribute *(^)(NSLayoutAttribute))attribute { return [self mas_attribute]; } - (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_makeConstraints:block]; } - (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_updateConstraints:block]; } - (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_remakeConstraints:block]; } @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/View+MASShorthandAdditions.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
712
```objective-c // // NSLayoutConstraint+MASDebugAdditions.m // Masonry // // Created by Jonas Budelmann on 3/08/13. // #import "NSLayoutConstraint+MASDebugAdditions.h" #import "MASConstraint.h" #import "MASLayoutConstraint.h" @implementation NSLayoutConstraint (MASDebugAdditions) #pragma mark - description maps + (NSDictionary *)layoutRelationDescriptionsByValue { static dispatch_once_t once; static NSDictionary *descriptionMap; dispatch_once(&once, ^{ descriptionMap = @{ @(NSLayoutRelationEqual) : @"==", @(NSLayoutRelationGreaterThanOrEqual) : @">=", @(NSLayoutRelationLessThanOrEqual) : @"<=", }; }); return descriptionMap; } + (NSDictionary *)layoutAttributeDescriptionsByValue { static dispatch_once_t once; static NSDictionary *descriptionMap; dispatch_once(&once, ^{ descriptionMap = @{ @(NSLayoutAttributeTop) : @"top", @(NSLayoutAttributeLeft) : @"left", @(NSLayoutAttributeBottom) : @"bottom", @(NSLayoutAttributeRight) : @"right", @(NSLayoutAttributeLeading) : @"leading", @(NSLayoutAttributeTrailing) : @"trailing", @(NSLayoutAttributeWidth) : @"width", @(NSLayoutAttributeHeight) : @"height", @(NSLayoutAttributeCenterX) : @"centerX", @(NSLayoutAttributeCenterY) : @"centerY", @(NSLayoutAttributeBaseline) : @"baseline", #if TARGET_OS_IPHONE || TARGET_OS_TV @(NSLayoutAttributeLeftMargin) : @"leftMargin", @(NSLayoutAttributeRightMargin) : @"rightMargin", @(NSLayoutAttributeTopMargin) : @"topMargin", @(NSLayoutAttributeBottomMargin) : @"bottomMargin", @(NSLayoutAttributeLeadingMargin) : @"leadingMargin", @(NSLayoutAttributeTrailingMargin) : @"trailingMargin", @(NSLayoutAttributeCenterXWithinMargins) : @"centerXWithinMargins", @(NSLayoutAttributeCenterYWithinMargins) : @"centerYWithinMargins", #endif }; }); return descriptionMap; } + (NSDictionary *)layoutPriorityDescriptionsByValue { static dispatch_once_t once; static NSDictionary *descriptionMap; dispatch_once(&once, ^{ #if TARGET_OS_IPHONE || TARGET_OS_TV descriptionMap = @{ @(MASLayoutPriorityDefaultHigh) : @"high", @(MASLayoutPriorityDefaultLow) : @"low", @(MASLayoutPriorityDefaultMedium) : @"medium", @(MASLayoutPriorityRequired) : @"required", @(MASLayoutPriorityFittingSizeLevel) : @"fitting size", }; #elif TARGET_OS_MAC descriptionMap = @{ @(MASLayoutPriorityDefaultHigh) : @"high", @(MASLayoutPriorityDragThatCanResizeWindow) : @"drag can resize window", @(MASLayoutPriorityDefaultMedium) : @"medium", @(MASLayoutPriorityWindowSizeStayPut) : @"window size stay put", @(MASLayoutPriorityDragThatCannotResizeWindow) : @"drag cannot resize window", @(MASLayoutPriorityDefaultLow) : @"low", @(MASLayoutPriorityFittingSizeCompression) : @"fitting size", @(MASLayoutPriorityRequired) : @"required", }; #endif }); return descriptionMap; } #pragma mark - description override + (NSString *)descriptionForObject:(id)obj { if ([obj respondsToSelector:@selector(mas_key)] && [obj mas_key]) { return [NSString stringWithFormat:@"%@:%@", [obj class], [obj mas_key]]; } return [NSString stringWithFormat:@"%@:%p", [obj class], obj]; } - (NSString *)description { NSMutableString *description = [[NSMutableString alloc] initWithString:@"<"]; [description appendString:[self.class descriptionForObject:self]]; [description appendFormat:@" %@", [self.class descriptionForObject:self.firstItem]]; if (self.firstAttribute != NSLayoutAttributeNotAnAttribute) { [description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.firstAttribute)]]; } [description appendFormat:@" %@", self.class.layoutRelationDescriptionsByValue[@(self.relation)]]; if (self.secondItem) { [description appendFormat:@" %@", [self.class descriptionForObject:self.secondItem]]; } if (self.secondAttribute != NSLayoutAttributeNotAnAttribute) { [description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.secondAttribute)]]; } if (self.multiplier != 1) { [description appendFormat:@" * %g", self.multiplier]; } if (self.secondAttribute == NSLayoutAttributeNotAnAttribute) { [description appendFormat:@" %g", self.constant]; } else { if (self.constant) { [description appendFormat:@" %@ %g", (self.constant < 0 ? @"-" : @"+"), ABS(self.constant)]; } } if (self.priority != MASLayoutPriorityRequired) { [description appendFormat:@" ^%@", self.class.layoutPriorityDescriptionsByValue[@(self.priority)] ?: [NSNumber numberWithDouble:self.priority]]; } [description appendString:@">"]; return description; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/NSLayoutConstraint+MASDebugAdditions.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,133
```objective-c // // MASConstraintBuilder.h // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASConstraint.h" #import "MASUtilities.h" typedef NS_OPTIONS(NSInteger, MASAttribute) { MASAttributeLeft = 1 << NSLayoutAttributeLeft, MASAttributeRight = 1 << NSLayoutAttributeRight, MASAttributeTop = 1 << NSLayoutAttributeTop, MASAttributeBottom = 1 << NSLayoutAttributeBottom, MASAttributeLeading = 1 << NSLayoutAttributeLeading, MASAttributeTrailing = 1 << NSLayoutAttributeTrailing, MASAttributeWidth = 1 << NSLayoutAttributeWidth, MASAttributeHeight = 1 << NSLayoutAttributeHeight, MASAttributeCenterX = 1 << NSLayoutAttributeCenterX, MASAttributeCenterY = 1 << NSLayoutAttributeCenterY, MASAttributeBaseline = 1 << NSLayoutAttributeBaseline, #if TARGET_OS_IPHONE || TARGET_OS_TV MASAttributeLeftMargin = 1 << NSLayoutAttributeLeftMargin, MASAttributeRightMargin = 1 << NSLayoutAttributeRightMargin, MASAttributeTopMargin = 1 << NSLayoutAttributeTopMargin, MASAttributeBottomMargin = 1 << NSLayoutAttributeBottomMargin, MASAttributeLeadingMargin = 1 << NSLayoutAttributeLeadingMargin, MASAttributeTrailingMargin = 1 << NSLayoutAttributeTrailingMargin, MASAttributeCenterXWithinMargins = 1 << NSLayoutAttributeCenterXWithinMargins, MASAttributeCenterYWithinMargins = 1 << NSLayoutAttributeCenterYWithinMargins, #endif }; /** * Provides factory methods for creating MASConstraints. * Constraints are collected until they are ready to be installed * */ @interface MASConstraintMaker : NSObject /** * The following properties return a new MASViewConstraint * with the first item set to the makers associated view and the appropriate MASViewAttribute */ @property (nonatomic, strong, readonly) MASConstraint *left; @property (nonatomic, strong, readonly) MASConstraint *top; @property (nonatomic, strong, readonly) MASConstraint *right; @property (nonatomic, strong, readonly) MASConstraint *bottom; @property (nonatomic, strong, readonly) MASConstraint *leading; @property (nonatomic, strong, readonly) MASConstraint *trailing; @property (nonatomic, strong, readonly) MASConstraint *width; @property (nonatomic, strong, readonly) MASConstraint *height; @property (nonatomic, strong, readonly) MASConstraint *centerX; @property (nonatomic, strong, readonly) MASConstraint *centerY; @property (nonatomic, strong, readonly) MASConstraint *baseline; #if TARGET_OS_IPHONE || TARGET_OS_TV @property (nonatomic, strong, readonly) MASConstraint *leftMargin; @property (nonatomic, strong, readonly) MASConstraint *rightMargin; @property (nonatomic, strong, readonly) MASConstraint *topMargin; @property (nonatomic, strong, readonly) MASConstraint *bottomMargin; @property (nonatomic, strong, readonly) MASConstraint *leadingMargin; @property (nonatomic, strong, readonly) MASConstraint *trailingMargin; @property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins; @property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins; #endif /** * Returns a block which creates a new MASCompositeConstraint with the first item set * to the makers associated view and children corresponding to the set bits in the * MASAttribute parameter. Combine multiple attributes via binary-or. */ @property (nonatomic, strong, readonly) MASConstraint *(^attributes)(MASAttribute attrs); /** * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeEdges * which generates the appropriate MASViewConstraint children (top, left, bottom, right) * with the first item set to the makers associated view */ @property (nonatomic, strong, readonly) MASConstraint *edges; /** * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeSize * which generates the appropriate MASViewConstraint children (width, height) * with the first item set to the makers associated view */ @property (nonatomic, strong, readonly) MASConstraint *size; /** * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeCenter * which generates the appropriate MASViewConstraint children (centerX, centerY) * with the first item set to the makers associated view */ @property (nonatomic, strong, readonly) MASConstraint *center; /** * Whether or not to check for an existing constraint instead of adding constraint */ @property (nonatomic, assign) BOOL updateExisting; /** * Whether or not to remove existing constraints prior to installing */ @property (nonatomic, assign) BOOL removeExisting; /** * initialises the maker with a default view * * @param view any MASConstrait are created with this view as the first item * * @return a new MASConstraintMaker */ - (id)initWithView:(MAS_VIEW *)view; /** * Calls install method on any MASConstraints which have been created by this maker * * @return an array of all the installed MASConstraints */ - (NSArray *)install; - (MASConstraint * (^)(dispatch_block_t))group; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASConstraintMaker.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,094
```objective-c // // UIViewController+MASAdditions.h // Masonry // // Created by Craig Siemens on 2015-06-23. // // #import "MASUtilities.h" #import "MASConstraintMaker.h" #import "MASViewAttribute.h" #ifdef MAS_VIEW_CONTROLLER @interface MAS_VIEW_CONTROLLER (MASAdditions) /** * following properties return a new MASViewAttribute with appropriate UILayoutGuide and NSLayoutAttribute */ @property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuide; @property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuide; @property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuideTop; @property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuideBottom; @property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuideTop; @property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuideBottom; @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/ViewController+MASAdditions.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
199
```objective-c // // UIView+MASAdditions.m // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "View+MASAdditions.h" #import <objc/runtime.h> @implementation MAS_VIEW (MASAdditions) - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block { self.translatesAutoresizingMaskIntoConstraints = NO; MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; block(constraintMaker); return [constraintMaker install]; } - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block { self.translatesAutoresizingMaskIntoConstraints = NO; MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; constraintMaker.updateExisting = YES; block(constraintMaker); return [constraintMaker install]; } - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { self.translatesAutoresizingMaskIntoConstraints = NO; MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; constraintMaker.removeExisting = YES; block(constraintMaker); return [constraintMaker install]; } #pragma mark - NSLayoutAttribute properties - (MASViewAttribute *)mas_left { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeft]; } - (MASViewAttribute *)mas_top { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTop]; } - (MASViewAttribute *)mas_right { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRight]; } - (MASViewAttribute *)mas_bottom { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottom]; } - (MASViewAttribute *)mas_leading { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeading]; } - (MASViewAttribute *)mas_trailing { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailing]; } - (MASViewAttribute *)mas_width { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeWidth]; } - (MASViewAttribute *)mas_height { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeHeight]; } - (MASViewAttribute *)mas_centerX { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterX]; } - (MASViewAttribute *)mas_centerY { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterY]; } - (MASViewAttribute *)mas_baseline { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBaseline]; } - (MASViewAttribute *(^)(NSLayoutAttribute))mas_attribute { return ^(NSLayoutAttribute attr) { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:attr]; }; } #if TARGET_OS_IPHONE || TARGET_OS_TV - (MASViewAttribute *)mas_leftMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeftMargin]; } - (MASViewAttribute *)mas_rightMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRightMargin]; } - (MASViewAttribute *)mas_topMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTopMargin]; } - (MASViewAttribute *)mas_bottomMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottomMargin]; } - (MASViewAttribute *)mas_leadingMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeadingMargin]; } - (MASViewAttribute *)mas_trailingMargin { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailingMargin]; } - (MASViewAttribute *)mas_centerXWithinMargins { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterXWithinMargins]; } - (MASViewAttribute *)mas_centerYWithinMargins { return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterYWithinMargins]; } #endif #pragma mark - associated properties - (id)mas_key { return objc_getAssociatedObject(self, @selector(mas_key)); } - (void)setMas_key:(id)key { objc_setAssociatedObject(self, @selector(mas_key), key, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - heirachy - (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view { MAS_VIEW *closestCommonSuperview = nil; MAS_VIEW *secondViewSuperview = view; while (!closestCommonSuperview && secondViewSuperview) { MAS_VIEW *firstViewSuperview = self; while (!closestCommonSuperview && firstViewSuperview) { if (secondViewSuperview == firstViewSuperview) { closestCommonSuperview = secondViewSuperview; } firstViewSuperview = firstViewSuperview.superview; } secondViewSuperview = secondViewSuperview.superview; } return closestCommonSuperview; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/View+MASAdditions.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,033
```objective-c // // MASUtilities.h // Masonry // // Created by Jonas Budelmann on 19/08/13. // #import <Foundation/Foundation.h> #if TARGET_OS_IPHONE || TARGET_OS_TV #import <UIKit/UIKit.h> #define MAS_VIEW UIView #define MAS_VIEW_CONTROLLER UIViewController #define MASEdgeInsets UIEdgeInsets typedef UILayoutPriority MASLayoutPriority; static const MASLayoutPriority MASLayoutPriorityRequired = UILayoutPriorityRequired; static const MASLayoutPriority MASLayoutPriorityDefaultHigh = UILayoutPriorityDefaultHigh; static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 500; static const MASLayoutPriority MASLayoutPriorityDefaultLow = UILayoutPriorityDefaultLow; static const MASLayoutPriority MASLayoutPriorityFittingSizeLevel = UILayoutPriorityFittingSizeLevel; #elif TARGET_OS_MAC #import <AppKit/AppKit.h> #define MAS_VIEW NSView #define MASEdgeInsets NSEdgeInsets typedef NSLayoutPriority MASLayoutPriority; static const MASLayoutPriority MASLayoutPriorityRequired = NSLayoutPriorityRequired; static const MASLayoutPriority MASLayoutPriorityDefaultHigh = NSLayoutPriorityDefaultHigh; static const MASLayoutPriority MASLayoutPriorityDragThatCanResizeWindow = NSLayoutPriorityDragThatCanResizeWindow; static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 501; static const MASLayoutPriority MASLayoutPriorityWindowSizeStayPut = NSLayoutPriorityWindowSizeStayPut; static const MASLayoutPriority MASLayoutPriorityDragThatCannotResizeWindow = NSLayoutPriorityDragThatCannotResizeWindow; static const MASLayoutPriority MASLayoutPriorityDefaultLow = NSLayoutPriorityDefaultLow; static const MASLayoutPriority MASLayoutPriorityFittingSizeCompression = NSLayoutPriorityFittingSizeCompression; #endif /** * Allows you to attach keys to objects matching the variable names passed. * * view1.mas_key = @"view1", view2.mas_key = @"view2"; * * is equivalent to: * * MASAttachKeys(view1, view2); */ #define MASAttachKeys(...) \ { \ NSDictionary *keyPairs = NSDictionaryOfVariableBindings(__VA_ARGS__); \ for (id key in keyPairs.allKeys) { \ id obj = keyPairs[key]; \ NSAssert([obj respondsToSelector:@selector(setMas_key:)], \ @"Cannot attach mas_key to %@", obj); \ [obj setMas_key:key]; \ } \ } /** * Used to create object hashes * Based on path_to_url */ #define MAS_NSUINT_BIT (CHAR_BIT * sizeof(NSUInteger)) #define MAS_NSUINTROTATE(val, howmuch) ((((NSUInteger)val) << howmuch) | (((NSUInteger)val) >> (MAS_NSUINT_BIT - howmuch))) /** * Given a scalar or struct value, wraps it in NSValue * Based on EXPObjectify: path_to_url */ static inline id _MASBoxValue(const char *type, ...) { va_list v; va_start(v, type); id obj = nil; if (strcmp(type, @encode(id)) == 0) { id actual = va_arg(v, id); obj = actual; } else if (strcmp(type, @encode(CGPoint)) == 0) { CGPoint actual = (CGPoint)va_arg(v, CGPoint); obj = [NSValue value:&actual withObjCType:type]; } else if (strcmp(type, @encode(CGSize)) == 0) { CGSize actual = (CGSize)va_arg(v, CGSize); obj = [NSValue value:&actual withObjCType:type]; } else if (strcmp(type, @encode(MASEdgeInsets)) == 0) { MASEdgeInsets actual = (MASEdgeInsets)va_arg(v, MASEdgeInsets); obj = [NSValue value:&actual withObjCType:type]; } else if (strcmp(type, @encode(double)) == 0) { double actual = (double)va_arg(v, double); obj = [NSNumber numberWithDouble:actual]; } else if (strcmp(type, @encode(float)) == 0) { float actual = (float)va_arg(v, double); obj = [NSNumber numberWithFloat:actual]; } else if (strcmp(type, @encode(int)) == 0) { int actual = (int)va_arg(v, int); obj = [NSNumber numberWithInt:actual]; } else if (strcmp(type, @encode(long)) == 0) { long actual = (long)va_arg(v, long); obj = [NSNumber numberWithLong:actual]; } else if (strcmp(type, @encode(long long)) == 0) { long long actual = (long long)va_arg(v, long long); obj = [NSNumber numberWithLongLong:actual]; } else if (strcmp(type, @encode(short)) == 0) { short actual = (short)va_arg(v, int); obj = [NSNumber numberWithShort:actual]; } else if (strcmp(type, @encode(char)) == 0) { char actual = (char)va_arg(v, int); obj = [NSNumber numberWithChar:actual]; } else if (strcmp(type, @encode(bool)) == 0) { bool actual = (bool)va_arg(v, int); obj = [NSNumber numberWithBool:actual]; } else if (strcmp(type, @encode(unsigned char)) == 0) { unsigned char actual = (unsigned char)va_arg(v, unsigned int); obj = [NSNumber numberWithUnsignedChar:actual]; } else if (strcmp(type, @encode(unsigned int)) == 0) { unsigned int actual = (unsigned int)va_arg(v, unsigned int); obj = [NSNumber numberWithUnsignedInt:actual]; } else if (strcmp(type, @encode(unsigned long)) == 0) { unsigned long actual = (unsigned long)va_arg(v, unsigned long); obj = [NSNumber numberWithUnsignedLong:actual]; } else if (strcmp(type, @encode(unsigned long long)) == 0) { unsigned long long actual = (unsigned long long)va_arg(v, unsigned long long); obj = [NSNumber numberWithUnsignedLongLong:actual]; } else if (strcmp(type, @encode(unsigned short)) == 0) { unsigned short actual = (unsigned short)va_arg(v, unsigned int); obj = [NSNumber numberWithUnsignedShort:actual]; } va_end(v); return obj; } #define MASBoxValue(value) _MASBoxValue(@encode(__typeof__((value))), (value)) ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASUtilities.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,424
```objective-c // // MASConstraint.m // Masonry // // Created by Nick Tymchenko on 1/20/14. // #import "MASConstraint.h" #import "MASConstraint+Private.h" #define MASMethodNotImplemented() \ @throw [NSException exceptionWithName:NSInternalInconsistencyException \ reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", NSStringFromSelector(_cmd)] \ userInfo:nil] @implementation MASConstraint #pragma mark - Init - (id)init { NSAssert(![self isMemberOfClass:[MASConstraint class]], @"MASConstraint is an abstract class, you should not instantiate it directly."); return [super init]; } #pragma mark - NSLayoutRelation proxies - (MASConstraint * (^)(id))equalTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationEqual); }; } - (MASConstraint * (^)(id))mas_equalTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationEqual); }; } - (MASConstraint * (^)(id))greaterThanOrEqualTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); }; } - (MASConstraint * (^)(id))mas_greaterThanOrEqualTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); }; } - (MASConstraint * (^)(id))lessThanOrEqualTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); }; } - (MASConstraint * (^)(id))mas_lessThanOrEqualTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); }; } #pragma mark - MASLayoutPriority proxies - (MASConstraint * (^)())priorityLow { return ^id{ self.priority(MASLayoutPriorityDefaultLow); return self; }; } - (MASConstraint * (^)())priorityMedium { return ^id{ self.priority(MASLayoutPriorityDefaultMedium); return self; }; } - (MASConstraint * (^)())priorityHigh { return ^id{ self.priority(MASLayoutPriorityDefaultHigh); return self; }; } #pragma mark - NSLayoutConstraint constant proxies - (MASConstraint * (^)(MASEdgeInsets))insets { return ^id(MASEdgeInsets insets){ self.insets = insets; return self; }; } - (MASConstraint * (^)(CGSize))sizeOffset { return ^id(CGSize offset) { self.sizeOffset = offset; return self; }; } - (MASConstraint * (^)(CGPoint))centerOffset { return ^id(CGPoint offset) { self.centerOffset = offset; return self; }; } - (MASConstraint * (^)(CGFloat))offset { return ^id(CGFloat offset){ self.offset = offset; return self; }; } - (MASConstraint * (^)(NSValue *value))valueOffset { return ^id(NSValue *offset) { [self setLayoutConstantWithValue:offset]; return self; }; } - (MASConstraint * (^)(id offset))mas_offset { // Will never be called due to macro return nil; } #pragma mark - NSLayoutConstraint constant setter - (void)setLayoutConstantWithValue:(NSValue *)value { if ([value isKindOfClass:NSNumber.class]) { self.offset = [(NSNumber *)value doubleValue]; } else if (strcmp(value.objCType, @encode(CGPoint)) == 0) { CGPoint point; [value getValue:&point]; self.centerOffset = point; } else if (strcmp(value.objCType, @encode(CGSize)) == 0) { CGSize size; [value getValue:&size]; self.sizeOffset = size; } else if (strcmp(value.objCType, @encode(MASEdgeInsets)) == 0) { MASEdgeInsets insets; [value getValue:&insets]; self.insets = insets; } else { } } #pragma mark - Semantic properties - (MASConstraint *)with { return self; } - (MASConstraint *)and { return self; } #pragma mark - Chaining - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute __unused)layoutAttribute { MASMethodNotImplemented(); } - (MASConstraint *)left { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; } - (MASConstraint *)top { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; } - (MASConstraint *)right { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; } - (MASConstraint *)bottom { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; } - (MASConstraint *)leading { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; } - (MASConstraint *)trailing { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; } - (MASConstraint *)width { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; } - (MASConstraint *)height { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; } - (MASConstraint *)centerX { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; } - (MASConstraint *)centerY { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; } - (MASConstraint *)baseline { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; } #if TARGET_OS_IPHONE || TARGET_OS_TV - (MASConstraint *)leftMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; } - (MASConstraint *)rightMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; } - (MASConstraint *)topMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; } - (MASConstraint *)bottomMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; } - (MASConstraint *)leadingMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; } - (MASConstraint *)trailingMargin { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; } - (MASConstraint *)centerXWithinMargins { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; } - (MASConstraint *)centerYWithinMargins { return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; } #endif #pragma mark - Abstract - (MASConstraint * (^)(CGFloat multiplier))multipliedBy { MASMethodNotImplemented(); } - (MASConstraint * (^)(CGFloat divider))dividedBy { MASMethodNotImplemented(); } - (MASConstraint * (^)(MASLayoutPriority priority))priority { MASMethodNotImplemented(); } - (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { MASMethodNotImplemented(); } - (MASConstraint * (^)(id key))key { MASMethodNotImplemented(); } - (void)setInsets:(MASEdgeInsets __unused)insets { MASMethodNotImplemented(); } - (void)setSizeOffset:(CGSize __unused)sizeOffset { MASMethodNotImplemented(); } - (void)setCenterOffset:(CGPoint __unused)centerOffset { MASMethodNotImplemented(); } - (void)setOffset:(CGFloat __unused)offset { MASMethodNotImplemented(); } #if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) - (MASConstraint *)animator { MASMethodNotImplemented(); } #endif - (void)activate { MASMethodNotImplemented(); } - (void)deactivate { MASMethodNotImplemented(); } - (void)install { MASMethodNotImplemented(); } - (void)uninstall { MASMethodNotImplemented(); } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASConstraint.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,627
```objective-c // // UIViewController+MASAdditions.m // Masonry // // Created by Craig Siemens on 2015-06-23. // // #import "ViewController+MASAdditions.h" #ifdef MAS_VIEW_CONTROLLER @implementation MAS_VIEW_CONTROLLER (MASAdditions) - (MASViewAttribute *)mas_topLayoutGuide { return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; } - (MASViewAttribute *)mas_topLayoutGuideTop { return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeTop]; } - (MASViewAttribute *)mas_topLayoutGuideBottom { return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; } - (MASViewAttribute *)mas_bottomLayoutGuide { return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeTop]; } - (MASViewAttribute *)mas_bottomLayoutGuideTop { return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeTop]; } - (MASViewAttribute *)mas_bottomLayoutGuideBottom { return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; } @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/ViewController+MASAdditions.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
275
```objective-c // // NSArray+MASShorthandAdditions.h // Masonry // // Created by Jonas Budelmann on 22/07/13. // #import "NSArray+MASAdditions.h" #ifdef MAS_SHORTHAND /** * Shorthand array additions without the 'mas_' prefixes, * only enabled if MAS_SHORTHAND is defined */ @interface NSArray (MASShorthandAdditions) - (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; - (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; @end @implementation NSArray (MASShorthandAdditions) - (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_makeConstraints:block]; } - (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_updateConstraints:block]; } - (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *))block { return [self mas_remakeConstraints:block]; } @end #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/NSArray+MASShorthandAdditions.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
219
```objective-c // // UIView+MASAdditions.h // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASUtilities.h" #import "MASConstraintMaker.h" #import "MASViewAttribute.h" /** * Provides constraint maker block * and convience methods for creating MASViewAttribute which are view + NSLayoutAttribute pairs */ @interface MAS_VIEW (MASAdditions) /** * following properties return a new MASViewAttribute with current view and appropriate NSLayoutAttribute */ @property (nonatomic, strong, readonly) MASViewAttribute *mas_left; @property (nonatomic, strong, readonly) MASViewAttribute *mas_top; @property (nonatomic, strong, readonly) MASViewAttribute *mas_right; @property (nonatomic, strong, readonly) MASViewAttribute *mas_bottom; @property (nonatomic, strong, readonly) MASViewAttribute *mas_leading; @property (nonatomic, strong, readonly) MASViewAttribute *mas_trailing; @property (nonatomic, strong, readonly) MASViewAttribute *mas_width; @property (nonatomic, strong, readonly) MASViewAttribute *mas_height; @property (nonatomic, strong, readonly) MASViewAttribute *mas_centerX; @property (nonatomic, strong, readonly) MASViewAttribute *mas_centerY; @property (nonatomic, strong, readonly) MASViewAttribute *mas_baseline; @property (nonatomic, strong, readonly) MASViewAttribute *(^mas_attribute)(NSLayoutAttribute attr); #if TARGET_OS_IPHONE || TARGET_OS_TV @property (nonatomic, strong, readonly) MASViewAttribute *mas_leftMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_rightMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_topMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_leadingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_trailingMargin; @property (nonatomic, strong, readonly) MASViewAttribute *mas_centerXWithinMargins; @property (nonatomic, strong, readonly) MASViewAttribute *mas_centerYWithinMargins; #endif /** * a key to associate with this view */ @property (nonatomic, strong) id mas_key; /** * Finds the closest common superview between this view and another view * * @param view other view * * @return returns nil if common superview could not be found */ - (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view; /** * Creates a MASConstraintMaker with the callee view. * Any constraints defined are added to the view or the appropriate superview once the block has finished executing * * @param block scope within which you can build up the constraints which you wish to apply to the view. * * @return Array of created MASConstraints */ - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block; /** * Creates a MASConstraintMaker with the callee view. * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. * If an existing constraint exists then it will be updated instead. * * @param block scope within which you can build up the constraints which you wish to apply to the view. * * @return Array of created/updated MASConstraints */ - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block; /** * Creates a MASConstraintMaker with the callee view. * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. * All constraints previously installed for the view will be removed. * * @param block scope within which you can build up the constraints which you wish to apply to the view. * * @return Array of created/updated MASConstraints */ - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/View+MASAdditions.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
816
```objective-c // // MASAttribute.h // Masonry // // Created by Jonas Budelmann on 21/07/13. // #import "MASUtilities.h" /** * An immutable tuple which stores the view and the related NSLayoutAttribute. * Describes part of either the left or right hand side of a constraint equation */ @interface MASViewAttribute : NSObject /** * The view which the reciever relates to. Can be nil if item is not a view. */ @property (nonatomic, weak, readonly) MAS_VIEW *view; /** * The item which the reciever relates to. */ @property (nonatomic, weak, readonly) id item; /** * The attribute which the reciever relates to */ @property (nonatomic, assign, readonly) NSLayoutAttribute layoutAttribute; /** * Convenience initializer. */ - (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute; /** * The designated initializer. */ - (id)initWithView:(MAS_VIEW *)view item:(id)item layoutAttribute:(NSLayoutAttribute)layoutAttribute; /** * Determine whether the layoutAttribute is a size attribute * * @return YES if layoutAttribute is equal to NSLayoutAttributeWidth or NSLayoutAttributeHeight */ - (BOOL)isSizeAttribute; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASViewAttribute.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
272
```objective-c // // Masonry.h // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import <Foundation/Foundation.h> //! Project version number for Masonry. FOUNDATION_EXPORT double MasonryVersionNumber; //! Project version string for Masonry. FOUNDATION_EXPORT const unsigned char MasonryVersionString[]; #import "MASUtilities.h" #import "View+MASAdditions.h" #import "View+MASShorthandAdditions.h" #import "ViewController+MASAdditions.h" #import "NSArray+MASAdditions.h" #import "NSArray+MASShorthandAdditions.h" #import "MASConstraint.h" #import "MASCompositeConstraint.h" #import "MASViewAttribute.h" #import "MASViewConstraint.h" #import "MASConstraintMaker.h" #import "MASLayoutConstraint.h" #import "NSLayoutConstraint+MASDebugAdditions.h" ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/Masonry.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
177
```objective-c // // MASAttribute.m // Masonry // // Created by Jonas Budelmann on 21/07/13. // #import "MASViewAttribute.h" @implementation MASViewAttribute - (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute { self = [self initWithView:view item:view layoutAttribute:layoutAttribute]; return self; } - (id)initWithView:(MAS_VIEW *)view item:(id)item layoutAttribute:(NSLayoutAttribute)layoutAttribute { self = [super init]; if (!self) return nil; _view = view; _item = item; _layoutAttribute = layoutAttribute; return self; } - (BOOL)isSizeAttribute { return self.layoutAttribute == NSLayoutAttributeWidth || self.layoutAttribute == NSLayoutAttributeHeight; } - (BOOL)isEqual:(MASViewAttribute *)viewAttribute { if ([viewAttribute isKindOfClass:self.class]) { return self.view == viewAttribute.view && self.layoutAttribute == viewAttribute.layoutAttribute; } return [super isEqual:viewAttribute]; } - (NSUInteger)hash { return MAS_NSUINTROTATE([self.view hash], MAS_NSUINT_BIT / 2) ^ self.layoutAttribute; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASViewAttribute.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
269
```objective-c // // NSArray+MASAdditions.h // // // Created by Daniel Hammond on 11/26/13. // // #import "MASUtilities.h" #import "MASConstraintMaker.h" #import "MASViewAttribute.h" typedef NS_ENUM(NSUInteger, MASAxisType) { MASAxisTypeHorizontal, MASAxisTypeVertical }; @interface NSArray (MASAdditions) /** * Creates a MASConstraintMaker with each view in the callee. * Any constraints defined are added to the view or the appropriate superview once the block has finished executing on each view * * @param block scope within which you can build up the constraints which you wish to apply to each view. * * @return Array of created MASConstraints */ - (NSArray *)mas_makeConstraints:(void (^)(MASConstraintMaker *make))block; /** * Creates a MASConstraintMaker with each view in the callee. * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. * If an existing constraint exists then it will be updated instead. * * @param block scope within which you can build up the constraints which you wish to apply to each view. * * @return Array of created/updated MASConstraints */ - (NSArray *)mas_updateConstraints:(void (^)(MASConstraintMaker *make))block; /** * Creates a MASConstraintMaker with each view in the callee. * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. * All constraints previously installed for the views will be removed. * * @param block scope within which you can build up the constraints which you wish to apply to each view. * * @return Array of created/updated MASConstraints */ - (NSArray *)mas_remakeConstraints:(void (^)(MASConstraintMaker *make))block; /** * distribute with fixed spacing * * @param axisType which axis to distribute items along * @param fixedSpacing the spacing between each item * @param leadSpacing the spacing before the first item and the container * @param tailSpacing the spacing after the last item and the container */ - (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing; /** * distribute with fixed item size * * @param axisType which axis to distribute items along * @param fixedItemLength the fixed length of each item * @param leadSpacing the spacing before the first item and the container * @param tailSpacing the spacing after the last item and the container */ - (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/NSArray+MASAdditions.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
609
```objective-c // // NSLayoutConstraint+MASDebugAdditions.h // Masonry // // Created by Jonas Budelmann on 3/08/13. // #import "MASUtilities.h" /** * makes debug and log output of NSLayoutConstraints more readable */ @interface NSLayoutConstraint (MASDebugAdditions) @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/NSLayoutConstraint+MASDebugAdditions.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
67
```objective-c // // MASConstraint.h // Masonry // // Created by Jonas Budelmann on 22/07/13. // #import "MASUtilities.h" /** * Enables Constraints to be created with chainable syntax * Constraint can represent single NSLayoutConstraint (MASViewConstraint) * or a group of NSLayoutConstraints (MASComposisteConstraint) */ @interface MASConstraint : NSObject // Chaining Support /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight */ - (MASConstraint * (^)(MASEdgeInsets insets))insets; /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeWidth, NSLayoutAttributeHeight */ - (MASConstraint * (^)(CGSize offset))sizeOffset; /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY */ - (MASConstraint * (^)(CGPoint offset))centerOffset; /** * Modifies the NSLayoutConstraint constant */ - (MASConstraint * (^)(CGFloat offset))offset; /** * Modifies the NSLayoutConstraint constant based on a value type */ - (MASConstraint * (^)(NSValue *value))valueOffset; /** * Sets the NSLayoutConstraint multiplier property */ - (MASConstraint * (^)(CGFloat multiplier))multipliedBy; /** * Sets the NSLayoutConstraint multiplier to 1.0/dividedBy */ - (MASConstraint * (^)(CGFloat divider))dividedBy; /** * Sets the NSLayoutConstraint priority to a float or MASLayoutPriority */ - (MASConstraint * (^)(MASLayoutPriority priority))priority; /** * Sets the NSLayoutConstraint priority to MASLayoutPriorityLow */ - (MASConstraint * (^)())priorityLow; /** * Sets the NSLayoutConstraint priority to MASLayoutPriorityMedium */ - (MASConstraint * (^)())priorityMedium; /** * Sets the NSLayoutConstraint priority to MASLayoutPriorityHigh */ - (MASConstraint * (^)())priorityHigh; /** * Sets the constraint relation to NSLayoutRelationEqual * returns a block which accepts one of the following: * MASViewAttribute, UIView, NSValue, NSArray * see readme for more details. */ - (MASConstraint * (^)(id attr))equalTo; /** * Sets the constraint relation to NSLayoutRelationGreaterThanOrEqual * returns a block which accepts one of the following: * MASViewAttribute, UIView, NSValue, NSArray * see readme for more details. */ - (MASConstraint * (^)(id attr))greaterThanOrEqualTo; /** * Sets the constraint relation to NSLayoutRelationLessThanOrEqual * returns a block which accepts one of the following: * MASViewAttribute, UIView, NSValue, NSArray * see readme for more details. */ - (MASConstraint * (^)(id attr))lessThanOrEqualTo; /** * Optional semantic property which has no effect but improves the readability of constraint */ - (MASConstraint *)with; /** * Optional semantic property which has no effect but improves the readability of constraint */ - (MASConstraint *)and; /** * Creates a new MASCompositeConstraint with the called attribute and reciever */ - (MASConstraint *)left; - (MASConstraint *)top; - (MASConstraint *)right; - (MASConstraint *)bottom; - (MASConstraint *)leading; - (MASConstraint *)trailing; - (MASConstraint *)width; - (MASConstraint *)height; - (MASConstraint *)centerX; - (MASConstraint *)centerY; - (MASConstraint *)baseline; #if TARGET_OS_IPHONE || TARGET_OS_TV - (MASConstraint *)leftMargin; - (MASConstraint *)rightMargin; - (MASConstraint *)topMargin; - (MASConstraint *)bottomMargin; - (MASConstraint *)leadingMargin; - (MASConstraint *)trailingMargin; - (MASConstraint *)centerXWithinMargins; - (MASConstraint *)centerYWithinMargins; #endif /** * Sets the constraint debug name */ - (MASConstraint * (^)(id key))key; // NSLayoutConstraint constant Setters // for use outside of mas_updateConstraints/mas_makeConstraints blocks /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight */ - (void)setInsets:(MASEdgeInsets)insets; /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeWidth, NSLayoutAttributeHeight */ - (void)setSizeOffset:(CGSize)sizeOffset; /** * Modifies the NSLayoutConstraint constant, * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY */ - (void)setCenterOffset:(CGPoint)centerOffset; /** * Modifies the NSLayoutConstraint constant */ - (void)setOffset:(CGFloat)offset; // NSLayoutConstraint Installation support #if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) /** * Whether or not to go through the animator proxy when modifying the constraint */ @property (nonatomic, copy, readonly) MASConstraint *animator; #endif /** * Activates an NSLayoutConstraint if it's supported by an OS. * Invokes install otherwise. */ - (void)activate; /** * Deactivates previously installed/activated NSLayoutConstraint. */ - (void)deactivate; /** * Creates a NSLayoutConstraint and adds it to the appropriate view. */ - (void)install; /** * Removes previously installed NSLayoutConstraint */ - (void)uninstall; @end /** * Convenience auto-boxing macros for MASConstraint methods. * * Defining MAS_SHORTHAND_GLOBALS will turn on auto-boxing for default syntax. * A potential drawback of this is that the unprefixed macros will appear in global scope. */ #define mas_equalTo(...) equalTo(MASBoxValue((__VA_ARGS__))) #define mas_greaterThanOrEqualTo(...) greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__))) #define mas_lessThanOrEqualTo(...) lessThanOrEqualTo(MASBoxValue((__VA_ARGS__))) #define mas_offset(...) valueOffset(MASBoxValue((__VA_ARGS__))) #ifdef MAS_SHORTHAND_GLOBALS #define equalTo(...) mas_equalTo(__VA_ARGS__) #define greaterThanOrEqualTo(...) mas_greaterThanOrEqualTo(__VA_ARGS__) #define lessThanOrEqualTo(...) mas_lessThanOrEqualTo(__VA_ARGS__) #define offset(...) mas_offset(__VA_ARGS__) #endif @interface MASConstraint (AutoboxingSupport) /** * Aliases to corresponding relation methods (for shorthand macros) * Also needed to aid autocompletion */ - (MASConstraint * (^)(id attr))mas_equalTo; - (MASConstraint * (^)(id attr))mas_greaterThanOrEqualTo; - (MASConstraint * (^)(id attr))mas_lessThanOrEqualTo; /** * A dummy method to aid autocompletion */ - (MASConstraint * (^)(id offset))mas_offset; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASConstraint.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,541
```objective-c // // MASConstraint.h // Masonry // // Created by Jonas Budelmann on 20/07/13. // #import "MASViewAttribute.h" #import "MASConstraint.h" #import "MASLayoutConstraint.h" #import "MASUtilities.h" /** * A single constraint. * Contains the attributes neccessary for creating a NSLayoutConstraint and adding it to the appropriate view */ @interface MASViewConstraint : MASConstraint <NSCopying> /** * First item/view and first attribute of the NSLayoutConstraint */ @property (nonatomic, strong, readonly) MASViewAttribute *firstViewAttribute; /** * Second item/view and second attribute of the NSLayoutConstraint */ @property (nonatomic, strong, readonly) MASViewAttribute *secondViewAttribute; /** * initialises the MASViewConstraint with the first part of the equation * * @param firstViewAttribute view.mas_left, view.mas_width etc. * * @return a new view constraint */ - (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute; /** * Returns all MASViewConstraints installed with this view as a first item. * * @param view A view to retrieve constraints for. * * @return An array of MASViewConstraints. */ + (NSArray *)installedConstraintsForView:(MAS_VIEW *)view; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/MASViewConstraint.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
274
```objective-c // // MJIvar.m // MJExtension // // Created by mj on 14-1-15. // #import "MJIvar.h" #import "MJTypeEncoding.h" #import "MJConst.h" @implementation MJIvar /** * * * @param ivar * @param srcObject * * @return */ - (instancetype)initWithIvar:(Ivar)ivar srcObject:(id)srcObject { if (self = [super initWithSrcObject:srcObject]) { self.ivar = ivar; } return self; } /** * */ - (void)setIvar:(Ivar)ivar { _ivar = ivar; MJAssertParamNotNil(ivar); // 1. _name = [NSString stringWithUTF8String:ivar_getName(ivar)]; // 2. if ([_name hasPrefix:@"_"]) { _propertyName = [_name stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""]; } else { _propertyName = _name; } // 3. NSString *code = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)]; _type = [[MJType alloc] initWithCode:code]; } /** * */ - (id)value { if (_type.KVCDisabled) return [NSNull null]; return [_srcObject valueForKey:_propertyName]; } /** * */ - (void)setValue:(id)value { if (_type.KVCDisabled) return; [_srcObject setValue:value forKey:_propertyName]; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJIvar.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
346
```objective-c // // MJMember.m // MJExtension // // Created by mj on 14-1-15. // #import "MJMember.h" #import "MJExtension.h" #import "MJFoundation.h" #import "MJConst.h" @implementation MJMember /** * * * @param srcObject * * @return */ - (instancetype)initWithSrcObject:(id)srcObject { if (self = [super init]) { _srcObject = srcObject; } return self; } - (void)setSrcClass:(Class)srcClass { _srcClass = srcClass; MJAssertParamNotNil(srcClass); _srcClassFromFoundation = [MJFoundation isClassFromFoundation:srcClass]; } MJLogAllIvrs @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJMember.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
171
```objective-c // // NSArray+MASAdditions.m // // // Created by Daniel Hammond on 11/26/13. // // #import "NSArray+MASAdditions.h" #import "View+MASAdditions.h" @implementation NSArray (MASAdditions) - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block { NSMutableArray *constraints = [NSMutableArray array]; for (MAS_VIEW *view in self) { NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); [constraints addObjectsFromArray:[view mas_makeConstraints:block]]; } return constraints; } - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block { NSMutableArray *constraints = [NSMutableArray array]; for (MAS_VIEW *view in self) { NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); [constraints addObjectsFromArray:[view mas_updateConstraints:block]]; } return constraints; } - (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { NSMutableArray *constraints = [NSMutableArray array]; for (MAS_VIEW *view in self) { NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); [constraints addObjectsFromArray:[view mas_remakeConstraints:block]]; } return constraints; } - (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing { if (self.count < 2) { NSAssert(self.count>1,@"views to distribute need to bigger than one"); return; } MAS_VIEW *tempSuperView = [self mas_commonSuperviewOfViews]; if (axisType == MASAxisTypeHorizontal) { MAS_VIEW *prev; for (int i = 0; i < self.count; i++) { MAS_VIEW *v = self[i]; [v mas_makeConstraints:^(MASConstraintMaker *make) { if (prev) { make.width.equalTo(prev); make.left.equalTo(prev.mas_right).offset(fixedSpacing); if (i == (CGFloat)self.count - 1) {//last one make.right.equalTo(tempSuperView).offset(-tailSpacing); } } else {//first one make.left.equalTo(tempSuperView).offset(leadSpacing); } }]; prev = v; } } else { MAS_VIEW *prev; for (int i = 0; i < self.count; i++) { MAS_VIEW *v = self[i]; [v mas_makeConstraints:^(MASConstraintMaker *make) { if (prev) { make.height.equalTo(prev); make.top.equalTo(prev.mas_bottom).offset(fixedSpacing); if (i == (CGFloat)self.count - 1) {//last one make.bottom.equalTo(tempSuperView).offset(-tailSpacing); } } else {//first one make.top.equalTo(tempSuperView).offset(leadSpacing); } }]; prev = v; } } } - (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing { if (self.count < 2) { NSAssert(self.count>1,@"views to distribute need to bigger than one"); return; } MAS_VIEW *tempSuperView = [self mas_commonSuperviewOfViews]; if (axisType == MASAxisTypeHorizontal) { MAS_VIEW *prev; for (int i = 0; i < self.count; i++) { MAS_VIEW *v = self[i]; [v mas_makeConstraints:^(MASConstraintMaker *make) { if (prev) { CGFloat offset = (1-(i/((CGFloat)self.count-1)))*(fixedItemLength+leadSpacing)-i*tailSpacing/(((CGFloat)self.count-1)); make.width.equalTo(@(fixedItemLength)); if (i == (CGFloat)self.count - 1) {//last one make.right.equalTo(tempSuperView).offset(-tailSpacing); } else { make.right.equalTo(tempSuperView).multipliedBy(i/((CGFloat)self.count-1)).with.offset(offset); } } else {//first one make.left.equalTo(tempSuperView).offset(leadSpacing); make.width.equalTo(@(fixedItemLength)); } }]; prev = v; } } else { MAS_VIEW *prev; for (int i = 0; i < self.count; i++) { MAS_VIEW *v = self[i]; [v mas_makeConstraints:^(MASConstraintMaker *make) { if (prev) { CGFloat offset = (1-(i/((CGFloat)self.count-1)))*(fixedItemLength+leadSpacing)-i*tailSpacing/(((CGFloat)self.count-1)); make.height.equalTo(@(fixedItemLength)); if (i == (CGFloat)self.count - 1) {//last one make.bottom.equalTo(tempSuperView).offset(-tailSpacing); } else { make.bottom.equalTo(tempSuperView).multipliedBy(i/((CGFloat)self.count-1)).with.offset(offset); } } else {//first one make.top.equalTo(tempSuperView).offset(leadSpacing); make.height.equalTo(@(fixedItemLength)); } }]; prev = v; } } } - (MAS_VIEW *)mas_commonSuperviewOfViews { MAS_VIEW *commonSuperview = nil; MAS_VIEW *previousView = nil; for (id object in self) { if ([object isKindOfClass:[MAS_VIEW class]]) { MAS_VIEW *view = (MAS_VIEW *)object; if (previousView) { commonSuperview = [view mas_closestCommonSuperview:commonSuperview]; } else { commonSuperview = view; } previousView = view; } } NSAssert(commonSuperview, @"Can't constrain views that do not share a common superview. Make sure that all the views in this array have been added into the same view hierarchy."); return commonSuperview; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/Masonry/NSArray+MASAdditions.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,329
```objective-c // // MJTypeEncoding.m // MJExtension // // Created by mj on 14-1-15. // #import <Foundation/Foundation.h> /** * */ NSString *const MJTypeInt = @"i"; NSString *const MJTypeFloat = @"f"; NSString *const MJTypeDouble = @"d"; NSString *const MJTypeLong = @"q"; NSString *const MJTypeLongLong = @"q"; NSString *const MJTypeChar = @"c"; NSString *const MJTypeBOOL = @"c"; NSString *const MJTypePointer = @"*"; NSString *const MJTypeIvar = @"^{objc_ivar=}"; NSString *const MJTypeMethod = @"^{objc_method=}"; NSString *const MJTypeBlock = @"@?"; NSString *const MJTypeClass = @"#"; NSString *const MJTypeSEL = @":"; NSString *const MJTypeId = @"@"; /** * (unsigned) */ NSString *const MJReturnTypeVoid = @"v"; NSString *const MJReturnTypeObject = @"@"; ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJTypeEncoding.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
215
```objective-c // // NSObject+MJCoding.m // MJExtension // // Created by mj on 14-1-15. // #import "NSObject+MJCoding.h" #import "NSObject+MJMember.h" @implementation NSObject (MJCoding) /** * */ - (void)encode:(NSCoder *)encoder { [self enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) { if (ivar.isSrcClassFromFoundation) return; [encoder encodeObject:ivar.value forKey:ivar.name]; }]; } /** * */ - (void)decode:(NSCoder *)decoder { [self enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) { if (ivar.isSrcClassFromFoundation) return; ivar.value = [decoder decodeObjectForKey:ivar.name]; }]; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/NSObject+MJCoding.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
186
```objective-c // // NSObject+MJKeyValue.h // MJExtension // // Created by mj on 13-8-24. // #import <Foundation/Foundation.h> /** * KeyValue */ @protocol MJKeyValue <NSObject> @optional /** * key * * @return keyvaluekey */ - (NSDictionary *)replacedKeyFromPropertyName; /** * * * @return keyvalueClass */ - (NSDictionary *)objectClassInArray; /** * */ - (void)keyValuesDidFinishConvertingToObject; /** * */ - (void)objectDidFinishConvertingToKeyValues; @end @interface NSObject (MJKeyValue) <MJKeyValue> /** * * @param keyValues */ - (void)setKeyValues:(NSDictionary *)keyValues; /** * * @return */ - (NSDictionary *)keyValues; /** * * @param objectArray * @return */ + (NSArray *)keyValuesArrayWithObjectArray:(NSArray *)objectArray; #pragma mark - /** * JSON * @param data JSON * @return */ + (instancetype)objectWithJSONData:(NSData *)data; /** * * @param keyValues * @return */ + (instancetype)objectWithKeyValues:(NSDictionary *)keyValues; /** * plist * @param filename (mainBundle) * @return */ + (instancetype)objectWithFilename:(NSString *)filename; /** * plist * @param file * @return */ + (instancetype)objectWithFile:(NSString *)file; #pragma mark - /** * JSON * @param data JSON * @return */ + (NSArray *)objectArrayWithJSONData:(NSData *)data; /** * * @param keyValuesArray * @return */ + (NSArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray; /** * plist * @param filename (mainBundle) * @return */ + (NSArray *)objectArrayWithFilename:(NSString *)filename; /** * plist * @param file * @return */ + (NSArray *)objectArrayWithFile:(NSString *)file; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/NSObject+MJKeyValue.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
470
```objective-c // // MJIvar.h // MJExtension // // Created by mj on 14-1-15. // #import "MJMember.h" @class MJType; /** * */ @interface MJIvar : MJMember /** */ @property (nonatomic, assign) Ivar ivar; /** */ @property (nonatomic, copy, readonly) NSString *propertyName; /** */ @property (nonatomic) id value; /** */ @property (nonatomic, strong, readonly) MJType *type; /** * * * @param ivar * @param srcObject * * @return */ - (instancetype)initWithIvar:(Ivar)ivar srcObject:(id)srcObject; @end /** * block * * @param ivar * @param stop YESNO */ typedef void (^MJIvarsBlock)(MJIvar *ivar, BOOL *stop); ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJIvar.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
194
```objective-c // // MJMember.h // MJExtension // // Created by mj on 14-1-15. // #import <Foundation/Foundation.h> #import <objc/message.h> #import "MJType.h" #import "MJArgument.h" @interface MJMember : NSObject { __weak id _srcObject; NSString *_name; } /** */ @property (nonatomic, assign) Class srcClass; /** Foundation */ @property (nonatomic, readonly, getter = isSrcClassFromFoundation) BOOL srcClassFromFoundation; /** */ @property (nonatomic, weak, readonly) id srcObject; /** */ @property (nonatomic, copy, readonly) NSString *name; /** * * * @param srcObject * * @return */ - (instancetype)initWithSrcObject:(id)srcObject; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJMember.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
171
```objective-c // // MJMethod.m // MJExtension // // Created by mj on 14-1-15. // #import "MJMethod.h" #import "MJConst.h" @implementation MJMethod /** * * * @param method * @param srcObject * * @return */ - (instancetype)initWithMethod:(Method)method srcObject:(id)srcObject { if (self = [super initWithSrcObject:srcObject]) { self.method = method; } return self; } /** * */ - (void)setMethod:(Method)method { _method = method; MJAssertParamNotNil(method); // 1. _selector = method_getName(method); _name = NSStringFromSelector(self.selector); // 2. int step = 2; // 2 int argsCount = method_getNumberOfArguments(method); NSMutableArray *args = [NSMutableArray arrayWithCapacity:argsCount - step]; for (int i = step; i<argsCount; i++) { MJArgument *arg = [[MJArgument alloc] init]; arg.index = i - step; char *argCode = method_copyArgumentType(method, i); arg.type = [NSString stringWithUTF8String:argCode]; free(argCode); [args addObject:arg]; } _arguments = args; // 3. char *returnCode = method_copyReturnType(method); _returnType = [NSString stringWithUTF8String:returnCode]; free(returnCode); } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJMethod.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
335
```objective-c // // MJMethod.h // MJExtension // // Created by mj on 14-1-15. // #import "MJMember.h" /** * */ @interface MJMethod : MJMember /** */ @property (nonatomic, assign) Method method; /** */ @property (nonatomic, assign, readonly) SEL selector; /** MJArgument */ @property (nonatomic, strong, readonly) NSArray *arguments; /** */ @property (nonatomic, copy, readonly) NSString *returnType; /** * * * @param method * @param srcObject * * @return */ - (instancetype)initWithMethod:(Method)method srcObject:(id)srcObject; @end /** * block * * @param method * @param stop YESNO */ typedef void (^MJMethodsBlock)(MJMethod *method, BOOL *stop); ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJMethod.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
185
```objective-c // // NSObject+MJMember.h // MJExtension // // Created by mj on 14-1-15. // #import <Foundation/Foundation.h> #import "MJIvar.h" #import "MJMethod.h" /** * block */ typedef void (^MJClassesBlock)(Class c, BOOL *stop); @interface NSObject (MJMember) /** * */ - (void)enumerateIvarsWithBlock:(MJIvarsBlock)block; /** * */ - (void)enumerateMethodsWithBlock:(MJMethodsBlock)block; /** * */ - (void)enumerateClassesWithBlock:(MJClassesBlock)block; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/NSObject+MJMember.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
136
```objective-c // // MJExtension.h // MJExtension // // Created by mj on 14-1-15. // :path_to_url // :path_to_url #import "MJTypeEncoding.h" #import "NSObject+MJCoding.h" #import "NSObject+MJMember.h" #import "NSObject+MJKeyValue.h" #define MJLogAllIvrs \ - (NSString *)description \ { \ return [self keyValues].description; \ } ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJExtension.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
100
```objective-c // // MJType.h // MJExtension // // Created by mj on 14-1-15. // #import <Foundation/Foundation.h> /** * */ @interface MJType : NSObject /** */ @property (nonatomic, copy) NSString *code; /** nil */ @property (nonatomic, assign, readonly) Class typeClass; /** FoundationNSStringNSArray */ @property (nonatomic, readonly, getter = isFromFoundation) BOOL fromFoundation; /** KVC */ @property (nonatomic, readonly, getter = isKVCDisabled) BOOL KVCDisabled; /** * * * @param code */ - (instancetype)initWithCode:(NSString *)code; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJType.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
138
```objective-c #ifndef __MJConst__M__ #define __MJConst__M__ #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJConst.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
16
```objective-c // // MJArgument.m // ItcastWeibo // // Created by mj on 14-1-15. // #import "MJArgument.h" #import "MJExtension.h" @implementation MJArgument MJLogAllIvrs @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJArgument.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
55
```objective-c // // MJFoundation.h // MJExtensionExample // // Created by MJ Lee on 14/7/16. // #import <Foundation/Foundation.h> @interface MJFoundation : NSObject + (BOOL)isClassFromFoundation:(Class)c; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJFoundation.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
56
```objective-c // // MJArgument.h // ItcastWeibo // // Created by mj on 14-1-15. // #import <Foundation/Foundation.h> /** * */ @interface MJArgument : NSObject /** */ @property (nonatomic, assign) int index; /** */ @property (nonatomic, copy) NSString *type; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJArgument.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
74
```objective-c #ifndef __MJConst__H__ #define __MJConst__H__ #ifdef DEBUG // // LOG #define MJLog(...) NSLog(__VA_ARGS__) #else // // LOG #define MJLog(...) #endif // #define MJColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0] // #define MJRandomColor MJColor(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256)) // #define MJAssert2(condition, desc, returnValue) \ if ((condition) == NO) { \ NSString *file = [NSString stringWithUTF8String:__FILE__]; \ MJLog(@"\n%@\n%d\n%s\n%@", file, __LINE__, __FUNCTION__, desc); \ MJLog(@"\nMJConst.h2324"); \ return returnValue; \ } #define MJAssert(condition, desc) MJAssert2(condition, desc, ) #define MJAssertParamNotNil2(param, returnValue) \ MJAssert2(param, [[NSString stringWithFormat:@#param] stringByAppendingString:@"nil"], returnValue) #define MJAssertParamNotNil(param) MJAssertParamNotNil2(param, ) #endif ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJConst.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
254
```objective-c // // NSObject+MJMember.m // MJExtension // // Created by mj on 14-1-15. // #import "NSObject+MJMember.h" @implementation NSObject (MJMember) /** * */ - (void)enumerateIvarsWithBlock:(MJIvarsBlock)block { [self enumerateClassesWithBlock:^(__unsafe_unretained Class c, BOOL *stop) { // 1. unsigned int outCount = 0; Ivar *ivars = class_copyIvarList(c, &outCount); // 2. for (int i = 0; i<outCount; i++) { MJIvar *ivar = [[MJIvar alloc] initWithIvar:ivars[i] srcObject:self]; ivar.srcClass = c; block(ivar, stop); } // 3. free(ivars); }]; } /** * */ - (void)enumerateMethodsWithBlock:(MJMethodsBlock)block { [self enumerateClassesWithBlock:^(__unsafe_unretained Class c, BOOL *stop) { // 1. unsigned int outCount = 0; Method *methods = class_copyMethodList(c, &outCount); // 2. for (int i = 0; i<outCount; i++) { MJMethod *method = [[MJMethod alloc] initWithMethod:methods[i] srcObject:self]; method.srcClass = c; block(method, stop); } // 3. free(methods); }]; } /** * */ - (void)enumerateClassesWithBlock:(MJClassesBlock)block { // 1.block if (block == nil) return; // 2. BOOL stop = NO; // 3. Class c = [self class]; // 4. while (c && !stop) { // 4.1. block(c, &stop); // 4.2. c = class_getSuperclass(c); } } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/NSObject+MJMember.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
453
```objective-c // // NSObject+MJCoding.h // MJExtension // // Created by mj on 14-1-15. // #import <Foundation/Foundation.h> @interface NSObject (MJCoding) /** * */ - (void)decode:(NSCoder *)decoder; /** * */ - (void)encode:(NSCoder *)encoder; @end /** */ #define MJCodingImplementation \ - (id)initWithCoder:(NSCoder *)decoder \ { \ if (self = [super init]) { \ [self decode:decoder]; \ } \ return self; \ } \ \ - (void)encodeWithCoder:(NSCoder *)encoder \ { \ [self encode:encoder]; \ } ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/NSObject+MJCoding.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
145
```objective-c // // MJTypeEncoding.h // MJExtension // // Created by mj on 14-1-15. // #import <Foundation/Foundation.h> /** * */ extern NSString *const MJTypeInt; extern NSString *const MJTypeFloat; extern NSString *const MJTypeDouble; extern NSString *const MJTypeLong; extern NSString *const MJTypeLongLong; extern NSString *const MJTypeChar; extern NSString *const MJTypeBOOL; extern NSString *const MJTypePointer; extern NSString *const MJTypeIvar; extern NSString *const MJTypeMethod; extern NSString *const MJTypeBlock; extern NSString *const MJTypeClass; extern NSString *const MJTypeSEL; extern NSString *const MJTypeId; /** * */ extern NSString *const MJReturnTypeVoid; extern NSString *const MJReturnTypeObject; ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJTypeEncoding.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
172
```objective-c // // MJType.m // MJExtension // // Created by mj on 14-1-15. // #import "MJType.h" #import "MJExtension.h" #import "MJFoundation.h" #import "MJConst.h" @implementation MJType - (instancetype)initWithCode:(NSString *)code { if (self = [super init]) { self.code = code; } return self; } /** */ - (void)setCode:(NSString *)code { _code = code; MJAssertParamNotNil(code); if (code.length == 0 || [code isEqualToString:MJTypeSEL] || [code isEqualToString:MJTypeIvar] || [code isEqualToString:MJTypeMethod]) { _KVCDisabled = YES; } else if ([code hasPrefix:@"@"] && code.length > 3) { // @"" _code = [code substringFromIndex:2]; _code = [_code substringToIndex:_code.length - 1]; _typeClass = NSClassFromString(_code); _fromFoundation = [MJFoundation isClassFromFoundation:_typeClass]; } } MJLogAllIvrs @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJType.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
257
```objective-c // // MJFoundation.m // MJExtensionExample // // Created by MJ Lee on 14/7/16. // #import "MJFoundation.h" #import "MJConst.h" static NSArray *_foundationClasses; @implementation MJFoundation + (void)initialize { _foundationClasses = @[@"NSObject", @"NSNumber",@"NSArray", @"NSURL", @"NSMutableURL",@"NSMutableArray",@"NSData",@"NSMutableData",@"NSDate",@"NSDictionary",@"NSMutableDictionary",@"NSString",@"NSMutableString"]; } + (BOOL)isClassFromFoundation:(Class)c { MJAssertParamNotNil2(c, NO); return [_foundationClasses containsObject:NSStringFromClass(c)]; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/MJFoundation.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
137
```objective-c // // NSObject+MJKeyValue.m // MJExtension // // Created by mj on 13-8-24. // #import "NSObject+MJKeyValue.h" #import "NSObject+MJMember.h" #import "MJConst.h" @implementation NSObject (MJKeyValue) #pragma mark - #pragma mark - /** * JSON * @param data JSON * @return */ + (instancetype)objectWithJSONData:(NSData *)data { MJAssertParamNotNil2(data, nil); NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; return [self objectWithKeyValues:dict]; } /** * * @param keyValues * @return */ + (instancetype)objectWithKeyValues:(NSDictionary *)keyValues { NSString *desc = [NSString stringWithFormat:@"keyValues is not a NSDictionary - keyValues, keyValues is a %@ - keyValues%@", keyValues.class, keyValues.class]; MJAssert2([keyValues isKindOfClass:[NSDictionary class]], desc, nil); id model = [[self alloc] init]; [model setKeyValues:keyValues]; return model; } /** * plist * @param filename (mainBundle) * @return */ + (instancetype)objectWithFilename:(NSString *)filename { MJAssertParamNotNil2(filename, nil); NSString *file = [[NSBundle mainBundle] pathForResource:filename ofType:nil]; return [self objectWithFile:file]; } /** * plist * @param file * @return */ + (instancetype)objectWithFile:(NSString *)file { MJAssertParamNotNil2(file, nil); NSDictionary *keyValues = [NSDictionary dictionaryWithContentsOfFile:file]; return [self objectWithKeyValues:keyValues]; } /** * * @param keyValues */ - (void)setKeyValues:(NSDictionary *)keyValues { NSString *desc = [NSString stringWithFormat:@"keyValues is not a NSDictionary - keyValues, keyValues is a %@ - keyValues%@", keyValues.class, keyValues.class]; MJAssert2([keyValues isKindOfClass:[NSDictionary class]], desc, ); [self enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) { // Foundation if (ivar.isSrcClassFromFoundation) return; // 1. NSString *key = [self keyWithPropertyName:ivar.propertyName]; id value = keyValues[key]; if (!value || [value isKindOfClass:[NSNull class]]) return; // 2. if (ivar.type.typeClass && !ivar.type.isFromFoundation) { value = [ivar.type.typeClass objectWithKeyValues:value]; } else if (ivar.type.typeClass == [NSString class] && [value isKindOfClass:[NSNumber class]]) { // NSNumber -> NSString NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init]; value = [fmt stringFromNumber:value]; } else if (ivar.type.typeClass == [NSNumber class] && [value isKindOfClass:[NSString class]]) { // NSString -> NSNumber NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init]; value = [fmt numberFromString:value]; } else if (ivar.type.typeClass == [NSURL class] && [value isKindOfClass:[NSString class]]) { // NSString -> NSURL value = [NSURL URLWithString:value]; } else if (ivar.type.typeClass == [NSString class] && [value isKindOfClass:[NSURL class]]) { // NSURL -> NSString value = [value absoluteString]; } else if ([self respondsToSelector:@selector(objectClassInArray)]) { // 3.--> Class objectClass = self.objectClassInArray[ivar.propertyName]; if (objectClass) { value = [objectClass objectArrayWithKeyValuesArray:value]; } } // 4. ivar.value = value; }]; // if ([self respondsToSelector:@selector(keyValuesDidFinishConvertingToObject)]) { [self keyValuesDidFinishConvertingToObject]; } } /** * * @return */ - (NSDictionary *)keyValues { NSMutableDictionary *keyValues = [NSMutableDictionary dictionary]; [self enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) { if (ivar.isSrcClassFromFoundation) return; // 1. id value = ivar.value; if (!value) return; // 2. if (ivar.type.typeClass && !ivar.type.isFromFoundation) { value = [value keyValues]; } else if (ivar.type.typeClass == [NSURL class]) { value = [value absoluteString]; } else if ([self respondsToSelector:@selector(objectClassInArray)]) { // 3. Class objectClass = self.objectClassInArray[ivar.propertyName]; if (objectClass) { value = [objectClass keyValuesArrayWithObjectArray:value]; } } // 4. NSString *key = [self keyWithPropertyName:ivar.propertyName]; keyValues[key] = value; }]; // if ([self respondsToSelector:@selector(objectDidFinishConvertingToKeyValues)]) { [self objectDidFinishConvertingToKeyValues]; } return keyValues; } /** * JSON * @param data JSON * @return */ + (NSArray *)objectArrayWithJSONData:(NSData *)data { MJAssertParamNotNil2(data, nil); NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; return [self objectArrayWithKeyValuesArray:array]; } /** * * @param objectArray * @return */ + (NSArray *)keyValuesArrayWithObjectArray:(NSArray *)objectArray { // 0. NSString *desc = [NSString stringWithFormat:@"objectArray is not a NSArray - objectArray, objectArray is a %@ - objectArray%@", objectArray.class, objectArray.class]; MJAssert2([objectArray isKindOfClass:[NSArray class]], desc, nil); // 1. if (![objectArray isKindOfClass:[NSArray class]]) return objectArray; if (![[objectArray lastObject] isKindOfClass:self]) return objectArray; // 2. NSMutableArray *keyValuesArray = [NSMutableArray array]; for (id object in objectArray) { [keyValuesArray addObject:[object keyValues]]; } return keyValuesArray; } #pragma mark - /** * * @param keyValuesArray * @return */ + (NSArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray { // 1. NSString *desc = [NSString stringWithFormat:@"keyValuesArray is not a keyValuesArray - keyValuesArray, keyValuesArray is a %@ - keyValuesArray%@", keyValuesArray.class, keyValuesArray.class]; MJAssert2([keyValuesArray isKindOfClass:[NSArray class]], desc, nil); // 2. NSMutableArray *modelArray = [NSMutableArray array]; // 3. for (NSDictionary *keyValues in keyValuesArray) { if (![keyValues isKindOfClass:[NSDictionary class]]) continue; id model = [self objectWithKeyValues:keyValues]; [modelArray addObject:model]; } return modelArray; } /** * plist * @param filename (mainBundle) * @return */ + (NSArray *)objectArrayWithFilename:(NSString *)filename { MJAssertParamNotNil2(filename, nil); NSString *file = [[NSBundle mainBundle] pathForResource:filename ofType:nil]; return [self objectArrayWithFile:file]; } /** * plist * @param file * @return */ + (NSArray *)objectArrayWithFile:(NSString *)file { MJAssertParamNotNil2(file, nil); NSArray *keyValuesArray = [NSArray arrayWithContentsOfFile:file]; return [self objectArrayWithKeyValuesArray:keyValuesArray]; } #pragma mark - /** * key * * @param propertyName * * @return key */ - (NSString *)keyWithPropertyName:(NSString *)propertyName { MJAssertParamNotNil2(propertyName, nil); NSString *key = nil; // 1.key if ([self respondsToSelector:@selector(replacedKeyFromPropertyName)]) { key = self.replacedKeyFromPropertyName[propertyName]; } // 2.key if (!key) key = propertyName; return key; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/MJExtension/NSObject+MJKeyValue.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,818
```objective-c #import <Foundation/Foundation.h> #import "FMResultSet.h" #import "FMDatabasePool.h" #if ! __has_feature(objc_arc) #define FMDBAutorelease(__v) ([__v autorelease]); #define FMDBReturnAutoreleased FMDBAutorelease #define FMDBRetain(__v) ([__v retain]); #define FMDBReturnRetained FMDBRetain #define FMDBRelease(__v) ([__v release]); #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); #else // -fobjc-arc #define FMDBAutorelease(__v) #define FMDBReturnAutoreleased(__v) (__v) #define FMDBRetain(__v) #define FMDBReturnRetained(__v) (__v) #define FMDBRelease(__v) // If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects // and will participate in ARC. // See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. #if OS_OBJECT_USE_OBJC #define FMDBDispatchQueueRelease(__v) #else #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); #endif #endif #if !__has_feature(objc_instancetype) #define instancetype id #endif typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); /** A SQLite ([path_to_url Objective-C wrapper. ### Usage The three main classes in FMDB are: - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. - `<FMResultSet>` - Represents the results of executing a query on an `FMDatabase`. - `<FMDatabaseQueue>` - If you want to perform queries and updates on multiple threads, you'll want to use this class. ### See also - `<FMDatabasePool>` - A pool of `FMDatabase` objects. - `<FMStatement>` - A wrapper for `sqlite_stmt`. ### External links - [FMDB on GitHub](path_to_url including introductory documentation - [SQLite web site](path_to_url - [FMDB mailing list](path_to_url - [SQLite FAQ](path_to_url @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use `<FMDatabaseQueue>`. */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wobjc-interface-ivars" @interface FMDatabase : NSObject { void* _db; NSString* _databasePath; BOOL _logsErrors; BOOL _crashOnErrors; BOOL _traceExecution; BOOL _checkedOut; BOOL _shouldCacheStatements; BOOL _isExecutingStatement; BOOL _inTransaction; NSTimeInterval _maxBusyRetryTimeInterval; NSTimeInterval _startBusyRetryTime; NSMutableDictionary *_cachedStatements; NSMutableSet *_openResultSets; NSMutableSet *_openFunctions; NSDateFormatter *_dateFormat; } ///----------------- /// @name Properties ///----------------- /** Whether should trace execution */ @property (atomic, assign) BOOL traceExecution; /** Whether checked out or not */ @property (atomic, assign) BOOL checkedOut; /** Crash on errors */ @property (atomic, assign) BOOL crashOnErrors; /** Logs errors */ @property (atomic, assign) BOOL logsErrors; /** Dictionary of cached statements */ @property (atomic, retain) NSMutableDictionary *cachedStatements; ///--------------------- /// @name Initialization ///--------------------- /** Create a `FMDatabase` object. An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. For example, to create/open a database in your Mac OS X `tmp` folder: FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; Or, in iOS, you might open a database in the app's `Documents` directory: NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [path_to_url @param inPath Path of database file @return `FMDatabase` object if successful; `nil` if failure. */ + (instancetype)databaseWithPath:(NSString*)inPath; /** Initialize a `FMDatabase` object. An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. For example, to create/open a database in your Mac OS X `tmp` folder: FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; Or, in iOS, you might open a database in the app's `Documents` directory: NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [path_to_url @param inPath Path of database file @return `FMDatabase` object if successful; `nil` if failure. */ - (instancetype)initWithPath:(NSString*)inPath; ///----------------------------------- /// @name Opening and closing database ///----------------------------------- /** Opening a new database connection The database is opened for reading and writing, and is created if it does not already exist. @return `YES` if successful, `NO` on error. @see [sqlite3_open()](path_to_url @see openWithFlags: @see close */ - (BOOL)open; /** Opening a new database connection with flags and an optional virtual file system (VFS) @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: `SQLITE_OPEN_READONLY` The database is opened in read-only mode. If the database does not already exist, an error is returned. `SQLITE_OPEN_READWRITE` The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. @return `YES` if successful, `NO` on error. @see [sqlite3_open_v2()](path_to_url @see open @see close */ - (BOOL)openWithFlags:(int)flags; /** Opening a new database connection with flags and an optional virtual file system (VFS) @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: `SQLITE_OPEN_READONLY` The database is opened in read-only mode. If the database does not already exist, an error is returned. `SQLITE_OPEN_READWRITE` The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. @param vfsName If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2. @return `YES` if successful, `NO` on error. @see [sqlite3_open_v2()](path_to_url @see open @see close */ - (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName; /** Closing a database connection @return `YES` if success, `NO` on error. @see [sqlite3_close()](path_to_url @see open @see openWithFlags: */ - (BOOL)close; /** Test to see if we have a good connection to the database. This will confirm whether: - is database open - if open, it will try a simple SELECT statement and confirm that it succeeds. @return `YES` if everything succeeds, `NO` on failure. */ - (BOOL)goodConnection; ///---------------------- /// @name Perform updates ///---------------------- /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](path_to_url [`sqlite3_bind`](path_to_url to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](path_to_url to perform the update. The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. @param sql The SQL to be performed, with optional `?` placeholders. @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned. @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage @see [`sqlite3_bind`](path_to_url */ - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...; /** Execute single update statement @see executeUpdate:withErrorAndBindings: @warning **Deprecated**: Please use `<executeUpdate:withErrorAndBindings>` instead. */ - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated)); /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](path_to_url [`sqlite3_bind`](path_to_url to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](path_to_url to perform the update. The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. @param sql The SQL to be performed, with optional `?` placeholders. @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage @see [`sqlite3_bind`](path_to_url @note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as `<executeUpdate:withArgumentsInArray:>`. */ - (BOOL)executeUpdate:(NSString*)sql, ...; /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](path_to_url and [`sqlite_step`](path_to_url to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method. @param format The SQL to be performed, with `printf`-style escape sequences. @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see executeUpdate: @see lastError @see lastErrorCode @see lastErrorMessage @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"]; is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeUpdate:>` [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"]; There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`. */ - (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](path_to_url and [`sqlite3_bind`](path_to_url binding any `?` placeholders in the SQL with the optional list of parameters. The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. @param sql The SQL to be performed, with optional `?` placeholders. @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see executeUpdate:values:error: @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](path_to_url and [`sqlite3_bind`](path_to_url binding any `?` placeholders in the SQL with the optional list of parameters. The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. This is similar to `<executeUpdate:withArgumentsInArray:>`, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned. In Swift 2, this throws errors, as if it were defined as follows: `func executeUpdate(sql: String!, values: [AnyObject]!) throws -> Bool` @param sql The SQL to be performed, with optional `?` placeholders. @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. @param error A `NSError` object to receive any error object (if any). @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error; /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](path_to_url and [`sqlite_step`](path_to_url to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. @param sql The SQL to be performed, with optional `?` placeholders. @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments; /** Execute single update statement This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](path_to_url and [`sqlite_step`](path_to_url to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. @param sql The SQL to be performed, with optional `?` placeholders. @param args A `va_list` of arguments. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args; /** Execute multiple SQL statements This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. @param sql The SQL to be performed @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see executeStatements:withResultBlock: @see [sqlite3_exec()](path_to_url */ - (BOOL)executeStatements:(NSString *)sql; /** Execute multiple SQL statements with callback handler This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. @param sql The SQL to be performed. @param block A block that will be called for any result sets returned by any SQL statements. Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK), non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary. This may be `nil` if you don't care to receive any results. @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see executeStatements: @see [sqlite3_exec()](path_to_url */ - (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block; /** Last insert rowid Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid. This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned. @return The rowid of the last inserted row. @see [sqlite3_last_insert_rowid()](path_to_url */ - (int64_t)lastInsertRowId; /** The number of rows changed by prior SQL statement. This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted. @return The number of rows changed by prior SQL statement. @see [sqlite3_changes()](path_to_url */ - (int)changes; ///------------------------- /// @name Retrieving results ///------------------------- /** Execute select statement Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed. In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. This method employs [`sqlite3_bind`](path_to_url for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method. @param sql The SELECT statement to be performed, with optional `?` placeholders. @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) @see [`sqlite3_bind`](path_to_url @note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as `<executeQuery:withArgumentsInArray:>`. */ - (FMResultSet *)executeQuery:(NSString*)sql, ...; /** Execute select statement Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed. In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. @param format The SQL to be performed, with `printf`-style escape sequences. @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see executeQuery: @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"]; is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeQuery:>` [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"]; There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`. */ - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); /** Execute select statement Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed. In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. @param sql The SELECT statement to be performed, with optional `?` placeholders. @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see -executeQuery:values:error: @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) */ - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; /** Execute select statement Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed. In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. This is similar to `<executeQuery:withArgumentsInArray:>`, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned. In Swift 2, this throws errors, as if it were defined as follows: `func executeQuery(sql: String!, values: [AnyObject]!) throws -> FMResultSet!` @param sql The SELECT statement to be performed, with optional `?` placeholders. @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. @param error A `NSError` object to receive any error object (if any). @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) @note When called from Swift, only use the first two parameters, `sql` and `values`. This but throws the error. */ - (FMResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error; /** Execute select statement Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed. In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. @param sql The SELECT statement to be performed, with optional `?` placeholders. @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. @return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see FMResultSet @see [`FMResultSet next`](<[FMResultSet next]>) */ - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments; // Documentation forthcoming. - (FMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args; ///------------------- /// @name Transactions ///------------------- /** Begin a transaction @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see commit @see rollback @see beginDeferredTransaction @see inTransaction */ - (BOOL)beginTransaction; /** Begin a deferred transaction @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see commit @see rollback @see beginTransaction @see inTransaction */ - (BOOL)beginDeferredTransaction; /** Commit a transaction Commit a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see beginTransaction @see beginDeferredTransaction @see rollback @see inTransaction */ - (BOOL)commit; /** Rollback a transaction Rollback a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`. @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see beginTransaction @see beginDeferredTransaction @see commit @see inTransaction */ - (BOOL)rollback; /** Identify whether currently in a transaction or not @return `YES` if currently within transaction; `NO` if not. @see beginTransaction @see beginDeferredTransaction @see commit @see rollback */ - (BOOL)inTransaction; ///---------------------------------------- /// @name Cached statements and result sets ///---------------------------------------- /** Clear cached statements */ - (void)clearCachedStatements; /** Close all open result sets */ - (void)closeOpenResultSets; /** Whether database has any open result sets @return `YES` if there are open result sets; `NO` if not. */ - (BOOL)hasOpenResultSets; /** Return whether should cache statements or not @return `YES` if should cache statements; `NO` if not. */ - (BOOL)shouldCacheStatements; /** Set whether should cache statements or not @param value `YES` if should cache statements; `NO` if not. */ - (void)setShouldCacheStatements:(BOOL)value; ///------------------------- /// @name Encryption methods ///------------------------- /** Set encryption key. @param key The key to be used. @return `YES` if success, `NO` on error. @see path_to_url @warning You need to have purchased the sqlite encryption extensions for this method to work. */ - (BOOL)setKey:(NSString*)key; /** Reset encryption key @param key The key to be used. @return `YES` if success, `NO` on error. @see path_to_url @warning You need to have purchased the sqlite encryption extensions for this method to work. */ - (BOOL)rekey:(NSString*)key; /** Set encryption key using `keyData`. @param keyData The `NSData` to be used. @return `YES` if success, `NO` on error. @see path_to_url @warning You need to have purchased the sqlite encryption extensions for this method to work. */ - (BOOL)setKeyWithData:(NSData *)keyData; /** Reset encryption key using `keyData`. @param keyData The `NSData` to be used. @return `YES` if success, `NO` on error. @see path_to_url @warning You need to have purchased the sqlite encryption extensions for this method to work. */ - (BOOL)rekeyWithData:(NSData *)keyData; ///------------------------------ /// @name General inquiry methods ///------------------------------ /** The path of the database file @return path of database. */ - (NSString *)databasePath; /** The underlying SQLite handle @return The `sqlite3` pointer. */ - (void*)sqliteHandle; ///----------------------------- /// @name Retrieving error codes ///----------------------------- /** Last error message Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. @return `NSString` of the last error message. @see [sqlite3_errmsg()](path_to_url @see lastErrorCode @see lastError */ - (NSString*)lastErrorMessage; /** Last error code Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. @return Integer value of the last error code. @see [sqlite3_errcode()](path_to_url @see lastErrorMessage @see lastError */ - (int)lastErrorCode; /** Had error @return `YES` if there was an error, `NO` if no error. @see lastError @see lastErrorCode @see lastErrorMessage */ - (BOOL)hadError; /** Last error @return `NSError` representing the last error. @see lastErrorCode @see lastErrorMessage */ - (NSError*)lastError; // description forthcoming - (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds; - (NSTimeInterval)maxBusyRetryTimeInterval; ///------------------ /// @name Save points ///------------------ /** Start save point @param name Name of save point. @param outErr A `NSError` object to receive any error object (if any). @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see releaseSavePointWithName:error: @see rollbackToSavePointWithName:error: */ - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr; /** Release save point @param name Name of save point. @param outErr A `NSError` object to receive any error object (if any). @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see startSavePointWithName:error: @see rollbackToSavePointWithName:error: */ - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr; /** Roll back to save point @param name Name of save point. @param outErr A `NSError` object to receive any error object (if any). @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure. @see startSavePointWithName:error: @see releaseSavePointWithName:error: */ - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr; /** Start save point @param block Block of code to perform from within save point. @return The NSError corresponding to the error, if any. If no error, returns `nil`. @see startSavePointWithName:error: @see releaseSavePointWithName:error: @see rollbackToSavePointWithName:error: */ - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block; ///---------------------------- /// @name SQLite library status ///---------------------------- /** Test to see if the library is threadsafe @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0. @see [sqlite3_threadsafe()](path_to_url */ + (BOOL)isSQLiteThreadSafe; /** Run-time library version numbers @return The sqlite library version string. @see [sqlite3_libversion()](path_to_url */ + (NSString*)sqliteLibVersion; + (NSString*)FMDBUserVersion; + (SInt32)FMDBVersion; ///------------------------ /// @name Make SQL function ///------------------------ /** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. For example: [queue inDatabase:^(FMDatabase *adb) { [adb executeUpdate:@"create table ftest (foo text)"]; [adb executeUpdate:@"insert into ftest values ('hello')"]; [adb executeUpdate:@"insert into ftest values ('hi')"]; [adb executeUpdate:@"insert into ftest values ('not h!')"]; [adb executeUpdate:@"insert into ftest values ('definitely not h!')"]; [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) { if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) { @autoreleasepool { const char *c = (const char *)sqlite3_value_text(aargv[0]); NSString *s = [NSString stringWithUTF8String:c]; sqlite3_result_int(context, [s hasPrefix:@"h"]); } } else { NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__); sqlite3_result_null(context); } }]; int rowCount = 0; FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"]; while ([ars next]) { rowCount++; NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]); } FMDBQuickCheck(rowCount == 2); }]; @param name Name of function @param count Maximum number of parameters @param block The block of code for the function @see [sqlite3_create_function()](path_to_url */ - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void **argv))block; ///--------------------- /// @name Date formatter ///--------------------- /** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales. Use this method to generate values to set the dateFormat property. Example: myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; @param format A valid NSDateFormatter format string. @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa. @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: @warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes. */ + (NSDateFormatter *)storeableDateFormat:(NSString *)format; /** Test whether the database has a date formatter assigned. @return `YES` if there is a date formatter; `NO` if not. @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: */ - (BOOL)hasDateFormatter; /** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps. @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat. @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe. */ - (void)setDateFormat:(NSDateFormatter *)format; /** Convert the supplied NSString to NSDate, using the current database formatter. @param s `NSString` to convert to `NSDate`. @return The `NSDate` object; or `nil` if no formatter is set. @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: */ - (NSDate *)dateFromString:(NSString *)s; /** Convert the supplied NSDate to NSString, using the current database formatter. @param date `NSDate` of date to convert to `NSString`. @return The `NSString` representation of the date; `nil` if no formatter is set. @see hasDateFormatter @see setDateFormat: @see dateFromString: @see stringFromDate: @see storeableDateFormat: */ - (NSString *)stringFromDate:(NSDate *)date; @end /** Objective-C wrapper for `sqlite3_stmt` This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `<FMDatabase>` and `<FMResultSet>` only. ### See also - `<FMDatabase>` - `<FMResultSet>` - [`sqlite3_stmt`](path_to_url */ @interface FMStatement : NSObject { void *_statement; NSString *_query; long _useCount; BOOL _inUse; } ///----------------- /// @name Properties ///----------------- /** Usage count */ @property (atomic, assign) long useCount; /** SQL statement */ @property (atomic, retain) NSString *query; /** SQLite sqlite3_stmt @see [`sqlite3_stmt`](path_to_url */ @property (atomic, assign) void *statement; /** Indication of whether the statement is in use */ @property (atomic, assign) BOOL inUse; ///---------------------------- /// @name Closing and Resetting ///---------------------------- /** Close statement */ - (void)close; /** Reset statement */ - (void)reset; @end #pragma clang diagnostic pop ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMDatabase.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
10,310
```objective-c #import "FMDatabase.h" #import "unistd.h" #import <objc/runtime.h> #if FMDB_SQLITE_STANDALONE #import <sqlite3/sqlite3.h> #else #import <sqlite3.h> #endif @interface FMDatabase () - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; @end @implementation FMDatabase @synthesize cachedStatements=_cachedStatements; @synthesize logsErrors=_logsErrors; @synthesize crashOnErrors=_crashOnErrors; @synthesize checkedOut=_checkedOut; @synthesize traceExecution=_traceExecution; #pragma mark FMDatabase instantiation and deallocation + (instancetype)databaseWithPath:(NSString*)aPath { return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); } - (instancetype)init { return [self initWithPath:nil]; } - (instancetype)initWithPath:(NSString*)aPath { assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do. self = [super init]; if (self) { _databasePath = [aPath copy]; _openResultSets = [[NSMutableSet alloc] init]; _db = nil; _logsErrors = YES; _crashOnErrors = NO; _maxBusyRetryTimeInterval = 2; } return self; } - (void)finalize { [self close]; [super finalize]; } - (void)dealloc { [self close]; FMDBRelease(_openResultSets); FMDBRelease(_cachedStatements); FMDBRelease(_dateFormat); FMDBRelease(_databasePath); FMDBRelease(_openFunctions); #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (NSString *)databasePath { return _databasePath; } + (NSString*)FMDBUserVersion { return @"2.6.2"; } // returns 0x0240 for version 2.4. This makes it super easy to do things like: // /* need to make sure to do X with FMDB version 2.4 or later */ // if ([FMDatabase FMDBVersion] >= 0x0240) { } + (SInt32)FMDBVersion { // we go through these hoops so that we only have to change the version number in a single spot. static dispatch_once_t once; static SInt32 FMDBVersionVal = 0; dispatch_once(&once, ^{ NSString *prodVersion = [self FMDBUserVersion]; if ([[prodVersion componentsSeparatedByString:@"."] count] < 3) { prodVersion = [prodVersion stringByAppendingString:@".0"]; } NSString *junk = [prodVersion stringByReplacingOccurrencesOfString:@"." withString:@""]; char *e = nil; FMDBVersionVal = (int) strtoul([junk UTF8String], &e, 16); }); return FMDBVersionVal; } #pragma mark SQLite information + (NSString*)sqliteLibVersion { return [NSString stringWithFormat:@"%s", sqlite3_libversion()]; } + (BOOL)isSQLiteThreadSafe { // make sure to read the sqlite headers on this guy! return sqlite3_threadsafe() != 0; } - (void*)sqliteHandle { return _db; } - (const char*)sqlitePath { if (!_databasePath) { return ":memory:"; } if ([_databasePath length] == 0) { return ""; // this creates a temporary database (it's an sqlite thing). } return [_databasePath fileSystemRepresentation]; } #pragma mark Open and close database - (BOOL)open { if (_db) { return YES; } int err = sqlite3_open([self sqlitePath], (sqlite3**)&_db ); if(err != SQLITE_OK) { NSLog(@"error opening!: %d", err); return NO; } if (_maxBusyRetryTimeInterval > 0.0) { // set the handler [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; } return YES; } - (BOOL)openWithFlags:(int)flags { return [self openWithFlags:flags vfs:nil]; } - (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName { #if SQLITE_VERSION_NUMBER >= 3005000 if (_db) { return YES; } int err = sqlite3_open_v2([self sqlitePath], (sqlite3**)&_db, flags, [vfsName UTF8String]); if(err != SQLITE_OK) { NSLog(@"error opening!: %d", err); return NO; } if (_maxBusyRetryTimeInterval > 0.0) { // set the handler [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; } return YES; #else NSLog(@"openWithFlags requires SQLite 3.5"); return NO; #endif } - (BOOL)close { [self clearCachedStatements]; [self closeOpenResultSets]; if (!_db) { return YES; } int rc; BOOL retry; BOOL triedFinalizingOpenStatements = NO; do { retry = NO; rc = sqlite3_close(_db); if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { if (!triedFinalizingOpenStatements) { triedFinalizingOpenStatements = YES; sqlite3_stmt *pStmt; while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) { NSLog(@"Closing leaked statement"); sqlite3_finalize(pStmt); retry = YES; } } } else if (SQLITE_OK != rc) { NSLog(@"error closing!: %d", rc); } } while (retry); _db = nil; return YES; } #pragma mark Busy handler routines // NOTE: appledoc seems to choke on this function for some reason; // so when generating documentation, you might want to ignore the // .m files so that it only documents the public interfaces outlined // in the .h files. // // This is a known appledoc bug that it has problems with C functions // within a class implementation, but for some reason, only this // C function causes problems; the rest don't. Anyway, ignoring the .m // files with appledoc will prevent this problem from occurring. static int FMDBDatabaseBusyHandler(void *f, int count) { FMDatabase *self = (__bridge FMDatabase*)f; if (count == 0) { self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate]; return 1; } NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime); if (delta < [self maxBusyRetryTimeInterval]) { int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50; int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds); if (actualSleepInMilliseconds != requestedSleepInMillseconds) { NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds); } return 1; } return 0; } - (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout { _maxBusyRetryTimeInterval = timeout; if (!_db) { return; } if (timeout > 0) { sqlite3_busy_handler(_db, &FMDBDatabaseBusyHandler, (__bridge void *)(self)); } else { // turn it off otherwise sqlite3_busy_handler(_db, nil, nil); } } - (NSTimeInterval)maxBusyRetryTimeInterval { return _maxBusyRetryTimeInterval; } // we no longer make busyRetryTimeout public // but for folks who don't bother noticing that the interface to FMDatabase changed, // we'll still implement the method so they don't get suprise crashes - (int)busyRetryTimeout { NSLog(@"%s:%d", __FUNCTION__, __LINE__); NSLog(@"FMDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval"); return -1; } - (void)setBusyRetryTimeout:(int)i { #pragma unused(i) NSLog(@"%s:%d", __FUNCTION__, __LINE__); NSLog(@"FMDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:"); } #pragma mark Result set functions - (BOOL)hasOpenResultSets { return [_openResultSets count] > 0; } - (void)closeOpenResultSets { //Copy the set so we don't get mutation errors NSSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]); for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; [rs setParentDB:nil]; [rs close]; [_openResultSets removeObject:rsInWrappedInATastyValueMeal]; } } - (void)resultSetDidClose:(FMResultSet *)resultSet { NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet]; [_openResultSets removeObject:setValue]; } #pragma mark Cached statements - (void)clearCachedStatements { for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) { for (FMStatement *statement in [statements allObjects]) { [statement close]; } } [_cachedStatements removeAllObjects]; } - (FMStatement*)cachedStatementForQuery:(NSString*)query { NSMutableSet* statements = [_cachedStatements objectForKey:query]; return [[statements objectsPassingTest:^BOOL(FMStatement* statement, BOOL *stop) { *stop = ![statement inUse]; return *stop; }] anyObject]; } - (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query { query = [query copy]; // in case we got handed in a mutable string... [statement setQuery:query]; NSMutableSet* statements = [_cachedStatements objectForKey:query]; if (!statements) { statements = [NSMutableSet set]; } [statements addObject:statement]; [_cachedStatements setObject:statements forKey:query]; FMDBRelease(query); } #pragma mark Key routines - (BOOL)rekey:(NSString*)key { NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; return [self rekeyWithData:keyData]; } - (BOOL)rekeyWithData:(NSData *)keyData { #ifdef SQLITE_HAS_CODEC if (!keyData) { return NO; } int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]); if (rc != SQLITE_OK) { NSLog(@"error on rekey: %d", rc); NSLog(@"%@", [self lastErrorMessage]); } return (rc == SQLITE_OK); #else #pragma unused(keyData) return NO; #endif } - (BOOL)setKey:(NSString*)key { NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; return [self setKeyWithData:keyData]; } - (BOOL)setKeyWithData:(NSData *)keyData { #ifdef SQLITE_HAS_CODEC if (!keyData) { return NO; } int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]); return (rc == SQLITE_OK); #else #pragma unused(keyData) return NO; #endif } #pragma mark Date routines + (NSDateFormatter *)storeableDateFormat:(NSString *)format { NSDateFormatter *result = FMDBReturnAutoreleased([[NSDateFormatter alloc] init]); result.dateFormat = format; result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; result.locale = FMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]); return result; } - (BOOL)hasDateFormatter { return _dateFormat != nil; } - (void)setDateFormat:(NSDateFormatter *)format { FMDBAutorelease(_dateFormat); _dateFormat = FMDBReturnRetained(format); } - (NSDate *)dateFromString:(NSString *)s { return [_dateFormat dateFromString:s]; } - (NSString *)stringFromDate:(NSDate *)date { return [_dateFormat stringFromDate:date]; } #pragma mark State of database - (BOOL)goodConnection { if (!_db) { return NO; } FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"]; if (rs) { [rs close]; return YES; } return NO; } - (void)warnInUse { NSLog(@"The FMDatabase %@ is currently in use.", self); #ifndef NS_BLOCK_ASSERTIONS if (_crashOnErrors) { // NSAssert(false, @"The FMDatabase %@ is currently in use.", self); abort(); } #endif } - (BOOL)databaseExists { if (!_db) { NSLog(@"The FMDatabase %@ is not open.", self); #ifndef NS_BLOCK_ASSERTIONS if (_crashOnErrors) { // NSAssert(false, @"The FMDatabase %@ is not open.", self); abort(); } #endif return NO; } return YES; } #pragma mark Error routines - (NSString*)lastErrorMessage { return [NSString stringWithUTF8String:sqlite3_errmsg(_db)]; } - (BOOL)hadError { int lastErrCode = [self lastErrorCode]; return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW); } - (int)lastErrorCode { return sqlite3_errcode(_db); } - (NSError*)errorWithMessage:(NSString*)message { NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey]; return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage]; } - (NSError*)lastError { return [self errorWithMessage:[self lastErrorMessage]]; } #pragma mark Update information routines - (sqlite_int64)lastInsertRowId { if (_isExecutingStatement) { [self warnInUse]; return NO; } _isExecutingStatement = YES; sqlite_int64 ret = sqlite3_last_insert_rowid(_db); _isExecutingStatement = NO; return ret; } - (int)changes { if (_isExecutingStatement) { [self warnInUse]; return 0; } _isExecutingStatement = YES; int ret = sqlite3_changes(_db); _isExecutingStatement = NO; return ret; } #pragma mark SQL manipulation - (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt { if ((!obj) || ((NSNull *)obj == [NSNull null])) { sqlite3_bind_null(pStmt, idx); } // FIXME - someday check the return codes on these binds. else if ([obj isKindOfClass:[NSData class]]) { const void *bytes = [obj bytes]; if (!bytes) { // it's an empty NSData object, aka [NSData data]. // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob. bytes = ""; } sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC); } else if ([obj isKindOfClass:[NSDate class]]) { if (self.hasDateFormatter) sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC); else sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]); } else if ([obj isKindOfClass:[NSNumber class]]) { if (strcmp([obj objCType], @encode(char)) == 0) { sqlite3_bind_int(pStmt, idx, [obj charValue]); } else if (strcmp([obj objCType], @encode(unsigned char)) == 0) { sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]); } else if (strcmp([obj objCType], @encode(short)) == 0) { sqlite3_bind_int(pStmt, idx, [obj shortValue]); } else if (strcmp([obj objCType], @encode(unsigned short)) == 0) { sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]); } else if (strcmp([obj objCType], @encode(int)) == 0) { sqlite3_bind_int(pStmt, idx, [obj intValue]); } else if (strcmp([obj objCType], @encode(unsigned int)) == 0) { sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]); } else if (strcmp([obj objCType], @encode(long)) == 0) { sqlite3_bind_int64(pStmt, idx, [obj longValue]); } else if (strcmp([obj objCType], @encode(unsigned long)) == 0) { sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]); } else if (strcmp([obj objCType], @encode(long long)) == 0) { sqlite3_bind_int64(pStmt, idx, [obj longLongValue]); } else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) { sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]); } else if (strcmp([obj objCType], @encode(float)) == 0) { sqlite3_bind_double(pStmt, idx, [obj floatValue]); } else if (strcmp([obj objCType], @encode(double)) == 0) { sqlite3_bind_double(pStmt, idx, [obj doubleValue]); } else if (strcmp([obj objCType], @encode(BOOL)) == 0) { sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0)); } else { sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); } } else { sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); } } - (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments { NSUInteger length = [sql length]; unichar last = '\0'; for (NSUInteger i = 0; i < length; ++i) { id arg = nil; unichar current = [sql characterAtIndex:i]; unichar add = current; if (last == '%') { switch (current) { case '@': arg = va_arg(args, id); break; case 'c': // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int' arg = [NSString stringWithFormat:@"%c", va_arg(args, int)]; break; case 's': arg = [NSString stringWithUTF8String:va_arg(args, char*)]; break; case 'd': case 'D': case 'i': arg = [NSNumber numberWithInt:va_arg(args, int)]; break; case 'u': case 'U': arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)]; break; case 'h': i++; if (i < length && [sql characterAtIndex:i] == 'i') { // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int' arg = [NSNumber numberWithShort:(short)(va_arg(args, int))]; } else if (i < length && [sql characterAtIndex:i] == 'u') { // warning: second argument to 'va_arg' is of promotable type 'unsigned short'; this va_arg has undefined behavior because arguments will be promoted to 'int' arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))]; } else { i--; } break; case 'q': i++; if (i < length && [sql characterAtIndex:i] == 'i') { arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; } else if (i < length && [sql characterAtIndex:i] == 'u') { arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; } else { i--; } break; case 'f': arg = [NSNumber numberWithDouble:va_arg(args, double)]; break; case 'g': // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double' arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))]; break; case 'l': i++; if (i < length) { unichar next = [sql characterAtIndex:i]; if (next == 'l') { i++; if (i < length && [sql characterAtIndex:i] == 'd') { //%lld arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; } else if (i < length && [sql characterAtIndex:i] == 'u') { //%llu arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; } else { i--; } } else if (next == 'd') { //%ld arg = [NSNumber numberWithLong:va_arg(args, long)]; } else if (next == 'u') { //%lu arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)]; } else { i--; } } else { i--; } break; default: // something else that we can't interpret. just pass it on through like normal break; } } else if (current == '%') { // percent sign; skip this character add = '\0'; } if (arg != nil) { [cleanedSQL appendString:@"?"]; [arguments addObject:arg]; } else if (add == (unichar)'@' && last == (unichar) '%') { [cleanedSQL appendFormat:@"NULL"]; } else if (add != '\0') { [cleanedSQL appendFormat:@"%C", add]; } last = current; } } #pragma mark Execute queries - (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments { return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; } - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { if (![self databaseExists]) { return 0x00; } if (_isExecutingStatement) { [self warnInUse]; return 0x00; } _isExecutingStatement = YES; int rc = 0x00; sqlite3_stmt *pStmt = 0x00; FMStatement *statement = 0x00; FMResultSet *rs = 0x00; if (_traceExecution && sql) { NSLog(@"%@ executeQuery: %@", self, sql); } if (_shouldCacheStatements) { statement = [self cachedStatementForQuery:sql]; pStmt = statement ? [statement statement] : 0x00; [statement reset]; } if (!pStmt) { rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); if (SQLITE_OK != rc) { if (_logsErrors) { NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); NSLog(@"DB Query: %@", sql); NSLog(@"DB Path: %@", _databasePath); } if (_crashOnErrors) { // NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); abort(); } sqlite3_finalize(pStmt); _isExecutingStatement = NO; return nil; } } id obj; int idx = 0; int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!) // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support if (dictionaryArgs) { for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { // Prefix the key with a colon. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; if (_traceExecution) { NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); } // Get the index for the parameter name. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); FMDBRelease(parameterName); if (namedIdx > 0) { // Standard binding from here. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; // increment the binding count, so our check below works out idx++; } else { NSLog(@"Could not find index for %@", dictionaryKey); } } } else { while (idx < queryCount) { if (arrayArgs && idx < (int)[arrayArgs count]) { obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; } else if (args) { obj = va_arg(args, id); } else { //We ran out of arguments break; } if (_traceExecution) { if ([obj isKindOfClass:[NSData class]]) { NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); } else { NSLog(@"obj: %@", obj); } } idx++; [self bindObject:obj toColumn:idx inStatement:pStmt]; } } if (idx != queryCount) { NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)"); sqlite3_finalize(pStmt); _isExecutingStatement = NO; return nil; } FMDBRetain(statement); // to balance the release below if (!statement) { statement = [[FMStatement alloc] init]; [statement setStatement:pStmt]; if (_shouldCacheStatements && sql) { [self setCachedStatement:statement forQuery:sql]; } } // the statement gets closed in rs's dealloc or [rs close]; rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self]; [rs setQuery:sql]; NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs]; [_openResultSets addObject:openResultSet]; [statement setUseCount:[statement useCount] + 1]; FMDBRelease(statement); _isExecutingStatement = NO; return rs; } - (FMResultSet *)executeQuery:(NSString*)sql, ... { va_list args; va_start(args, sql); id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; va_end(args); return result; } - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... { va_list args; va_start(args, format); NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; NSMutableArray *arguments = [NSMutableArray array]; [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; va_end(args); return [self executeQuery:sql withArgumentsInArray:arguments]; } - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments { return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; } - (FMResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { FMResultSet *rs = [self executeQuery:sql withArgumentsInArray:values orDictionary:nil orVAList:nil]; if (!rs && error) { *error = [self lastError]; } return rs; } - (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args { return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; } #pragma mark Execute updates - (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { if (![self databaseExists]) { return NO; } if (_isExecutingStatement) { [self warnInUse]; return NO; } _isExecutingStatement = YES; int rc = 0x00; sqlite3_stmt *pStmt = 0x00; FMStatement *cachedStmt = 0x00; if (_traceExecution && sql) { NSLog(@"%@ executeUpdate: %@", self, sql); } if (_shouldCacheStatements) { cachedStmt = [self cachedStatementForQuery:sql]; pStmt = cachedStmt ? [cachedStmt statement] : 0x00; [cachedStmt reset]; } if (!pStmt) { rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); if (SQLITE_OK != rc) { if (_logsErrors) { NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); NSLog(@"DB Query: %@", sql); NSLog(@"DB Path: %@", _databasePath); } if (_crashOnErrors) { // NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); abort(); } if (outErr) { *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]]; } sqlite3_finalize(pStmt); _isExecutingStatement = NO; return NO; } } id obj; int idx = 0; int queryCount = sqlite3_bind_parameter_count(pStmt); // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support if (dictionaryArgs) { for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { // Prefix the key with a colon. NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; if (_traceExecution) { NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); } // Get the index for the parameter name. int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); FMDBRelease(parameterName); if (namedIdx > 0) { // Standard binding from here. [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; // increment the binding count, so our check below works out idx++; } else { NSString *message = [NSString stringWithFormat:@"Could not find index for %@", dictionaryKey]; if (_logsErrors) { NSLog(@"%@", message); } if (outErr) { *outErr = [self errorWithMessage:message]; } } } } else { while (idx < queryCount) { if (arrayArgs && idx < (int)[arrayArgs count]) { obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; } else if (args) { obj = va_arg(args, id); } else { //We ran out of arguments break; } if (_traceExecution) { if ([obj isKindOfClass:[NSData class]]) { NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); } else { NSLog(@"obj: %@", obj); } } idx++; [self bindObject:obj toColumn:idx inStatement:pStmt]; } } if (idx != queryCount) { NSString *message = [NSString stringWithFormat:@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql]; if (_logsErrors) { NSLog(@"%@", message); } if (outErr) { *outErr = [self errorWithMessage:message]; } sqlite3_finalize(pStmt); _isExecutingStatement = NO; return NO; } /* Call sqlite3_step() to run the virtual machine. Since the SQL being ** executed is not a SELECT statement, we assume no data will be returned. */ rc = sqlite3_step(pStmt); if (SQLITE_DONE == rc) { // all is well, let's return. } else if (rc == SQLITE_ROW) { NSString *message = [NSString stringWithFormat:@"A executeUpdate is being called with a query string '%@'", sql]; if (_logsErrors) { NSLog(@"%@", message); NSLog(@"DB Query: %@", sql); } if (outErr) { *outErr = [self errorWithMessage:message]; } } else { if (outErr) { *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]]; } if (SQLITE_ERROR == rc) { if (_logsErrors) { NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db)); NSLog(@"DB Query: %@", sql); } } else if (SQLITE_MISUSE == rc) { // uh oh. if (_logsErrors) { NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db)); NSLog(@"DB Query: %@", sql); } } else { // wtf? if (_logsErrors) { NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db)); NSLog(@"DB Query: %@", sql); } } } if (_shouldCacheStatements && !cachedStmt) { cachedStmt = [[FMStatement alloc] init]; [cachedStmt setStatement:pStmt]; [self setCachedStatement:cachedStmt forQuery:sql]; FMDBRelease(cachedStmt); } int closeErrorCode; if (cachedStmt) { [cachedStmt setUseCount:[cachedStmt useCount] + 1]; closeErrorCode = sqlite3_reset(pStmt); } else { /* Finalize the virtual machine. This releases all memory and other ** resources allocated by the sqlite3_prepare() call above. */ closeErrorCode = sqlite3_finalize(pStmt); } if (closeErrorCode != SQLITE_OK) { if (_logsErrors) { NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db)); NSLog(@"DB Query: %@", sql); } } _isExecutingStatement = NO; return (rc == SQLITE_DONE || rc == SQLITE_OK); } - (BOOL)executeUpdate:(NSString*)sql, ... { va_list args; va_start(args, sql); BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; va_end(args); return result; } - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments { return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; } - (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { return [self executeUpdate:sql error:error withArgumentsInArray:values orDictionary:nil orVAList:nil]; } - (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments { return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; } - (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args { return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; } - (BOOL)executeUpdateWithFormat:(NSString*)format, ... { va_list args; va_start(args, format); NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; NSMutableArray *arguments = [NSMutableArray array]; [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; va_end(args); return [self executeUpdate:sql withArgumentsInArray:arguments]; } int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang. int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) { if (!theBlockAsVoid) { return SQLITE_OK; } int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid); NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns]; for (NSInteger i = 0; i < columns; i++) { NSString *key = [NSString stringWithUTF8String:names[i]]; id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null]; [dictionary setObject:value forKey:key]; } return execCallbackBlock(dictionary); } - (BOOL)executeStatements:(NSString *)sql { return [self executeStatements:sql withResultBlock:nil]; } - (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block { int rc; char *errmsg = nil; rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? FMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg); if (errmsg && [self logsErrors]) { NSLog(@"Error inserting batch: %s", errmsg); sqlite3_free(errmsg); } return (rc == SQLITE_OK); } - (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... { va_list args; va_start(args, outErr); BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; va_end(args); return result; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-implementations" - (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... { va_list args; va_start(args, outErr); BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; va_end(args); return result; } #pragma clang diagnostic pop #pragma mark Transactions - (BOOL)rollback { BOOL b = [self executeUpdate:@"rollback transaction"]; if (b) { _inTransaction = NO; } return b; } - (BOOL)commit { BOOL b = [self executeUpdate:@"commit transaction"]; if (b) { _inTransaction = NO; } return b; } - (BOOL)beginDeferredTransaction { BOOL b = [self executeUpdate:@"begin deferred transaction"]; if (b) { _inTransaction = YES; } return b; } - (BOOL)beginTransaction { BOOL b = [self executeUpdate:@"begin exclusive transaction"]; if (b) { _inTransaction = YES; } return b; } - (BOOL)inTransaction { return _inTransaction; } static NSString *FMDBEscapeSavePointName(NSString *savepointName) { return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; } - (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr { #if SQLITE_VERSION_NUMBER >= 3007000 NSParameterAssert(name); NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)]; return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; #else NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return NO; #endif } - (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr { #if SQLITE_VERSION_NUMBER >= 3007000 NSParameterAssert(name); NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)]; return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; #else NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return NO; #endif } - (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr { #if SQLITE_VERSION_NUMBER >= 3007000 NSParameterAssert(name); NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)]; return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; #else NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return NO; #endif } - (NSError*)inSavePoint:(void (^)(BOOL *rollback))block { #if SQLITE_VERSION_NUMBER >= 3007000 static unsigned long savePointIdx = 0; NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++]; BOOL shouldRollback = NO; NSError *err = 0x00; if (![self startSavePointWithName:name error:&err]) { return err; } if (block) { block(&shouldRollback); } if (shouldRollback) { // We need to rollback and release this savepoint to remove it [self rollbackToSavePointWithName:name error:&err]; } [self releaseSavePointWithName:name error:&err]; return err; #else NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; #endif } #pragma mark Cache statements - (BOOL)shouldCacheStatements { return _shouldCacheStatements; } - (void)setShouldCacheStatements:(BOOL)value { _shouldCacheStatements = value; if (_shouldCacheStatements && !_cachedStatements) { [self setCachedStatements:[NSMutableDictionary dictionary]]; } if (!_shouldCacheStatements) { [self setCachedStatements:nil]; } } #pragma mark Callback function void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) { #if ! __has_feature(objc_arc) void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context); #else void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context); #endif if (block) { block(context, argc, argv); } } - (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void **argv))block { if (!_openFunctions) { _openFunctions = [NSMutableSet new]; } id b = FMDBReturnAutoreleased([block copy]); [_openFunctions addObject:b]; /* I tried adding custom functions to release the block when the connection is destroyed- but they seemed to never be called, so we use _openFunctions to store the values instead. */ #if ! __has_feature(objc_arc) sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); #else sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); #endif } @end @implementation FMStatement @synthesize statement=_statement; @synthesize query=_query; @synthesize useCount=_useCount; @synthesize inUse=_inUse; - (void)finalize { [self close]; [super finalize]; } - (void)dealloc { [self close]; FMDBRelease(_query); #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (void)close { if (_statement) { sqlite3_finalize(_statement); _statement = 0x00; } _inUse = NO; } - (void)reset { if (_statement) { sqlite3_reset(_statement); } _inUse = NO; } - (NSString*)description { return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query]; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMDatabase.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
10,366
```objective-c // // FMDatabaseAdditions.m // fmdb // // Created by August Mueller on 10/30/05. // #import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "TargetConditionals.h" #if FMDB_SQLITE_STANDALONE #import <sqlite3/sqlite3.h> #else #import <sqlite3.h> #endif @interface FMDatabase (PrivateStuff) - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; @end @implementation FMDatabase (FMDatabaseAdditions) #define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \ va_list args; \ va_start(args, query); \ FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \ va_end(args); \ if (![resultSet next]) { return (type)0; } \ type ret = [resultSet sel:0]; \ [resultSet close]; \ [resultSet setParentDB:nil]; \ return ret; - (NSString*)stringForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex); } - (int)intForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex); } - (long)longForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex); } - (BOOL)boolForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex); } - (double)doubleForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex); } - (NSData*)dataForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex); } - (NSDate*)dateForQuery:(NSString*)query, ... { RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex); } - (BOOL)tableExists:(NSString*)tableName { tableName = [tableName lowercaseString]; FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName]; //if at least one next exists, table exists BOOL returnBool = [rs next]; //close and free object [rs close]; return returnBool; } /* get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] check if table exist in database (patch from OZLB) */ - (FMResultSet*)getSchema { //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"]; return rs; } /* get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] */ - (FMResultSet*)getTableSchema:(NSString*)tableName { //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]]; return rs; } - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName { BOOL returnBool = NO; tableName = [tableName lowercaseString]; columnName = [columnName lowercaseString]; FMResultSet *rs = [self getTableSchema:tableName]; //check if column is present in table schema while ([rs next]) { if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) { returnBool = YES; break; } } //If this is not done FMDatabase instance stays out of pool [rs close]; return returnBool; } - (uint32_t)applicationID { #if SQLITE_VERSION_NUMBER >= 3007017 uint32_t r = 0; FMResultSet *rs = [self executeQuery:@"pragma application_id"]; if ([rs next]) { r = (uint32_t)[rs longLongIntForColumnIndex:0]; } [rs close]; return r; #else NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return 0; #endif } - (void)setApplicationID:(uint32_t)appID { #if SQLITE_VERSION_NUMBER >= 3007017 NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; FMResultSet *rs = [self executeQuery:query]; [rs next]; [rs close]; #else NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); #endif } #if TARGET_OS_MAC && !TARGET_OS_IPHONE - (NSString*)applicationIDString { #if SQLITE_VERSION_NUMBER >= 3007017 NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); assert([s length] == 6); s = [s substringWithRange:NSMakeRange(1, 4)]; return s; #else NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return nil; #endif } - (void)setApplicationIDString:(NSString*)s { #if SQLITE_VERSION_NUMBER >= 3007017 if ([s length] != 4) { NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); } [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; #else NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); #endif } #endif - (uint32_t)userVersion { uint32_t r = 0; FMResultSet *rs = [self executeQuery:@"pragma user_version"]; if ([rs next]) { r = (uint32_t)[rs longLongIntForColumnIndex:0]; } [rs close]; return r; } - (void)setUserVersion:(uint32_t)version { NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version]; FMResultSet *rs = [self executeQuery:query]; [rs next]; [rs close]; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-implementations" - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) { return [self columnExists:columnName inTableWithName:tableName]; } #pragma clang diagnostic pop - (BOOL)validateSQL:(NSString*)sql error:(NSError**)error { sqlite3_stmt *pStmt = NULL; BOOL validationSucceeded = YES; int rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); if (rc != SQLITE_OK) { validationSucceeded = NO; if (error) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:[self lastErrorCode] userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] forKey:NSLocalizedDescriptionKey]]; } } sqlite3_finalize(pStmt); return validationSucceeded; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMDatabaseAdditions.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,749
```objective-c #import <Foundation/Foundation.h> FOUNDATION_EXPORT double FMDBVersionNumber; FOUNDATION_EXPORT const unsigned char FMDBVersionString[]; #import "FMDatabase.h" #import "FMResultSet.h" #import "FMDatabaseAdditions.h" #import "FMDatabaseQueue.h" #import "FMDatabasePool.h" ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMDB.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
59
```objective-c // // FMDatabasePool.m // fmdb // // Created by August Mueller on 6/22/11. // #if FMDB_SQLITE_STANDALONE #import <sqlite3/sqlite3.h> #else #import <sqlite3.h> #endif #import "FMDatabasePool.h" #import "FMDatabase.h" @interface FMDatabasePool() - (void)pushDatabaseBackInPool:(FMDatabase*)db; - (FMDatabase*)db; @end @implementation FMDatabasePool @synthesize path=_path; @synthesize delegate=_delegate; @synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate; @synthesize openFlags=_openFlags; + (instancetype)databasePoolWithPath:(NSString*)aPath { return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); } + (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags { return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]); } - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { self = [super init]; if (self != nil) { _path = [aPath copy]; _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); _databaseInPool = FMDBReturnRetained([NSMutableArray array]); _databaseOutPool = FMDBReturnRetained([NSMutableArray array]); _openFlags = openFlags; _vfsName = [vfsName copy]; } return self; } - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { return [self initWithPath:aPath flags:openFlags vfs:nil]; } - (instancetype)initWithPath:(NSString*)aPath { // default flags for sqlite3_open return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; } - (instancetype)init { return [self initWithPath:nil]; } + (Class)databaseClass { return [FMDatabase class]; } - (void)dealloc { _delegate = 0x00; FMDBRelease(_path); FMDBRelease(_databaseInPool); FMDBRelease(_databaseOutPool); if (_lockQueue) { FMDBDispatchQueueRelease(_lockQueue); _lockQueue = 0x00; } #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (void)executeLocked:(void (^)(void))aBlock { dispatch_sync(_lockQueue, aBlock); } - (void)pushDatabaseBackInPool:(FMDatabase*)db { if (!db) { // db can be null if we set an upper bound on the # of databases to create. return; } [self executeLocked:^() { if ([self->_databaseInPool containsObject:db]) { [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise]; } [self->_databaseInPool addObject:db]; [self->_databaseOutPool removeObject:db]; }]; } - (FMDatabase*)db { __block FMDatabase *db; [self executeLocked:^() { db = [self->_databaseInPool lastObject]; BOOL shouldNotifyDelegate = NO; if (db) { [self->_databaseOutPool addObject:db]; [self->_databaseInPool removeLastObject]; } else { if (self->_maximumNumberOfDatabasesToCreate) { NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count]; if (currentCount >= self->_maximumNumberOfDatabasesToCreate) { NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount); return; } } db = [[[self class] databaseClass] databaseWithPath:self->_path]; shouldNotifyDelegate = YES; } //This ensures that the db is opened before returning #if SQLITE_VERSION_NUMBER >= 3005000 BOOL success = [db openWithFlags:self->_openFlags vfs:self->_vfsName]; #else BOOL success = [db open]; #endif if (success) { if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) { [db close]; db = 0x00; } else { //It should not get added in the pool twice if lastObject was found if (![self->_databaseOutPool containsObject:db]) { [self->_databaseOutPool addObject:db]; if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) { [self->_delegate databasePool:self didAddDatabase:db]; } } } } else { NSLog(@"Could not open up the database at path %@", self->_path); db = 0x00; } }]; return db; } - (NSUInteger)countOfCheckedInDatabases { __block NSUInteger count; [self executeLocked:^() { count = [self->_databaseInPool count]; }]; return count; } - (NSUInteger)countOfCheckedOutDatabases { __block NSUInteger count; [self executeLocked:^() { count = [self->_databaseOutPool count]; }]; return count; } - (NSUInteger)countOfOpenDatabases { __block NSUInteger count; [self executeLocked:^() { count = [self->_databaseOutPool count] + [self->_databaseInPool count]; }]; return count; } - (void)releaseAllDatabases { [self executeLocked:^() { [self->_databaseOutPool removeAllObjects]; [self->_databaseInPool removeAllObjects]; }]; } - (void)inDatabase:(void (^)(FMDatabase *db))block { FMDatabase *db = [self db]; block(db); [self pushDatabaseBackInPool:db]; } - (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { BOOL shouldRollback = NO; FMDatabase *db = [self db]; if (useDeferred) { [db beginDeferredTransaction]; } else { [db beginTransaction]; } block(db, &shouldRollback); if (shouldRollback) { [db rollback]; } else { [db commit]; } [self pushDatabaseBackInPool:db]; } - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:YES withBlock:block]; } - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:NO withBlock:block]; } - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { #if SQLITE_VERSION_NUMBER >= 3007000 static unsigned long savePointIdx = 0; NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; BOOL shouldRollback = NO; FMDatabase *db = [self db]; NSError *err = 0x00; if (![db startSavePointWithName:name error:&err]) { [self pushDatabaseBackInPool:db]; return err; } block(db, &shouldRollback); if (shouldRollback) { // We need to rollback and release this savepoint to remove it [db rollbackToSavePointWithName:name error:&err]; } [db releaseSavePointWithName:name error:&err]; [self pushDatabaseBackInPool:db]; return err; #else NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; #endif } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMDatabasePool.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,798
```objective-c // // FMDatabaseQueue.m // fmdb // // Created by August Mueller on 6/22/11. // #import "FMDatabaseQueue.h" #import "FMDatabase.h" #if FMDB_SQLITE_STANDALONE #import <sqlite3/sqlite3.h> #else #import <sqlite3.h> #endif /* Note: we call [self retain]; before using dispatch_sync, just incase FMDatabaseQueue is released on another thread and we're in the middle of doing something in dispatch_sync */ /* * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses. * This in turn is used for deadlock detection by seeing if inDatabase: is called on * the queue's dispatch queue, which should not happen and causes a deadlock. */ static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey; @implementation FMDatabaseQueue @synthesize path = _path; @synthesize openFlags = _openFlags; @synthesize vfsName = _vfsName; + (instancetype)databaseQueueWithPath:(NSString*)aPath { FMDatabaseQueue *q = [[self alloc] initWithPath:aPath]; FMDBAutorelease(q); return q; } + (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags { FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; FMDBAutorelease(q); return q; } + (Class)databaseClass { return [FMDatabase class]; } - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { self = [super init]; if (self != nil) { _db = [[[self class] databaseClass] databaseWithPath:aPath]; FMDBRetain(_db); #if SQLITE_VERSION_NUMBER >= 3005000 BOOL success = [_db openWithFlags:openFlags vfs:vfsName]; #else BOOL success = [_db open]; #endif if (!success) { NSLog(@"Could not create database queue for path %@", aPath); FMDBRelease(self); return 0x00; } _path = FMDBReturnRetained(aPath); _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL); _openFlags = openFlags; _vfsName = [vfsName copy]; } return self; } - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { return [self initWithPath:aPath flags:openFlags vfs:nil]; } - (instancetype)initWithPath:(NSString*)aPath { // default flags for sqlite3_open return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:nil]; } - (instancetype)init { return [self initWithPath:nil]; } - (void)dealloc { FMDBRelease(_db); FMDBRelease(_path); if (_queue) { FMDBDispatchQueueRelease(_queue); _queue = 0x00; } #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (void)close { FMDBRetain(self); dispatch_sync(_queue, ^() { [self->_db close]; FMDBRelease(_db); self->_db = 0x00; }); FMDBRelease(self); } - (FMDatabase*)database { if (!_db) { _db = FMDBReturnRetained([[[self class] databaseClass] databaseWithPath:_path]); #if SQLITE_VERSION_NUMBER >= 3005000 BOOL success = [_db openWithFlags:_openFlags vfs:_vfsName]; #else BOOL success = [_db open]; #endif if (!success) { NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path); FMDBRelease(_db); _db = 0x00; return 0x00; } } return _db; } - (void)inDatabase:(void (^)(FMDatabase *db))block { /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue * and then check it against self to make sure we're not about to deadlock. */ FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey); assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock"); FMDBRetain(self); dispatch_sync(_queue, ^() { FMDatabase *db = [self database]; block(db); if ([db hasOpenResultSets]) { NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]"); #if defined(DEBUG) && DEBUG NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]); for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; NSLog(@"query: '%@'", [rs query]); } #endif } }); FMDBRelease(self); } - (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { FMDBRetain(self); dispatch_sync(_queue, ^() { BOOL shouldRollback = NO; if (useDeferred) { [[self database] beginDeferredTransaction]; } else { [[self database] beginTransaction]; } block([self database], &shouldRollback); if (shouldRollback) { [[self database] rollback]; } else { [[self database] commit]; } }); FMDBRelease(self); } - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:YES withBlock:block]; } - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { [self beginTransaction:NO withBlock:block]; } - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { #if SQLITE_VERSION_NUMBER >= 3007000 static unsigned long savePointIdx = 0; __block NSError *err = 0x00; FMDBRetain(self); dispatch_sync(_queue, ^() { NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; BOOL shouldRollback = NO; if ([[self database] startSavePointWithName:name error:&err]) { block([self database], &shouldRollback); if (shouldRollback) { // We need to rollback and release this savepoint to remove it [[self database] rollbackToSavePointWithName:name error:&err]; } [[self database] releaseSavePointWithName:name error:&err]; } }); FMDBRelease(self); return err; #else NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); if (self.logsErrors) NSLog(@"%@", errorMessage); return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; #endif } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMDatabaseQueue.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,631
```objective-c #import <Foundation/Foundation.h> #ifndef __has_feature // Optional. #define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif #ifndef NS_RETURNS_NOT_RETAINED #if __has_feature(attribute_ns_returns_not_retained) #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) #else #define NS_RETURNS_NOT_RETAINED #endif #endif @class FMDatabase; @class FMStatement; /** Represents the results of executing a query on an `<FMDatabase>`. ### See also - `<FMDatabase>` */ @interface FMResultSet : NSObject { FMDatabase *_parentDB; FMStatement *_statement; NSString *_query; NSMutableDictionary *_columnNameToIndexMap; } ///----------------- /// @name Properties ///----------------- /** Executed query */ @property (atomic, retain) NSString *query; /** `NSMutableDictionary` mapping column names to numeric index */ @property (readonly) NSMutableDictionary *columnNameToIndexMap; /** `FMStatement` used by result set. */ @property (atomic, retain) FMStatement *statement; ///------------------------------------ /// @name Creating and closing database ///------------------------------------ /** Create result set from `<FMStatement>` @param statement A `<FMStatement>` to be performed @param aDB A `<FMDatabase>` to be used @return A `FMResultSet` on success; `nil` on failure */ + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB; /** Close result set */ - (void)close; - (void)setParentDB:(FMDatabase *)newDb; ///--------------------------------------- /// @name Iterating through the result set ///--------------------------------------- /** Retrieve next row for result set. You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. @return `YES` if row successfully retrieved; `NO` if end of result set reached @see hasAnotherRow */ - (BOOL)next; /** Retrieve next row for result set. You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. @param outErr A 'NSError' object to receive any error object (if any). @return 'YES' if row successfully retrieved; 'NO' if end of result set reached @see hasAnotherRow */ - (BOOL)nextWithError:(NSError **)outErr; /** Did the last call to `<next>` succeed in retrieving another row? @return `YES` if the last call to `<next>` succeeded in retrieving another record; `NO` if not. @see next @warning The `hasAnotherRow` method must follow a call to `<next>`. If the previous database interaction was something other than a call to `next`, then this method may return `NO`, whether there is another row of data or not. */ - (BOOL)hasAnotherRow; ///--------------------------------------------- /// @name Retrieving information from result set ///--------------------------------------------- /** How many columns in result set @return Integer value of the number of columns. */ - (int)columnCount; /** Column index for column name @param columnName `NSString` value of the name of the column. @return Zero-based index for column. */ - (int)columnIndexForName:(NSString*)columnName; /** Column name for column index @param columnIdx Zero-based index for column. @return columnName `NSString` value of the name of the column. */ - (NSString*)columnNameForIndex:(int)columnIdx; /** Result set integer value for column. @param columnName `NSString` value of the name of the column. @return `int` value of the result set's column. */ - (int)intForColumn:(NSString*)columnName; /** Result set integer value for column. @param columnIdx Zero-based index for column. @return `int` value of the result set's column. */ - (int)intForColumnIndex:(int)columnIdx; /** Result set `long` value for column. @param columnName `NSString` value of the name of the column. @return `long` value of the result set's column. */ - (long)longForColumn:(NSString*)columnName; /** Result set long value for column. @param columnIdx Zero-based index for column. @return `long` value of the result set's column. */ - (long)longForColumnIndex:(int)columnIdx; /** Result set `long long int` value for column. @param columnName `NSString` value of the name of the column. @return `long long int` value of the result set's column. */ - (long long int)longLongIntForColumn:(NSString*)columnName; /** Result set `long long int` value for column. @param columnIdx Zero-based index for column. @return `long long int` value of the result set's column. */ - (long long int)longLongIntForColumnIndex:(int)columnIdx; /** Result set `unsigned long long int` value for column. @param columnName `NSString` value of the name of the column. @return `unsigned long long int` value of the result set's column. */ - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName; /** Result set `unsigned long long int` value for column. @param columnIdx Zero-based index for column. @return `unsigned long long int` value of the result set's column. */ - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx; /** Result set `BOOL` value for column. @param columnName `NSString` value of the name of the column. @return `BOOL` value of the result set's column. */ - (BOOL)boolForColumn:(NSString*)columnName; /** Result set `BOOL` value for column. @param columnIdx Zero-based index for column. @return `BOOL` value of the result set's column. */ - (BOOL)boolForColumnIndex:(int)columnIdx; /** Result set `double` value for column. @param columnName `NSString` value of the name of the column. @return `double` value of the result set's column. */ - (double)doubleForColumn:(NSString*)columnName; /** Result set `double` value for column. @param columnIdx Zero-based index for column. @return `double` value of the result set's column. */ - (double)doubleForColumnIndex:(int)columnIdx; /** Result set `NSString` value for column. @param columnName `NSString` value of the name of the column. @return `NSString` value of the result set's column. */ - (NSString*)stringForColumn:(NSString*)columnName; /** Result set `NSString` value for column. @param columnIdx Zero-based index for column. @return `NSString` value of the result set's column. */ - (NSString*)stringForColumnIndex:(int)columnIdx; /** Result set `NSDate` value for column. @param columnName `NSString` value of the name of the column. @return `NSDate` value of the result set's column. */ - (NSDate*)dateForColumn:(NSString*)columnName; /** Result set `NSDate` value for column. @param columnIdx Zero-based index for column. @return `NSDate` value of the result set's column. */ - (NSDate*)dateForColumnIndex:(int)columnIdx; /** Result set `NSData` value for column. This is useful when storing binary data in table (such as image or the like). @param columnName `NSString` value of the name of the column. @return `NSData` value of the result set's column. */ - (NSData*)dataForColumn:(NSString*)columnName; /** Result set `NSData` value for column. @param columnIdx Zero-based index for column. @return `NSData` value of the result set's column. */ - (NSData*)dataForColumnIndex:(int)columnIdx; /** Result set `(const unsigned char *)` value for column. @param columnName `NSString` value of the name of the column. @return `(const unsigned char *)` value of the result set's column. */ - (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName; /** Result set `(const unsigned char *)` value for column. @param columnIdx Zero-based index for column. @return `(const unsigned char *)` value of the result set's column. */ - (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx; /** Result set object for column. @param columnName `NSString` value of the name of the column. @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. @see objectForKeyedSubscript: */ - (id)objectForColumnName:(NSString*)columnName; /** Result set object for column. @param columnIdx Zero-based index for column. @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. @see objectAtIndexedSubscript: */ - (id)objectForColumnIndex:(int)columnIdx; /** Result set object for column. This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: id result = rs[@"employee_name"]; This simplified syntax is equivalent to calling: id result = [rs objectForKeyedSubscript:@"employee_name"]; which is, it turns out, equivalent to calling: id result = [rs objectForColumnName:@"employee_name"]; @param columnName `NSString` value of the name of the column. @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. */ - (id)objectForKeyedSubscript:(NSString *)columnName; /** Result set object for column. This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: id result = rs[0]; This simplified syntax is equivalent to calling: id result = [rs objectForKeyedSubscript:0]; which is, it turns out, equivalent to calling: id result = [rs objectForColumnName:0]; @param columnIdx Zero-based index for column. @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. */ - (id)objectAtIndexedSubscript:(int)columnIdx; /** Result set `NSData` value for column. @param columnName `NSString` value of the name of the column. @return `NSData` value of the result set's column. @warning If you are going to use this data after you iterate over the next row, or after you close the result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`) If you don't, you're going to be in a world of hurt when you try and use the data. */ - (NSData*)dataNoCopyForColumn:(NSString*)columnName NS_RETURNS_NOT_RETAINED; /** Result set `NSData` value for column. @param columnIdx Zero-based index for column. @return `NSData` value of the result set's column. @warning If you are going to use this data after you iterate over the next row, or after you close the result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`) If you don't, you're going to be in a world of hurt when you try and use the data. */ - (NSData*)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; /** Is the column `NULL`? @param columnIdx Zero-based index for column. @return `YES` if column is `NULL`; `NO` if not `NULL`. */ - (BOOL)columnIndexIsNull:(int)columnIdx; /** Is the column `NULL`? @param columnName `NSString` value of the name of the column. @return `YES` if column is `NULL`; `NO` if not `NULL`. */ - (BOOL)columnIsNull:(NSString*)columnName; /** Returns a dictionary of the row results mapped to case sensitive keys of the column names. @returns `NSDictionary` of the row results. @warning The keys to the dictionary are case sensitive of the column names. */ - (NSDictionary*)resultDictionary; /** Returns a dictionary of the row results @see resultDictionary @warning **Deprecated**: Please use `<resultDictionary>` instead. Also, beware that `<resultDictionary>` is case sensitive! */ - (NSDictionary*)resultDict __attribute__ ((deprecated)); ///----------------------------- /// @name Key value coding magic ///----------------------------- /** Performs `setValue` to yield support for key value observing. @param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe. */ - (void)kvcMagic:(id)object; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMResultSet.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,836
```objective-c #import "FMResultSet.h" #import "FMDatabase.h" #import "unistd.h" #if FMDB_SQLITE_STANDALONE #import <sqlite3/sqlite3.h> #else #import <sqlite3.h> #endif @interface FMDatabase () - (void)resultSetDidClose:(FMResultSet *)resultSet; @end @implementation FMResultSet @synthesize query=_query; @synthesize statement=_statement; + (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB { FMResultSet *rs = [[FMResultSet alloc] init]; [rs setStatement:statement]; [rs setParentDB:aDB]; NSParameterAssert(![statement inUse]); [statement setInUse:YES]; // weak reference return FMDBReturnAutoreleased(rs); } - (void)finalize { [self close]; [super finalize]; } - (void)dealloc { [self close]; FMDBRelease(_query); _query = nil; FMDBRelease(_columnNameToIndexMap); _columnNameToIndexMap = nil; #if ! __has_feature(objc_arc) [super dealloc]; #endif } - (void)close { [_statement reset]; FMDBRelease(_statement); _statement = nil; // we don't need this anymore... (i think) //[_parentDB setInUse:NO]; [_parentDB resultSetDidClose:self]; _parentDB = nil; } - (int)columnCount { return sqlite3_column_count([_statement statement]); } - (NSMutableDictionary *)columnNameToIndexMap { if (!_columnNameToIndexMap) { int columnCount = sqlite3_column_count([_statement statement]); _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount]; int columnIdx = 0; for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx] forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]]; } } return _columnNameToIndexMap; } - (void)kvcMagic:(id)object { int columnCount = sqlite3_column_count([_statement statement]); int columnIdx = 0; for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); // check for a null row if (c) { NSString *s = [NSString stringWithUTF8String:c]; [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]]; } } } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-implementations" - (NSDictionary*)resultDict { NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); if (num_cols > 0) { NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator]; NSString *columnName = nil; while ((columnName = [columnNames nextObject])) { id objectValue = [self objectForColumnName:columnName]; [dict setObject:objectValue forKey:columnName]; } return FMDBReturnAutoreleased([dict copy]); } else { NSLog(@"Warning: There seem to be no columns in this set."); } return nil; } #pragma clang diagnostic pop - (NSDictionary*)resultDictionary { NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); if (num_cols > 0) { NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; int columnCount = sqlite3_column_count([_statement statement]); int columnIdx = 0; for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]; id objectValue = [self objectForColumnIndex:columnIdx]; [dict setObject:objectValue forKey:columnName]; } return dict; } else { NSLog(@"Warning: There seem to be no columns in this set."); } return nil; } - (BOOL)next { return [self nextWithError:nil]; } - (BOOL)nextWithError:(NSError **)outErr { int rc = sqlite3_step([_statement statement]); if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]); NSLog(@"Database busy"); if (outErr) { *outErr = [_parentDB lastError]; } } else if (SQLITE_DONE == rc || SQLITE_ROW == rc) { // all is well, let's return. } else if (SQLITE_ERROR == rc) { NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); if (outErr) { *outErr = [_parentDB lastError]; } } else if (SQLITE_MISUSE == rc) { // uh oh. NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); if (outErr) { if (_parentDB) { *outErr = [_parentDB lastError]; } else { // If 'next' or 'nextWithError' is called after the result set is closed, // we need to return the appropriate error. NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey]; *outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage]; } } } else { // wtf? NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); if (outErr) { *outErr = [_parentDB lastError]; } } if (rc != SQLITE_ROW) { [self close]; } return (rc == SQLITE_ROW); } - (BOOL)hasAnotherRow { return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; } - (int)columnIndexForName:(NSString*)columnName { columnName = [columnName lowercaseString]; NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; if (n) { return [n intValue]; } NSLog(@"Warning: I could not find the column named '%@'.", columnName); return -1; } - (int)intForColumn:(NSString*)columnName { return [self intForColumnIndex:[self columnIndexForName:columnName]]; } - (int)intForColumnIndex:(int)columnIdx { return sqlite3_column_int([_statement statement], columnIdx); } - (long)longForColumn:(NSString*)columnName { return [self longForColumnIndex:[self columnIndexForName:columnName]]; } - (long)longForColumnIndex:(int)columnIdx { return (long)sqlite3_column_int64([_statement statement], columnIdx); } - (long long int)longLongIntForColumn:(NSString*)columnName { return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]]; } - (long long int)longLongIntForColumnIndex:(int)columnIdx { return sqlite3_column_int64([_statement statement], columnIdx); } - (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName { return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]]; } - (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx { return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx]; } - (BOOL)boolForColumn:(NSString*)columnName { return [self boolForColumnIndex:[self columnIndexForName:columnName]]; } - (BOOL)boolForColumnIndex:(int)columnIdx { return ([self intForColumnIndex:columnIdx] != 0); } - (double)doubleForColumn:(NSString*)columnName { return [self doubleForColumnIndex:[self columnIndexForName:columnName]]; } - (double)doubleForColumnIndex:(int)columnIdx { return sqlite3_column_double([_statement statement], columnIdx); } - (NSString*)stringForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { return nil; } const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); if (!c) { // null row. return nil; } return [NSString stringWithUTF8String:c]; } - (NSString*)stringForColumn:(NSString*)columnName { return [self stringForColumnIndex:[self columnIndexForName:columnName]]; } - (NSDate*)dateForColumn:(NSString*)columnName { return [self dateForColumnIndex:[self columnIndexForName:columnName]]; } - (NSDate*)dateForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { return nil; } return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]]; } - (NSData*)dataForColumn:(NSString*)columnName { return [self dataForColumnIndex:[self columnIndexForName:columnName]]; } - (NSData*)dataForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { return nil; } const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); if (dataBuffer == NULL) { return nil; } return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize]; } - (NSData*)dataNoCopyForColumn:(NSString*)columnName { return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]]; } - (NSData*)dataNoCopyForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { return nil; } const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO]; return data; } - (BOOL)columnIndexIsNull:(int)columnIdx { return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL; } - (BOOL)columnIsNull:(NSString*)columnName { return [self columnIndexIsNull:[self columnIndexForName:columnName]]; } - (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx { if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { return nil; } return sqlite3_column_text([_statement statement], columnIdx); } - (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; } - (id)objectForColumnIndex:(int)columnIdx { int columnType = sqlite3_column_type([_statement statement], columnIdx); id returnValue = nil; if (columnType == SQLITE_INTEGER) { returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]]; } else if (columnType == SQLITE_FLOAT) { returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]]; } else if (columnType == SQLITE_BLOB) { returnValue = [self dataForColumnIndex:columnIdx]; } else { //default to a string for everything else returnValue = [self stringForColumnIndex:columnIdx]; } if (returnValue == nil) { returnValue = [NSNull null]; } return returnValue; } - (id)objectForColumnName:(NSString*)columnName { return [self objectForColumnIndex:[self columnIndexForName:columnName]]; } // returns autoreleased NSString containing the name of the column in the result set - (NSString*)columnNameForIndex:(int)columnIdx { return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)]; } - (void)setParentDB:(FMDatabase *)newDb { _parentDB = newDb; } - (id)objectAtIndexedSubscript:(int)columnIdx { return [self objectForColumnIndex:columnIdx]; } - (id)objectForKeyedSubscript:(NSString *)columnName { return [self objectForColumnName:columnName]; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMResultSet.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,937
```objective-c // // FMDatabaseQueue.h // fmdb // // Created by August Mueller on 6/22/11. // #import <Foundation/Foundation.h> @class FMDatabase; /** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`. Using a single instance of `<FMDatabase>` from multiple threads at once is a bad idea. It has always been OK to make a `<FMDatabase>` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. Instead, use `FMDatabaseQueue`. Here's how to use it: First, make your queue. FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; Then use it like so: [queue inDatabase:^(FMDatabase *db) { [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; FMResultSet *rs = [db executeQuery:@"select * from foo"]; while ([rs next]) { // } }]; An easy way to wrap things up in a transaction can be done like this: [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; if (whoopsSomethingWrongHappened) { *rollback = YES; return; } // etc [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; }]; `FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. ### See also - `<FMDatabase>` @warning Do not instantiate a single `<FMDatabase>` object and use it across multiple threads. Use `FMDatabaseQueue` instead. @warning The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. */ @interface FMDatabaseQueue : NSObject { NSString *_path; dispatch_queue_t _queue; FMDatabase *_db; int _openFlags; NSString *_vfsName; } /** Path of database */ @property (atomic, retain) NSString *path; /** Open flags */ @property (atomic, readonly) int openFlags; /** Custom virtual file system name */ @property (atomic, copy) NSString *vfsName; ///---------------------------------------------------- /// @name Initialization, opening, and closing of queue ///---------------------------------------------------- /** Create queue using path. @param aPath The file path of the database. @return The `FMDatabaseQueue` object. `nil` on error. */ + (instancetype)databaseQueueWithPath:(NSString*)aPath; /** Create queue using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database @return The `FMDatabaseQueue` object. `nil` on error. */ + (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags; /** Create queue using path. @param aPath The file path of the database. @return The `FMDatabaseQueue` object. `nil` on error. */ - (instancetype)initWithPath:(NSString*)aPath; /** Create queue using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database @return The `FMDatabaseQueue` object. `nil` on error. */ - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; /** Create queue using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database @param vfsName The name of a custom virtual file system @return The `FMDatabaseQueue` object. `nil` on error. */ - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName; /** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. Subclasses can override this method to return specified Class of 'FMDatabase' subclass. @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. */ + (Class)databaseClass; /** Close database used by queue. */ - (void)close; ///----------------------------------------------- /// @name Dispatching database operations to queue ///----------------------------------------------- /** Synchronously perform database operations on queue. @param block The code to be run on the queue of `FMDatabaseQueue` */ - (void)inDatabase:(void (^)(FMDatabase *db))block; /** Synchronously perform database operations on queue, using transactions. @param block The code to be run on the queue of `FMDatabaseQueue` */ - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations on queue, using deferred transactions. @param block The code to be run on the queue of `FMDatabaseQueue` */ - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; ///----------------------------------------------- /// @name Dispatching database operations to queue ///----------------------------------------------- /** Synchronously perform database operations using save point. @param block The code to be run on the queue of `FMDatabaseQueue` */ // NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. // If you need to nest, use FMDatabase's startSavePointWithName:error: instead. - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMDatabaseQueue.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,344
```objective-c // // FMDatabasePool.h // fmdb // // Created by August Mueller on 6/22/11. // #import <Foundation/Foundation.h> @class FMDatabase; /** Pool of `<FMDatabase>` objects. ### See also - `<FMDatabaseQueue>` - `<FMDatabase>` @warning Before using `FMDatabasePool`, please consider using `<FMDatabaseQueue>` instead. If you really really really know what you're doing and `FMDatabasePool` is what you really really need (ie, you're using a read only database), OK you can use it. But just be careful not to deadlock! For an example on deadlocking, search for: `your_sha256_hashK_USE_FMDATABASEQUEUE_INSTEAD` in the main.m file. */ @interface FMDatabasePool : NSObject { NSString *_path; dispatch_queue_t _lockQueue; NSMutableArray *_databaseInPool; NSMutableArray *_databaseOutPool; __unsafe_unretained id _delegate; NSUInteger _maximumNumberOfDatabasesToCreate; int _openFlags; NSString *_vfsName; } /** Database path */ @property (atomic, retain) NSString *path; /** Delegate object */ @property (atomic, assign) id delegate; /** Maximum number of databases to create */ @property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate; /** Open flags */ @property (atomic, readonly) int openFlags; /** Custom virtual file system name */ @property (atomic, copy) NSString *vfsName; ///--------------------- /// @name Initialization ///--------------------- /** Create pool using path. @param aPath The file path of the database. @return The `FMDatabasePool` object. `nil` on error. */ + (instancetype)databasePoolWithPath:(NSString*)aPath; /** Create pool using path and specified flags @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database @return The `FMDatabasePool` object. `nil` on error. */ + (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags; /** Create pool using path. @param aPath The file path of the database. @return The `FMDatabasePool` object. `nil` on error. */ - (instancetype)initWithPath:(NSString*)aPath; /** Create pool using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database @return The `FMDatabasePool` object. `nil` on error. */ - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; /** Create pool using path and specified flags. @param aPath The file path of the database. @param openFlags Flags passed to the openWithFlags method of the database @param vfsName The name of a custom virtual file system @return The `FMDatabasePool` object. `nil` on error. */ - (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName; /** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. Subclasses can override this method to return specified Class of 'FMDatabase' subclass. @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. */ + (Class)databaseClass; ///------------------------------------------------ /// @name Keeping track of checked in/out databases ///------------------------------------------------ /** Number of checked-in databases in pool @returns Number of databases */ - (NSUInteger)countOfCheckedInDatabases; /** Number of checked-out databases in pool @returns Number of databases */ - (NSUInteger)countOfCheckedOutDatabases; /** Total number of databases in pool @returns Number of databases */ - (NSUInteger)countOfOpenDatabases; /** Release all databases in pool */ - (void)releaseAllDatabases; ///------------------------------------------ /// @name Perform database operations in pool ///------------------------------------------ /** Synchronously perform database operations in pool. @param block The code to be run on the `FMDatabasePool` pool. */ - (void)inDatabase:(void (^)(FMDatabase *db))block; /** Synchronously perform database operations in pool using transaction. @param block The code to be run on the `FMDatabasePool` pool. */ - (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations in pool using deferred transaction. @param block The code to be run on the `FMDatabasePool` pool. */ - (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; /** Synchronously perform database operations in pool using save point. @param block The code to be run on the `FMDatabasePool` pool. @return `NSError` object if error; `nil` if successful. @warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead. */ - (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; @end /** FMDatabasePool delegate category This is a category that defines the protocol for the FMDatabasePool delegate */ @interface NSObject (FMDatabasePoolDelegate) /** Asks the delegate whether database should be added to the pool. @param pool The `FMDatabasePool` object. @param database The `FMDatabase` object. @return `YES` if it should add database to pool; `NO` if not. */ - (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database; /** Tells the delegate that database was added to the pool. @param pool The `FMDatabasePool` object. @param database The `FMDatabase` object. */ - (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMDatabasePool.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,283
```objective-c // // FMDatabaseAdditions.h // fmdb // // Created by August Mueller on 10/30/05. // #import <Foundation/Foundation.h> #import "FMDatabase.h" /** Category of additions for `<FMDatabase>` class. ### See also - `<FMDatabase>` */ @interface FMDatabase (FMDatabaseAdditions) ///---------------------------------------- /// @name Return results of SQL to variable ///---------------------------------------- /** Return `int` value for query @param query The SQL query to be performed. @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. @return `int` value. @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. */ - (int)intForQuery:(NSString*)query, ...; /** Return `long` value for query @param query The SQL query to be performed. @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. @return `long` value. @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. */ - (long)longForQuery:(NSString*)query, ...; /** Return `BOOL` value for query @param query The SQL query to be performed. @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. @return `BOOL` value. @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. */ - (BOOL)boolForQuery:(NSString*)query, ...; /** Return `double` value for query @param query The SQL query to be performed. @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. @return `double` value. @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. */ - (double)doubleForQuery:(NSString*)query, ...; /** Return `NSString` value for query @param query The SQL query to be performed. @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. @return `NSString` value. @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. */ - (NSString*)stringForQuery:(NSString*)query, ...; /** Return `NSData` value for query @param query The SQL query to be performed. @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. @return `NSData` value. @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. */ - (NSData*)dataForQuery:(NSString*)query, ...; /** Return `NSDate` value for query @param query The SQL query to be performed. @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. @return `NSDate` value. @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. */ - (NSDate*)dateForQuery:(NSString*)query, ...; // Notice that there's no dataNoCopyForQuery:. // That would be a bad idea, because we close out the result set, and then what // happens to the data that we just didn't copy? Who knows, not I. ///-------------------------------- /// @name Schema related operations ///-------------------------------- /** Does table exist in database? @param tableName The name of the table being looked for. @return `YES` if table found; `NO` if not found. */ - (BOOL)tableExists:(NSString*)tableName; /** The schema of the database. This will be the schema for the entire database. For each entity, each row of the result set will include the following fields: - `type` - The type of entity (e.g. table, index, view, or trigger) - `name` - The name of the object - `tbl_name` - The name of the table to which the object references - `rootpage` - The page number of the root b-tree page for tables and indices - `sql` - The SQL that created the entity @return `FMResultSet` of schema; `nil` on error. @see [SQLite File Format](path_to_url */ - (FMResultSet*)getSchema; /** The schema of the database. This will be the schema for a particular table as report by SQLite `PRAGMA`, for example: PRAGMA table_info('employees') This will report: - `cid` - The column ID number - `name` - The name of the column - `type` - The data type specified for the column - `notnull` - whether the field is defined as NOT NULL (i.e. values required) - `dflt_value` - The default value for the column - `pk` - Whether the field is part of the primary key of the table @param tableName The name of the table for whom the schema will be returned. @return `FMResultSet` of schema; `nil` on error. @see [table_info](path_to_url#pragma_table_info) */ - (FMResultSet*)getTableSchema:(NSString*)tableName; /** Test to see if particular column exists for particular table in database @param columnName The name of the column. @param tableName The name of the table. @return `YES` if column exists in table in question; `NO` otherwise. */ - (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName; /** Test to see if particular column exists for particular table in database @param columnName The name of the column. @param tableName The name of the table. @return `YES` if column exists in table in question; `NO` otherwise. @see columnExists:inTableWithName: @warning Deprecated - use `<columnExists:inTableWithName:>` instead. */ - (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)); /** Validate SQL statement This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`. @param sql The SQL statement being validated. @param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned. @return `YES` if validation succeeded without incident; `NO` otherwise. */ - (BOOL)validateSQL:(NSString*)sql error:(NSError**)error; ///----------------------------------- /// @name Application identifier tasks ///----------------------------------- /** Retrieve application ID @return The `uint32_t` numeric value of the application ID. @see setApplicationID: */ - (uint32_t)applicationID; /** Set the application ID @param appID The `uint32_t` numeric value of the application ID. @see applicationID */ - (void)setApplicationID:(uint32_t)appID; #if TARGET_OS_MAC && !TARGET_OS_IPHONE /** Retrieve application ID string @return The `NSString` value of the application ID. @see setApplicationIDString: */ - (NSString*)applicationIDString; /** Set the application ID string @param string The `NSString` value of the application ID. @see applicationIDString */ - (void)setApplicationIDString:(NSString*)string; #endif ///----------------------------------- /// @name user version identifier tasks ///----------------------------------- /** Retrieve user version @return The `uint32_t` numeric value of the user version. @see setUserVersion: */ - (uint32_t)userVersion; /** Set the user-version @param version The `uint32_t` numeric value of the user version. @see userVersion */ - (void)setUserVersion:(uint32_t)version; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/FMDB/FMDatabaseAdditions.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,734
```objective-c // // YNPageConfigration.h // YNPageViewController // // Created by ZYN on 2018/4/22. // #import <UIKit/UIKit.h> /** YNPage - YNPageStyleTop: MenuView - YNPageStyleNavigation: MenuView - YNPageStyleSuspensionTop: MenuViewHeaderView - YNPageStyleSuspensionCenter: MenuViewHeaderView - YNPageStyleSuspensionTopPause: MenuViewHeaderView QQ SuspensionTopPause YNTableViewYNCollectionView YES */ typedef NS_ENUM(NSInteger, YNPageStyle) { YNPageStyleTop = 0, YNPageStyleNavigation = 1, YNPageStyleSuspensionTop = 2, YNPageStyleSuspensionCenter = 3, YNPageStyleSuspensionTopPause = 4, }; /** - YNPageHeaderViewScaleModeTop: Top - YNPageHeaderViewScaleModeCenter: Center */ typedef NS_ENUM(NSInteger, YNPageHeaderViewScaleMode) { YNPageHeaderViewScaleModeTop = 0, YNPageHeaderViewScaleModeCenter = 1, }; @interface YNPageConfigration : NSObject #pragma mark - YNPage Config /** YES */ @property (nonatomic, assign) BOOL showNavigation; /** Tabbar NO */ @property (nonatomic, assign) BOOL showTabbar; /** YNPageStyleTop */ @property (nonatomic, assign) YNPageStyle pageStyle; /** ScrollMenu 0 */ @property (nonatomic, assign) CGFloat suspenOffsetY; /** YES */ @property (nonatomic, assign) BOOL pageScrollEnabled; /** NO */ @property (nonatomic, assign) BOOL headerViewCouldScale; /** */ @property (nonatomic, assign) YNPageHeaderViewScaleMode headerViewScaleMode; /** NO */ @property (nonatomic, assign) BOOL headerViewCouldScrollPage; /** headerView + menu height */ @property (nonatomic, assign, readonly) CGFloat pageHeaderViewOriginHeight; #pragma mark - UIScrollMenuView Config /** */ @property (nonatomic, assign) BOOL showConver; /** YES */ @property (nonatomic, assign) BOOL showScrollLine; /** NO */ @property (nonatomic, assign) BOOL showBottomLine; /** YES */ @property (nonatomic, assign) BOOL showGradientColor; /** NO */ @property (nonatomic, assign) BOOL showAddButton; /** YES */ @property (nonatomic, assign) BOOL scrollMenu; /** NO */ @property (nonatomic, assign) BOOL bounces; /** * (Item+marginScrollView) YES * scrollMenu = NO,aligmentModeCenter = NO */ @property (nonatomic, assign) BOOL aligmentModeCenter; /** aligmentModeCenter NO */ @property (nonatomic, assign) BOOL lineWidthEqualFontWidth; /** Item ... */ @property (nonatomic, copy) NSArray<UIButton *> *buttonArray; /** N */ @property (nonatomic, copy) NSString *addButtonNormalImageName; /** H */ @property (nonatomic, copy) NSString *addButtonHightImageName; /** */ @property (nonatomic, strong) UIColor *addButtonBackgroundColor; /** color */ @property (nonatomic, strong) UIColor *lineColor; /** color */ @property (nonatomic, strong) UIColor *converColor; /** color */ @property (nonatomic, strong) UIColor *scrollViewBackgroundColor; /** color */ @property (nonatomic, strong) UIColor *normalItemColor; /** color */ @property (nonatomic, strong) UIColor *selectedItemColor; /** */ @property (nonatomic, strong) UIColor *bottomLineBgColor; /** 0 */ @property (nonatomic, assign) CGFloat bottomLineLeftAndRightMargin; /** 0 */ @property (nonatomic, assign) CGFloat bottomLineCorner; /** height 2 */ @property (nonatomic, assign) CGFloat lineHeight; /** 0*/ @property (nonatomic, assign) CGFloat lineBottomMargin; /** 0 */ @property (nonatomic, assign) CGFloat lineLeftAndRightMargin; /** 0 */ @property (nonatomic, assign) CGFloat lineCorner; /** 0 item */ @property (nonatomic, assign) CGFloat lineLeftAndRightAddWidth; /** height 2 */ @property (nonatomic, assign) CGFloat bottomLineHeight; /** height 28 */ @property (nonatomic, assign) CGFloat converHeight; /** height 44 */ @property (nonatomic, assign) CGFloat menuHeight; /** widht */ @property (nonatomic, assign) CGFloat menuWidth; /** 14 */ @property (nonatomic, assign) CGFloat coverCornerRadius; /** 15 */ @property (nonatomic, assign) CGFloat itemMargin; /** 15 */ @property (nonatomic, assign) CGFloat itemLeftAndRightMargin; /** 14 */ @property (nonatomic, strong) UIFont *itemFont; /** */ @property (nonatomic, strong) UIFont *selectedItemFont; /** */ @property (nonatomic, assign) CGFloat itemMaxScale; /** Top */ @property (nonatomic, assign) CGFloat tempTopHeight; /** */ @property (nonatomic, assign) CGFloat contentHeight; + (instancetype)new UNAVAILABLE_ATTRIBUTE; + (instancetype)init UNAVAILABLE_ATTRIBUTE; + (instancetype)defaultConfig; //############################################################################ @property (nonatomic, assign) CGFloat deltaScale; @property (nonatomic, assign) CGFloat deltaNorR; @property (nonatomic, assign) CGFloat deltaNorG; @property (nonatomic, assign) CGFloat deltaNorB; @property (nonatomic, assign) CGFloat deltaSelR; @property (nonatomic, assign) CGFloat deltaSelG; @property (nonatomic, assign) CGFloat deltaSelB; - (void)setRGBWithProgress:(CGFloat)progress; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/YNPageViewController/YNPageConfigration.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,179
```objective-c // // YNPageConfigration.m // YNPageViewController // // Created by ZYN on 2018/4/22. // #import "YNPageConfigration.h" #import "UIView+YNPageExtend.h" @interface YNPageConfigration () @property (nonatomic, strong) NSArray *normalColorArrays; @property (nonatomic, strong) NSArray *selectedColorArrays; @property (nonatomic, strong) NSArray *deltaColorArrays; @end @implementation YNPageConfigration - (instancetype)init { self = [super init]; if (self) { _showNavigation = YES; _showTabbar = NO; _pageStyle = YNPageStyleTop; _showConver = NO; _showScrollLine = YES; _showBottomLine = NO; _showGradientColor =YES; _showAddButton = NO; _scrollMenu = YES; _bounces = YES; _aligmentModeCenter = YES; _lineWidthEqualFontWidth = NO; _pageScrollEnabled = YES; _headerViewCouldScale = NO; _lineColor = [UIColor redColor]; _converColor = [UIColor groupTableViewBackgroundColor]; _addButtonBackgroundColor = [UIColor whiteColor]; _bottomLineBgColor = [UIColor greenColor]; _scrollViewBackgroundColor = [UIColor whiteColor]; _normalItemColor = [UIColor grayColor]; _selectedItemColor = [UIColor greenColor]; _lineHeight = 2; _converHeight = 28; _menuHeight = 44; _menuWidth = kYNPAGE_SCREEN_WIDTH; _coverCornerRadius = 14; _itemMargin = 15; _itemLeftAndRightMargin = 15; _itemFont = [UIFont systemFontOfSize:14]; _selectedItemFont = _itemFont; _itemMaxScale = 0; _lineBottomMargin = 0; _lineLeftAndRightAddWidth = 0; _bottomLineHeight = 2; } return self; } - (void)setRGBWithProgress:(CGFloat)progress { _deltaSelR = [self.normalColorArrays[0] floatValue] + [self.deltaColorArrays[0] floatValue] * progress; _deltaSelG = [self.normalColorArrays[1] floatValue] + [self.deltaColorArrays[1] floatValue] * progress; _deltaSelB = [self.normalColorArrays[2] floatValue] + [self.deltaColorArrays[2] floatValue] * progress; _deltaNorR = [self.selectedColorArrays[0] floatValue] - [self.deltaColorArrays[0] floatValue] * progress; _deltaNorG = [self.selectedColorArrays[1] floatValue] - [self.deltaColorArrays[1] floatValue] * progress; _deltaNorB = [self.selectedColorArrays[2] floatValue] - [self.deltaColorArrays[2] floatValue] * progress; } - (CGFloat)lineHeight { return _showScrollLine ? _lineHeight : 0; } - (CGFloat)deltaScale { return _deltaScale = _itemMaxScale - 1.0; } - (NSArray *)getRGBArrayWithColor:(UIColor *)color { CGFloat r = 0, g = 0, b = 0, a = 0; [color getRed:&r green:&g blue:&b alpha:&a]; return @[@(r),@(g),@(b)]; } - (NSArray *)normalColorArrays { if (!_normalColorArrays) { _normalColorArrays = [self getRGBArrayWithColor:_normalItemColor]; } return _normalColorArrays; } - (NSArray *)selectedColorArrays { if (!_selectedColorArrays) { _selectedColorArrays = [self getRGBArrayWithColor:self.selectedItemColor]; } return _selectedColorArrays; } - (NSArray *)deltaColorArrays { if (!_deltaColorArrays) { NSMutableArray *arrayM = [[NSMutableArray alloc]initWithCapacity:self.normalColorArrays.count]; [self.normalColorArrays enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { [arrayM addObject: @([self.selectedColorArrays[idx] floatValue] - [obj floatValue])]; }]; _deltaColorArrays = [arrayM copy]; } return _deltaColorArrays; } + (instancetype)defaultConfig { return [[self alloc] init]; }; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/YNPageViewController/YNPageConfigration.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
984
```objective-c // // YNPageViewController.h // YNPageViewController // // Created by ZYN on 2018/4/22. // #import <UIKit/UIKit.h> #import "YNPageConfigration.h" #import "YNPageScrollMenuView.h" #import "YNPageScrollView.h" @class YNPageViewController; @protocol YNPageViewControllerDelegate <NSObject> @optional /** @param pageViewController PageVC @param contentOffsetY @param progress */ - (void)pageViewController:(YNPageViewController *)pageViewController contentOffsetY:(CGFloat)contentOffsetY progress:(CGFloat)progress; /** UIScrollView, ScrollMenuView @param pageViewController PageVC @param scrollView UIScrollView */ - (void)pageViewController:(YNPageViewController *)pageViewController didEndDecelerating:(UIScrollView *)scrollView; /** UIScrollView, ScrollMenuView @param pageViewController PageVC @param scrollView UIScrollView @param progress @param fromIndex @param toIndex */ - (void)pageViewController:(YNPageViewController *)pageViewController didScroll:(UIScrollView *)scrollView progress:(CGFloat)progress formIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex; /** UIScrollMenuView AddAction @param pageViewController PageVC @param button Add */ - (void)pageViewController:(YNPageViewController *)pageViewController didAddButtonAction:(UIButton *)button; @end @protocol YNPageViewControllerDataSource <NSObject> @required /** index ScrollView @param pageViewController PageVC @param index pageIndex @return */ - (__kindof UIScrollView *)pageViewController:(YNPageViewController *)pageViewController pageForIndex:(NSInteger )index; @optional /** Key title Key @param pageViewController pageVC @param index pageIndex @return (ID) */ - (NSString *)pageViewController:(YNPageViewController *)pageViewController customCacheKeyForIndex:(NSInteger )index; @end @interface YNPageViewController : UIViewController /// @property (nonatomic, strong) YNPageConfigration *config; /// @property (nonatomic, strong) NSMutableArray<__kindof UIViewController *> *controllersM; /// key title @property (nonatomic, strong) NSMutableArray<NSString *> *titlesM; /// @property (nonatomic, strong) YNPageScrollMenuView *scrollMenuView; /// ScrollView @property (nonatomic, strong, readonly) YNPageScrollView *bgScrollView; /// headerView @property (nonatomic, strong) UIView *headerView; /// @property (nonatomic, weak) id<YNPageViewControllerDataSource> dataSource; /// @property (nonatomic, weak) id<YNPageViewControllerDelegate> delegate; /// index @property (nonatomic, assign) NSInteger pageIndex; /// View @property (nonatomic, strong) UIView *scaleBackgroundView; #pragma mark - initialize + (instancetype)new UNAVAILABLE_ATTRIBUTE; - (instancetype)init UNAVAILABLE_ATTRIBUTE; /** @param controllers @param titles @param config */ + (instancetype)pageViewControllerWithControllers:(NSArray *)controllers titles:(NSArray *)titles config:(YNPageConfigration *)config; /** @param controllers @param titles @param config */ - (instancetype)initPageViewControllerWithControllers:(NSArray *)controllers titles:(NSArray *)titles config:(YNPageConfigration *)config; /** * PageScrollViewVC * @param parentViewControler */ - (void)addSelfToParentViewController:(UIViewController *)parentViewControler; /** * PageScrollViewVC */ - (void)removeSelfViewController; /** ViewheaderView - e.g: vc.config = ... vc.titlesM = [self getArrayTitles].mutableCopy; ViewDidLoad controllers e.g: vc.controllersM = [self getArrayVCs].mutableCopy; */ - (void)reloadData; /** @param pageIndex */ - (void)setSelectedPageIndex:(NSInteger)pageIndex; /** @param title @param index index */ - (void)updateMenuItemTitle:(NSString *)title index:(NSInteger)index; /** @param titles */ - (void)updateMenuItemTitles:(NSArray *)titles; /** @param titles @param controllers @param index */ - (void)insertPageChildControllersWithTitles:(NSArray *)titles controllers:(NSArray *)controllers index:(NSInteger)index; /** @param title */ - (void)removePageControllerWithTitle:(NSString *)title; /** @param index */ - (void)removePageControllerWithIndex:(NSInteger)index; /** * - * * @param titleArray titles */ - (void)replaceTitlesArrayForSort:(NSArray *)titleArray; /** * HeaderViewFrame * YNPageStyleSuspensionTop 1. 2. * YNPageStyleSuspensionCenter 1. */ - (void)reloadSuspendHeaderViewFrame; /** () @param animated */ - (void)scrollToTop:(BOOL)animated; @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/YNPageViewController/YNPageViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,061
```objective-c // // YNPageCollectionView.m // YNPageViewController // // Created by ZYN on 2018/7/14. // #import "YNPageCollectionView.h" @interface YNPageCollectionView () <UIGestureRecognizerDelegate> @end @implementation YNPageCollectionView - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; } @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/YNPageViewController/View/YNPageCollectionView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
97
```objective-c // // YNPageHeaderScrollView.h // YNPageViewController // // Created by ZYN on 2018/5/25. // #import <UIKit/UIKit.h> #import "YNPageScrollView.h" @interface YNPageHeaderScrollView : YNPageScrollView @end ```
/content/code_sandbox/BigShow1949/Classes/Main/Lib/YNPageViewController/View/YNPageHeaderScrollView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
62