├── .DS_Store ├── .gitignore ├── README.md ├── tomahawk-ios.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ │ └── tomahawk-ios.xccheckout │ └── xcuserdata │ │ └── shawn.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── shawn.xcuserdatad │ └── xcschemes │ ├── tomahawk-ios.xcscheme │ └── xcschememanagement.plist ├── tomahawk-ios ├── AFHTTPRequestOperation.h ├── AFHTTPRequestOperation.m ├── AFHTTPRequestOperationManager.h ├── AFHTTPRequestOperationManager.m ├── AFHTTPSessionManager.h ├── AFHTTPSessionManager.m ├── AFNetworkReachabilityManager.h ├── AFNetworkReachabilityManager.m ├── AFNetworking.h ├── AFSecurityPolicy.h ├── AFSecurityPolicy.m ├── AFURLConnectionOperation.h ├── AFURLConnectionOperation.m ├── AFURLRequestSerialization.h ├── AFURLRequestSerialization.m ├── AFURLResponseSerialization.h ├── AFURLResponseSerialization.m ├── AFURLSessionManager.h ├── AFURLSessionManager.m ├── AppDelegate.h ├── AppDelegate.m ├── Base.lproj │ ├── LaunchScreen.xib │ └── Main.storyboard ├── Images.xcassets │ └── AppIcon.appiconset │ │ └── Contents.json ├── Info.plist ├── MKAnnotationView+WebCache.h ├── MKAnnotationView+WebCache.m ├── NSData+ImageContentType.h ├── NSData+ImageContentType.m ├── SDImageCache.h ├── SDImageCache.m ├── SDWebImageCompat.h ├── SDWebImageCompat.m ├── SDWebImageDecoder.h ├── SDWebImageDecoder.m ├── SDWebImageDownloader.h ├── SDWebImageDownloader.m ├── SDWebImageDownloaderOperation.h ├── SDWebImageDownloaderOperation.m ├── SDWebImageManager.h ├── SDWebImageManager.m ├── SDWebImageOperation.h ├── SDWebImagePrefetcher.h ├── SDWebImagePrefetcher.m ├── SVIndefiniteAnimatedView.h ├── SVIndefiniteAnimatedView.m ├── SVProgressHUD.h ├── SVProgressHUD.m ├── UIButton+WebCache.h ├── UIButton+WebCache.m ├── UIImage+GIF.h ├── UIImage+GIF.m ├── UIImage+MultiFormat.h ├── UIImage+MultiFormat.m ├── UIImage+WebP.h ├── UIImage+WebP.m ├── UIImageView+HighlightedWebCache.h ├── UIImageView+HighlightedWebCache.m ├── UIImageView+WebCache.h ├── UIImageView+WebCache.m ├── UIView+WebCacheOperation.h ├── UIView+WebCacheOperation.m ├── ViewController.h ├── ViewController.m ├── main.m └── tomahawk_ios.xcdatamodeld │ ├── .xccurrentversion │ └── tomahawk_ios.xcdatamodel │ └── contents └── tomahawk-iosTests ├── Info.plist └── tomahawk_iosTests.m /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomahawk-player/tomahawk-ios/b5349a85d9a09aa764c4f75a55b1d6f019433590/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ######################### 2 | # .gitignore file for Xcode4 / OS X Source projects 3 | # 4 | # Version 2.0 5 | # For latest version, see: http://stackoverflow.com/questions/49478/git-ignore-file-for-xcode-projects 6 | # 7 | # 2013 updates: 8 | # - fixed the broken "save personal Schemes" 9 | # 10 | # NB: if you are storing "built" products, this WILL NOT WORK, 11 | # and you should use a different .gitignore (or none at all) 12 | # This file is for SOURCE projects, where there are many extra 13 | # files that we want to exclude 14 | # 15 | ######################### 16 | 17 | ##### 18 | # OS X temporary files that should never be committed 19 | 20 | .DS_Store 21 | *.swp 22 | *.lock 23 | profile 24 | 25 | 26 | #### 27 | # Xcode temporary files that should never be committed 28 | # 29 | # NB: NIB/XIB files still exist even on Storyboard projects, so we want this... 30 | 31 | *~.nib 32 | 33 | 34 | #### 35 | # Xcode build files - 36 | # 37 | # NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "DerivedData" 38 | 39 | DerivedData/ 40 | 41 | # NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "build" 42 | 43 | build/ 44 | 45 | 46 | ##### 47 | # Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups) 48 | # 49 | # This is complicated: 50 | # 51 | # SOMETIMES you need to put this file in version control. 52 | # Apple designed it poorly - if you use "custom executables", they are 53 | # saved in this file. 54 | # 99% of projects do NOT use those, so they do NOT want to version control this file. 55 | # ..but if you're in the 1%, comment out the line "*.pbxuser" 56 | 57 | *.pbxuser 58 | *.mode1v3 59 | *.mode2v3 60 | *.perspectivev3 61 | # NB: also, whitelist the default ones, some projects need to use these 62 | !default.pbxuser 63 | !default.mode1v3 64 | !default.mode2v3 65 | !default.perspectivev3 66 | 67 | 68 | #### 69 | # Xcode 4 - semi-personal settings 70 | # 71 | # 72 | # OPTION 1: --------------------------------- 73 | # throw away ALL personal settings (including custom schemes! 74 | # - unless they are "shared") 75 | # 76 | # NB: this is exclusive with OPTION 2 below 77 | xcuserdata 78 | 79 | # OPTION 2: --------------------------------- 80 | # get rid of ALL personal settings, but KEEP SOME OF THEM 81 | # - NB: you must manually uncomment the bits you want to keep 82 | # 83 | # NB: this is exclusive with OPTION 1 above 84 | # 85 | #xcuserdata/**/* 86 | 87 | # (requires option 2 above): Personal Schemes 88 | # 89 | #!xcuserdata/**/xcschemes/* 90 | 91 | #### 92 | # XCode 4 workspaces - more detailed 93 | # 94 | # Workspaces are important! They are a core feature of Xcode - don't exclude them :) 95 | # 96 | # Workspace layout is quite spammy. For reference: 97 | # 98 | # /(root)/ 99 | # /(project-name).xcodeproj/ 100 | # project.pbxproj 101 | # /project.xcworkspace/ 102 | # contents.xcworkspacedata 103 | # /xcuserdata/ 104 | # /(your name)/xcuserdatad/ 105 | # UserInterfaceState.xcuserstate 106 | # /xcsshareddata/ 107 | # /xcschemes/ 108 | # (shared scheme name).xcscheme 109 | # /xcuserdata/ 110 | # /(your name)/xcuserdatad/ 111 | # (private scheme).xcscheme 112 | # xcschememanagement.plist 113 | # 114 | # 115 | 116 | #### 117 | # Xcode 4 - Deprecated classes 118 | # 119 | # Allegedly, if you manually "deprecate" your classes, they get moved here. 120 | # 121 | # We're using source-control, so this is a "feature" that we do not want! 122 | 123 | *.moved-aside 124 | 125 | 126 | #### 127 | # UNKNOWN: recommended by others, but I can't discover what these files are 128 | # 129 | # ...none. Everything is now explained. 130 | 131 | # CocoaPods 132 | Pods -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tomahawk-ios 2 | Music is everywhere, now you don’t have to be. Tomahawk, the critically acclaimed multi-source music player, is now under-development (with your help) for iOS. Given the name of an artist, album or song Tomahawk will find the best available source and play it - whether that be from Spotify, Beats Music, Rdio, Deezer, GMusic, Grooveshark, Soundcloud, Official.fm, Jamendo, Beets, Ampache, Subsonic or your phone’s local storage. Tomahawk for iOS also syncs your history, your loved tracks, artists, albums and your playlists to/from the desktop version of Tomahawk via our new music community, Hatchet. On Hatchet you can hear your friends' favorite tracks and see what they're currently listening to. 3 | -------------------------------------------------------------------------------- /tomahawk-ios.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /tomahawk-ios.xcodeproj/project.xcworkspace/xcshareddata/tomahawk-ios.xccheckout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDESourceControlProjectFavoriteDictionaryKey 6 | 7 | IDESourceControlProjectIdentifier 8 | 569F514C-52CE-4CC5-A66F-699F20341131 9 | IDESourceControlProjectName 10 | tomahawk-ios 11 | IDESourceControlProjectOriginsDictionary 12 | 13 | EC526102DC61A47C5A4710AD9D7BD2C4F6783055 14 | https://github.com/IntergalacticInteractive/tomahawk-ios.git 15 | 16 | IDESourceControlProjectPath 17 | tomahawk-ios.xcodeproj 18 | IDESourceControlProjectRelativeInstallPathDictionary 19 | 20 | EC526102DC61A47C5A4710AD9D7BD2C4F6783055 21 | ../.. 22 | 23 | IDESourceControlProjectURL 24 | https://github.com/IntergalacticInteractive/tomahawk-ios.git 25 | IDESourceControlProjectVersion 26 | 111 27 | IDESourceControlProjectWCCIdentifier 28 | EC526102DC61A47C5A4710AD9D7BD2C4F6783055 29 | IDESourceControlProjectWCConfigurations 30 | 31 | 32 | IDESourceControlRepositoryExtensionIdentifierKey 33 | public.vcs.git 34 | IDESourceControlWCCIdentifierKey 35 | EC526102DC61A47C5A4710AD9D7BD2C4F6783055 36 | IDESourceControlWCCName 37 | tomahawk-ios 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /tomahawk-ios.xcodeproj/project.xcworkspace/xcuserdata/shawn.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomahawk-player/tomahawk-ios/b5349a85d9a09aa764c4f75a55b1d6f019433590/tomahawk-ios.xcodeproj/project.xcworkspace/xcuserdata/shawn.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /tomahawk-ios.xcodeproj/xcuserdata/shawn.xcuserdatad/xcschemes/tomahawk-ios.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 47 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 65 | 66 | 75 | 77 | 83 | 84 | 85 | 86 | 87 | 88 | 94 | 96 | 102 | 103 | 104 | 105 | 107 | 108 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /tomahawk-ios.xcodeproj/xcuserdata/shawn.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | tomahawk-ios.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 2941454F1AC3496A00CBD951 16 | 17 | primary 18 | 19 | 20 | 2941456B1AC3496B00CBD951 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /tomahawk-ios/AFHTTPRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperation.h 2 | // 3 | // Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import "AFURLConnectionOperation.h" 25 | 26 | /** 27 | `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. 28 | */ 29 | @interface AFHTTPRequestOperation : AFURLConnectionOperation 30 | 31 | ///------------------------------------------------ 32 | /// @name Getting HTTP URL Connection Information 33 | ///------------------------------------------------ 34 | 35 | /** 36 | The last HTTP response received by the operation's connection. 37 | */ 38 | @property (readonly, nonatomic, strong) NSHTTPURLResponse *response; 39 | 40 | /** 41 | 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. 42 | 43 | @warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value 44 | */ 45 | @property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; 46 | 47 | /** 48 | 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. 49 | */ 50 | @property (readonly, nonatomic, strong) id responseObject; 51 | 52 | ///----------------------------------------------------------- 53 | /// @name Setting Completion Block Success / Failure Callbacks 54 | ///----------------------------------------------------------- 55 | 56 | /** 57 | 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. 58 | 59 | This method should be overridden in subclasses in order to specify the response object passed into the success block. 60 | 61 | @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. 62 | @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. 63 | */ 64 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 65 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 66 | 67 | @end 68 | -------------------------------------------------------------------------------- /tomahawk-ios/AFHTTPRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperation.m 2 | // 3 | // Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFHTTPRequestOperation.h" 24 | 25 | static dispatch_queue_t http_request_operation_processing_queue() { 26 | static dispatch_queue_t af_http_request_operation_processing_queue; 27 | static dispatch_once_t onceToken; 28 | dispatch_once(&onceToken, ^{ 29 | af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT); 30 | }); 31 | 32 | return af_http_request_operation_processing_queue; 33 | } 34 | 35 | static dispatch_group_t http_request_operation_completion_group() { 36 | static dispatch_group_t af_http_request_operation_completion_group; 37 | static dispatch_once_t onceToken; 38 | dispatch_once(&onceToken, ^{ 39 | af_http_request_operation_completion_group = dispatch_group_create(); 40 | }); 41 | 42 | return af_http_request_operation_completion_group; 43 | } 44 | 45 | #pragma mark - 46 | 47 | @interface AFURLConnectionOperation () 48 | @property (readwrite, nonatomic, strong) NSURLRequest *request; 49 | @property (readwrite, nonatomic, strong) NSURLResponse *response; 50 | @end 51 | 52 | @interface AFHTTPRequestOperation () 53 | @property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; 54 | @property (readwrite, nonatomic, strong) id responseObject; 55 | @property (readwrite, nonatomic, strong) NSError *responseSerializationError; 56 | @property (readwrite, nonatomic, strong) NSRecursiveLock *lock; 57 | @end 58 | 59 | @implementation AFHTTPRequestOperation 60 | @dynamic response; 61 | @dynamic lock; 62 | 63 | - (instancetype)initWithRequest:(NSURLRequest *)urlRequest { 64 | self = [super initWithRequest:urlRequest]; 65 | if (!self) { 66 | return nil; 67 | } 68 | 69 | self.responseSerializer = [AFHTTPResponseSerializer serializer]; 70 | 71 | return self; 72 | } 73 | 74 | - (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { 75 | NSParameterAssert(responseSerializer); 76 | 77 | [self.lock lock]; 78 | _responseSerializer = responseSerializer; 79 | self.responseObject = nil; 80 | self.responseSerializationError = nil; 81 | [self.lock unlock]; 82 | } 83 | 84 | - (id)responseObject { 85 | [self.lock lock]; 86 | if (!_responseObject && [self isFinished] && !self.error) { 87 | NSError *error = nil; 88 | self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error]; 89 | if (error) { 90 | self.responseSerializationError = error; 91 | } 92 | } 93 | [self.lock unlock]; 94 | 95 | return _responseObject; 96 | } 97 | 98 | - (NSError *)error { 99 | if (_responseSerializationError) { 100 | return _responseSerializationError; 101 | } else { 102 | return [super error]; 103 | } 104 | } 105 | 106 | #pragma mark - AFHTTPRequestOperation 107 | 108 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 109 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 110 | { 111 | // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. 112 | #pragma clang diagnostic push 113 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 114 | #pragma clang diagnostic ignored "-Wgnu" 115 | self.completionBlock = ^{ 116 | if (self.completionGroup) { 117 | dispatch_group_enter(self.completionGroup); 118 | } 119 | 120 | dispatch_async(http_request_operation_processing_queue(), ^{ 121 | if (self.error) { 122 | if (failure) { 123 | dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ 124 | failure(self, self.error); 125 | }); 126 | } 127 | } else { 128 | id responseObject = self.responseObject; 129 | if (self.error) { 130 | if (failure) { 131 | dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ 132 | failure(self, self.error); 133 | }); 134 | } 135 | } else { 136 | if (success) { 137 | dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ 138 | success(self, responseObject); 139 | }); 140 | } 141 | } 142 | } 143 | 144 | if (self.completionGroup) { 145 | dispatch_group_leave(self.completionGroup); 146 | } 147 | }); 148 | }; 149 | #pragma clang diagnostic pop 150 | } 151 | 152 | #pragma mark - AFURLRequestOperation 153 | 154 | - (void)pause { 155 | [super pause]; 156 | 157 | u_int64_t offset = 0; 158 | if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { 159 | offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; 160 | } else { 161 | offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; 162 | } 163 | 164 | NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; 165 | if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) { 166 | [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; 167 | } 168 | [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; 169 | self.request = mutableURLRequest; 170 | } 171 | 172 | #pragma mark - NSSecureCoding 173 | 174 | + (BOOL)supportsSecureCoding { 175 | return YES; 176 | } 177 | 178 | - (id)initWithCoder:(NSCoder *)decoder { 179 | self = [super initWithCoder:decoder]; 180 | if (!self) { 181 | return nil; 182 | } 183 | 184 | self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; 185 | 186 | return self; 187 | } 188 | 189 | - (void)encodeWithCoder:(NSCoder *)coder { 190 | [super encodeWithCoder:coder]; 191 | 192 | [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; 193 | } 194 | 195 | #pragma mark - NSCopying 196 | 197 | - (id)copyWithZone:(NSZone *)zone { 198 | AFHTTPRequestOperation *operation = [super copyWithZone:zone]; 199 | 200 | operation.responseSerializer = [self.responseSerializer copyWithZone:zone]; 201 | operation.completionQueue = self.completionQueue; 202 | operation.completionGroup = self.completionGroup; 203 | 204 | return operation; 205 | } 206 | 207 | @end 208 | -------------------------------------------------------------------------------- /tomahawk-ios/AFNetworkReachabilityManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.h 2 | // 3 | // Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import 25 | 26 | #ifndef NS_DESIGNATED_INITIALIZER 27 | #if __has_attribute(objc_designated_initializer) 28 | #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) 29 | #else 30 | #define NS_DESIGNATED_INITIALIZER 31 | #endif 32 | #endif 33 | 34 | typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { 35 | AFNetworkReachabilityStatusUnknown = -1, 36 | AFNetworkReachabilityStatusNotReachable = 0, 37 | AFNetworkReachabilityStatusReachableViaWWAN = 1, 38 | AFNetworkReachabilityStatusReachableViaWiFi = 2, 39 | }; 40 | 41 | /** 42 | `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. 43 | 44 | 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. 45 | 46 | See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/) 47 | 48 | @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. 49 | */ 50 | @interface AFNetworkReachabilityManager : NSObject 51 | 52 | /** 53 | The current network reachability status. 54 | */ 55 | @property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 56 | 57 | /** 58 | Whether or not the network is currently reachable. 59 | */ 60 | @property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; 61 | 62 | /** 63 | Whether or not the network is currently reachable via WWAN. 64 | */ 65 | @property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; 66 | 67 | /** 68 | Whether or not the network is currently reachable via WiFi. 69 | */ 70 | @property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; 71 | 72 | ///--------------------- 73 | /// @name Initialization 74 | ///--------------------- 75 | 76 | /** 77 | Returns the shared network reachability manager. 78 | */ 79 | + (instancetype)sharedManager; 80 | 81 | /** 82 | Creates and returns a network reachability manager for the specified domain. 83 | 84 | @param domain The domain used to evaluate network reachability. 85 | 86 | @return An initialized network reachability manager, actively monitoring the specified domain. 87 | */ 88 | + (instancetype)managerForDomain:(NSString *)domain; 89 | 90 | /** 91 | Creates and returns a network reachability manager for the socket address. 92 | 93 | @param address The socket address (`sockaddr_in`) used to evaluate network reachability. 94 | 95 | @return An initialized network reachability manager, actively monitoring the specified socket address. 96 | */ 97 | + (instancetype)managerForAddress:(const void *)address; 98 | 99 | /** 100 | Initializes an instance of a network reachability manager from the specified reachability object. 101 | 102 | @param reachability The reachability object to monitor. 103 | 104 | @return An initialized network reachability manager, actively monitoring the specified reachability. 105 | */ 106 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; 107 | 108 | ///-------------------------------------------------- 109 | /// @name Starting & Stopping Reachability Monitoring 110 | ///-------------------------------------------------- 111 | 112 | /** 113 | Starts monitoring for changes in network reachability status. 114 | */ 115 | - (void)startMonitoring; 116 | 117 | /** 118 | Stops monitoring for changes in network reachability status. 119 | */ 120 | - (void)stopMonitoring; 121 | 122 | ///------------------------------------------------- 123 | /// @name Getting Localized Reachability Description 124 | ///------------------------------------------------- 125 | 126 | /** 127 | Returns a localized string representation of the current network reachability status. 128 | */ 129 | - (NSString *)localizedNetworkReachabilityStatusString; 130 | 131 | ///--------------------------------------------------- 132 | /// @name Setting Network Reachability Change Callback 133 | ///--------------------------------------------------- 134 | 135 | /** 136 | Sets a callback to be executed when the network availability of the `baseURL` host changes. 137 | 138 | @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`. 139 | */ 140 | - (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block; 141 | 142 | @end 143 | 144 | ///---------------- 145 | /// @name Constants 146 | ///---------------- 147 | 148 | /** 149 | ## Network Reachability 150 | 151 | The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. 152 | 153 | enum { 154 | AFNetworkReachabilityStatusUnknown, 155 | AFNetworkReachabilityStatusNotReachable, 156 | AFNetworkReachabilityStatusReachableViaWWAN, 157 | AFNetworkReachabilityStatusReachableViaWiFi, 158 | } 159 | 160 | `AFNetworkReachabilityStatusUnknown` 161 | The `baseURL` host reachability is not known. 162 | 163 | `AFNetworkReachabilityStatusNotReachable` 164 | The `baseURL` host cannot be reached. 165 | 166 | `AFNetworkReachabilityStatusReachableViaWWAN` 167 | The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. 168 | 169 | `AFNetworkReachabilityStatusReachableViaWiFi` 170 | The `baseURL` host can be reached via a Wi-Fi connection. 171 | 172 | ### Keys for Notification UserInfo Dictionary 173 | 174 | Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. 175 | 176 | `AFNetworkingReachabilityNotificationStatusItem` 177 | A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. 178 | The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. 179 | */ 180 | 181 | ///-------------------- 182 | /// @name Notifications 183 | ///-------------------- 184 | 185 | /** 186 | Posted when network reachability changes. 187 | 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. 188 | 189 | @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). 190 | */ 191 | extern NSString * const AFNetworkingReachabilityDidChangeNotification; 192 | extern NSString * const AFNetworkingReachabilityNotificationStatusItem; 193 | 194 | ///-------------------- 195 | /// @name Functions 196 | ///-------------------- 197 | 198 | /** 199 | Returns a localized string representation of an `AFNetworkReachabilityStatus` value. 200 | */ 201 | extern NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); 202 | -------------------------------------------------------------------------------- /tomahawk-ios/AFNetworkReachabilityManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.m 2 | // 3 | // Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFNetworkReachabilityManager.h" 24 | 25 | #import 26 | #import 27 | #import 28 | #import 29 | #import 30 | 31 | NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; 32 | NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; 33 | 34 | typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); 35 | 36 | NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { 37 | switch (status) { 38 | case AFNetworkReachabilityStatusNotReachable: 39 | return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); 40 | case AFNetworkReachabilityStatusReachableViaWWAN: 41 | return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); 42 | case AFNetworkReachabilityStatusReachableViaWiFi: 43 | return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); 44 | case AFNetworkReachabilityStatusUnknown: 45 | default: 46 | return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); 47 | } 48 | } 49 | 50 | static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { 51 | BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); 52 | BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); 53 | BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); 54 | BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); 55 | BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); 56 | 57 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; 58 | if (isNetworkReachable == NO) { 59 | status = AFNetworkReachabilityStatusNotReachable; 60 | } 61 | #if TARGET_OS_IPHONE 62 | else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { 63 | status = AFNetworkReachabilityStatusReachableViaWWAN; 64 | } 65 | #endif 66 | else { 67 | status = AFNetworkReachabilityStatusReachableViaWiFi; 68 | } 69 | 70 | return status; 71 | } 72 | 73 | static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { 74 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); 75 | AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info; 76 | if (block) { 77 | block(status); 78 | } 79 | 80 | 81 | dispatch_async(dispatch_get_main_queue(), ^{ 82 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 83 | NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; 84 | [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; 85 | }); 86 | 87 | } 88 | 89 | static const void * AFNetworkReachabilityRetainCallback(const void *info) { 90 | return Block_copy(info); 91 | } 92 | 93 | static void AFNetworkReachabilityReleaseCallback(const void *info) { 94 | if (info) { 95 | Block_release(info); 96 | } 97 | } 98 | 99 | @interface AFNetworkReachabilityManager () 100 | @property (readwrite, nonatomic, assign) SCNetworkReachabilityRef networkReachability; 101 | @property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 102 | @property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; 103 | @end 104 | 105 | @implementation AFNetworkReachabilityManager 106 | 107 | + (instancetype)sharedManager { 108 | static AFNetworkReachabilityManager *_sharedManager = nil; 109 | static dispatch_once_t onceToken; 110 | dispatch_once(&onceToken, ^{ 111 | struct sockaddr_in address; 112 | bzero(&address, sizeof(address)); 113 | address.sin_len = sizeof(address); 114 | address.sin_family = AF_INET; 115 | 116 | _sharedManager = [self managerForAddress:&address]; 117 | }); 118 | 119 | return _sharedManager; 120 | } 121 | 122 | + (instancetype)managerForDomain:(NSString *)domain { 123 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); 124 | 125 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 126 | 127 | return manager; 128 | } 129 | 130 | + (instancetype)managerForAddress:(const void *)address { 131 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); 132 | 133 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 134 | 135 | return manager; 136 | } 137 | 138 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { 139 | self = [super init]; 140 | if (!self) { 141 | return nil; 142 | } 143 | 144 | self.networkReachability = reachability; 145 | self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; 146 | 147 | return self; 148 | } 149 | 150 | - (void)dealloc { 151 | [self stopMonitoring]; 152 | 153 | if (_networkReachability) { 154 | CFRelease(_networkReachability); 155 | _networkReachability = NULL; 156 | } 157 | } 158 | 159 | #pragma mark - 160 | 161 | - (BOOL)isReachable { 162 | return [self isReachableViaWWAN] || [self isReachableViaWiFi]; 163 | } 164 | 165 | - (BOOL)isReachableViaWWAN { 166 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; 167 | } 168 | 169 | - (BOOL)isReachableViaWiFi { 170 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; 171 | } 172 | 173 | #pragma mark - 174 | 175 | - (void)startMonitoring { 176 | [self stopMonitoring]; 177 | 178 | if (!self.networkReachability) { 179 | return; 180 | } 181 | 182 | __weak __typeof(self)weakSelf = self; 183 | AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { 184 | __strong __typeof(weakSelf)strongSelf = weakSelf; 185 | 186 | strongSelf.networkReachabilityStatus = status; 187 | if (strongSelf.networkReachabilityStatusBlock) { 188 | strongSelf.networkReachabilityStatusBlock(status); 189 | } 190 | 191 | }; 192 | 193 | SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; 194 | SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); 195 | SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 196 | 197 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ 198 | SCNetworkReachabilityFlags flags; 199 | SCNetworkReachabilityGetFlags(self.networkReachability, &flags); 200 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); 201 | dispatch_async(dispatch_get_main_queue(), ^{ 202 | callback(status); 203 | 204 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 205 | NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; 206 | [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; 207 | }); 208 | }); 209 | } 210 | 211 | - (void)stopMonitoring { 212 | if (!self.networkReachability) { 213 | return; 214 | } 215 | 216 | SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 217 | } 218 | 219 | #pragma mark - 220 | 221 | - (NSString *)localizedNetworkReachabilityStatusString { 222 | return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); 223 | } 224 | 225 | #pragma mark - 226 | 227 | - (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { 228 | self.networkReachabilityStatusBlock = block; 229 | } 230 | 231 | #pragma mark - NSKeyValueObserving 232 | 233 | + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { 234 | if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { 235 | return [NSSet setWithObject:@"networkReachabilityStatus"]; 236 | } 237 | 238 | return [super keyPathsForValuesAffectingValueForKey:key]; 239 | } 240 | 241 | @end 242 | -------------------------------------------------------------------------------- /tomahawk-ios/AFNetworking.h: -------------------------------------------------------------------------------- 1 | // AFNetworking.h 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import 25 | 26 | #ifndef _AFNETWORKING_ 27 | #define _AFNETWORKING_ 28 | 29 | #import "AFURLRequestSerialization.h" 30 | #import "AFURLResponseSerialization.h" 31 | #import "AFSecurityPolicy.h" 32 | #import "AFNetworkReachabilityManager.h" 33 | 34 | #import "AFURLConnectionOperation.h" 35 | #import "AFHTTPRequestOperation.h" 36 | #import "AFHTTPRequestOperationManager.h" 37 | 38 | #if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \ 39 | ( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) ) 40 | #import "AFURLSessionManager.h" 41 | #import "AFHTTPSessionManager.h" 42 | #endif 43 | 44 | #endif /* _AFNETWORKING_ */ 45 | -------------------------------------------------------------------------------- /tomahawk-ios/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.h 2 | // 3 | // Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import 25 | 26 | typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { 27 | AFSSLPinningModeNone, 28 | AFSSLPinningModePublicKey, 29 | AFSSLPinningModeCertificate, 30 | }; 31 | 32 | /** 33 | `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. 34 | 35 | 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. 36 | */ 37 | @interface AFSecurityPolicy : NSObject 38 | 39 | /** 40 | The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. 41 | */ 42 | @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 43 | 44 | /** 45 | Whether to evaluate an entire SSL certificate chain, or just the leaf certificate. Defaults to `YES`. 46 | */ 47 | @property (nonatomic, assign) BOOL validatesCertificateChain; 48 | 49 | /** 50 | 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. 51 | */ 52 | @property (nonatomic, strong) NSArray *pinnedCertificates; 53 | 54 | /** 55 | Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. 56 | */ 57 | @property (nonatomic, assign) BOOL allowInvalidCertificates; 58 | 59 | /** 60 | Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES` for `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate`, otherwise `NO`. 61 | */ 62 | @property (nonatomic, assign) BOOL validatesDomainName; 63 | 64 | ///----------------------------------------- 65 | /// @name Getting Specific Security Policies 66 | ///----------------------------------------- 67 | 68 | /** 69 | Returns the shared default security policy, which does not allow invalid certificates, does not validate domain name, and does not validate against pinned certificates or public keys. 70 | 71 | @return The default security policy. 72 | */ 73 | + (instancetype)defaultPolicy; 74 | 75 | ///--------------------- 76 | /// @name Initialization 77 | ///--------------------- 78 | 79 | /** 80 | Creates and returns a security policy with the specified pinning mode. 81 | 82 | @param pinningMode The SSL pinning mode. 83 | 84 | @return A new security policy. 85 | */ 86 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; 87 | 88 | ///------------------------------ 89 | /// @name Evaluating Server Trust 90 | ///------------------------------ 91 | 92 | /** 93 | Whether or not the specified server trust should be accepted, based on the security policy. 94 | 95 | This method should be used when responding to an authentication challenge from a server. 96 | 97 | @param serverTrust The X.509 certificate trust of the server. 98 | 99 | @return Whether or not to trust the server. 100 | 101 | @warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`. 102 | */ 103 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE; 104 | 105 | /** 106 | Whether or not the specified server trust should be accepted, based on the security policy. 107 | 108 | This method should be used when responding to an authentication challenge from a server. 109 | 110 | @param serverTrust The X.509 certificate trust of the server. 111 | @param domain The domain of serverTrust. If `nil`, the domain will not be validated. 112 | 113 | @return Whether or not to trust the server. 114 | */ 115 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 116 | forDomain:(NSString *)domain; 117 | 118 | @end 119 | 120 | ///---------------- 121 | /// @name Constants 122 | ///---------------- 123 | 124 | /** 125 | ## SSL Pinning Modes 126 | 127 | The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. 128 | 129 | enum { 130 | AFSSLPinningModeNone, 131 | AFSSLPinningModePublicKey, 132 | AFSSLPinningModeCertificate, 133 | } 134 | 135 | `AFSSLPinningModeNone` 136 | Do not used pinned certificates to validate servers. 137 | 138 | `AFSSLPinningModePublicKey` 139 | Validate host certificates against public keys of pinned certificates. 140 | 141 | `AFSSLPinningModeCertificate` 142 | Validate host certificates against pinned certificates. 143 | */ 144 | -------------------------------------------------------------------------------- /tomahawk-ios/AFSecurityPolicy.m: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.m 2 | // 3 | // Copyright (c) 2013-2015 AFNetworking (http://afnetworking.com) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFSecurityPolicy.h" 24 | 25 | #import 26 | 27 | #if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 28 | static NSData * AFSecKeyGetData(SecKeyRef key) { 29 | CFDataRef data = NULL; 30 | 31 | __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); 32 | 33 | return (__bridge_transfer NSData *)data; 34 | 35 | _out: 36 | if (data) { 37 | CFRelease(data); 38 | } 39 | 40 | return nil; 41 | } 42 | #endif 43 | 44 | static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { 45 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 46 | return [(__bridge id)key1 isEqual:(__bridge id)key2]; 47 | #else 48 | return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; 49 | #endif 50 | } 51 | 52 | static id AFPublicKeyForCertificate(NSData *certificate) { 53 | id allowedPublicKey = nil; 54 | SecCertificateRef allowedCertificate; 55 | SecCertificateRef allowedCertificates[1]; 56 | CFArrayRef tempCertificates = nil; 57 | SecPolicyRef policy = nil; 58 | SecTrustRef allowedTrust = nil; 59 | SecTrustResultType result; 60 | 61 | allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); 62 | __Require_Quiet(allowedCertificate != NULL, _out); 63 | 64 | allowedCertificates[0] = allowedCertificate; 65 | tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); 66 | 67 | policy = SecPolicyCreateBasicX509(); 68 | __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); 69 | __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); 70 | 71 | allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); 72 | 73 | _out: 74 | if (allowedTrust) { 75 | CFRelease(allowedTrust); 76 | } 77 | 78 | if (policy) { 79 | CFRelease(policy); 80 | } 81 | 82 | if (tempCertificates) { 83 | CFRelease(tempCertificates); 84 | } 85 | 86 | if (allowedCertificate) { 87 | CFRelease(allowedCertificate); 88 | } 89 | 90 | return allowedPublicKey; 91 | } 92 | 93 | static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { 94 | BOOL isValid = NO; 95 | SecTrustResultType result; 96 | __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); 97 | 98 | isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); 99 | 100 | _out: 101 | return isValid; 102 | } 103 | 104 | static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { 105 | CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); 106 | NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; 107 | 108 | for (CFIndex i = 0; i < certificateCount; i++) { 109 | SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); 110 | [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; 111 | } 112 | 113 | return [NSArray arrayWithArray:trustChain]; 114 | } 115 | 116 | static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { 117 | SecPolicyRef policy = SecPolicyCreateBasicX509(); 118 | CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); 119 | NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; 120 | for (CFIndex i = 0; i < certificateCount; i++) { 121 | SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); 122 | 123 | SecCertificateRef someCertificates[] = {certificate}; 124 | CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); 125 | 126 | SecTrustRef trust; 127 | __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); 128 | 129 | SecTrustResultType result; 130 | __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); 131 | 132 | [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; 133 | 134 | _out: 135 | if (trust) { 136 | CFRelease(trust); 137 | } 138 | 139 | if (certificates) { 140 | CFRelease(certificates); 141 | } 142 | 143 | continue; 144 | } 145 | CFRelease(policy); 146 | 147 | return [NSArray arrayWithArray:trustChain]; 148 | } 149 | 150 | #pragma mark - 151 | 152 | @interface AFSecurityPolicy() 153 | @property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 154 | @property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys; 155 | @end 156 | 157 | @implementation AFSecurityPolicy 158 | 159 | + (NSArray *)defaultPinnedCertificates { 160 | static NSArray *_defaultPinnedCertificates = nil; 161 | static dispatch_once_t onceToken; 162 | dispatch_once(&onceToken, ^{ 163 | NSBundle *bundle = [NSBundle bundleForClass:[self class]]; 164 | NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; 165 | 166 | NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]]; 167 | for (NSString *path in paths) { 168 | NSData *certificateData = [NSData dataWithContentsOfFile:path]; 169 | [certificates addObject:certificateData]; 170 | } 171 | 172 | _defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates]; 173 | }); 174 | 175 | return _defaultPinnedCertificates; 176 | } 177 | 178 | + (instancetype)defaultPolicy { 179 | AFSecurityPolicy *securityPolicy = [[self alloc] init]; 180 | securityPolicy.SSLPinningMode = AFSSLPinningModeNone; 181 | 182 | return securityPolicy; 183 | } 184 | 185 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { 186 | AFSecurityPolicy *securityPolicy = [[self alloc] init]; 187 | securityPolicy.SSLPinningMode = pinningMode; 188 | 189 | [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]]; 190 | 191 | return securityPolicy; 192 | } 193 | 194 | - (id)init { 195 | self = [super init]; 196 | if (!self) { 197 | return nil; 198 | } 199 | 200 | self.validatesCertificateChain = YES; 201 | 202 | return self; 203 | } 204 | 205 | #pragma mark - 206 | 207 | - (void)setSSLPinningMode:(AFSSLPinningMode)SSLPinningMode { 208 | _SSLPinningMode = SSLPinningMode; 209 | 210 | switch (self.SSLPinningMode) { 211 | case AFSSLPinningModePublicKey: 212 | case AFSSLPinningModeCertificate: 213 | self.validatesDomainName = YES; 214 | break; 215 | default: 216 | self.validatesDomainName = NO; 217 | break; 218 | } 219 | } 220 | 221 | - (void)setPinnedCertificates:(NSArray *)pinnedCertificates { 222 | _pinnedCertificates = pinnedCertificates; 223 | 224 | if (self.pinnedCertificates) { 225 | NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]]; 226 | for (NSData *certificate in self.pinnedCertificates) { 227 | id publicKey = AFPublicKeyForCertificate(certificate); 228 | if (!publicKey) { 229 | continue; 230 | } 231 | [mutablePinnedPublicKeys addObject:publicKey]; 232 | } 233 | self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys]; 234 | } else { 235 | self.pinnedPublicKeys = nil; 236 | } 237 | } 238 | 239 | #pragma mark - 240 | 241 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust { 242 | return [self evaluateServerTrust:serverTrust forDomain:nil]; 243 | } 244 | 245 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 246 | forDomain:(NSString *)domain 247 | { 248 | NSMutableArray *policies = [NSMutableArray array]; 249 | if (self.validatesDomainName) { 250 | [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; 251 | } else { 252 | [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; 253 | } 254 | 255 | SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); 256 | 257 | if (self.SSLPinningMode != AFSSLPinningModeNone && !AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { 258 | return NO; 259 | } 260 | 261 | NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); 262 | switch (self.SSLPinningMode) { 263 | case AFSSLPinningModeNone: 264 | return YES; 265 | case AFSSLPinningModeCertificate: { 266 | NSMutableArray *pinnedCertificates = [NSMutableArray array]; 267 | for (NSData *certificateData in self.pinnedCertificates) { 268 | [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; 269 | } 270 | SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); 271 | 272 | if (!AFServerTrustIsValid(serverTrust)) { 273 | return NO; 274 | } 275 | 276 | if (!self.validatesCertificateChain) { 277 | return YES; 278 | } 279 | 280 | NSUInteger trustedCertificateCount = 0; 281 | for (NSData *trustChainCertificate in serverCertificates) { 282 | if ([self.pinnedCertificates containsObject:trustChainCertificate]) { 283 | trustedCertificateCount++; 284 | } 285 | } 286 | 287 | return trustedCertificateCount == [serverCertificates count]; 288 | } 289 | case AFSSLPinningModePublicKey: { 290 | NSUInteger trustedPublicKeyCount = 0; 291 | NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); 292 | if (!self.validatesCertificateChain && [publicKeys count] > 0) { 293 | publicKeys = @[[publicKeys firstObject]]; 294 | } 295 | 296 | for (id trustChainPublicKey in publicKeys) { 297 | for (id pinnedPublicKey in self.pinnedPublicKeys) { 298 | if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { 299 | trustedPublicKeyCount += 1; 300 | } 301 | } 302 | } 303 | 304 | return trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1)); 305 | } 306 | } 307 | 308 | return NO; 309 | } 310 | 311 | #pragma mark - NSKeyValueObserving 312 | 313 | + (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { 314 | return [NSSet setWithObject:@"pinnedCertificates"]; 315 | } 316 | 317 | @end 318 | -------------------------------------------------------------------------------- /tomahawk-ios/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // tomahawk-ios 4 | // 5 | // Created by Shawn Bernard on 3/25/15. 6 | // Copyright (c) 2015 Tomahawk. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @interface AppDelegate : UIResponder 13 | 14 | @property (strong, nonatomic) UIWindow *window; 15 | 16 | @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; 17 | @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; 18 | @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; 19 | 20 | - (void)saveContext; 21 | - (NSURL *)applicationDocumentsDirectory; 22 | 23 | 24 | @end 25 | 26 | -------------------------------------------------------------------------------- /tomahawk-ios/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // tomahawk-ios 4 | // 5 | // Created by Shawn Bernard on 3/25/15. 6 | // Copyright (c) 2015 Tomahawk. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | // Override point for customization after application launch. 20 | return YES; 21 | } 22 | 23 | - (void)applicationWillResignActive:(UIApplication *)application { 24 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 25 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 26 | } 27 | 28 | - (void)applicationDidEnterBackground:(UIApplication *)application { 29 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 30 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 31 | } 32 | 33 | - (void)applicationWillEnterForeground:(UIApplication *)application { 34 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 35 | } 36 | 37 | - (void)applicationDidBecomeActive:(UIApplication *)application { 38 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 39 | } 40 | 41 | - (void)applicationWillTerminate:(UIApplication *)application { 42 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 43 | // Saves changes in the application's managed object context before the application terminates. 44 | [self saveContext]; 45 | } 46 | 47 | #pragma mark - Core Data stack 48 | 49 | @synthesize managedObjectContext = _managedObjectContext; 50 | @synthesize managedObjectModel = _managedObjectModel; 51 | @synthesize persistentStoreCoordinator = _persistentStoreCoordinator; 52 | 53 | - (NSURL *)applicationDocumentsDirectory { 54 | // The directory the application uses to store the Core Data store file. This code uses a directory named "com.tomahawk.tomahawk_ios" in the application's documents directory. 55 | return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 56 | } 57 | 58 | - (NSManagedObjectModel *)managedObjectModel { 59 | // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. 60 | if (_managedObjectModel != nil) { 61 | return _managedObjectModel; 62 | } 63 | NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"tomahawk_ios" withExtension:@"momd"]; 64 | _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 65 | return _managedObjectModel; 66 | } 67 | 68 | - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 69 | // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. 70 | if (_persistentStoreCoordinator != nil) { 71 | return _persistentStoreCoordinator; 72 | } 73 | 74 | // Create the coordinator and store 75 | 76 | _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 77 | NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"tomahawk_ios.sqlite"]; 78 | NSError *error = nil; 79 | NSString *failureReason = @"There was an error creating or loading the application's saved data."; 80 | if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 81 | // Report any error we got. 82 | NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 83 | dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data"; 84 | dict[NSLocalizedFailureReasonErrorKey] = failureReason; 85 | dict[NSUnderlyingErrorKey] = error; 86 | error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict]; 87 | // Replace this with code to handle the error appropriately. 88 | // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 89 | NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 90 | abort(); 91 | } 92 | 93 | return _persistentStoreCoordinator; 94 | } 95 | 96 | 97 | - (NSManagedObjectContext *)managedObjectContext { 98 | // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) 99 | if (_managedObjectContext != nil) { 100 | return _managedObjectContext; 101 | } 102 | 103 | NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 104 | if (!coordinator) { 105 | return nil; 106 | } 107 | _managedObjectContext = [[NSManagedObjectContext alloc] init]; 108 | [_managedObjectContext setPersistentStoreCoordinator:coordinator]; 109 | return _managedObjectContext; 110 | } 111 | 112 | #pragma mark - Core Data Saving support 113 | 114 | - (void)saveContext { 115 | NSManagedObjectContext *managedObjectContext = self.managedObjectContext; 116 | if (managedObjectContext != nil) { 117 | NSError *error = nil; 118 | if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 119 | // Replace this implementation with code to handle the error appropriately. 120 | // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 121 | NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 122 | abort(); 123 | } 124 | } 125 | } 126 | 127 | @end 128 | -------------------------------------------------------------------------------- /tomahawk-ios/Base.lproj/LaunchScreen.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 20 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /tomahawk-ios/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /tomahawk-ios/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /tomahawk-ios/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | com.tomahawk.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 0.1 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIMainStoryboardFile 28 | Main 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /tomahawk-ios/MKAnnotationView+WebCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // MKAnnotationView+WebCache.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 14/03/12. 6 | // Copyright (c) 2012 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "MapKit/MapKit.h" 10 | #import "SDWebImageManager.h" 11 | 12 | /** 13 | * Integrates SDWebImage async downloading and caching of remote images with MKAnnotationView. 14 | */ 15 | @interface MKAnnotationView (WebCache) 16 | 17 | /** 18 | * Get the current image URL. 19 | * 20 | * Note that because of the limitations of categories this property can get out of sync 21 | * if you use sd_setImage: directly. 22 | */ 23 | - (NSURL *)sd_imageURL; 24 | 25 | /** 26 | * Set the imageView `image` with an `url`. 27 | * 28 | * The download is asynchronous and cached. 29 | * 30 | * @param url The url for the image. 31 | */ 32 | - (void)sd_setImageWithURL:(NSURL *)url; 33 | 34 | /** 35 | * Set the imageView `image` with an `url` and a placeholder. 36 | * 37 | * The download is asynchronous and cached. 38 | * 39 | * @param url The url for the image. 40 | * @param placeholder The image to be set initially, until the image request finishes. 41 | * @see sd_setImageWithURL:placeholderImage:options: 42 | */ 43 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; 44 | 45 | /** 46 | * Set the imageView `image` with an `url`, placeholder and custom options. 47 | * 48 | * The download is asynchronous and cached. 49 | * 50 | * @param url The url for the image. 51 | * @param placeholder The image to be set initially, until the image request finishes. 52 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 53 | */ 54 | 55 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; 56 | 57 | /** 58 | * Set the imageView `image` with an `url`. 59 | * 60 | * The download is asynchronous and cached. 61 | * 62 | * @param url The url for the image. 63 | * @param completedBlock A block called when operation has been completed. This block has no return value 64 | * and takes the requested UIImage as first parameter. In case of error the image parameter 65 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 66 | * indicating if the image was retrived from the local cache or from the network. 67 | * The fourth parameter is the original image url. 68 | */ 69 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; 70 | 71 | /** 72 | * Set the imageView `image` with an `url`, placeholder. 73 | * 74 | * The download is asynchronous and cached. 75 | * 76 | * @param url The url for the image. 77 | * @param placeholder The image to be set initially, until the image request finishes. 78 | * @param completedBlock A block called when operation has been completed. This block has no return value 79 | * and takes the requested UIImage as first parameter. In case of error the image parameter 80 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 81 | * indicating if the image was retrived from the local cache or from the network. 82 | * The fourth parameter is the original image url. 83 | */ 84 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; 85 | 86 | /** 87 | * Set the imageView `image` with an `url`, placeholder and custom options. 88 | * 89 | * The download is asynchronous and cached. 90 | * 91 | * @param url The url for the image. 92 | * @param placeholder The image to be set initially, until the image request finishes. 93 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 94 | * @param completedBlock A block called when operation has been completed. This block has no return value 95 | * and takes the requested UIImage as first parameter. In case of error the image parameter 96 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 97 | * indicating if the image was retrived from the local cache or from the network. 98 | * The fourth parameter is the original image url. 99 | */ 100 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 101 | 102 | /** 103 | * Cancel the current download 104 | */ 105 | - (void)sd_cancelCurrentImageLoad; 106 | 107 | @end 108 | 109 | 110 | @interface MKAnnotationView (WebCacheDeprecated) 111 | 112 | - (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`"); 113 | 114 | - (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`"); 115 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`"); 116 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:`"); 117 | 118 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`"); 119 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`"); 120 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`"); 121 | 122 | - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`"); 123 | 124 | @end 125 | -------------------------------------------------------------------------------- /tomahawk-ios/MKAnnotationView+WebCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // MKAnnotationView+WebCache.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 14/03/12. 6 | // Copyright (c) 2012 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "MKAnnotationView+WebCache.h" 10 | #import "objc/runtime.h" 11 | #import "UIView+WebCacheOperation.h" 12 | 13 | static char imageURLKey; 14 | 15 | @implementation MKAnnotationView (WebCache) 16 | 17 | - (NSURL *)sd_imageURL { 18 | return objc_getAssociatedObject(self, &imageURLKey); 19 | } 20 | 21 | - (void)sd_setImageWithURL:(NSURL *)url { 22 | [self sd_setImageWithURL:url placeholderImage:nil options:0 completed:nil]; 23 | } 24 | 25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 completed:nil]; 27 | } 28 | 29 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 30 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options completed:nil]; 31 | } 32 | 33 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 34 | [self sd_setImageWithURL:url placeholderImage:nil options:0 completed:completedBlock]; 35 | } 36 | 37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 completed:completedBlock]; 39 | } 40 | 41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 42 | [self sd_cancelCurrentImageLoad]; 43 | 44 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 45 | self.image = placeholder; 46 | 47 | if (url) { 48 | __weak __typeof(self)wself = self; 49 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 50 | if (!wself) return; 51 | dispatch_main_sync_safe(^{ 52 | __strong MKAnnotationView *sself = wself; 53 | if (!sself) return; 54 | if (image) { 55 | sself.image = image; 56 | } 57 | if (completedBlock && finished) { 58 | completedBlock(image, error, cacheType, url); 59 | } 60 | }); 61 | }]; 62 | [self sd_setImageLoadOperation:operation forKey:@"MKAnnotationViewImage"]; 63 | } else { 64 | dispatch_main_async_safe(^{ 65 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 66 | if (completedBlock) { 67 | completedBlock(nil, error, SDImageCacheTypeNone, url); 68 | } 69 | }); 70 | } 71 | } 72 | 73 | - (void)sd_cancelCurrentImageLoad { 74 | [self sd_cancelImageLoadOperationWithKey:@"MKAnnotationViewImage"]; 75 | } 76 | 77 | @end 78 | 79 | 80 | @implementation MKAnnotationView (WebCacheDeprecated) 81 | 82 | - (NSURL *)imageURL { 83 | return [self sd_imageURL]; 84 | } 85 | 86 | - (void)setImageWithURL:(NSURL *)url { 87 | [self sd_setImageWithURL:url placeholderImage:nil options:0 completed:nil]; 88 | } 89 | 90 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 91 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 completed:nil]; 92 | } 93 | 94 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 95 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options completed:nil]; 96 | } 97 | 98 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { 99 | [self sd_setImageWithURL:url placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 100 | if (completedBlock) { 101 | completedBlock(image, error, cacheType); 102 | } 103 | }]; 104 | } 105 | 106 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { 107 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 108 | if (completedBlock) { 109 | completedBlock(image, error, cacheType); 110 | } 111 | }]; 112 | } 113 | 114 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 115 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 116 | if (completedBlock) { 117 | completedBlock(image, error, cacheType); 118 | } 119 | }]; 120 | } 121 | 122 | - (void)cancelCurrentImageLoad { 123 | [self sd_cancelCurrentImageLoad]; 124 | } 125 | 126 | @end 127 | -------------------------------------------------------------------------------- /tomahawk-ios/NSData+ImageContentType.h: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Fabrice Aneche on 06/01/14. 3 | // Copyright (c) 2014 Dailymotion. All rights reserved. 4 | // 5 | 6 | #import 7 | 8 | @interface NSData (ImageContentType) 9 | 10 | /** 11 | * Compute the content type for an image data 12 | * 13 | * @param data the input data 14 | * 15 | * @return the content type as string (i.e. image/jpeg, image/gif) 16 | */ 17 | + (NSString *)sd_contentTypeForImageData:(NSData *)data; 18 | 19 | @end 20 | 21 | 22 | @interface NSData (ImageContentTypeDeprecated) 23 | 24 | + (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`"); 25 | 26 | @end 27 | -------------------------------------------------------------------------------- /tomahawk-ios/NSData+ImageContentType.m: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Fabrice Aneche on 06/01/14. 3 | // Copyright (c) 2014 Dailymotion. All rights reserved. 4 | // 5 | 6 | #import "NSData+ImageContentType.h" 7 | 8 | 9 | @implementation NSData (ImageContentType) 10 | 11 | + (NSString *)sd_contentTypeForImageData:(NSData *)data { 12 | uint8_t c; 13 | [data getBytes:&c length:1]; 14 | switch (c) { 15 | case 0xFF: 16 | return @"image/jpeg"; 17 | case 0x89: 18 | return @"image/png"; 19 | case 0x47: 20 | return @"image/gif"; 21 | case 0x49: 22 | case 0x4D: 23 | return @"image/tiff"; 24 | case 0x52: 25 | // R as RIFF for WEBP 26 | if ([data length] < 12) { 27 | return nil; 28 | } 29 | 30 | NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; 31 | if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { 32 | return @"image/webp"; 33 | } 34 | 35 | return nil; 36 | } 37 | return nil; 38 | } 39 | 40 | @end 41 | 42 | 43 | @implementation NSData (ImageContentTypeDeprecated) 44 | 45 | + (NSString *)contentTypeForImageData:(NSData *)data { 46 | return [self sd_contentTypeForImageData:data]; 47 | } 48 | 49 | @end 50 | -------------------------------------------------------------------------------- /tomahawk-ios/SDImageCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | 12 | typedef NS_ENUM(NSInteger, SDImageCacheType) { 13 | /** 14 | * The image wasn't available the SDWebImage caches, but was downloaded from the web. 15 | */ 16 | SDImageCacheTypeNone, 17 | /** 18 | * The image was obtained from the disk cache. 19 | */ 20 | SDImageCacheTypeDisk, 21 | /** 22 | * The image was obtained from the memory cache. 23 | */ 24 | SDImageCacheTypeMemory 25 | }; 26 | 27 | typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); 28 | 29 | typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); 30 | 31 | typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); 32 | 33 | /** 34 | * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed 35 | * asynchronous so it doesn’t add unnecessary latency to the UI. 36 | */ 37 | @interface SDImageCache : NSObject 38 | 39 | /** 40 | * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory. 41 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. 42 | */ 43 | @property (assign, nonatomic) BOOL shouldDecompressImages; 44 | 45 | /** 46 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. 47 | */ 48 | @property (assign, nonatomic) NSUInteger maxMemoryCost; 49 | 50 | /** 51 | * The maximum length of time to keep an image in the cache, in seconds 52 | */ 53 | @property (assign, nonatomic) NSInteger maxCacheAge; 54 | 55 | /** 56 | * The maximum size of the cache, in bytes. 57 | */ 58 | @property (assign, nonatomic) NSUInteger maxCacheSize; 59 | 60 | /** 61 | * Returns global shared cache instance 62 | * 63 | * @return SDImageCache global instance 64 | */ 65 | + (SDImageCache *)sharedImageCache; 66 | 67 | /** 68 | * Init a new cache store with a specific namespace 69 | * 70 | * @param ns The namespace to use for this cache store 71 | */ 72 | - (id)initWithNamespace:(NSString *)ns; 73 | 74 | -(NSString *)makeDiskCachePath:(NSString*)fullNamespace; 75 | 76 | /** 77 | * Add a read-only cache path to search for images pre-cached by SDImageCache 78 | * Useful if you want to bundle pre-loaded images with your app 79 | * 80 | * @param path The path to use for this read-only cache path 81 | */ 82 | - (void)addReadOnlyCachePath:(NSString *)path; 83 | 84 | /** 85 | * Store an image into memory and disk cache at the given key. 86 | * 87 | * @param image The image to store 88 | * @param key The unique image cache key, usually it's image absolute URL 89 | */ 90 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key; 91 | 92 | /** 93 | * Store an image into memory and optionally disk cache at the given key. 94 | * 95 | * @param image The image to store 96 | * @param key The unique image cache key, usually it's image absolute URL 97 | * @param toDisk Store the image to disk cache if YES 98 | */ 99 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; 100 | 101 | /** 102 | * Store an image into memory and optionally disk cache at the given key. 103 | * 104 | * @param image The image to store 105 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage 106 | * @param imageData The image data as returned by the server, this representation will be used for disk storage 107 | * instead of converting the given image object into a storable/compressed image format in order 108 | * to save quality and CPU 109 | * @param key The unique image cache key, usually it's image absolute URL 110 | * @param toDisk Store the image to disk cache if YES 111 | */ 112 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; 113 | 114 | /** 115 | * Query the disk cache asynchronously. 116 | * 117 | * @param key The unique key used to store the wanted image 118 | */ 119 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; 120 | 121 | /** 122 | * Query the memory cache synchronously. 123 | * 124 | * @param key The unique key used to store the wanted image 125 | */ 126 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; 127 | 128 | /** 129 | * Query the disk cache synchronously after checking the memory cache. 130 | * 131 | * @param key The unique key used to store the wanted image 132 | */ 133 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; 134 | 135 | /** 136 | * Remove the image from memory and disk cache synchronously 137 | * 138 | * @param key The unique image cache key 139 | */ 140 | - (void)removeImageForKey:(NSString *)key; 141 | 142 | 143 | /** 144 | * Remove the image from memory and disk cache synchronously 145 | * 146 | * @param key The unique image cache key 147 | * @param completion An block that should be executed after the image has been removed (optional) 148 | */ 149 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; 150 | 151 | /** 152 | * Remove the image from memory and optionally disk cache synchronously 153 | * 154 | * @param key The unique image cache key 155 | * @param fromDisk Also remove cache entry from disk if YES 156 | */ 157 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; 158 | 159 | /** 160 | * Remove the image from memory and optionally disk cache synchronously 161 | * 162 | * @param key The unique image cache key 163 | * @param fromDisk Also remove cache entry from disk if YES 164 | * @param completion An block that should be executed after the image has been removed (optional) 165 | */ 166 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; 167 | 168 | /** 169 | * Clear all memory cached images 170 | */ 171 | - (void)clearMemory; 172 | 173 | /** 174 | * Clear all disk cached images. Non-blocking method - returns immediately. 175 | * @param completion An block that should be executed after cache expiration completes (optional) 176 | */ 177 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; 178 | 179 | /** 180 | * Clear all disk cached images 181 | * @see clearDiskOnCompletion: 182 | */ 183 | - (void)clearDisk; 184 | 185 | /** 186 | * Remove all expired cached image from disk. Non-blocking method - returns immediately. 187 | * @param completionBlock An block that should be executed after cache expiration completes (optional) 188 | */ 189 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; 190 | 191 | /** 192 | * Remove all expired cached image from disk 193 | * @see cleanDiskWithCompletionBlock: 194 | */ 195 | - (void)cleanDisk; 196 | 197 | /** 198 | * Get the size used by the disk cache 199 | */ 200 | - (NSUInteger)getSize; 201 | 202 | /** 203 | * Get the number of images in the disk cache 204 | */ 205 | - (NSUInteger)getDiskCount; 206 | 207 | /** 208 | * Asynchronously calculate the disk cache's size. 209 | */ 210 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; 211 | 212 | /** 213 | * Async check if image exists in disk cache already (does not load the image) 214 | * 215 | * @param key the key describing the url 216 | * @param completionBlock the block to be executed when the check is done. 217 | * @note the completion block will be always executed on the main queue 218 | */ 219 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 220 | 221 | /** 222 | * Check if image exists in disk cache already (does not load the image) 223 | * 224 | * @param key the key describing the url 225 | * 226 | * @return YES if an image exists for the given key 227 | */ 228 | - (BOOL)diskImageExistsWithKey:(NSString *)key; 229 | 230 | /** 231 | * Get the cache path for a certain key (needs the cache path root folder) 232 | * 233 | * @param key the key (can be obtained from url using cacheKeyForURL) 234 | * @param path the cach path root folder 235 | * 236 | * @return the cache path 237 | */ 238 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; 239 | 240 | /** 241 | * Get the default cache path for a certain key 242 | * 243 | * @param key the key (can be obtained from url using cacheKeyForURL) 244 | * 245 | * @return the default cache path 246 | */ 247 | - (NSString *)defaultCachePathForKey:(NSString *)key; 248 | 249 | @end 250 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImageCompat.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) Jamie Pinkham 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import 11 | 12 | #ifdef __OBJC_GC__ 13 | #error SDWebImage does not support Objective-C Garbage Collection 14 | #endif 15 | 16 | #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 17 | #error SDWebImage doesn't support Deployement Target version < 5.0 18 | #endif 19 | 20 | #if !TARGET_OS_IPHONE 21 | #import 22 | #ifndef UIImage 23 | #define UIImage NSImage 24 | #endif 25 | #ifndef UIImageView 26 | #define UIImageView NSImageView 27 | #endif 28 | #else 29 | 30 | #import 31 | 32 | #endif 33 | 34 | #ifndef NS_ENUM 35 | #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type 36 | #endif 37 | 38 | #ifndef NS_OPTIONS 39 | #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type 40 | #endif 41 | 42 | #if OS_OBJECT_USE_OBJC 43 | #undef SDDispatchQueueRelease 44 | #undef SDDispatchQueueSetterSementics 45 | #define SDDispatchQueueRelease(q) 46 | #define SDDispatchQueueSetterSementics strong 47 | #else 48 | #undef SDDispatchQueueRelease 49 | #undef SDDispatchQueueSetterSementics 50 | #define SDDispatchQueueRelease(q) (dispatch_release(q)) 51 | #define SDDispatchQueueSetterSementics assign 52 | #endif 53 | 54 | extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); 55 | 56 | typedef void(^SDWebImageNoParamsBlock)(); 57 | 58 | extern NSString *const SDWebImageErrorDomain; 59 | 60 | #define dispatch_main_sync_safe(block)\ 61 | if ([NSThread isMainThread]) {\ 62 | block();\ 63 | } else {\ 64 | dispatch_sync(dispatch_get_main_queue(), block);\ 65 | } 66 | 67 | #define dispatch_main_async_safe(block)\ 68 | if ([NSThread isMainThread]) {\ 69 | block();\ 70 | } else {\ 71 | dispatch_async(dispatch_get_main_queue(), block);\ 72 | } 73 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImageCompat.m: -------------------------------------------------------------------------------- 1 | // 2 | // SDWebImageCompat.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 11/12/12. 6 | // Copyright (c) 2012 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if !__has_feature(objc_arc) 12 | #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag 13 | #endif 14 | 15 | inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) { 16 | if (!image) { 17 | return nil; 18 | } 19 | 20 | if ([image.images count] > 0) { 21 | NSMutableArray *scaledImages = [NSMutableArray array]; 22 | 23 | for (UIImage *tempImage in image.images) { 24 | [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; 25 | } 26 | 27 | return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; 28 | } 29 | else { 30 | if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { 31 | CGFloat scale = 1.0; 32 | if (key.length >= 8) { 33 | // Search @2x. or @3x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x./@3x. + 4 len ext) 34 | NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)]; 35 | if (range.location != NSNotFound) { 36 | scale = 2.0; 37 | } 38 | 39 | range = [key rangeOfString:@"@3x." options:0 range:NSMakeRange(key.length - 8, 5)]; 40 | if (range.location != NSNotFound) { 41 | scale = 3.0; 42 | } 43 | } 44 | 45 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; 46 | image = scaledImage; 47 | } 48 | return image; 49 | } 50 | } 51 | 52 | NSString *const SDWebImageErrorDomain = @"SDWebImageErrorDomain"; 53 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImageDecoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * Created by james on 9/28/11. 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | #import 12 | #import "SDWebImageCompat.h" 13 | 14 | @interface UIImage (ForceDecode) 15 | 16 | + (UIImage *)decodedImageWithImage:(UIImage *)image; 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImageDecoder.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * Created by james on 9/28/11. 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | #import "SDWebImageDecoder.h" 12 | 13 | @implementation UIImage (ForceDecode) 14 | 15 | + (UIImage *)decodedImageWithImage:(UIImage *)image { 16 | if (image.images) { 17 | // Do not decode animated images 18 | return image; 19 | } 20 | 21 | CGImageRef imageRef = image.CGImage; 22 | CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); 23 | CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; 24 | 25 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 26 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); 27 | 28 | int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); 29 | BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || 30 | infoMask == kCGImageAlphaNoneSkipFirst || 31 | infoMask == kCGImageAlphaNoneSkipLast); 32 | 33 | // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. 34 | // https://developer.apple.com/library/mac/#qa/qa1037/_index.html 35 | if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { 36 | // Unset the old alpha info. 37 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 38 | 39 | // Set noneSkipFirst. 40 | bitmapInfo |= kCGImageAlphaNoneSkipFirst; 41 | } 42 | // Some PNGs tell us they have alpha but only 3 components. Odd. 43 | else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { 44 | // Unset the old alpha info. 45 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 46 | bitmapInfo |= kCGImageAlphaPremultipliedFirst; 47 | } 48 | 49 | // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. 50 | CGContextRef context = CGBitmapContextCreate(NULL, 51 | imageSize.width, 52 | imageSize.height, 53 | CGImageGetBitsPerComponent(imageRef), 54 | 0, 55 | colorSpace, 56 | bitmapInfo); 57 | CGColorSpaceRelease(colorSpace); 58 | 59 | // If failed, return undecompressed image 60 | if (!context) return image; 61 | 62 | CGContextDrawImage(context, imageRect, imageRef); 63 | CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); 64 | 65 | CGContextRelease(context); 66 | 67 | UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; 68 | CGImageRelease(decompressedImageRef); 69 | return decompressedImage; 70 | } 71 | 72 | @end 73 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImageDownloader.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { 14 | SDWebImageDownloaderLowPriority = 1 << 0, 15 | SDWebImageDownloaderProgressiveDownload = 1 << 1, 16 | 17 | /** 18 | * By default, request prevent the of NSURLCache. With this flag, NSURLCache 19 | * is used with default policies. 20 | */ 21 | SDWebImageDownloaderUseNSURLCache = 1 << 2, 22 | 23 | /** 24 | * Call completion block with nil image/imageData if the image was read from NSURLCache 25 | * (to be combined with `SDWebImageDownloaderUseNSURLCache`). 26 | */ 27 | 28 | SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, 29 | /** 30 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 31 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 32 | */ 33 | 34 | SDWebImageDownloaderContinueInBackground = 1 << 4, 35 | 36 | /** 37 | * Handles cookies stored in NSHTTPCookieStore by setting 38 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 39 | */ 40 | SDWebImageDownloaderHandleCookies = 1 << 5, 41 | 42 | /** 43 | * Enable to allow untrusted SSL ceriticates. 44 | * Useful for testing purposes. Use with caution in production. 45 | */ 46 | SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, 47 | 48 | /** 49 | * Put the image in the high priority queue. 50 | */ 51 | SDWebImageDownloaderHighPriority = 1 << 7, 52 | }; 53 | 54 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { 55 | /** 56 | * Default value. All download operations will execute in queue style (first-in-first-out). 57 | */ 58 | SDWebImageDownloaderFIFOExecutionOrder, 59 | 60 | /** 61 | * All download operations will execute in stack style (last-in-first-out). 62 | */ 63 | SDWebImageDownloaderLIFOExecutionOrder 64 | }; 65 | 66 | extern NSString *const SDWebImageDownloadStartNotification; 67 | extern NSString *const SDWebImageDownloadStopNotification; 68 | 69 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); 70 | 71 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); 72 | 73 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); 74 | 75 | /** 76 | * Asynchronous downloader dedicated and optimized for image loading. 77 | */ 78 | @interface SDWebImageDownloader : NSObject 79 | 80 | /** 81 | * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory. 82 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. 83 | */ 84 | @property (assign, nonatomic) BOOL shouldDecompressImages; 85 | 86 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads; 87 | 88 | /** 89 | * Shows the current amount of downloads that still need to be downloaded 90 | */ 91 | @property (readonly, nonatomic) NSUInteger currentDownloadCount; 92 | 93 | 94 | /** 95 | * The timeout value (in seconds) for the download operation. Default: 15.0. 96 | */ 97 | @property (assign, nonatomic) NSTimeInterval downloadTimeout; 98 | 99 | 100 | /** 101 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. 102 | */ 103 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; 104 | 105 | /** 106 | * Singleton method, returns the shared instance 107 | * 108 | * @return global shared instance of downloader class 109 | */ 110 | + (SDWebImageDownloader *)sharedDownloader; 111 | 112 | /** 113 | * Set username 114 | */ 115 | @property (strong, nonatomic) NSString *username; 116 | 117 | /** 118 | * Set password 119 | */ 120 | @property (strong, nonatomic) NSString *password; 121 | 122 | /** 123 | * Set filter to pick headers for downloading image HTTP request. 124 | * 125 | * This block will be invoked for each downloading image request, returned 126 | * NSDictionary will be used as headers in corresponding HTTP request. 127 | */ 128 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; 129 | 130 | /** 131 | * Set a value for a HTTP header to be appended to each download HTTP request. 132 | * 133 | * @param value The value for the header field. Use `nil` value to remove the header. 134 | * @param field The name of the header field to set. 135 | */ 136 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; 137 | 138 | /** 139 | * Returns the value of the specified HTTP header field. 140 | * 141 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field. 142 | */ 143 | - (NSString *)valueForHTTPHeaderField:(NSString *)field; 144 | 145 | /** 146 | * Sets a subclass of `SDWebImageDownloaderOperation` as the default 147 | * `NSOperation` to be used each time SDWebImage constructs a request 148 | * operation to download an image. 149 | * 150 | * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set 151 | * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. 152 | */ 153 | - (void)setOperationClass:(Class)operationClass; 154 | 155 | /** 156 | * Creates a SDWebImageDownloader async downloader instance with a given URL 157 | * 158 | * The delegate will be informed when the image is finish downloaded or an error has happen. 159 | * 160 | * @see SDWebImageDownloaderDelegate 161 | * 162 | * @param url The URL to the image to download 163 | * @param options The options to be used for this download 164 | * @param progressBlock A block called repeatedly while the image is downloading 165 | * @param completedBlock A block called once the download is completed. 166 | * If the download succeeded, the image parameter is set, in case of error, 167 | * error parameter is set with the error. The last parameter is always YES 168 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the 169 | * SDWebImageDownloaderProgressiveDownload option, this block is called 170 | * repeatedly with the partial image object and the finished argument set to NO 171 | * before to be called a last time with the full image and finished argument 172 | * set to YES. In case of error, the finished argument is always YES. 173 | * 174 | * @return A cancellable SDWebImageOperation 175 | */ 176 | - (id )downloadImageWithURL:(NSURL *)url 177 | options:(SDWebImageDownloaderOptions)options 178 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 179 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock; 180 | 181 | /** 182 | * Sets the download queue suspension state 183 | */ 184 | - (void)setSuspended:(BOOL)suspended; 185 | 186 | @end 187 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImageDownloader.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageDownloader.h" 10 | #import "SDWebImageDownloaderOperation.h" 11 | #import 12 | 13 | static NSString *const kProgressCallbackKey = @"progress"; 14 | static NSString *const kCompletedCallbackKey = @"completed"; 15 | 16 | @interface SDWebImageDownloader () 17 | 18 | @property (strong, nonatomic) NSOperationQueue *downloadQueue; 19 | @property (weak, nonatomic) NSOperation *lastAddedOperation; 20 | @property (assign, nonatomic) Class operationClass; 21 | @property (strong, nonatomic) NSMutableDictionary *URLCallbacks; 22 | @property (strong, nonatomic) NSMutableDictionary *HTTPHeaders; 23 | // This queue is used to serialize the handling of the network responses of all the download operation in a single queue 24 | @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue; 25 | 26 | @end 27 | 28 | @implementation SDWebImageDownloader 29 | 30 | + (void)initialize { 31 | // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) 32 | // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import 33 | if (NSClassFromString(@"SDNetworkActivityIndicator")) { 34 | 35 | #pragma clang diagnostic push 36 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 37 | id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; 38 | #pragma clang diagnostic pop 39 | 40 | // Remove observer in case it was previously added. 41 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; 42 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; 43 | 44 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator 45 | selector:NSSelectorFromString(@"startActivity") 46 | name:SDWebImageDownloadStartNotification object:nil]; 47 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator 48 | selector:NSSelectorFromString(@"stopActivity") 49 | name:SDWebImageDownloadStopNotification object:nil]; 50 | } 51 | } 52 | 53 | + (SDWebImageDownloader *)sharedDownloader { 54 | static dispatch_once_t once; 55 | static id instance; 56 | dispatch_once(&once, ^{ 57 | instance = [self new]; 58 | }); 59 | return instance; 60 | } 61 | 62 | - (id)init { 63 | if ((self = [super init])) { 64 | _operationClass = [SDWebImageDownloaderOperation class]; 65 | _shouldDecompressImages = YES; 66 | _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; 67 | _downloadQueue = [NSOperationQueue new]; 68 | _downloadQueue.maxConcurrentOperationCount = 6; 69 | _URLCallbacks = [NSMutableDictionary new]; 70 | _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"]; 71 | _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); 72 | _downloadTimeout = 15.0; 73 | } 74 | return self; 75 | } 76 | 77 | - (void)dealloc { 78 | [self.downloadQueue cancelAllOperations]; 79 | SDDispatchQueueRelease(_barrierQueue); 80 | } 81 | 82 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field { 83 | if (value) { 84 | self.HTTPHeaders[field] = value; 85 | } 86 | else { 87 | [self.HTTPHeaders removeObjectForKey:field]; 88 | } 89 | } 90 | 91 | - (NSString *)valueForHTTPHeaderField:(NSString *)field { 92 | return self.HTTPHeaders[field]; 93 | } 94 | 95 | - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { 96 | _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; 97 | } 98 | 99 | - (NSUInteger)currentDownloadCount { 100 | return _downloadQueue.operationCount; 101 | } 102 | 103 | - (NSInteger)maxConcurrentDownloads { 104 | return _downloadQueue.maxConcurrentOperationCount; 105 | } 106 | 107 | - (void)setOperationClass:(Class)operationClass { 108 | _operationClass = operationClass ?: [SDWebImageDownloaderOperation class]; 109 | } 110 | 111 | - (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock { 112 | __block SDWebImageDownloaderOperation *operation; 113 | __weak __typeof(self)wself = self; 114 | 115 | [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{ 116 | NSTimeInterval timeoutInterval = wself.downloadTimeout; 117 | if (timeoutInterval == 0.0) { 118 | timeoutInterval = 15.0; 119 | } 120 | 121 | // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise 122 | NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval]; 123 | request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); 124 | request.HTTPShouldUsePipelining = YES; 125 | if (wself.headersFilter) { 126 | request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]); 127 | } 128 | else { 129 | request.allHTTPHeaderFields = wself.HTTPHeaders; 130 | } 131 | operation = [[wself.operationClass alloc] initWithRequest:request 132 | options:options 133 | progress:^(NSInteger receivedSize, NSInteger expectedSize) { 134 | SDWebImageDownloader *sself = wself; 135 | if (!sself) return; 136 | __block NSArray *callbacksForURL; 137 | dispatch_sync(sself.barrierQueue, ^{ 138 | callbacksForURL = [sself.URLCallbacks[url] copy]; 139 | }); 140 | for (NSDictionary *callbacks in callbacksForURL) { 141 | SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey]; 142 | if (callback) callback(receivedSize, expectedSize); 143 | } 144 | } 145 | completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { 146 | SDWebImageDownloader *sself = wself; 147 | if (!sself) return; 148 | __block NSArray *callbacksForURL; 149 | dispatch_barrier_sync(sself.barrierQueue, ^{ 150 | callbacksForURL = [sself.URLCallbacks[url] copy]; 151 | if (finished) { 152 | [sself.URLCallbacks removeObjectForKey:url]; 153 | } 154 | }); 155 | for (NSDictionary *callbacks in callbacksForURL) { 156 | SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey]; 157 | if (callback) callback(image, data, error, finished); 158 | } 159 | } 160 | cancelled:^{ 161 | SDWebImageDownloader *sself = wself; 162 | if (!sself) return; 163 | dispatch_barrier_async(sself.barrierQueue, ^{ 164 | [sself.URLCallbacks removeObjectForKey:url]; 165 | }); 166 | }]; 167 | operation.shouldDecompressImages = wself.shouldDecompressImages; 168 | 169 | if (wself.username && wself.password) { 170 | operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession]; 171 | } 172 | 173 | if (options & SDWebImageDownloaderHighPriority) { 174 | operation.queuePriority = NSOperationQueuePriorityHigh; 175 | } else if (options & SDWebImageDownloaderLowPriority) { 176 | operation.queuePriority = NSOperationQueuePriorityLow; 177 | } 178 | 179 | [wself.downloadQueue addOperation:operation]; 180 | if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { 181 | // Emulate LIFO execution order by systematically adding new operations as last operation's dependency 182 | [wself.lastAddedOperation addDependency:operation]; 183 | wself.lastAddedOperation = operation; 184 | } 185 | }]; 186 | 187 | return operation; 188 | } 189 | 190 | - (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback { 191 | // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. 192 | if (url == nil) { 193 | if (completedBlock != nil) { 194 | completedBlock(nil, nil, nil, NO); 195 | } 196 | return; 197 | } 198 | 199 | dispatch_barrier_sync(self.barrierQueue, ^{ 200 | BOOL first = NO; 201 | if (!self.URLCallbacks[url]) { 202 | self.URLCallbacks[url] = [NSMutableArray new]; 203 | first = YES; 204 | } 205 | 206 | // Handle single download of simultaneous download request for the same URL 207 | NSMutableArray *callbacksForURL = self.URLCallbacks[url]; 208 | NSMutableDictionary *callbacks = [NSMutableDictionary new]; 209 | if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; 210 | if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; 211 | [callbacksForURL addObject:callbacks]; 212 | self.URLCallbacks[url] = callbacksForURL; 213 | 214 | if (first) { 215 | createCallback(); 216 | } 217 | }); 218 | } 219 | 220 | - (void)setSuspended:(BOOL)suspended { 221 | [self.downloadQueue setSuspended:suspended]; 222 | } 223 | 224 | @end 225 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImageDownloaderOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageDownloader.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | extern NSString *const SDWebImageDownloadStartNotification; 14 | extern NSString *const SDWebImageDownloadReceiveResponseNotification; 15 | extern NSString *const SDWebImageDownloadStopNotification; 16 | extern NSString *const SDWebImageDownloadFinishNotification; 17 | 18 | @interface SDWebImageDownloaderOperation : NSOperation 19 | 20 | /** 21 | * The request used by the operation's connection. 22 | */ 23 | @property (strong, nonatomic, readonly) NSURLRequest *request; 24 | 25 | 26 | @property (assign, nonatomic) BOOL shouldDecompressImages; 27 | 28 | /** 29 | * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. 30 | * 31 | * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. 32 | */ 33 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage; 34 | 35 | /** 36 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. 37 | * 38 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. 39 | */ 40 | @property (nonatomic, strong) NSURLCredential *credential; 41 | 42 | /** 43 | * The SDWebImageDownloaderOptions for the receiver. 44 | */ 45 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; 46 | 47 | /** 48 | * The expected size of data. 49 | */ 50 | @property (assign, nonatomic) NSInteger expectedSize; 51 | 52 | /** 53 | * The response returned by the operation's connection. 54 | */ 55 | @property (strong, nonatomic) NSURLResponse *response; 56 | 57 | /** 58 | * Initializes a `SDWebImageDownloaderOperation` object 59 | * 60 | * @see SDWebImageDownloaderOperation 61 | * 62 | * @param request the URL request 63 | * @param options downloader options 64 | * @param progressBlock the block executed when a new chunk of data arrives. 65 | * @note the progress block is executed on a background queue 66 | * @param completedBlock the block executed when the download is done. 67 | * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue 68 | * @param cancelBlock the block executed if the download (operation) is cancelled 69 | * 70 | * @return the initialized instance 71 | */ 72 | - (id)initWithRequest:(NSURLRequest *)request 73 | options:(SDWebImageDownloaderOptions)options 74 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 75 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 76 | cancelled:(SDWebImageNoParamsBlock)cancelBlock; 77 | 78 | @end 79 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImageManager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageOperation.h" 11 | #import "SDWebImageDownloader.h" 12 | #import "SDImageCache.h" 13 | 14 | typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { 15 | /** 16 | * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. 17 | * This flag disable this blacklisting. 18 | */ 19 | SDWebImageRetryFailed = 1 << 0, 20 | 21 | /** 22 | * By default, image downloads are started during UI interactions, this flags disable this feature, 23 | * leading to delayed download on UIScrollView deceleration for instance. 24 | */ 25 | SDWebImageLowPriority = 1 << 1, 26 | 27 | /** 28 | * This flag disables on-disk caching 29 | */ 30 | SDWebImageCacheMemoryOnly = 1 << 2, 31 | 32 | /** 33 | * This flag enables progressive download, the image is displayed progressively during download as a browser would do. 34 | * By default, the image is only displayed once completely downloaded. 35 | */ 36 | SDWebImageProgressiveDownload = 1 << 3, 37 | 38 | /** 39 | * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. 40 | * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. 41 | * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. 42 | * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. 43 | * 44 | * Use this flag only if you can't make your URLs static with embeded cache busting parameter. 45 | */ 46 | SDWebImageRefreshCached = 1 << 4, 47 | 48 | /** 49 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 50 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 51 | */ 52 | SDWebImageContinueInBackground = 1 << 5, 53 | 54 | /** 55 | * Handles cookies stored in NSHTTPCookieStore by setting 56 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 57 | */ 58 | SDWebImageHandleCookies = 1 << 6, 59 | 60 | /** 61 | * Enable to allow untrusted SSL ceriticates. 62 | * Useful for testing purposes. Use with caution in production. 63 | */ 64 | SDWebImageAllowInvalidSSLCertificates = 1 << 7, 65 | 66 | /** 67 | * By default, image are loaded in the order they were queued. This flag move them to 68 | * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which 69 | * could take a while). 70 | */ 71 | SDWebImageHighPriority = 1 << 8, 72 | 73 | /** 74 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 75 | * of the placeholder image until after the image has finished loading. 76 | */ 77 | SDWebImageDelayPlaceholder = 1 << 9, 78 | 79 | /** 80 | * We usually don't call transformDownloadedImage delegate method on animated images, 81 | * as most transformation code would mangle it. 82 | * Use this flag to transform them anyway. 83 | */ 84 | SDWebImageTransformAnimatedImage = 1 << 10, 85 | }; 86 | 87 | typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL); 88 | 89 | typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); 90 | 91 | typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url); 92 | 93 | 94 | @class SDWebImageManager; 95 | 96 | @protocol SDWebImageManagerDelegate 97 | 98 | @optional 99 | 100 | /** 101 | * Controls which image should be downloaded when the image is not found in the cache. 102 | * 103 | * @param imageManager The current `SDWebImageManager` 104 | * @param imageURL The url of the image to be downloaded 105 | * 106 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. 107 | */ 108 | - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; 109 | 110 | /** 111 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. 112 | * NOTE: This method is called from a global queue in order to not to block the main thread. 113 | * 114 | * @param imageManager The current `SDWebImageManager` 115 | * @param image The image to transform 116 | * @param imageURL The url of the image to transform 117 | * 118 | * @return The transformed image object. 119 | */ 120 | - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; 121 | 122 | @end 123 | 124 | /** 125 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. 126 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). 127 | * You can use this class directly to benefit from web image downloading with caching in another context than 128 | * a UIView. 129 | * 130 | * Here is a simple example of how to use SDWebImageManager: 131 | * 132 | * @code 133 | 134 | SDWebImageManager *manager = [SDWebImageManager sharedManager]; 135 | [manager downloadImageWithURL:imageURL 136 | options:0 137 | progress:nil 138 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 139 | if (image) { 140 | // do something with image 141 | } 142 | }]; 143 | 144 | * @endcode 145 | */ 146 | @interface SDWebImageManager : NSObject 147 | 148 | @property (weak, nonatomic) id delegate; 149 | 150 | @property (strong, nonatomic, readonly) SDImageCache *imageCache; 151 | @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; 152 | 153 | /** 154 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can 155 | * be used to remove dynamic part of an image URL. 156 | * 157 | * The following example sets a filter in the application delegate that will remove any query-string from the 158 | * URL before to use it as a cache key: 159 | * 160 | * @code 161 | 162 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { 163 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; 164 | return [url absoluteString]; 165 | }]; 166 | 167 | * @endcode 168 | */ 169 | @property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter; 170 | 171 | /** 172 | * Returns global SDWebImageManager instance. 173 | * 174 | * @return SDWebImageManager shared instance 175 | */ 176 | + (SDWebImageManager *)sharedManager; 177 | 178 | /** 179 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 180 | * 181 | * @param url The URL to the image 182 | * @param options A mask to specify options to use for this request 183 | * @param progressBlock A block called while image is downloading 184 | * @param completedBlock A block called when operation has been completed. 185 | * 186 | * This parameter is required. 187 | * 188 | * This block has no return value and takes the requested UIImage as first parameter. 189 | * In case of error the image parameter is nil and the second parameter may contain an NSError. 190 | * 191 | * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache 192 | * or from the memory cache or from the network. 193 | * 194 | * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is 195 | * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the 196 | * block is called a last time with the full image and the last parameter set to YES. 197 | * 198 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation 199 | */ 200 | - (id )downloadImageWithURL:(NSURL *)url 201 | options:(SDWebImageOptions)options 202 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 203 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; 204 | 205 | /** 206 | * Saves image to cache for given URL 207 | * 208 | * @param image The image to cache 209 | * @param url The URL to the image 210 | * 211 | */ 212 | 213 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url; 214 | 215 | /** 216 | * Cancel all current opreations 217 | */ 218 | - (void)cancelAll; 219 | 220 | /** 221 | * Check one or more operations running 222 | */ 223 | - (BOOL)isRunning; 224 | 225 | /** 226 | * Check if image has already been cached 227 | * 228 | * @param url image url 229 | * 230 | * @return if the image was already cached 231 | */ 232 | - (BOOL)cachedImageExistsForURL:(NSURL *)url; 233 | 234 | /** 235 | * Check if image has already been cached on disk only 236 | * 237 | * @param url image url 238 | * 239 | * @return if the image was already cached (disk only) 240 | */ 241 | - (BOOL)diskImageExistsForURL:(NSURL *)url; 242 | 243 | /** 244 | * Async check if image has already been cached 245 | * 246 | * @param url image url 247 | * @param completionBlock the block to be executed when the check is finished 248 | * 249 | * @note the completion block is always executed on the main queue 250 | */ 251 | - (void)cachedImageExistsForURL:(NSURL *)url 252 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 253 | 254 | /** 255 | * Async check if image has already been cached on disk only 256 | * 257 | * @param url image url 258 | * @param completionBlock the block to be executed when the check is finished 259 | * 260 | * @note the completion block is always executed on the main queue 261 | */ 262 | - (void)diskImageExistsForURL:(NSURL *)url 263 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 264 | 265 | 266 | /** 267 | *Return the cache key for a given URL 268 | */ 269 | - (NSString *)cacheKeyForURL:(NSURL *)url; 270 | 271 | @end 272 | 273 | 274 | #pragma mark - Deprecated 275 | 276 | typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`"); 277 | typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`"); 278 | 279 | 280 | @interface SDWebImageManager (Deprecated) 281 | 282 | /** 283 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 284 | * 285 | * @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:` 286 | */ 287 | - (id )downloadWithURL:(NSURL *)url 288 | options:(SDWebImageOptions)options 289 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 290 | completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`"); 291 | 292 | @end 293 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImageOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | 11 | @protocol SDWebImageOperation 12 | 13 | - (void)cancel; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImagePrefetcher.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageManager.h" 11 | 12 | @class SDWebImagePrefetcher; 13 | 14 | @protocol SDWebImagePrefetcherDelegate 15 | 16 | @optional 17 | 18 | /** 19 | * Called when an image was prefetched. 20 | * 21 | * @param imagePrefetcher The current image prefetcher 22 | * @param imageURL The image url that was prefetched 23 | * @param finishedCount The total number of images that were prefetched (successful or not) 24 | * @param totalCount The total number of images that were to be prefetched 25 | */ 26 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; 27 | 28 | /** 29 | * Called when all images are prefetched. 30 | * @param imagePrefetcher The current image prefetcher 31 | * @param totalCount The total number of images that were prefetched (whether successful or not) 32 | * @param skippedCount The total number of images that were skipped 33 | */ 34 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; 35 | 36 | @end 37 | 38 | typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); 39 | typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); 40 | 41 | /** 42 | * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. 43 | */ 44 | @interface SDWebImagePrefetcher : NSObject 45 | 46 | /** 47 | * The web image manager 48 | */ 49 | @property (strong, nonatomic, readonly) SDWebImageManager *manager; 50 | 51 | /** 52 | * Maximum number of URLs to prefetch at the same time. Defaults to 3. 53 | */ 54 | @property (nonatomic, assign) NSUInteger maxConcurrentDownloads; 55 | 56 | /** 57 | * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. 58 | */ 59 | @property (nonatomic, assign) SDWebImageOptions options; 60 | 61 | /** 62 | * Queue options for Prefetcher. Defaults to Main Queue. 63 | */ 64 | @property (nonatomic, assign) dispatch_queue_t prefetcherQueue; 65 | 66 | @property (weak, nonatomic) id delegate; 67 | 68 | /** 69 | * Return the global image prefetcher instance. 70 | */ 71 | + (SDWebImagePrefetcher *)sharedImagePrefetcher; 72 | 73 | /** 74 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 75 | * currently one image is downloaded at a time, 76 | * and skips images for failed downloads and proceed to the next image in the list 77 | * 78 | * @param urls list of URLs to prefetch 79 | */ 80 | - (void)prefetchURLs:(NSArray *)urls; 81 | 82 | /** 83 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 84 | * currently one image is downloaded at a time, 85 | * and skips images for failed downloads and proceed to the next image in the list 86 | * 87 | * @param urls list of URLs to prefetch 88 | * @param progressBlock block to be called when progress updates; 89 | * first parameter is the number of completed (successful or not) requests, 90 | * second parameter is the total number of images originally requested to be prefetched 91 | * @param completionBlock block to be called when prefetching is completed 92 | * first param is the number of completed (successful or not) requests, 93 | * second parameter is the number of skipped requests 94 | */ 95 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; 96 | 97 | /** 98 | * Remove and cancel queued list 99 | */ 100 | - (void)cancelPrefetching; 101 | 102 | 103 | @end 104 | -------------------------------------------------------------------------------- /tomahawk-ios/SDWebImagePrefetcher.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImagePrefetcher.h" 10 | 11 | #if (!defined(DEBUG) && !defined (SD_VERBOSE)) || defined(SD_LOG_NONE) 12 | #define NSLog(...) 13 | #endif 14 | 15 | @interface SDWebImagePrefetcher () 16 | 17 | @property (strong, nonatomic) SDWebImageManager *manager; 18 | @property (strong, nonatomic) NSArray *prefetchURLs; 19 | @property (assign, nonatomic) NSUInteger requestedCount; 20 | @property (assign, nonatomic) NSUInteger skippedCount; 21 | @property (assign, nonatomic) NSUInteger finishedCount; 22 | @property (assign, nonatomic) NSTimeInterval startedTime; 23 | @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock; 24 | @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock; 25 | 26 | @end 27 | 28 | @implementation SDWebImagePrefetcher 29 | 30 | + (SDWebImagePrefetcher *)sharedImagePrefetcher { 31 | static dispatch_once_t once; 32 | static id instance; 33 | dispatch_once(&once, ^{ 34 | instance = [self new]; 35 | }); 36 | return instance; 37 | } 38 | 39 | - (id)init { 40 | if ((self = [super init])) { 41 | _manager = [SDWebImageManager new]; 42 | _options = SDWebImageLowPriority; 43 | _prefetcherQueue = dispatch_get_main_queue(); 44 | self.maxConcurrentDownloads = 3; 45 | } 46 | return self; 47 | } 48 | 49 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { 50 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; 51 | } 52 | 53 | - (NSUInteger)maxConcurrentDownloads { 54 | return self.manager.imageDownloader.maxConcurrentDownloads; 55 | } 56 | 57 | - (void)startPrefetchingAtIndex:(NSUInteger)index { 58 | if (index >= self.prefetchURLs.count) return; 59 | self.requestedCount++; 60 | [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 61 | if (!finished) return; 62 | self.finishedCount++; 63 | 64 | if (image) { 65 | if (self.progressBlock) { 66 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 67 | } 68 | NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count)); 69 | } 70 | else { 71 | if (self.progressBlock) { 72 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 73 | } 74 | NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count)); 75 | 76 | // Add last failed 77 | self.skippedCount++; 78 | } 79 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { 80 | [self.delegate imagePrefetcher:self 81 | didPrefetchURL:self.prefetchURLs[index] 82 | finishedCount:self.finishedCount 83 | totalCount:self.prefetchURLs.count 84 | ]; 85 | } 86 | if (self.prefetchURLs.count > self.requestedCount) { 87 | dispatch_async(self.prefetcherQueue, ^{ 88 | [self startPrefetchingAtIndex:self.requestedCount]; 89 | }); 90 | } 91 | else if (self.finishedCount == self.requestedCount) { 92 | [self reportStatus]; 93 | if (self.completionBlock) { 94 | self.completionBlock(self.finishedCount, self.skippedCount); 95 | self.completionBlock = nil; 96 | } 97 | self.progressBlock = nil; 98 | } 99 | }]; 100 | } 101 | 102 | - (void)reportStatus { 103 | NSUInteger total = [self.prefetchURLs count]; 104 | NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime); 105 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { 106 | [self.delegate imagePrefetcher:self 107 | didFinishWithTotalCount:(total - self.skippedCount) 108 | skippedCount:self.skippedCount 109 | ]; 110 | } 111 | } 112 | 113 | - (void)prefetchURLs:(NSArray *)urls { 114 | [self prefetchURLs:urls progress:nil completed:nil]; 115 | } 116 | 117 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock { 118 | [self cancelPrefetching]; // Prevent duplicate prefetch request 119 | self.startedTime = CFAbsoluteTimeGetCurrent(); 120 | self.prefetchURLs = urls; 121 | self.completionBlock = completionBlock; 122 | self.progressBlock = progressBlock; 123 | 124 | if(urls.count == 0){ 125 | if(completionBlock){ 126 | completionBlock(0,0); 127 | } 128 | }else{ 129 | // Starts prefetching from the very first image on the list with the max allowed concurrency 130 | NSUInteger listCount = self.prefetchURLs.count; 131 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { 132 | [self startPrefetchingAtIndex:i]; 133 | } 134 | } 135 | } 136 | 137 | - (void)cancelPrefetching { 138 | self.prefetchURLs = nil; 139 | self.skippedCount = 0; 140 | self.requestedCount = 0; 141 | self.finishedCount = 0; 142 | [self.manager cancelAll]; 143 | } 144 | 145 | @end 146 | -------------------------------------------------------------------------------- /tomahawk-ios/SVIndefiniteAnimatedView.h: -------------------------------------------------------------------------------- 1 | // 2 | // SVIndefiniteAnimatedView.h 3 | // SVProgressHUD 4 | // 5 | // Created by Guillaume Campagna on 2014-12-05. 6 | // 7 | // 8 | 9 | #import 10 | 11 | @interface SVIndefiniteAnimatedView : UIView 12 | 13 | @property (nonatomic, assign) CGFloat strokeThickness; 14 | @property (nonatomic, assign) CGFloat radius; 15 | @property (nonatomic, strong) UIColor *strokeColor; 16 | 17 | @end 18 | 19 | -------------------------------------------------------------------------------- /tomahawk-ios/SVIndefiniteAnimatedView.m: -------------------------------------------------------------------------------- 1 | // 2 | // SVIndefiniteAnimatedView.m 3 | // SVProgressHUD 4 | // 5 | // Created by Guillaume Campagna on 2014-12-05. 6 | // 7 | // 8 | 9 | #import "SVIndefiniteAnimatedView.h" 10 | 11 | #pragma mark SVIndefiniteAnimatedView 12 | 13 | @interface SVIndefiniteAnimatedView () 14 | 15 | @property (nonatomic, strong) CAShapeLayer *indefiniteAnimatedLayer; 16 | 17 | @end 18 | 19 | @implementation SVIndefiniteAnimatedView 20 | 21 | - (void)willMoveToSuperview:(UIView *)newSuperview { 22 | if (newSuperview) { 23 | [self layoutAnimatedLayer]; 24 | } else { 25 | [_indefiniteAnimatedLayer removeFromSuperlayer]; 26 | _indefiniteAnimatedLayer = nil; 27 | } 28 | } 29 | 30 | - (void)layoutAnimatedLayer { 31 | CALayer *layer = self.indefiniteAnimatedLayer; 32 | 33 | [self.layer addSublayer:layer]; 34 | layer.position = CGPointMake(CGRectGetWidth(self.bounds) - CGRectGetWidth(layer.bounds) / 2, CGRectGetHeight(self.bounds) - CGRectGetHeight(layer.bounds) / 2); 35 | } 36 | 37 | - (CAShapeLayer*)indefiniteAnimatedLayer { 38 | if(!_indefiniteAnimatedLayer) { 39 | CGPoint arcCenter = CGPointMake(self.radius+self.strokeThickness/2+5, self.radius+self.strokeThickness/2+5); 40 | CGRect rect = CGRectMake(0.0f, 0.0f, arcCenter.x*2, arcCenter.y*2); 41 | 42 | UIBezierPath* smoothedPath = [UIBezierPath bezierPathWithArcCenter:arcCenter 43 | radius:self.radius 44 | startAngle:M_PI*3/2 45 | endAngle:M_PI/2+M_PI*5 46 | clockwise:YES]; 47 | 48 | _indefiniteAnimatedLayer = [CAShapeLayer layer]; 49 | _indefiniteAnimatedLayer.contentsScale = [[UIScreen mainScreen] scale]; 50 | _indefiniteAnimatedLayer.frame = rect; 51 | _indefiniteAnimatedLayer.fillColor = [UIColor clearColor].CGColor; 52 | _indefiniteAnimatedLayer.strokeColor = self.strokeColor.CGColor; 53 | _indefiniteAnimatedLayer.lineWidth = self.strokeThickness; 54 | _indefiniteAnimatedLayer.lineCap = kCALineCapRound; 55 | _indefiniteAnimatedLayer.lineJoin = kCALineJoinBevel; 56 | _indefiniteAnimatedLayer.path = smoothedPath.CGPath; 57 | 58 | CALayer *maskLayer = [CALayer layer]; 59 | 60 | NSBundle *bundle = [NSBundle bundleForClass:self.class]; 61 | NSURL *url = [bundle URLForResource:@"SVProgressHUD" withExtension:@"bundle"]; 62 | NSBundle *imageBundle = [NSBundle bundleWithURL:url]; 63 | NSString *path = [imageBundle pathForResource:@"angle-mask" ofType:@"png"]; 64 | 65 | maskLayer.contents = (id)[[UIImage imageWithContentsOfFile:path] CGImage];; 66 | maskLayer.frame = _indefiniteAnimatedLayer.bounds; 67 | _indefiniteAnimatedLayer.mask = maskLayer; 68 | 69 | NSTimeInterval animationDuration = 1; 70 | CAMediaTimingFunction *linearCurve = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; 71 | 72 | CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; 73 | animation.fromValue = 0; 74 | animation.toValue = [NSNumber numberWithFloat:M_PI*2]; 75 | animation.duration = animationDuration; 76 | animation.timingFunction = linearCurve; 77 | animation.removedOnCompletion = NO; 78 | animation.repeatCount = INFINITY; 79 | animation.fillMode = kCAFillModeForwards; 80 | animation.autoreverses = NO; 81 | [_indefiniteAnimatedLayer.mask addAnimation:animation forKey:@"rotate"]; 82 | 83 | CAAnimationGroup *animationGroup = [CAAnimationGroup animation]; 84 | animationGroup.duration = animationDuration; 85 | animationGroup.repeatCount = INFINITY; 86 | animationGroup.removedOnCompletion = NO; 87 | animationGroup.timingFunction = linearCurve; 88 | 89 | CABasicAnimation *strokeStartAnimation = [CABasicAnimation animationWithKeyPath:@"strokeStart"]; 90 | strokeStartAnimation.fromValue = @0.015; 91 | strokeStartAnimation.toValue = @0.515; 92 | 93 | CABasicAnimation *strokeEndAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; 94 | strokeEndAnimation.fromValue = @0.485; 95 | strokeEndAnimation.toValue = @0.985; 96 | 97 | animationGroup.animations = @[strokeStartAnimation, strokeEndAnimation]; 98 | [_indefiniteAnimatedLayer addAnimation:animationGroup forKey:@"progress"]; 99 | 100 | } 101 | return _indefiniteAnimatedLayer; 102 | } 103 | 104 | - (void)setFrame:(CGRect)frame { 105 | [super setFrame:frame]; 106 | 107 | if (self.superview) { 108 | [self layoutAnimatedLayer]; 109 | } 110 | } 111 | 112 | - (void)setRadius:(CGFloat)radius { 113 | _radius = radius; 114 | 115 | [_indefiniteAnimatedLayer removeFromSuperlayer]; 116 | _indefiniteAnimatedLayer = nil; 117 | 118 | if (self.superview) { 119 | [self layoutAnimatedLayer]; 120 | } 121 | } 122 | 123 | - (void)setStrokeColor:(UIColor *)strokeColor { 124 | _strokeColor = strokeColor; 125 | _indefiniteAnimatedLayer.strokeColor = strokeColor.CGColor; 126 | } 127 | 128 | - (void)setStrokeThickness:(CGFloat)strokeThickness { 129 | _strokeThickness = strokeThickness; 130 | _indefiniteAnimatedLayer.lineWidth = _strokeThickness; 131 | } 132 | 133 | - (CGSize)sizeThatFits:(CGSize)size { 134 | return CGSizeMake((self.radius+self.strokeThickness/2+5)*2, (self.radius+self.strokeThickness/2+5)*2); 135 | } 136 | 137 | @end 138 | -------------------------------------------------------------------------------- /tomahawk-ios/SVProgressHUD.h: -------------------------------------------------------------------------------- 1 | // 2 | // SVProgressHUD.h 3 | // 4 | // Copyright 2011-2014 Sam Vermette. All rights reserved. 5 | // 6 | // https://github.com/samvermette/SVProgressHUD 7 | // 8 | 9 | #import 10 | #import 11 | 12 | extern NSString * const SVProgressHUDDidReceiveTouchEventNotification; 13 | extern NSString * const SVProgressHUDDidTouchDownInsideNotification; 14 | extern NSString * const SVProgressHUDWillDisappearNotification; 15 | extern NSString * const SVProgressHUDDidDisappearNotification; 16 | extern NSString * const SVProgressHUDWillAppearNotification; 17 | extern NSString * const SVProgressHUDDidAppearNotification; 18 | 19 | extern NSString * const SVProgressHUDStatusUserInfoKey; 20 | 21 | typedef NS_ENUM(NSUInteger, SVProgressHUDMaskType) { 22 | SVProgressHUDMaskTypeNone = 1, // allow user interactions while HUD is displayed 23 | SVProgressHUDMaskTypeClear, // don't allow user interactions 24 | SVProgressHUDMaskTypeBlack, // don't allow user interactions and dim the UI in the back of the HUD 25 | SVProgressHUDMaskTypeGradient // don't allow user interactions and dim the UI with a a-la-alert-view background gradient 26 | }; 27 | 28 | @interface SVProgressHUD : UIView 29 | 30 | #pragma mark - Customization 31 | 32 | + (void)setBackgroundColor:(UIColor*)color; // default is [UIColor whiteColor] 33 | + (void)setForegroundColor:(UIColor*)color; // default is [UIColor blackColor] 34 | + (void)setRingThickness:(CGFloat)width; // default is 4 pt 35 | + (void)setFont:(UIFont*)font; // default is [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline] 36 | + (void)setInfoImage:(UIImage*)image; // default is the bundled info image provided by Freepik 37 | + (void)setSuccessImage:(UIImage*)image; // default is the bundled success image provided by Freepik 38 | + (void)setErrorImage:(UIImage*)image; // default is the bundled error image provided by Freepik 39 | + (void)setDefaultMaskType:(SVProgressHUDMaskType)maskType; // default is SVProgressHUDMaskTypeNone 40 | + (void)setViewForExtension:(UIView*)view; // default is nil, only used if #define SV_APP_EXTENSIONS is set 41 | 42 | #pragma mark - Show Methods 43 | 44 | + (void)show; 45 | + (void)showWithMaskType:(SVProgressHUDMaskType)maskType; 46 | + (void)showWithStatus:(NSString*)status; 47 | + (void)showWithStatus:(NSString*)status maskType:(SVProgressHUDMaskType)maskType; 48 | 49 | + (void)showProgress:(float)progress; 50 | + (void)showProgress:(float)progress maskType:(SVProgressHUDMaskType)maskType; 51 | + (void)showProgress:(float)progress status:(NSString*)status; 52 | + (void)showProgress:(float)progress status:(NSString*)status maskType:(SVProgressHUDMaskType)maskType; 53 | 54 | + (void)setStatus:(NSString*)string; // change the HUD loading status while it's showing 55 | 56 | // stops the activity indicator, shows a glyph + status, and dismisses HUD a little bit later 57 | + (void)showInfoWithStatus:(NSString *)string; 58 | + (void)showInfoWithStatus:(NSString *)string maskType:(SVProgressHUDMaskType)maskType; 59 | 60 | + (void)showSuccessWithStatus:(NSString*)string; 61 | + (void)showSuccessWithStatus:(NSString*)string maskType:(SVProgressHUDMaskType)maskType; 62 | 63 | + (void)showErrorWithStatus:(NSString *)string; 64 | + (void)showErrorWithStatus:(NSString *)string maskType:(SVProgressHUDMaskType)maskType; 65 | 66 | // use 28x28 white pngs 67 | + (void)showImage:(UIImage*)image status:(NSString*)status; 68 | + (void)showImage:(UIImage*)image status:(NSString*)status maskType:(SVProgressHUDMaskType)maskType; 69 | 70 | + (void)setOffsetFromCenter:(UIOffset)offset; 71 | + (void)resetOffsetFromCenter; 72 | 73 | + (void)popActivity; // decrease activity count, if activity count == 0 the HUD is dismissed 74 | + (void)dismiss; 75 | 76 | + (BOOL)isVisible; 77 | 78 | @end 79 | 80 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImage+GIF.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+GIF.h 3 | // LBGIFImage 4 | // 5 | // Created by Laurin Brandner on 06.01.12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface UIImage (GIF) 12 | 13 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name; 14 | 15 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data; 16 | 17 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImage+GIF.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+GIF.m 3 | // LBGIFImage 4 | // 5 | // Created by Laurin Brandner on 06.01.12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "UIImage+GIF.h" 10 | #import 11 | 12 | @implementation UIImage (GIF) 13 | 14 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data { 15 | if (!data) { 16 | return nil; 17 | } 18 | 19 | CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); 20 | 21 | size_t count = CGImageSourceGetCount(source); 22 | 23 | UIImage *animatedImage; 24 | 25 | if (count <= 1) { 26 | animatedImage = [[UIImage alloc] initWithData:data]; 27 | } 28 | else { 29 | NSMutableArray *images = [NSMutableArray array]; 30 | 31 | NSTimeInterval duration = 0.0f; 32 | 33 | for (size_t i = 0; i < count; i++) { 34 | CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); 35 | 36 | duration += [self sd_frameDurationAtIndex:i source:source]; 37 | 38 | [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; 39 | 40 | CGImageRelease(image); 41 | } 42 | 43 | if (!duration) { 44 | duration = (1.0f / 10.0f) * count; 45 | } 46 | 47 | animatedImage = [UIImage animatedImageWithImages:images duration:duration]; 48 | } 49 | 50 | CFRelease(source); 51 | 52 | return animatedImage; 53 | } 54 | 55 | + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { 56 | float frameDuration = 0.1f; 57 | CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); 58 | NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; 59 | NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; 60 | 61 | NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; 62 | if (delayTimeUnclampedProp) { 63 | frameDuration = [delayTimeUnclampedProp floatValue]; 64 | } 65 | else { 66 | 67 | NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; 68 | if (delayTimeProp) { 69 | frameDuration = [delayTimeProp floatValue]; 70 | } 71 | } 72 | 73 | // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. 74 | // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify 75 | // a duration of <= 10 ms. See and 76 | // for more information. 77 | 78 | if (frameDuration < 0.011f) { 79 | frameDuration = 0.100f; 80 | } 81 | 82 | CFRelease(cfFrameProperties); 83 | return frameDuration; 84 | } 85 | 86 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name { 87 | CGFloat scale = [UIScreen mainScreen].scale; 88 | 89 | if (scale > 1.0f) { 90 | NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; 91 | 92 | NSData *data = [NSData dataWithContentsOfFile:retinaPath]; 93 | 94 | if (data) { 95 | return [UIImage sd_animatedGIFWithData:data]; 96 | } 97 | 98 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 99 | 100 | data = [NSData dataWithContentsOfFile:path]; 101 | 102 | if (data) { 103 | return [UIImage sd_animatedGIFWithData:data]; 104 | } 105 | 106 | return [UIImage imageNamed:name]; 107 | } 108 | else { 109 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 110 | 111 | NSData *data = [NSData dataWithContentsOfFile:path]; 112 | 113 | if (data) { 114 | return [UIImage sd_animatedGIFWithData:data]; 115 | } 116 | 117 | return [UIImage imageNamed:name]; 118 | } 119 | } 120 | 121 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { 122 | if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { 123 | return self; 124 | } 125 | 126 | CGSize scaledSize = size; 127 | CGPoint thumbnailPoint = CGPointZero; 128 | 129 | CGFloat widthFactor = size.width / self.size.width; 130 | CGFloat heightFactor = size.height / self.size.height; 131 | CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; 132 | scaledSize.width = self.size.width * scaleFactor; 133 | scaledSize.height = self.size.height * scaleFactor; 134 | 135 | if (widthFactor > heightFactor) { 136 | thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; 137 | } 138 | else if (widthFactor < heightFactor) { 139 | thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; 140 | } 141 | 142 | NSMutableArray *scaledImages = [NSMutableArray array]; 143 | 144 | UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); 145 | 146 | for (UIImage *image in self.images) { 147 | [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; 148 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 149 | 150 | [scaledImages addObject:newImage]; 151 | } 152 | 153 | UIGraphicsEndImageContext(); 154 | 155 | return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; 156 | } 157 | 158 | @end 159 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImage+MultiFormat.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+MultiFormat.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface UIImage (MultiFormat) 12 | 13 | + (UIImage *)sd_imageWithData:(NSData *)data; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImage+MultiFormat.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+MultiFormat.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "UIImage+MultiFormat.h" 10 | #import "UIImage+GIF.h" 11 | #import "NSData+ImageContentType.h" 12 | #import 13 | 14 | #ifdef SD_WEBP 15 | #import "UIImage+WebP.h" 16 | #endif 17 | 18 | @implementation UIImage (MultiFormat) 19 | 20 | + (UIImage *)sd_imageWithData:(NSData *)data { 21 | UIImage *image; 22 | NSString *imageContentType = [NSData sd_contentTypeForImageData:data]; 23 | if ([imageContentType isEqualToString:@"image/gif"]) { 24 | image = [UIImage sd_animatedGIFWithData:data]; 25 | } 26 | #ifdef SD_WEBP 27 | else if ([imageContentType isEqualToString:@"image/webp"]) 28 | { 29 | image = [UIImage sd_imageWithWebPData:data]; 30 | } 31 | #endif 32 | else { 33 | image = [[UIImage alloc] initWithData:data]; 34 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; 35 | if (orientation != UIImageOrientationUp) { 36 | image = [UIImage imageWithCGImage:image.CGImage 37 | scale:image.scale 38 | orientation:orientation]; 39 | } 40 | } 41 | 42 | 43 | return image; 44 | } 45 | 46 | 47 | +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData { 48 | UIImageOrientation result = UIImageOrientationUp; 49 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); 50 | if (imageSource) { 51 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 52 | if (properties) { 53 | CFTypeRef val; 54 | int exifOrientation; 55 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 56 | if (val) { 57 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); 58 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; 59 | } // else - if it's not set it remains at up 60 | CFRelease((CFTypeRef) properties); 61 | } else { 62 | //NSLog(@"NO PROPERTIES, FAIL"); 63 | } 64 | CFRelease(imageSource); 65 | } 66 | return result; 67 | } 68 | 69 | #pragma mark EXIF orientation tag converter 70 | // Convert an EXIF image orientation to an iOS one. 71 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html 72 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { 73 | UIImageOrientation orientation = UIImageOrientationUp; 74 | switch (exifOrientation) { 75 | case 1: 76 | orientation = UIImageOrientationUp; 77 | break; 78 | 79 | case 3: 80 | orientation = UIImageOrientationDown; 81 | break; 82 | 83 | case 8: 84 | orientation = UIImageOrientationLeft; 85 | break; 86 | 87 | case 6: 88 | orientation = UIImageOrientationRight; 89 | break; 90 | 91 | case 2: 92 | orientation = UIImageOrientationUpMirrored; 93 | break; 94 | 95 | case 4: 96 | orientation = UIImageOrientationDownMirrored; 97 | break; 98 | 99 | case 5: 100 | orientation = UIImageOrientationLeftMirrored; 101 | break; 102 | 103 | case 7: 104 | orientation = UIImageOrientationRightMirrored; 105 | break; 106 | default: 107 | break; 108 | } 109 | return orientation; 110 | } 111 | 112 | 113 | 114 | @end 115 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImage+WebP.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | 11 | #import 12 | 13 | // Fix for issue #416 Undefined symbols for architecture armv7 since WebP introduction when deploying to device 14 | void WebPInitPremultiplyNEON(void); 15 | 16 | void WebPInitUpsamplersNEON(void); 17 | 18 | void VP8DspInitNEON(void); 19 | 20 | @interface UIImage (WebP) 21 | 22 | + (UIImage *)sd_imageWithWebPData:(NSData *)data; 23 | 24 | @end 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImage+WebP.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | #import "UIImage+WebP.h" 11 | #import "webp/decode.h" 12 | 13 | // Callback for CGDataProviderRelease 14 | static void FreeImageData(void *info, const void *data, size_t size) 15 | { 16 | free((void *)data); 17 | } 18 | 19 | @implementation UIImage (WebP) 20 | 21 | + (UIImage *)sd_imageWithWebPData:(NSData *)data { 22 | WebPDecoderConfig config; 23 | if (!WebPInitDecoderConfig(&config)) { 24 | return nil; 25 | } 26 | 27 | if (WebPGetFeatures(data.bytes, data.length, &config.input) != VP8_STATUS_OK) { 28 | return nil; 29 | } 30 | 31 | config.output.colorspace = config.input.has_alpha ? MODE_rgbA : MODE_RGB; 32 | config.options.use_threads = 1; 33 | 34 | // Decode the WebP image data into a RGBA value array. 35 | if (WebPDecode(data.bytes, data.length, &config) != VP8_STATUS_OK) { 36 | return nil; 37 | } 38 | 39 | int width = config.input.width; 40 | int height = config.input.height; 41 | if (config.options.use_scaling) { 42 | width = config.options.scaled_width; 43 | height = config.options.scaled_height; 44 | } 45 | 46 | // Construct a UIImage from the decoded RGBA value array. 47 | CGDataProviderRef provider = 48 | CGDataProviderCreateWithData(NULL, config.output.u.RGBA.rgba, config.output.u.RGBA.size, FreeImageData); 49 | CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); 50 | CGBitmapInfo bitmapInfo = config.input.has_alpha ? kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast : 0; 51 | size_t components = config.input.has_alpha ? 4 : 3; 52 | CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; 53 | CGImageRef imageRef = CGImageCreate(width, height, 8, components * 8, components * width, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); 54 | 55 | CGColorSpaceRelease(colorSpaceRef); 56 | CGDataProviderRelease(provider); 57 | 58 | UIImage *image = [[UIImage alloc] initWithCGImage:imageRef]; 59 | CGImageRelease(imageRef); 60 | 61 | return image; 62 | } 63 | 64 | @end 65 | 66 | #if !COCOAPODS 67 | // Functions to resolve some undefined symbols when using WebP and force_load flag 68 | void WebPInitPremultiplyNEON(void) {} 69 | void WebPInitUpsamplersNEON(void) {} 70 | void VP8DspInitNEON(void) {} 71 | #endif 72 | 73 | #endif 74 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImageView+HighlightedWebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | #import "SDWebImageManager.h" 12 | 13 | /** 14 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state. 15 | */ 16 | @interface UIImageView (HighlightedWebCache) 17 | 18 | /** 19 | * Set the imageView `highlightedImage` with an `url`. 20 | * 21 | * The download is asynchronous and cached. 22 | * 23 | * @param url The url for the image. 24 | */ 25 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url; 26 | 27 | /** 28 | * Set the imageView `highlightedImage` with an `url` and custom options. 29 | * 30 | * The download is asynchronous and cached. 31 | * 32 | * @param url The url for the image. 33 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 34 | */ 35 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options; 36 | 37 | /** 38 | * Set the imageView `highlightedImage` with an `url`. 39 | * 40 | * The download is asynchronous and cached. 41 | * 42 | * @param url The url for the image. 43 | * @param completedBlock A block called when operation has been completed. This block has no return value 44 | * and takes the requested UIImage as first parameter. In case of error the image parameter 45 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 46 | * indicating if the image was retrived from the local cache or from the network. 47 | * The fourth parameter is the original image url. 48 | */ 49 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; 50 | 51 | /** 52 | * Set the imageView `highlightedImage` with an `url` and custom options. 53 | * 54 | * The download is asynchronous and cached. 55 | * 56 | * @param url The url for the image. 57 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 58 | * @param completedBlock A block called when operation has been completed. This block has no return value 59 | * and takes the requested UIImage as first parameter. In case of error the image parameter 60 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 61 | * indicating if the image was retrived from the local cache or from the network. 62 | * The fourth parameter is the original image url. 63 | */ 64 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 65 | 66 | /** 67 | * Set the imageView `highlightedImage` with an `url` and custom options. 68 | * 69 | * The download is asynchronous and cached. 70 | * 71 | * @param url The url for the image. 72 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 73 | * @param progressBlock A block called while image is downloading 74 | * @param completedBlock A block called when operation has been completed. This block has no return value 75 | * and takes the requested UIImage as first parameter. In case of error the image parameter 76 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 77 | * indicating if the image was retrived from the local cache or from the network. 78 | * The fourth parameter is the original image url. 79 | */ 80 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 81 | 82 | /** 83 | * Cancel the current download 84 | */ 85 | - (void)sd_cancelCurrentHighlightedImageLoad; 86 | 87 | @end 88 | 89 | 90 | @interface UIImageView (HighlightedWebCacheDeprecated) 91 | 92 | - (void)setHighlightedImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:`"); 93 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:`"); 94 | - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:completed:`"); 95 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:completed:`"); 96 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:progress:completed:`"); 97 | 98 | - (void)cancelCurrentHighlightedImageLoad __deprecated_msg("Use `sd_cancelCurrentHighlightedImageLoad`"); 99 | 100 | @end 101 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImageView+HighlightedWebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImageView+HighlightedWebCache.h" 10 | #import "UIView+WebCacheOperation.h" 11 | 12 | #define UIImageViewHighlightedWebCacheOperationKey @"highlightedImage" 13 | 14 | @implementation UIImageView (HighlightedWebCache) 15 | 16 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url { 17 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; 18 | } 19 | 20 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { 21 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; 22 | } 23 | 24 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 25 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; 26 | } 27 | 28 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 29 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; 30 | } 31 | 32 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 33 | [self sd_cancelCurrentHighlightedImageLoad]; 34 | 35 | if (url) { 36 | __weak __typeof(self)wself = self; 37 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 38 | if (!wself) return; 39 | dispatch_main_sync_safe (^ 40 | { 41 | if (!wself) return; 42 | if (image) { 43 | wself.highlightedImage = image; 44 | [wself setNeedsLayout]; 45 | } 46 | if (completedBlock && finished) { 47 | completedBlock(image, error, cacheType, url); 48 | } 49 | }); 50 | }]; 51 | [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey]; 52 | } else { 53 | dispatch_main_async_safe(^{ 54 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 55 | if (completedBlock) { 56 | completedBlock(nil, error, SDImageCacheTypeNone, url); 57 | } 58 | }); 59 | } 60 | } 61 | 62 | - (void)sd_cancelCurrentHighlightedImageLoad { 63 | [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey]; 64 | } 65 | 66 | @end 67 | 68 | 69 | @implementation UIImageView (HighlightedWebCacheDeprecated) 70 | 71 | - (void)setHighlightedImageWithURL:(NSURL *)url { 72 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; 73 | } 74 | 75 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { 76 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; 77 | } 78 | 79 | - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { 80 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 81 | if (completedBlock) { 82 | completedBlock(image, error, cacheType); 83 | } 84 | }]; 85 | } 86 | 87 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 88 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 89 | if (completedBlock) { 90 | completedBlock(image, error, cacheType); 91 | } 92 | }]; 93 | } 94 | 95 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { 96 | [self sd_setHighlightedImageWithURL:url options:0 progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 97 | if (completedBlock) { 98 | completedBlock(image, error, cacheType); 99 | } 100 | }]; 101 | } 102 | 103 | - (void)cancelCurrentHighlightedImageLoad { 104 | [self sd_cancelCurrentHighlightedImageLoad]; 105 | } 106 | 107 | @end 108 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImageView+WebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageManager.h" 11 | 12 | /** 13 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView. 14 | * 15 | * Usage with a UITableViewCell sub-class: 16 | * 17 | * @code 18 | 19 | #import 20 | 21 | ... 22 | 23 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 24 | { 25 | static NSString *MyIdentifier = @"MyIdentifier"; 26 | 27 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 28 | 29 | if (cell == nil) { 30 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] 31 | autorelease]; 32 | } 33 | 34 | // Here we use the provided sd_setImageWithURL: method to load the web image 35 | // Ensure you use a placeholder image otherwise cells will be initialized with no image 36 | [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] 37 | placeholderImage:[UIImage imageNamed:@"placeholder"]]; 38 | 39 | cell.textLabel.text = @"My Text"; 40 | return cell; 41 | } 42 | 43 | * @endcode 44 | */ 45 | @interface UIImageView (WebCache) 46 | 47 | /** 48 | * Get the current image URL. 49 | * 50 | * Note that because of the limitations of categories this property can get out of sync 51 | * if you use sd_setImage: directly. 52 | */ 53 | - (NSURL *)sd_imageURL; 54 | 55 | /** 56 | * Set the imageView `image` with an `url`. 57 | * 58 | * The download is asynchronous and cached. 59 | * 60 | * @param url The url for the image. 61 | */ 62 | - (void)sd_setImageWithURL:(NSURL *)url; 63 | 64 | /** 65 | * Set the imageView `image` with an `url` and a placeholder. 66 | * 67 | * The download is asynchronous and cached. 68 | * 69 | * @param url The url for the image. 70 | * @param placeholder The image to be set initially, until the image request finishes. 71 | * @see sd_setImageWithURL:placeholderImage:options: 72 | */ 73 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; 74 | 75 | /** 76 | * Set the imageView `image` with an `url`, placeholder and custom options. 77 | * 78 | * The download is asynchronous and cached. 79 | * 80 | * @param url The url for the image. 81 | * @param placeholder The image to be set initially, until the image request finishes. 82 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 83 | */ 84 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; 85 | 86 | /** 87 | * Set the imageView `image` with an `url`. 88 | * 89 | * The download is asynchronous and cached. 90 | * 91 | * @param url The url for the image. 92 | * @param completedBlock A block called when operation has been completed. This block has no return value 93 | * and takes the requested UIImage as first parameter. In case of error the image parameter 94 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 95 | * indicating if the image was retrived from the local cache or from the network. 96 | * The fourth parameter is the original image url. 97 | */ 98 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; 99 | 100 | /** 101 | * Set the imageView `image` with an `url`, placeholder. 102 | * 103 | * The download is asynchronous and cached. 104 | * 105 | * @param url The url for the image. 106 | * @param placeholder The image to be set initially, until the image request finishes. 107 | * @param completedBlock A block called when operation has been completed. This block has no return value 108 | * and takes the requested UIImage as first parameter. In case of error the image parameter 109 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 110 | * indicating if the image was retrived from the local cache or from the network. 111 | * The fourth parameter is the original image url. 112 | */ 113 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; 114 | 115 | /** 116 | * Set the imageView `image` with an `url`, placeholder and custom options. 117 | * 118 | * The download is asynchronous and cached. 119 | * 120 | * @param url The url for the image. 121 | * @param placeholder The image to be set initially, until the image request finishes. 122 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 123 | * @param completedBlock A block called when operation has been completed. This block has no return value 124 | * and takes the requested UIImage as first parameter. In case of error the image parameter 125 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 126 | * indicating if the image was retrived from the local cache or from the network. 127 | * The fourth parameter is the original image url. 128 | */ 129 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 130 | 131 | /** 132 | * Set the imageView `image` with an `url`, placeholder and custom options. 133 | * 134 | * The download is asynchronous and cached. 135 | * 136 | * @param url The url for the image. 137 | * @param placeholder The image to be set initially, until the image request finishes. 138 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 139 | * @param progressBlock A block called while image is downloading 140 | * @param completedBlock A block called when operation has been completed. This block has no return value 141 | * and takes the requested UIImage as first parameter. In case of error the image parameter 142 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 143 | * indicating if the image was retrived from the local cache or from the network. 144 | * The fourth parameter is the original image url. 145 | */ 146 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 147 | 148 | /** 149 | * Set the imageView `image` with an `url` and a optionaly placeholder image. 150 | * 151 | * The download is asynchronous and cached. 152 | * 153 | * @param url The url for the image. 154 | * @param placeholder The image to be set initially, until the image request finishes. 155 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 156 | * @param progressBlock A block called while image is downloading 157 | * @param completedBlock A block called when operation has been completed. This block has no return value 158 | * and takes the requested UIImage as first parameter. In case of error the image parameter 159 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 160 | * indicating if the image was retrived from the local cache or from the network. 161 | * The fourth parameter is the original image url. 162 | */ 163 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 164 | 165 | /** 166 | * Download an array of images and starts them in an animation loop 167 | * 168 | * @param arrayOfURLs An array of NSURL 169 | */ 170 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs; 171 | 172 | /** 173 | * Cancel the current download 174 | */ 175 | - (void)sd_cancelCurrentImageLoad; 176 | 177 | - (void)sd_cancelCurrentAnimationImagesLoad; 178 | 179 | @end 180 | 181 | 182 | @interface UIImageView (WebCacheDeprecated) 183 | 184 | - (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`"); 185 | 186 | - (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`"); 187 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`"); 188 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`"); 189 | 190 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`"); 191 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`"); 192 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`"); 193 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:progress:completed:`"); 194 | 195 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`"); 196 | 197 | - (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`"); 198 | 199 | - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`"); 200 | 201 | @end 202 | -------------------------------------------------------------------------------- /tomahawk-ios/UIImageView+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImageView+WebCache.h" 10 | #import "objc/runtime.h" 11 | #import "UIView+WebCacheOperation.h" 12 | 13 | static char imageURLKey; 14 | 15 | @implementation UIImageView (WebCache) 16 | 17 | - (void)sd_setImageWithURL:(NSURL *)url { 18 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 19 | } 20 | 21 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 22 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 23 | } 24 | 25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 27 | } 28 | 29 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 30 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; 31 | } 32 | 33 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 34 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; 35 | } 36 | 37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; 39 | } 40 | 41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 42 | [self sd_cancelCurrentImageLoad]; 43 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 44 | 45 | if (!(options & SDWebImageDelayPlaceholder)) { 46 | dispatch_main_async_safe(^{ 47 | self.image = placeholder; 48 | }); 49 | } 50 | 51 | if (url) { 52 | __weak __typeof(self)wself = self; 53 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 54 | if (!wself) return; 55 | dispatch_main_sync_safe(^{ 56 | if (!wself) return; 57 | if (image) { 58 | wself.image = image; 59 | [wself setNeedsLayout]; 60 | } else { 61 | if ((options & SDWebImageDelayPlaceholder)) { 62 | wself.image = placeholder; 63 | [wself setNeedsLayout]; 64 | } 65 | } 66 | if (completedBlock && finished) { 67 | completedBlock(image, error, cacheType, url); 68 | } 69 | }); 70 | }]; 71 | [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; 72 | } else { 73 | dispatch_main_async_safe(^{ 74 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 75 | if (completedBlock) { 76 | completedBlock(nil, error, SDImageCacheTypeNone, url); 77 | } 78 | }); 79 | } 80 | } 81 | 82 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 83 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; 84 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key]; 85 | 86 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; 87 | } 88 | 89 | - (NSURL *)sd_imageURL { 90 | return objc_getAssociatedObject(self, &imageURLKey); 91 | } 92 | 93 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 94 | [self sd_cancelCurrentAnimationImagesLoad]; 95 | __weak __typeof(self)wself = self; 96 | 97 | NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; 98 | 99 | for (NSURL *logoImageURL in arrayOfURLs) { 100 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 101 | if (!wself) return; 102 | dispatch_main_sync_safe(^{ 103 | __strong UIImageView *sself = wself; 104 | [sself stopAnimating]; 105 | if (sself && image) { 106 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; 107 | if (!currentImages) { 108 | currentImages = [[NSMutableArray alloc] init]; 109 | } 110 | [currentImages addObject:image]; 111 | 112 | sself.animationImages = currentImages; 113 | [sself setNeedsLayout]; 114 | } 115 | [sself startAnimating]; 116 | }); 117 | }]; 118 | [operationsArray addObject:operation]; 119 | } 120 | 121 | [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"]; 122 | } 123 | 124 | - (void)sd_cancelCurrentImageLoad { 125 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; 126 | } 127 | 128 | - (void)sd_cancelCurrentAnimationImagesLoad { 129 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; 130 | } 131 | 132 | @end 133 | 134 | 135 | @implementation UIImageView (WebCacheDeprecated) 136 | 137 | - (NSURL *)imageURL { 138 | return [self sd_imageURL]; 139 | } 140 | 141 | - (void)setImageWithURL:(NSURL *)url { 142 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 143 | } 144 | 145 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 146 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 147 | } 148 | 149 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 150 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 151 | } 152 | 153 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { 154 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 155 | if (completedBlock) { 156 | completedBlock(image, error, cacheType); 157 | } 158 | }]; 159 | } 160 | 161 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { 162 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 163 | if (completedBlock) { 164 | completedBlock(image, error, cacheType); 165 | } 166 | }]; 167 | } 168 | 169 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 170 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 171 | if (completedBlock) { 172 | completedBlock(image, error, cacheType); 173 | } 174 | }]; 175 | } 176 | 177 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { 178 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 179 | if (completedBlock) { 180 | completedBlock(image, error, cacheType); 181 | } 182 | }]; 183 | } 184 | 185 | - (void)cancelCurrentArrayLoad { 186 | [self sd_cancelCurrentAnimationImagesLoad]; 187 | } 188 | 189 | - (void)cancelCurrentImageLoad { 190 | [self sd_cancelCurrentImageLoad]; 191 | } 192 | 193 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 194 | [self sd_setAnimationImagesWithURLs:arrayOfURLs]; 195 | } 196 | 197 | @end 198 | -------------------------------------------------------------------------------- /tomahawk-ios/UIView+WebCacheOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageManager.h" 11 | 12 | @interface UIView (WebCacheOperation) 13 | 14 | /** 15 | * Set the image load operation (storage in a UIView based dictionary) 16 | * 17 | * @param operation the operation 18 | * @param key key for storing the operation 19 | */ 20 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key; 21 | 22 | /** 23 | * Cancel all operations for the current UIView and key 24 | * 25 | * @param key key for identifying the operations 26 | */ 27 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key; 28 | 29 | /** 30 | * Just remove the operations corresponding to the current UIView and key without cancelling them 31 | * 32 | * @param key key for identifying the operations 33 | */ 34 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key; 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /tomahawk-ios/UIView+WebCacheOperation.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIView+WebCacheOperation.h" 10 | #import "objc/runtime.h" 11 | 12 | static char loadOperationKey; 13 | 14 | @implementation UIView (WebCacheOperation) 15 | 16 | - (NSMutableDictionary *)operationDictionary { 17 | NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); 18 | if (operations) { 19 | return operations; 20 | } 21 | operations = [NSMutableDictionary dictionary]; 22 | objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 23 | return operations; 24 | } 25 | 26 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key { 27 | [self sd_cancelImageLoadOperationWithKey:key]; 28 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 29 | [operationDictionary setObject:operation forKey:key]; 30 | } 31 | 32 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key { 33 | // Cancel in progress downloader from queue 34 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 35 | id operations = [operationDictionary objectForKey:key]; 36 | if (operations) { 37 | if ([operations isKindOfClass:[NSArray class]]) { 38 | for (id operation in operations) { 39 | if (operation) { 40 | [operation cancel]; 41 | } 42 | } 43 | } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ 44 | [(id) operations cancel]; 45 | } 46 | [operationDictionary removeObjectForKey:key]; 47 | } 48 | } 49 | 50 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key { 51 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 52 | [operationDictionary removeObjectForKey:key]; 53 | } 54 | 55 | @end 56 | -------------------------------------------------------------------------------- /tomahawk-ios/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // tomahawk-ios 4 | // 5 | // Created by Shawn Bernard on 3/25/15. 6 | // Copyright (c) 2015 Tomahawk. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /tomahawk-ios/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // tomahawk-ios 4 | // 5 | // Created by Shawn Bernard on 3/25/15. 6 | // Copyright (c) 2015 Tomahawk. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | 11 | @interface ViewController () 12 | 13 | @end 14 | 15 | @implementation ViewController 16 | 17 | - (void)viewDidLoad { 18 | [super viewDidLoad]; 19 | // Do any additional setup after loading the view, typically from a nib. 20 | } 21 | 22 | - (void)didReceiveMemoryWarning { 23 | [super didReceiveMemoryWarning]; 24 | // Dispose of any resources that can be recreated. 25 | } 26 | 27 | @end 28 | -------------------------------------------------------------------------------- /tomahawk-ios/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // tomahawk-ios 4 | // 5 | // Created by Shawn Bernard on 3/25/15. 6 | // Copyright (c) 2015 Tomahawk. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tomahawk-ios/tomahawk_ios.xcdatamodeld/.xccurrentversion: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | _XCCurrentVersionName 6 | tomahawk_ios.xcdatamodel 7 | 8 | 9 | -------------------------------------------------------------------------------- /tomahawk-ios/tomahawk_ios.xcdatamodeld/tomahawk_ios.xcdatamodel/contents: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /tomahawk-iosTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | com.tomahawk.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /tomahawk-iosTests/tomahawk_iosTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // tomahawk_iosTests.m 3 | // tomahawk-iosTests 4 | // 5 | // Created by Shawn Bernard on 3/25/15. 6 | // Copyright (c) 2015 Tomahawk. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @interface tomahawk_iosTests : XCTestCase 13 | 14 | @end 15 | 16 | @implementation tomahawk_iosTests 17 | 18 | - (void)setUp { 19 | [super setUp]; 20 | // Put setup code here. This method is called before the invocation of each test method in the class. 21 | } 22 | 23 | - (void)tearDown { 24 | // Put teardown code here. This method is called after the invocation of each test method in the class. 25 | [super tearDown]; 26 | } 27 | 28 | - (void)testExample { 29 | // This is an example of a functional test case. 30 | XCTAssert(YES, @"Pass"); 31 | } 32 | 33 | - (void)testPerformanceExample { 34 | // This is an example of a performance test case. 35 | [self measureBlock:^{ 36 | // Put the code you want to measure the time of here. 37 | }]; 38 | } 39 | 40 | @end 41 | --------------------------------------------------------------------------------