├── .gitignore ├── README.md ├── RepositoryPattern.xcodeproj └── project.pbxproj └── RepositoryPattern ├── Controllers ├── RPCityViewController.h ├── RPCityViewController.m ├── RPWeatherViewController.h └── RPWeatherViewController.m ├── Libraries └── AFNetworking │ ├── AFHTTPClient.h │ ├── AFHTTPClient.m │ ├── AFHTTPRequestOperation.h │ ├── AFHTTPRequestOperation.m │ ├── AFImageRequestOperation.h │ ├── AFImageRequestOperation.m │ ├── AFJSONRequestOperation.h │ ├── AFJSONRequestOperation.m │ ├── AFNetworkActivityIndicatorManager.h │ ├── AFNetworkActivityIndicatorManager.m │ ├── AFNetworking.h │ ├── AFPropertyListRequestOperation.h │ ├── AFPropertyListRequestOperation.m │ ├── AFURLConnectionOperation.h │ ├── AFURLConnectionOperation.m │ ├── AFXMLRequestOperation.h │ ├── AFXMLRequestOperation.m │ ├── UIImageView+AFNetworking.h │ └── UIImageView+AFNetworking.m ├── Models ├── BaseManagedObjectModel.h ├── BaseManagedObjectModel.m ├── BaseModel.h ├── BaseModel.m ├── City.h ├── City.m ├── Photo.h ├── Photo.m ├── User.h ├── User.m ├── Weather.h ├── Weather.m ├── _City.h ├── _City.m ├── _Photo.h ├── _Photo.m ├── _User.h └── _User.m ├── RPAppDelegate.h ├── RPAppDelegate.m ├── Repositories ├── Fake │ ├── RPFakeCityRepository.h │ └── RPFakeCityRepository.m ├── Generic │ ├── RPGenericRepository.h │ ├── RPGenericRepository.m │ ├── RPICityRepository.h │ ├── RPIDbContext.h │ ├── RPIDbUnitOfWork.h │ ├── RPIRepository.h │ ├── RPIWeatherRepository.h │ └── RPIWeatherRepository.m ├── Implements │ ├── RPCityRepository.h │ ├── RPCityRepository.m │ ├── RPCoreDataContext.h │ ├── RPCoreDataContext.m │ ├── RPCoreDataUnitOfWork.h │ ├── RPCoreDataUnitOfWork.m │ ├── RPWeatherRepository.h │ └── RPWeatherRepository.m └── Supports │ ├── RPHTTPClient.h │ ├── RPHTTPClient.m │ ├── RPNSManagedObjectContext+Queryable.h │ └── RPNSManagedObjectContext+Queryable.m ├── RepositoryPattern-Info.plist ├── RepositoryPattern-Prefix.pch ├── Resource └── RepositoryPattern.xcdatamodeld │ ├── .xccurrentversion │ └── RepositoryPattern.xcdatamodel │ └── contents ├── Views ├── City │ ├── RPCityView.xib │ ├── RPCityViewCell.h │ ├── RPCityViewCell.m │ └── RPCityViewCell.xib └── Weather │ ├── RPWeatherView.xib │ ├── RPWeatherViewCell.h │ ├── RPWeatherViewCell.m │ └── RPWeatherViewCell.xib ├── en.lproj └── InfoPlist.strings └── main.m /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | build/* 3 | *.pbxuser 4 | !default.pbxuser 5 | *.mode1v3 6 | !default.mode1v3 7 | *.mode2v3 8 | !default.mode2v3 9 | *.perspectivev3 10 | !default.perspectivev3 11 | *.xcworkspace 12 | !default.xcworkspace 13 | xcuserdata 14 | profile 15 | *.moved-aside 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Repository-Pattern-in-Objective-C 2 | ================================= 3 | 4 | An implementation of [Repository](http://martinfowler.com/eaaCatalog/repository.html) and [Unit Of Work](http://martinfowler.com/eaaCatalog/unitOfWork.html) pattern in Objective-C. This project provide you a template to implement DAO layer in iOS project, including concurrency update database. 5 | 6 | How to use it? 7 | ================================= 8 | 9 | 1. Create Model classes 10 | --------------------------------- 11 | Start creating your model class using Core Data designer or just create POCO class. Inherit your model classes from BaseModel class or BaseManagedObjectModel class included in project, BaseMode is pure POCO class, BaseManageObjectModel class is class inherited from NSManagedObject class incase you used Core Data designer to generate model classes. See BaseModel and BaseManagedObjectModel class for reference. 12 | 13 | 2. Create Repository classes 14 | --------------------------------- 15 | Drag Repositories and Liraries folder to your project. 16 | 17 |

+ Generic folder:

18 | This folder contains all Repository interfaces. 19 | 20 |

21 | - RPIRepository: generic repository interface, it describe abstract methods for a repository, all your custom repository interface must inherite from this interface. You just don't have to modify anything in this interface, just let it be there. 22 | 23 |

24 | - RPIDbUnitOfWork: this is unit of work interface, it describes all repository properties like this: 25 |

26 | 27 |
28 |

@protocol RPIDbUnitOfWork

29 |

@required

30 |

// User repository for User model

31 |

@property(nonatomic,strong,readonly) id userRepository;

32 |

// Photo repository for Photo model

33 |

@property(nonatomic,strong,readonly) RPIPhotoRepository photoRepository;

34 |

....

35 |

@end

36 |
37 | 38 |

39 | You need to describe repository property to return an instance of repository class. 40 |

41 |

42 |

+ Implements folder:

43 | This folder contains all Repository implementations. 44 |

45 |

46 | - RPCoreDataUnitOfWork: an implementation of RPIDbUnitOfWork interface, you can return an repository instance with your model class without creating new implementation files by define: 47 |

48 |

- (id) xxxRepository{

49 |

return [[RPGenericRepository alloc] initWithDbContext:dbContext withModel:[YOUR_MODEL_CLASS class]];

50 |

}

51 |
52 | Or if you had to create custom repository implementation, just create new one and return its instance like this: 53 |
54 |

- (id) cityRepository{

55 |

return [[RPCityRepository alloc] initWithDbContext:dbContext withModel:[City class]];

56 |

}

57 |
58 | See RPWeatherRepository and RPCityRepository class for example. Simply replace or remove these repositories with your own repositories. 59 |

60 | 61 | 3. Usage through UnitOfWork 62 | --------------------------------- 63 | 64 |

1. Get unit of work single instance

65 | id unitOfWork = [UnitOfWork sharedInstance]; 66 |

2. Get a repository

67 | id repository = [unitOfWork userRepository]; 68 |

3. Make changes

69 | User *user = [repository create]; 70 | user.name = @"User 1"; 71 |

4. Save changes

72 | [unitOfWork saveChanges]; 73 | -------------------------------------------------------------------------------- /RepositoryPattern/Controllers/RPCityViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // CityViewController.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | 11 | @interface RPCityViewController : UIViewController{ 12 | NSArray /*City*/ *_cities; 13 | IBOutlet UITableView *tableView; 14 | } 15 | 16 | @end 17 | -------------------------------------------------------------------------------- /RepositoryPattern/Controllers/RPCityViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // CityViewController.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "RPCityViewController.h" 10 | #import "RPCityViewCell.h" 11 | #import "RPWeatherViewController.h" 12 | 13 | @interface RPCityViewController () 14 | 15 | @end 16 | 17 | @implementation RPCityViewController 18 | 19 | 20 | 21 | - (void)viewDidLoad 22 | { 23 | [super viewDidLoad]; 24 | self.title = @"My Favorite Cities"; 25 | // Do any additional setup after loading the view. 26 | [[dbUnitOfWork cityRepository] getCityFeed:^(NSArray *cities) { 27 | _cities = cities; 28 | id result = [[dbUnitOfWork cityRepository] find:@"name == 'Seoul' or name == 'Jakatar'"]; 29 | NSLog(@"query result: %@",result); 30 | [tableView reloadData]; 31 | } fail:^(int statusCode, NSError *error) { 32 | UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 33 | message:[error description] 34 | delegate:nil 35 | cancelButtonTitle:@"" 36 | otherButtonTitles:@"OK", nil]; 37 | [alert show]; 38 | }]; 39 | } 40 | 41 | - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 42 | return 1; 43 | } 44 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 45 | return [_cities count]; 46 | } 47 | 48 | - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 49 | return 44; 50 | } 51 | - (UITableViewCell*) tableView:tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 52 | RPCityViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"RPCityViewCell" owner:nil options:nil] objectAtIndex:0]; 53 | City *city = [_cities objectAtIndex:indexPath.row]; 54 | [cell setCity:city]; 55 | [cell bindData]; 56 | return cell; 57 | } 58 | 59 | -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 60 | id weather = [[RPWeatherViewController alloc] initWithNibName:@"RPWeatherView" bundle:nil]; 61 | [self.navigationController pushViewController:weather animated:YES]; 62 | } 63 | @end 64 | -------------------------------------------------------------------------------- /RepositoryPattern/Controllers/RPWeatherViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPWeatherViewController.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | #import "Weather.h" 11 | #import "RPWeatherViewCell.h" 12 | 13 | @interface RPWeatherViewController : UIViewController{ 14 | IBOutlet UITableView *tableView; 15 | NSArray /*weather*/ *_weathers; 16 | } 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /RepositoryPattern/Controllers/RPWeatherViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPWeatherViewController.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "RPWeatherViewController.h" 10 | 11 | @interface RPWeatherViewController () 12 | 13 | @end 14 | 15 | @implementation RPWeatherViewController 16 | 17 | - (void)viewDidLoad 18 | { 19 | [super viewDidLoad]; 20 | self.title = @"Weather Feed"; 21 | // Do any additional setup after loading the view. 22 | [[dbUnitOfWork weatherRepository] getWeatherFeed:^(NSArray *items) { 23 | _weathers = items; 24 | [tableView reloadData]; 25 | } fail:^(int statusCode, NSError *error) { 26 | UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 27 | message:[error description] 28 | delegate:nil 29 | cancelButtonTitle:@"" 30 | otherButtonTitles:@"OK", nil]; 31 | [alert show]; 32 | }]; 33 | } 34 | 35 | - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 36 | return 1; 37 | } 38 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 39 | return [_weathers count]; 40 | } 41 | 42 | - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 43 | return 44; 44 | } 45 | - (UITableViewCell*) tableView:tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 46 | RPWeatherViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"RPWeatherViewCell" owner:nil options:nil] objectAtIndex:0]; 47 | Weather *weather = [_weathers objectAtIndex:indexPath.row]; 48 | [cell setWeather:weather]; 49 | [cell bindData]; 50 | return cell; 51 | } 52 | 53 | -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 54 | id weather = [[RPWeatherViewController alloc] initWithNibName:@"RPWeatherView" bundle:nil]; 55 | [self.navigationController pushViewController:weather animated:YES]; 56 | } 57 | 58 | @end 59 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFHTTPRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 | /// @name Managing And Checking For Acceptable HTTP Responses 42 | ///---------------------------------------------------------- 43 | 44 | /** 45 | A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`. 46 | */ 47 | @property (readonly) BOOL hasAcceptableStatusCode; 48 | 49 | /** 50 | A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`. 51 | */ 52 | @property (readonly) BOOL hasAcceptableContentType; 53 | 54 | /** 55 | The callback dispatch queue on success. If `NULL` (default), the main queue is used. 56 | */ 57 | @property (nonatomic, assign) dispatch_queue_t successCallbackQueue; 58 | 59 | /** 60 | The callback dispatch queue on failure. If `NULL` (default), the main queue is used. 61 | */ 62 | @property (nonatomic, assign) dispatch_queue_t failureCallbackQueue; 63 | 64 | ///------------------------------------------------------------ 65 | /// @name Managing Acceptable HTTP Status Codes & Content Types 66 | ///------------------------------------------------------------ 67 | 68 | /** 69 | Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 70 | 71 | By default, this is the range 200 to 299, inclusive. 72 | */ 73 | + (NSIndexSet *)acceptableStatusCodes; 74 | 75 | /** 76 | Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants. 77 | 78 | @param statusCodes The status codes to be added to the set of acceptable HTTP status codes 79 | */ 80 | + (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes; 81 | 82 | /** 83 | Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17 84 | 85 | By default, this is `nil`. 86 | */ 87 | + (NSSet *)acceptableContentTypes; 88 | 89 | /** 90 | Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendants. 91 | 92 | @param contentTypes The content types to be added to the set of acceptable MIME types 93 | */ 94 | + (void)addAcceptableContentTypes:(NSSet *)contentTypes; 95 | 96 | 97 | ///----------------------------------------------------- 98 | /// @name Determining Whether A Request Can Be Processed 99 | ///----------------------------------------------------- 100 | 101 | /** 102 | A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`. 103 | 104 | @param urlRequest The request that is determined to be supported or not supported for this class. 105 | */ 106 | + (BOOL)canProcessRequest:(NSURLRequest *)urlRequest; 107 | 108 | ///----------------------------------------------------------- 109 | /// @name Setting Completion Block Success / Failure Callbacks 110 | ///----------------------------------------------------------- 111 | 112 | /** 113 | 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. 114 | 115 | @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. 116 | @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. 117 | 118 | @discussion This method should be overridden in subclasses in order to specify the response object passed into the success block. 119 | */ 120 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 121 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 122 | 123 | @end 124 | 125 | ///---------------- 126 | /// @name Functions 127 | ///---------------- 128 | 129 | /** 130 | Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header. 131 | */ 132 | extern NSSet * AFContentTypesFromHTTPHeader(NSString *string); 133 | 134 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFHTTPRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 | #import 25 | 26 | // Workaround for change in imp_implementationWithBlock() with Xcode 4.5 27 | #if defined(__IPHONE_6_0) || defined(__MAC_10_8) 28 | #define AF_CAST_TO_BLOCK id 29 | #else 30 | #define AF_CAST_TO_BLOCK __bridge void * 31 | #endif 32 | 33 | NSSet * AFContentTypesFromHTTPHeader(NSString *string) { 34 | if (!string) { 35 | return nil; 36 | } 37 | 38 | NSArray *mediaRanges = [string componentsSeparatedByString:@","]; 39 | NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count]; 40 | 41 | [mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, NSUInteger idx, BOOL *stop) { 42 | NSRange parametersRange = [mediaRange rangeOfString:@";"]; 43 | if (parametersRange.location != NSNotFound) { 44 | mediaRange = [mediaRange substringToIndex:parametersRange.location]; 45 | } 46 | 47 | mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 48 | 49 | if (mediaRange.length > 0) { 50 | [mutableContentTypes addObject:mediaRange]; 51 | } 52 | }]; 53 | 54 | return [NSSet setWithSet:mutableContentTypes]; 55 | } 56 | 57 | static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) { 58 | NSMutableString *string = [NSMutableString string]; 59 | 60 | NSRange range = NSMakeRange([indexSet firstIndex], 1); 61 | while (range.location != NSNotFound) { 62 | NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location]; 63 | while (nextIndex == range.location + range.length) { 64 | range.length++; 65 | nextIndex = [indexSet indexGreaterThanIndex:nextIndex]; 66 | } 67 | 68 | if (string.length) { 69 | [string appendString:@","]; 70 | } 71 | 72 | if (range.length == 1) { 73 | [string appendFormat:@"%lu", (long)range.location]; 74 | } else { 75 | NSUInteger firstIndex = range.location; 76 | NSUInteger lastIndex = firstIndex + range.length - 1; 77 | [string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex]; 78 | } 79 | 80 | range.location = nextIndex; 81 | range.length = 1; 82 | } 83 | 84 | return string; 85 | } 86 | 87 | static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) { 88 | Method originalMethod = class_getClassMethod(klass, selector); 89 | IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block); 90 | class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod)); 91 | } 92 | 93 | #pragma mark - 94 | 95 | @interface AFHTTPRequestOperation () 96 | @property (readwrite, nonatomic, strong) NSURLRequest *request; 97 | @property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; 98 | @property (readwrite, nonatomic, strong) NSError *HTTPError; 99 | @property (assign) long long totalContentLength; 100 | @property (assign) long long offsetContentLength; 101 | @end 102 | 103 | @implementation AFHTTPRequestOperation 104 | @synthesize HTTPError = _HTTPError; 105 | @synthesize successCallbackQueue = _successCallbackQueue; 106 | @synthesize failureCallbackQueue = _failureCallbackQueue; 107 | @synthesize totalContentLength = _totalContentLength; 108 | @synthesize offsetContentLength = _offsetContentLength; 109 | @dynamic request; 110 | @dynamic response; 111 | 112 | - (void)dealloc { 113 | if (_successCallbackQueue) { 114 | #if !OS_OBJECT_USE_OBJC 115 | dispatch_release(_successCallbackQueue); 116 | #endif 117 | _successCallbackQueue = NULL; 118 | } 119 | 120 | if (_failureCallbackQueue) { 121 | #if !OS_OBJECT_USE_OBJC 122 | dispatch_release(_failureCallbackQueue); 123 | #endif 124 | _failureCallbackQueue = NULL; 125 | } 126 | } 127 | 128 | - (NSError *)error { 129 | if (self.response && !self.HTTPError) { 130 | if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) { 131 | NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; 132 | [userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey]; 133 | [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; 134 | [userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey]; 135 | [userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey]; 136 | 137 | if (![self hasAcceptableStatusCode]) { 138 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; 139 | [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code in (%@), got %d", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey]; 140 | self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo]; 141 | } else if (![self hasAcceptableContentType]) { 142 | // Don't invalidate content type if there is no content 143 | if ([self.responseData length] > 0) { 144 | [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey]; 145 | self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; 146 | } 147 | } 148 | } 149 | } 150 | 151 | if (self.HTTPError) { 152 | return self.HTTPError; 153 | } else { 154 | return [super error]; 155 | } 156 | } 157 | 158 | - (void)pause { 159 | unsigned long long offset = 0; 160 | if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { 161 | offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; 162 | } else { 163 | offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; 164 | } 165 | 166 | NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; 167 | if ([[self.response allHeaderFields] valueForKey:@"ETag"]) { 168 | [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; 169 | } 170 | [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; 171 | self.request = mutableURLRequest; 172 | 173 | [super pause]; 174 | } 175 | 176 | - (BOOL)hasAcceptableStatusCode { 177 | if (!self.response) { 178 | return NO; 179 | } 180 | 181 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; 182 | return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode]; 183 | } 184 | 185 | - (BOOL)hasAcceptableContentType { 186 | if (!self.response) { 187 | return NO; 188 | } 189 | 190 | // According to RFC 2616: 191 | // Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream". 192 | // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html 193 | NSString *contentType = [self.response MIMEType]; 194 | if (!contentType) { 195 | contentType = @"application/octet-stream"; 196 | } 197 | 198 | return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType]; 199 | } 200 | 201 | - (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue { 202 | if (successCallbackQueue != _successCallbackQueue) { 203 | if (_successCallbackQueue) { 204 | #if !OS_OBJECT_USE_OBJC 205 | dispatch_release(_successCallbackQueue); 206 | #endif 207 | _successCallbackQueue = NULL; 208 | } 209 | 210 | if (successCallbackQueue) { 211 | #if !OS_OBJECT_USE_OBJC 212 | dispatch_retain(successCallbackQueue); 213 | #endif 214 | _successCallbackQueue = successCallbackQueue; 215 | } 216 | } 217 | } 218 | 219 | - (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue { 220 | if (failureCallbackQueue != _failureCallbackQueue) { 221 | if (_failureCallbackQueue) { 222 | #if !OS_OBJECT_USE_OBJC 223 | dispatch_release(_failureCallbackQueue); 224 | #endif 225 | _failureCallbackQueue = NULL; 226 | } 227 | 228 | if (failureCallbackQueue) { 229 | #if !OS_OBJECT_USE_OBJC 230 | dispatch_retain(failureCallbackQueue); 231 | #endif 232 | _failureCallbackQueue = failureCallbackQueue; 233 | } 234 | } 235 | } 236 | 237 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 238 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 239 | { 240 | // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. 241 | #pragma clang diagnostic push 242 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 243 | self.completionBlock = ^{ 244 | if ([self isCancelled]) { 245 | return; 246 | } 247 | 248 | if (self.error) { 249 | if (failure) { 250 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 251 | failure(self, self.error); 252 | }); 253 | } 254 | } else { 255 | if (success) { 256 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 257 | success(self, self.responseData); 258 | }); 259 | } 260 | } 261 | }; 262 | #pragma clang diagnostic pop 263 | } 264 | 265 | #pragma mark - AFHTTPRequestOperation 266 | 267 | + (NSIndexSet *)acceptableStatusCodes { 268 | return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; 269 | } 270 | 271 | + (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes { 272 | NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]]; 273 | [mutableStatusCodes addIndexes:statusCodes]; 274 | AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(id _self) { 275 | return mutableStatusCodes; 276 | }); 277 | } 278 | 279 | + (NSSet *)acceptableContentTypes { 280 | return nil; 281 | } 282 | 283 | + (void)addAcceptableContentTypes:(NSSet *)contentTypes { 284 | NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES]; 285 | [mutableContentTypes unionSet:contentTypes]; 286 | AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(id _self) { 287 | return mutableContentTypes; 288 | }); 289 | } 290 | 291 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 292 | if ([[self class] isEqual:[AFHTTPRequestOperation class]]) { 293 | return YES; 294 | } 295 | 296 | return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])]; 297 | } 298 | 299 | #pragma mark - NSURLConnectionDelegate 300 | 301 | - (void)connection:(NSURLConnection *)connection 302 | didReceiveResponse:(NSURLResponse *)response 303 | { 304 | self.response = (NSHTTPURLResponse *)response; 305 | 306 | // Set Content-Range header if status code of response is 206 (Partial Content) 307 | // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7 308 | long long totalContentLength = self.response.expectedContentLength; 309 | long long fileOffset = 0; 310 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; 311 | if (statusCode == 206) { 312 | NSString *contentRange = [self.response.allHeaderFields valueForKey:@"Content-Range"]; 313 | if ([contentRange hasPrefix:@"bytes"]) { 314 | NSArray *byteRanges = [contentRange componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" -/"]]; 315 | if ([byteRanges count] == 4) { 316 | fileOffset = [[byteRanges objectAtIndex:1] longLongValue]; 317 | totalContentLength = [[byteRanges objectAtIndex:2] longLongValue] ?: -1; // if this is "*", it's converted to 0, but -1 is default. 318 | } 319 | } 320 | } else { 321 | if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { 322 | [self.outputStream setProperty:[NSNumber numberWithInteger:0] forKey:NSStreamFileCurrentOffsetKey]; 323 | } else { 324 | if ([[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length] > 0) { 325 | self.outputStream = [NSOutputStream outputStreamToMemory]; 326 | 327 | NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; 328 | for (NSString *runLoopMode in self.runLoopModes) { 329 | [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; 330 | } 331 | } 332 | } 333 | } 334 | 335 | self.offsetContentLength = MAX(fileOffset, 0); 336 | self.totalContentLength = totalContentLength; 337 | 338 | [self.outputStream open]; 339 | } 340 | 341 | @end 342 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFImageRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFImageRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFHTTPRequestOperation.h" 25 | 26 | #import 27 | 28 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 29 | #import 30 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 31 | #import 32 | #endif 33 | 34 | /** 35 | `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images. 36 | 37 | ## Acceptable Content Types 38 | 39 | By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: 40 | 41 | - `image/tiff` 42 | - `image/jpeg` 43 | - `image/gif` 44 | - `image/png` 45 | - `image/ico` 46 | - `image/x-icon` 47 | - `image/bmp` 48 | - `image/x-bmp` 49 | - `image/x-xbitmap` 50 | - `image/x-win-bitmap` 51 | */ 52 | @interface AFImageRequestOperation : AFHTTPRequestOperation 53 | 54 | /** 55 | An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error. 56 | */ 57 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 58 | @property (readonly, nonatomic, strong) UIImage *responseImage; 59 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 60 | @property (readonly, nonatomic, strong) NSImage *responseImage; 61 | #endif 62 | 63 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 64 | /** 65 | The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. 66 | */ 67 | @property (nonatomic, assign) CGFloat imageScale; 68 | #endif 69 | 70 | /** 71 | Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. 72 | 73 | @param urlRequest The request object to be loaded asynchronously during execution of the operation. 74 | @param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single arguments, the image created from the response data of the request. 75 | 76 | @return A new image request operation 77 | */ 78 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 79 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 80 | success:(void (^)(UIImage *image))success; 81 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 82 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 83 | success:(void (^)(NSImage *image))success; 84 | #endif 85 | 86 | /** 87 | Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. 88 | 89 | @param urlRequest The request object to be loaded asynchronously during execution of the operation. 90 | @param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image. 91 | @param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data. 92 | @param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation. 93 | 94 | @return A new image request operation 95 | */ 96 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 97 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 98 | imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock 99 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 100 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; 101 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 102 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 103 | imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock 104 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success 105 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; 106 | #endif 107 | 108 | @end 109 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFImageRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFImageRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFImageRequestOperation.h" 24 | 25 | static dispatch_queue_t af_image_request_operation_processing_queue; 26 | static dispatch_queue_t image_request_operation_processing_queue() { 27 | if (af_image_request_operation_processing_queue == NULL) { 28 | af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0); 29 | } 30 | 31 | return af_image_request_operation_processing_queue; 32 | } 33 | 34 | @interface AFImageRequestOperation () 35 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 36 | @property (readwrite, nonatomic, strong) UIImage *responseImage; 37 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 38 | @property (readwrite, nonatomic, strong) NSImage *responseImage; 39 | #endif 40 | @end 41 | 42 | @implementation AFImageRequestOperation 43 | @synthesize responseImage = _responseImage; 44 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 45 | @synthesize imageScale = _imageScale; 46 | #endif 47 | 48 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 49 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 50 | success:(void (^)(UIImage *image))success 51 | { 52 | return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) { 53 | if (success) { 54 | success(image); 55 | } 56 | } failure:nil]; 57 | } 58 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 59 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 60 | success:(void (^)(NSImage *image))success 61 | { 62 | return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) { 63 | if (success) { 64 | success(image); 65 | } 66 | } failure:nil]; 67 | } 68 | #endif 69 | 70 | 71 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 72 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 73 | imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock 74 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 75 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure 76 | { 77 | AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest]; 78 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 79 | if (success) { 80 | UIImage *image = responseObject; 81 | if (imageProcessingBlock) { 82 | dispatch_async(image_request_operation_processing_queue(), ^(void) { 83 | UIImage *processedImage = imageProcessingBlock(image); 84 | 85 | dispatch_async(requestOperation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { 86 | success(operation.request, operation.response, processedImage); 87 | }); 88 | }); 89 | } else { 90 | success(operation.request, operation.response, image); 91 | } 92 | } 93 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 94 | if (failure) { 95 | failure(operation.request, operation.response, error); 96 | } 97 | }]; 98 | 99 | 100 | return requestOperation; 101 | } 102 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 103 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 104 | imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock 105 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success 106 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure 107 | { 108 | AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest]; 109 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 110 | if (success) { 111 | NSImage *image = responseObject; 112 | if (imageProcessingBlock) { 113 | dispatch_async(image_request_operation_processing_queue(), ^(void) { 114 | NSImage *processedImage = imageProcessingBlock(image); 115 | 116 | dispatch_async(requestOperation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { 117 | success(operation.request, operation.response, processedImage); 118 | }); 119 | }); 120 | } else { 121 | success(operation.request, operation.response, image); 122 | } 123 | } 124 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 125 | if (failure) { 126 | failure(operation.request, operation.response, error); 127 | } 128 | }]; 129 | 130 | return requestOperation; 131 | } 132 | #endif 133 | 134 | - (id)initWithRequest:(NSURLRequest *)urlRequest { 135 | self = [super initWithRequest:urlRequest]; 136 | if (!self) { 137 | return nil; 138 | } 139 | 140 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 141 | self.imageScale = [[UIScreen mainScreen] scale]; 142 | #endif 143 | 144 | return self; 145 | } 146 | 147 | 148 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 149 | - (UIImage *)responseImage { 150 | if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { 151 | UIImage *image = [UIImage imageWithData:self.responseData]; 152 | 153 | self.responseImage = [UIImage imageWithCGImage:[image CGImage] scale:self.imageScale orientation:image.imageOrientation]; 154 | } 155 | 156 | return _responseImage; 157 | } 158 | 159 | - (void)setImageScale:(CGFloat)imageScale { 160 | #pragma clang diagnostic push 161 | #pragma clang diagnostic ignored "-Wfloat-equal" 162 | if (imageScale == _imageScale) { 163 | return; 164 | } 165 | #pragma clang diagnostic pop 166 | 167 | _imageScale = imageScale; 168 | 169 | self.responseImage = nil; 170 | } 171 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 172 | - (NSImage *)responseImage { 173 | if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { 174 | // Ensure that the image is set to it's correct pixel width and height 175 | NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData]; 176 | self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; 177 | [self.responseImage addRepresentation:bitimage]; 178 | } 179 | 180 | return _responseImage; 181 | } 182 | #endif 183 | 184 | #pragma mark - AFHTTPRequestOperation 185 | 186 | + (NSSet *)acceptableContentTypes { 187 | return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; 188 | } 189 | 190 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 191 | static NSSet * _acceptablePathExtension = nil; 192 | static dispatch_once_t onceToken; 193 | dispatch_once(&onceToken, ^{ 194 | _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; 195 | }); 196 | 197 | return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request]; 198 | } 199 | 200 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 201 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 202 | { 203 | #pragma clang diagnostic push 204 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 205 | self.completionBlock = ^ { 206 | if ([self isCancelled]) { 207 | return; 208 | } 209 | 210 | dispatch_async(image_request_operation_processing_queue(), ^(void) { 211 | if (self.error) { 212 | if (failure) { 213 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 214 | failure(self, self.error); 215 | }); 216 | } 217 | } else { 218 | if (success) { 219 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 220 | UIImage *image = nil; 221 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 222 | NSImage *image = nil; 223 | #endif 224 | 225 | image = self.responseImage; 226 | 227 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 228 | success(self, image); 229 | }); 230 | } 231 | } 232 | }); 233 | }; 234 | #pragma clang diagnostic pop 235 | } 236 | 237 | @end 238 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFJSONRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFJSONRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFHTTPRequestOperation.h" 25 | 26 | /** 27 | `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data. 28 | 29 | ## Acceptable Content Types 30 | 31 | By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: 32 | 33 | - `application/json` 34 | - `text/json` 35 | 36 | @warning JSON parsing will use the built-in `NSJSONSerialization` class. 37 | */ 38 | @interface AFJSONRequestOperation : AFHTTPRequestOperation 39 | 40 | ///---------------------------- 41 | /// @name Getting Response Data 42 | ///---------------------------- 43 | 44 | /** 45 | A JSON object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error. 46 | */ 47 | @property (readonly, nonatomic, strong) id responseJSON; 48 | 49 | /** 50 | Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". 51 | */ 52 | @property (nonatomic, assign) NSJSONReadingOptions JSONReadingOptions; 53 | 54 | ///---------------------------------- 55 | /// @name Creating Request Operations 56 | ///---------------------------------- 57 | 58 | /** 59 | Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks. 60 | 61 | @param urlRequest The request object to be loaded asynchronously during execution of the operation 62 | @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the JSON object created from the response data of request. 63 | @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as JSON. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. 64 | 65 | @return A new JSON request operation 66 | */ 67 | + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest 68 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 69 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure; 70 | 71 | @end 72 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFJSONRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFJSONRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFJSONRequestOperation.h" 24 | 25 | static dispatch_queue_t af_json_request_operation_processing_queue; 26 | static dispatch_queue_t json_request_operation_processing_queue() { 27 | if (af_json_request_operation_processing_queue == NULL) { 28 | af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", 0); 29 | } 30 | 31 | return af_json_request_operation_processing_queue; 32 | } 33 | 34 | @interface AFJSONRequestOperation () 35 | @property (readwrite, nonatomic, strong) id responseJSON; 36 | @property (readwrite, nonatomic, strong) NSError *JSONError; 37 | @end 38 | 39 | @implementation AFJSONRequestOperation 40 | @synthesize responseJSON = _responseJSON; 41 | @synthesize JSONReadingOptions = _JSONReadingOptions; 42 | @synthesize JSONError = _JSONError; 43 | 44 | + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest 45 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 46 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure 47 | { 48 | AFJSONRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; 49 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 50 | if (success) { 51 | success(operation.request, operation.response, responseObject); 52 | } 53 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 54 | if (failure) { 55 | failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]); 56 | } 57 | }]; 58 | 59 | return requestOperation; 60 | } 61 | 62 | 63 | - (id)responseJSON { 64 | if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) { 65 | NSError *error = nil; 66 | 67 | if ([self.responseData length] == 0) { 68 | self.responseJSON = nil; 69 | } else { 70 | self.responseJSON = [NSJSONSerialization JSONObjectWithData:self.responseData options:self.JSONReadingOptions error:&error]; 71 | } 72 | 73 | self.JSONError = error; 74 | } 75 | 76 | return _responseJSON; 77 | } 78 | 79 | - (NSError *)error { 80 | if (_JSONError) { 81 | return _JSONError; 82 | } else { 83 | return [super error]; 84 | } 85 | } 86 | 87 | #pragma mark - AFHTTPRequestOperation 88 | 89 | + (NSSet *)acceptableContentTypes { 90 | return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; 91 | } 92 | 93 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 94 | return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request]; 95 | } 96 | 97 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 98 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 99 | { 100 | #pragma clang diagnostic push 101 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 102 | self.completionBlock = ^ { 103 | if ([self isCancelled]) { 104 | return; 105 | } 106 | 107 | if (self.error) { 108 | if (failure) { 109 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 110 | failure(self, self.error); 111 | }); 112 | } 113 | } else { 114 | dispatch_async(json_request_operation_processing_queue(), ^{ 115 | id JSON = self.responseJSON; 116 | 117 | if (self.JSONError) { 118 | if (failure) { 119 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 120 | failure(self, self.error); 121 | }); 122 | } 123 | } else { 124 | if (success) { 125 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 126 | success(self, JSON); 127 | }); 128 | } 129 | } 130 | }); 131 | } 132 | }; 133 | #pragma clang diagnostic pop 134 | } 135 | 136 | @end 137 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFNetworkActivityIndicatorManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 | 25 | #import 26 | 27 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 28 | #import 29 | 30 | /** 31 | `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. 32 | 33 | You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: 34 | 35 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 36 | 37 | By setting `isNetworkActivityIndicatorVisible` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. 38 | 39 | See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: 40 | http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 41 | */ 42 | @interface AFNetworkActivityIndicatorManager : NSObject 43 | 44 | /** 45 | A Boolean value indicating whether the manager is enabled. 46 | 47 | @discussion If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. 48 | */ 49 | @property (nonatomic, assign, getter = isEnabled) BOOL enabled; 50 | 51 | /** 52 | A Boolean value indicating whether the network activity indicator is currently displayed in the status bar. 53 | */ 54 | @property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible; 55 | 56 | /** 57 | Returns the shared network activity indicator manager object for the system. 58 | 59 | @return The systemwide network activity indicator manager. 60 | */ 61 | + (AFNetworkActivityIndicatorManager *)sharedManager; 62 | 63 | /** 64 | Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. 65 | */ 66 | - (void)incrementActivityCount; 67 | 68 | /** 69 | Decrements the number of active network requests. If this number becomes zero before decrementing, this will stop animating the status bar network activity indicator. 70 | */ 71 | - (void)decrementActivityCount; 72 | 73 | @end 74 | 75 | #endif 76 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFNetworkActivityIndicatorManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFNetworkActivityIndicatorManager.h" 24 | 25 | #import "AFHTTPRequestOperation.h" 26 | 27 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 28 | static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17; 29 | 30 | @interface AFNetworkActivityIndicatorManager () 31 | @property (readwrite, assign) NSInteger activityCount; 32 | @property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer; 33 | @property (readonly, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; 34 | 35 | - (void)updateNetworkActivityIndicatorVisibility; 36 | - (void)updateNetworkActivityIndicatorVisibilityDelayed; 37 | @end 38 | 39 | @implementation AFNetworkActivityIndicatorManager 40 | @synthesize activityCount = _activityCount; 41 | @synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer; 42 | @synthesize enabled = _enabled; 43 | @dynamic networkActivityIndicatorVisible; 44 | 45 | + (AFNetworkActivityIndicatorManager *)sharedManager { 46 | static AFNetworkActivityIndicatorManager *_sharedManager = nil; 47 | static dispatch_once_t oncePredicate; 48 | dispatch_once(&oncePredicate, ^{ 49 | _sharedManager = [[self alloc] init]; 50 | }); 51 | 52 | return _sharedManager; 53 | } 54 | 55 | + (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible { 56 | return [NSSet setWithObject:@"activityCount"]; 57 | } 58 | 59 | - (id)init { 60 | self = [super init]; 61 | if (!self) { 62 | return nil; 63 | } 64 | 65 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil]; 66 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil]; 67 | 68 | return self; 69 | } 70 | 71 | - (void)dealloc { 72 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 73 | 74 | [_activityIndicatorVisibilityTimer invalidate]; 75 | 76 | } 77 | 78 | - (void)updateNetworkActivityIndicatorVisibilityDelayed { 79 | if (self.enabled) { 80 | // Delay hiding of activity indicator for a short interval, to avoid flickering 81 | if (![self isNetworkActivityIndicatorVisible]) { 82 | [self.activityIndicatorVisibilityTimer invalidate]; 83 | self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO]; 84 | [[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes]; 85 | } else { 86 | [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; 87 | } 88 | } 89 | } 90 | 91 | - (BOOL)isNetworkActivityIndicatorVisible { 92 | return _activityCount > 0; 93 | } 94 | 95 | - (void)updateNetworkActivityIndicatorVisibility { 96 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]]; 97 | } 98 | 99 | // Not exposed, but used if activityCount is set via KVC. 100 | - (NSInteger)activityCount { 101 | return _activityCount; 102 | } 103 | 104 | - (void)setActivityCount:(NSInteger)activityCount { 105 | @synchronized(self) { 106 | _activityCount = activityCount; 107 | } 108 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 109 | } 110 | 111 | - (void)incrementActivityCount { 112 | [self willChangeValueForKey:@"activityCount"]; 113 | @synchronized(self) { 114 | _activityCount++; 115 | } 116 | [self didChangeValueForKey:@"activityCount"]; 117 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 118 | } 119 | 120 | - (void)decrementActivityCount { 121 | [self willChangeValueForKey:@"activityCount"]; 122 | @synchronized(self) { 123 | _activityCount = MAX(_activityCount - 1, 0); 124 | } 125 | [self didChangeValueForKey:@"activityCount"]; 126 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 127 | } 128 | 129 | @end 130 | 131 | #endif 132 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFNetworking.h: -------------------------------------------------------------------------------- 1 | // AFNetworking.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFURLConnectionOperation.h" 30 | 31 | #import "AFHTTPRequestOperation.h" 32 | #import "AFJSONRequestOperation.h" 33 | #import "AFXMLRequestOperation.h" 34 | #import "AFPropertyListRequestOperation.h" 35 | #import "AFHTTPClient.h" 36 | 37 | #import "AFImageRequestOperation.h" 38 | 39 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 40 | #import "AFNetworkActivityIndicatorManager.h" 41 | #import "UIImageView+AFNetworking.h" 42 | #endif 43 | #endif /* _AFNETWORKING_ */ 44 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFPropertyListRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFPropertyListRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFHTTPRequestOperation.h" 25 | 26 | /** 27 | `AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data. 28 | 29 | ## Acceptable Content Types 30 | 31 | By default, `AFPropertyListRequestOperation` accepts the following MIME types: 32 | 33 | - `application/x-plist` 34 | */ 35 | @interface AFPropertyListRequestOperation : AFHTTPRequestOperation 36 | 37 | ///---------------------------- 38 | /// @name Getting Response Data 39 | ///---------------------------- 40 | 41 | /** 42 | An object deserialized from a plist constructed using the response data. 43 | */ 44 | @property (readonly, nonatomic) id responsePropertyList; 45 | 46 | ///-------------------------------------- 47 | /// @name Managing Property List Behavior 48 | ///-------------------------------------- 49 | 50 | /** 51 | One of the `NSPropertyListMutabilityOptions` options, specifying the mutability of objects deserialized from the property list. By default, this is `NSPropertyListImmutable`. 52 | */ 53 | @property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions; 54 | 55 | /** 56 | Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks. 57 | 58 | @param urlRequest The request object to be loaded asynchronously during execution of the operation 59 | @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the object deserialized from a plist constructed using the response data. 60 | @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. 61 | 62 | @return A new property list request operation 63 | */ 64 | + (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest 65 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success 66 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure; 67 | 68 | @end 69 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFPropertyListRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFPropertyListRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFPropertyListRequestOperation.h" 24 | 25 | static dispatch_queue_t af_property_list_request_operation_processing_queue; 26 | static dispatch_queue_t property_list_request_operation_processing_queue() { 27 | if (af_property_list_request_operation_processing_queue == NULL) { 28 | af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", 0); 29 | } 30 | 31 | return af_property_list_request_operation_processing_queue; 32 | } 33 | 34 | @interface AFPropertyListRequestOperation () 35 | @property (readwrite, nonatomic) id responsePropertyList; 36 | @property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat; 37 | @property (readwrite, nonatomic) NSError *propertyListError; 38 | @end 39 | 40 | @implementation AFPropertyListRequestOperation 41 | @synthesize responsePropertyList = _responsePropertyList; 42 | @synthesize propertyListReadOptions = _propertyListReadOptions; 43 | @synthesize propertyListFormat = _propertyListFormat; 44 | @synthesize propertyListError = _propertyListError; 45 | 46 | + (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)request 47 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success 48 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure 49 | { 50 | AFPropertyListRequestOperation *requestOperation = [[self alloc] initWithRequest:request]; 51 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 52 | if (success) { 53 | success(operation.request, operation.response, responseObject); 54 | } 55 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 56 | if (failure) { 57 | failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]); 58 | } 59 | }]; 60 | 61 | return requestOperation; 62 | } 63 | 64 | - (id)initWithRequest:(NSURLRequest *)urlRequest { 65 | self = [super initWithRequest:urlRequest]; 66 | if (!self) { 67 | return nil; 68 | } 69 | 70 | self.propertyListReadOptions = NSPropertyListImmutable; 71 | 72 | return self; 73 | } 74 | 75 | 76 | - (id)responsePropertyList { 77 | if (!_responsePropertyList && [self.responseData length] > 0 && [self isFinished]) { 78 | NSPropertyListFormat format; 79 | NSError *error = nil; 80 | self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error]; 81 | self.propertyListFormat = format; 82 | self.propertyListError = error; 83 | } 84 | 85 | return _responsePropertyList; 86 | } 87 | 88 | - (NSError *)error { 89 | if (_propertyListError) { 90 | return _propertyListError; 91 | } else { 92 | return [super error]; 93 | } 94 | } 95 | 96 | #pragma mark - AFHTTPRequestOperation 97 | 98 | + (NSSet *)acceptableContentTypes { 99 | return [NSSet setWithObjects:@"application/x-plist", nil]; 100 | } 101 | 102 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 103 | return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request]; 104 | } 105 | 106 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 107 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 108 | { 109 | #pragma clang diagnostic push 110 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 111 | self.completionBlock = ^ { 112 | if ([self isCancelled]) { 113 | return; 114 | } 115 | 116 | if (self.error) { 117 | if (failure) { 118 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 119 | failure(self, self.error); 120 | }); 121 | } 122 | } else { 123 | dispatch_async(property_list_request_operation_processing_queue(), ^(void) { 124 | id propertyList = self.responsePropertyList; 125 | 126 | if (self.propertyListError) { 127 | if (failure) { 128 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 129 | failure(self, self.error); 130 | }); 131 | } 132 | } else { 133 | if (success) { 134 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 135 | success(self, propertyList); 136 | }); 137 | } 138 | } 139 | }); 140 | } 141 | }; 142 | #pragma clang diagnostic pop 143 | } 144 | 145 | @end 146 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFURLConnectionOperation.h: -------------------------------------------------------------------------------- 1 | // AFURLConnectionOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 | 25 | #import 26 | 27 | /** 28 | `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods. 29 | 30 | ## Subclassing Notes 31 | 32 | This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors. 33 | 34 | If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. 35 | 36 | ## NSURLConnection Delegate Methods 37 | 38 | `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: 39 | 40 | - `connection:didReceiveResponse:` 41 | - `connection:didReceiveData:` 42 | - `connectionDidFinishLoading:` 43 | - `connection:didFailWithError:` 44 | - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:` 45 | - `connection:willCacheResponse:` 46 | - `connection:canAuthenticateAgainstProtectionSpace:` 47 | - `connection:didReceiveAuthenticationChallenge:` 48 | 49 | If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. 50 | 51 | ## Class Constructors 52 | 53 | Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`. 54 | 55 | ## Callbacks and Completion Blocks 56 | 57 | The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. 58 | 59 | Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). 60 | 61 | ## NSCoding & NSCopying Conformance 62 | 63 | `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: 64 | 65 | ### NSCoding Caveats 66 | 67 | - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. 68 | - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. 69 | 70 | ### NSCopying Caveats 71 | 72 | - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations. 73 | - A copy of an operation will not include the `outputStream` of the original. 74 | - Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied. 75 | */ 76 | @interface AFURLConnectionOperation : NSOperation 77 | 78 | ///------------------------------- 79 | /// @name Accessing Run Loop Modes 80 | ///------------------------------- 81 | 82 | /** 83 | The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. 84 | */ 85 | @property (nonatomic, strong) NSSet *runLoopModes; 86 | 87 | ///----------------------------------------- 88 | /// @name Getting URL Connection Information 89 | ///----------------------------------------- 90 | 91 | /** 92 | The request used by the operation's connection. 93 | */ 94 | @property (readonly, nonatomic, strong) NSURLRequest *request; 95 | 96 | /** 97 | The last response received by the operation's connection. 98 | */ 99 | @property (readonly, nonatomic, strong) NSURLResponse *response; 100 | 101 | /** 102 | The error, if any, that occurred in the lifecycle of the request. 103 | */ 104 | @property (readonly, nonatomic, strong) NSError *error; 105 | 106 | ///---------------------------- 107 | /// @name Getting Response Data 108 | ///---------------------------- 109 | 110 | /** 111 | The data received during the request. 112 | */ 113 | @property (readonly, nonatomic, strong) NSData *responseData; 114 | 115 | /** 116 | The string representation of the response data. 117 | 118 | @discussion This method uses the string encoding of the response, or if UTF-8 if not specified, to construct a string from the response data. 119 | */ 120 | @property (readonly, nonatomic, copy) NSString *responseString; 121 | 122 | ///------------------------ 123 | /// @name Accessing Streams 124 | ///------------------------ 125 | 126 | /** 127 | The input stream used to read data to be sent during the request. 128 | 129 | @discussion This property acts as a proxy to the `HTTPBodyStream` property of `request`. 130 | */ 131 | @property (nonatomic, strong) NSInputStream *inputStream; 132 | 133 | /** 134 | The output stream that is used to write data received until the request is finished. 135 | 136 | @discussion By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set. 137 | */ 138 | @property (nonatomic, strong) NSOutputStream *outputStream; 139 | 140 | ///------------------------------------------------------ 141 | /// @name Initializing an AFURLConnectionOperation Object 142 | ///------------------------------------------------------ 143 | 144 | /** 145 | Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. 146 | 147 | @param urlRequest The request object to be used by the operation connection. 148 | 149 | @discussion This is the designated initializer. 150 | */ 151 | - (id)initWithRequest:(NSURLRequest *)urlRequest; 152 | 153 | ///---------------------------------- 154 | /// @name Pausing / Resuming Requests 155 | ///---------------------------------- 156 | 157 | /** 158 | Pauses the execution of the request operation. 159 | 160 | @discussion A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. 161 | */ 162 | - (void)pause; 163 | 164 | /** 165 | Whether the request operation is currently paused. 166 | 167 | @return `YES` if the operation is currently paused, otherwise `NO`. 168 | */ 169 | - (BOOL)isPaused; 170 | 171 | /** 172 | Resumes the execution of the paused request operation. 173 | 174 | @discussion Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. 175 | */ 176 | - (void)resume; 177 | 178 | ///---------------------------------------------- 179 | /// @name Configuring Backgrounding Task Behavior 180 | ///---------------------------------------------- 181 | 182 | /** 183 | Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task. 184 | 185 | @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified. 186 | */ 187 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 188 | - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler; 189 | #endif 190 | 191 | ///--------------------------------- 192 | /// @name Setting Progress Callbacks 193 | ///--------------------------------- 194 | 195 | /** 196 | Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. 197 | 198 | @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. 199 | */ 200 | - (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; 201 | 202 | /** 203 | Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. 204 | 205 | @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. 206 | */ 207 | - (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; 208 | 209 | ///------------------------------------------------- 210 | /// @name Setting NSURLConnection Delegate Callbacks 211 | ///------------------------------------------------- 212 | 213 | /** 214 | Sets a block to be executed to determine whether the connection should be able to respond to a protection space's form of authentication, as handled by the `NSURLConnectionDelegate` method `connection:canAuthenticateAgainstProtectionSpace:`. 215 | 216 | @param block A block object to be executed to determine whether the connection should be able to respond to a protection space's form of authentication. The block has a `BOOL` return type and takes two arguments: the URL connection object, and the protection space to authenticate against. 217 | 218 | @discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:canAuthenticateAgainstProtectionSpace:` will accept invalid SSL certificates, returning `YES` if the protection space authentication method is `NSURLAuthenticationMethodServerTrust`. 219 | */ 220 | - (void)setAuthenticationAgainstProtectionSpaceBlock:(BOOL (^)(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace))block; 221 | 222 | /** 223 | Sets a block to be executed when the connection must authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:didReceiveAuthenticationChallenge:`. 224 | 225 | @param block A block object to be executed when the connection must authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. 226 | 227 | @discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:didReceiveAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. 228 | */ 229 | - (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block; 230 | 231 | /** 232 | Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`. 233 | 234 | @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect. 235 | */ 236 | - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block; 237 | 238 | 239 | /** 240 | Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`. 241 | 242 | @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. 243 | */ 244 | - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; 245 | 246 | @end 247 | 248 | ///---------------- 249 | /// @name Constants 250 | ///---------------- 251 | 252 | /** 253 | ## User info dictionary keys 254 | 255 | These keys may exist in the user info dictionary, in addition to those defined for NSError. 256 | 257 | - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` 258 | - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` 259 | 260 | ### Constants 261 | 262 | `AFNetworkingOperationFailingURLRequestErrorKey` 263 | The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`. 264 | 265 | `AFNetworkingOperationFailingURLResponseErrorKey` 266 | The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`. 267 | 268 | ## Error Domains 269 | 270 | The following error domain is predefined. 271 | 272 | - `NSString * const AFNetworkingErrorDomain` 273 | 274 | ### Constants 275 | 276 | `AFNetworkingErrorDomain` 277 | AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`. 278 | */ 279 | extern NSString * const AFNetworkingErrorDomain; 280 | extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; 281 | extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey; 282 | 283 | ///-------------------- 284 | /// @name Notifications 285 | ///-------------------- 286 | 287 | /** 288 | Posted when an operation begins executing. 289 | */ 290 | extern NSString * const AFNetworkingOperationDidStartNotification; 291 | 292 | /** 293 | Posted when an operation finishes. 294 | */ 295 | extern NSString * const AFNetworkingOperationDidFinishNotification; 296 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFXMLRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFXMLRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFHTTPRequestOperation.h" 25 | 26 | #import 27 | 28 | /** 29 | `AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data. 30 | 31 | ## Acceptable Content Types 32 | 33 | By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 34 | 35 | - `application/xml` 36 | - `text/xml` 37 | 38 | ## Use With AFHTTPClient 39 | 40 | When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback. 41 | */ 42 | @interface AFXMLRequestOperation : AFHTTPRequestOperation 43 | 44 | ///---------------------------- 45 | /// @name Getting Response Data 46 | ///---------------------------- 47 | 48 | /** 49 | An `NSXMLParser` object constructed from the response data. 50 | */ 51 | @property (readonly, nonatomic, strong) NSXMLParser *responseXMLParser; 52 | 53 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 54 | /** 55 | An `NSXMLDocument` object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error. 56 | */ 57 | @property (readonly, nonatomic, strong) NSXMLDocument *responseXMLDocument; 58 | #endif 59 | 60 | /** 61 | Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks. 62 | 63 | @param urlRequest The request object to be loaded asynchronously during execution of the operation 64 | @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML parser constructed with the response data of request. 65 | @param failure A block object to be executed when the operation finishes unsuccessfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network error that occurred. 66 | 67 | @return A new XML request operation 68 | */ 69 | + (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest 70 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success 71 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure; 72 | 73 | 74 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 75 | /** 76 | Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks. 77 | 78 | @param urlRequest The request object to be loaded asynchronously during execution of the operation 79 | @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML document created from the response data of request. 80 | @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as XML. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. 81 | 82 | @return A new XML request operation 83 | */ 84 | + (AFXMLRequestOperation *)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest 85 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success 86 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure; 87 | #endif 88 | 89 | @end 90 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/AFXMLRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFXMLRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFXMLRequestOperation.h" 24 | 25 | #include 26 | 27 | static dispatch_queue_t af_xml_request_operation_processing_queue; 28 | static dispatch_queue_t xml_request_operation_processing_queue() { 29 | if (af_xml_request_operation_processing_queue == NULL) { 30 | af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", 0); 31 | } 32 | 33 | return af_xml_request_operation_processing_queue; 34 | } 35 | 36 | @interface AFXMLRequestOperation () 37 | @property (readwrite, nonatomic, strong) NSXMLParser *responseXMLParser; 38 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 39 | @property (readwrite, nonatomic, strong) NSXMLDocument *responseXMLDocument; 40 | #endif 41 | @property (readwrite, nonatomic, strong) NSError *XMLError; 42 | @end 43 | 44 | @implementation AFXMLRequestOperation 45 | @synthesize responseXMLParser = _responseXMLParser; 46 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 47 | @synthesize responseXMLDocument = _responseXMLDocument; 48 | #endif 49 | @synthesize XMLError = _XMLError; 50 | 51 | + (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest 52 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success 53 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure 54 | { 55 | AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; 56 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 57 | if (success) { 58 | success(operation.request, operation.response, responseObject); 59 | } 60 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 61 | if (failure) { 62 | failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]); 63 | } 64 | }]; 65 | 66 | return requestOperation; 67 | } 68 | 69 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 70 | + (AFXMLRequestOperation *)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest 71 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success 72 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure 73 | { 74 | AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; 75 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) { 76 | if (success) { 77 | NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; 78 | success(operation.request, operation.response, XMLDocument); 79 | } 80 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 81 | if (failure) { 82 | NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; 83 | failure(operation.request, operation.response, error, XMLDocument); 84 | } 85 | }]; 86 | 87 | return requestOperation; 88 | } 89 | #endif 90 | 91 | 92 | - (NSXMLParser *)responseXMLParser { 93 | if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) { 94 | self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData]; 95 | } 96 | 97 | return _responseXMLParser; 98 | } 99 | 100 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 101 | - (NSXMLDocument *)responseXMLDocument { 102 | if (!_responseXMLDocument && [self.responseData length] > 0 && [self isFinished]) { 103 | NSError *error = nil; 104 | self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error]; 105 | self.XMLError = error; 106 | } 107 | 108 | return _responseXMLDocument; 109 | } 110 | #endif 111 | 112 | - (NSError *)error { 113 | if (_XMLError) { 114 | return _XMLError; 115 | } else { 116 | return [super error]; 117 | } 118 | } 119 | 120 | #pragma mark - NSOperation 121 | 122 | - (void)cancel { 123 | [super cancel]; 124 | 125 | self.responseXMLParser.delegate = nil; 126 | } 127 | 128 | #pragma mark - AFHTTPRequestOperation 129 | 130 | + (NSSet *)acceptableContentTypes { 131 | return [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; 132 | } 133 | 134 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 135 | return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request]; 136 | } 137 | 138 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 139 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 140 | { 141 | #pragma clang diagnostic push 142 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 143 | self.completionBlock = ^ { 144 | if ([self isCancelled]) { 145 | return; 146 | } 147 | 148 | dispatch_async(xml_request_operation_processing_queue(), ^(void) { 149 | NSXMLParser *XMLParser = self.responseXMLParser; 150 | 151 | if (self.error) { 152 | if (failure) { 153 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 154 | failure(self, self.error); 155 | }); 156 | } 157 | } else { 158 | if (success) { 159 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 160 | success(self, XMLParser); 161 | }); 162 | } 163 | } 164 | }); 165 | }; 166 | #pragma clang diagnostic pop 167 | } 168 | 169 | @end 170 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/UIImageView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIImageView+AFNetworking.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFImageRequestOperation.h" 25 | 26 | #import 27 | 28 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 29 | #import 30 | 31 | /** 32 | This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. 33 | */ 34 | @interface UIImageView (AFNetworking) 35 | 36 | /** 37 | Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 38 | 39 | @discussion By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` 40 | 41 | @param url The URL used for the image request. 42 | */ 43 | - (void)setImageWithURL:(NSURL *)url; 44 | 45 | /** 46 | Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 47 | 48 | @param url The URL used for the image request. 49 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. 50 | 51 | @discussion By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` 52 | */ 53 | - (void)setImageWithURL:(NSURL *)url 54 | placeholderImage:(UIImage *)placeholderImage; 55 | 56 | /** 57 | Creates and enqueues an image request operation, which asynchronously downloads the image with the specified URL request object. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 58 | 59 | @param urlRequest The URL request used for the image request. 60 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. 61 | @param success A block to be executed when the image request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`. 62 | @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 63 | 64 | @discussion If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is executed. 65 | */ 66 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 67 | placeholderImage:(UIImage *)placeholderImage 68 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 69 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; 70 | 71 | /** 72 | Cancels any executing image request operation for the receiver, if one exists. 73 | */ 74 | - (void)cancelImageRequestOperation; 75 | 76 | @end 77 | 78 | #endif 79 | -------------------------------------------------------------------------------- /RepositoryPattern/Libraries/AFNetworking/UIImageView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIImageView+AFNetworking.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 27 | #import "UIImageView+AFNetworking.h" 28 | 29 | @interface AFImageCache : NSCache 30 | - (UIImage *)cachedImageForRequest:(NSURLRequest *)request; 31 | - (void)cacheImage:(UIImage *)image 32 | forRequest:(NSURLRequest *)request; 33 | @end 34 | 35 | #pragma mark - 36 | 37 | static char kAFImageRequestOperationObjectKey; 38 | 39 | @interface UIImageView (_AFNetworking) 40 | @property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation; 41 | @end 42 | 43 | @implementation UIImageView (_AFNetworking) 44 | @dynamic af_imageRequestOperation; 45 | @end 46 | 47 | #pragma mark - 48 | 49 | @implementation UIImageView (AFNetworking) 50 | 51 | - (AFHTTPRequestOperation *)af_imageRequestOperation { 52 | return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey); 53 | } 54 | 55 | - (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation { 56 | objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 57 | } 58 | 59 | + (NSOperationQueue *)af_sharedImageRequestOperationQueue { 60 | static NSOperationQueue *_af_imageRequestOperationQueue = nil; 61 | static dispatch_once_t onceToken; 62 | dispatch_once(&onceToken, ^{ 63 | _af_imageRequestOperationQueue = [[NSOperationQueue alloc] init]; 64 | [_af_imageRequestOperationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount]; 65 | }); 66 | 67 | return _af_imageRequestOperationQueue; 68 | } 69 | 70 | + (AFImageCache *)af_sharedImageCache { 71 | static AFImageCache *_af_imageCache = nil; 72 | static dispatch_once_t oncePredicate; 73 | dispatch_once(&oncePredicate, ^{ 74 | _af_imageCache = [[AFImageCache alloc] init]; 75 | }); 76 | 77 | return _af_imageCache; 78 | } 79 | 80 | #pragma mark - 81 | 82 | - (void)setImageWithURL:(NSURL *)url { 83 | [self setImageWithURL:url placeholderImage:nil]; 84 | } 85 | 86 | - (void)setImageWithURL:(NSURL *)url 87 | placeholderImage:(UIImage *)placeholderImage 88 | { 89 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 90 | [request setHTTPShouldHandleCookies:NO]; 91 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; 92 | 93 | [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; 94 | } 95 | 96 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 97 | placeholderImage:(UIImage *)placeholderImage 98 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 99 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure 100 | { 101 | [self cancelImageRequestOperation]; 102 | 103 | UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest]; 104 | if (cachedImage) { 105 | self.image = cachedImage; 106 | self.af_imageRequestOperation = nil; 107 | 108 | if (success) { 109 | success(nil, nil, cachedImage); 110 | } 111 | } else { 112 | self.image = placeholderImage; 113 | 114 | AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest]; 115 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 116 | if ([[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]]) { 117 | if (success) { 118 | success(operation.request, operation.response, responseObject); 119 | } else { 120 | self.image = responseObject; 121 | } 122 | 123 | self.af_imageRequestOperation = nil; 124 | } 125 | 126 | [[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; 127 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 128 | if ([[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]]) { 129 | if (failure) { 130 | failure(operation.request, operation.response, error); 131 | } 132 | 133 | self.af_imageRequestOperation = nil; 134 | } 135 | }]; 136 | 137 | self.af_imageRequestOperation = requestOperation; 138 | 139 | [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; 140 | } 141 | } 142 | 143 | - (void)cancelImageRequestOperation { 144 | [self.af_imageRequestOperation cancel]; 145 | self.af_imageRequestOperation = nil; 146 | } 147 | 148 | @end 149 | 150 | #pragma mark - 151 | 152 | static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) { 153 | return [[request URL] absoluteString]; 154 | } 155 | 156 | @implementation AFImageCache 157 | 158 | - (UIImage *)cachedImageForRequest:(NSURLRequest *)request { 159 | switch ([request cachePolicy]) { 160 | case NSURLRequestReloadIgnoringCacheData: 161 | case NSURLRequestReloadIgnoringLocalAndRemoteCacheData: 162 | return nil; 163 | default: 164 | break; 165 | } 166 | 167 | return [self objectForKey:AFImageCacheKeyFromURLRequest(request)]; 168 | } 169 | 170 | - (void)cacheImage:(UIImage *)image 171 | forRequest:(NSURLRequest *)request 172 | { 173 | if (image && request) { 174 | [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)]; 175 | } 176 | } 177 | 178 | @end 179 | 180 | #endif 181 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/BaseManagedObjectModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // BaseManagedObjectModel.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | @interface BaseManagedObjectModel : NSManagedObject 11 | - (void) updateWithDictionary:(NSDictionary*)dictionary; 12 | - (NSDictionary *)toDictionary; 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/BaseManagedObjectModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // BaseManagedObjectModel.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "BaseManagedObjectModel.h" 10 | 11 | @implementation BaseManagedObjectModel 12 | - (void)updateWithDictionary:(NSDictionary *)dictionary{ 13 | unsigned int outCount, i; 14 | objc_property_t *properties = class_copyPropertyList([self class], &outCount); 15 | for (i = 0; i < outCount; i++) { 16 | objc_property_t property = properties[i]; 17 | NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)]; 18 | id propertyValue = [dictionary valueForKey:(NSString *)propertyName]; 19 | if (propertyValue) { 20 | [self setValue:propertyValue forKey:propertyName]; 21 | } 22 | } 23 | free(properties); 24 | } 25 | 26 | - (NSDictionary *)toDictionary{ 27 | unsigned int outCount, i; 28 | NSMutableDictionary *json = [[NSMutableDictionary alloc] initWithCapacity:1]; 29 | 30 | objc_property_t *properties = class_copyPropertyList([self class], &outCount); 31 | for (i = 0; i < outCount; i++) { 32 | objc_property_t property = properties[i]; 33 | NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)]; 34 | id propertyValue = [self valueForKey:(NSString *)propertyName]; 35 | if (propertyValue) { 36 | [json setValue:propertyValue forKey:propertyName]; 37 | } 38 | } 39 | free(properties); 40 | return json; 41 | } 42 | @end 43 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/BaseModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // BaseModel.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | 11 | @interface BaseModel : NSObject 12 | - (void)updateWithDictionary:(NSDictionary *)dictionary; 13 | - (NSDictionary *)toDictionary; 14 | @end 15 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/BaseModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // BaseModel.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "BaseModel.h" 10 | 11 | @implementation BaseModel 12 | - (void)updateWithDictionary:(NSDictionary *)dictionary{ 13 | unsigned int outCount, i; 14 | objc_property_t *properties = class_copyPropertyList([self class], &outCount); 15 | for (i = 0; i < outCount; i++) { 16 | objc_property_t property = properties[i]; 17 | NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)]; 18 | id propertyValue = [dictionary valueForKey:(NSString *)propertyName]; 19 | if (propertyValue) { 20 | [self setValue:propertyValue forKey:propertyName]; 21 | } 22 | } 23 | free(properties); 24 | } 25 | 26 | - (NSDictionary *)toDictionary{ 27 | unsigned int outCount, i; 28 | NSMutableDictionary *json = [[NSMutableDictionary alloc] initWithCapacity:1]; 29 | 30 | objc_property_t *properties = class_copyPropertyList([self class], &outCount); 31 | for (i = 0; i < outCount; i++) { 32 | objc_property_t property = properties[i]; 33 | NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)]; 34 | id propertyValue = [self valueForKey:(NSString *)propertyName]; 35 | if (propertyValue) { 36 | [json setValue:propertyValue forKey:propertyName]; 37 | } 38 | } 39 | free(properties); 40 | return json; 41 | } 42 | @end 43 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/City.h: -------------------------------------------------------------------------------- 1 | // 2 | // Location.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | #import "_City.h" 11 | @interface City : _City 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/City.m: -------------------------------------------------------------------------------- 1 | // 2 | // Location.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "City.h" 10 | 11 | @implementation City 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/Photo.h: -------------------------------------------------------------------------------- 1 | // 2 | // Photo.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "_Photo.h" 10 | 11 | @interface Photo : _Photo 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/Photo.m: -------------------------------------------------------------------------------- 1 | // 2 | // Photo.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "Photo.h" 10 | 11 | @implementation Photo 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/User.h: -------------------------------------------------------------------------------- 1 | // 2 | // User.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "_User.h" 10 | 11 | @interface User : _User 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/User.m: -------------------------------------------------------------------------------- 1 | // 2 | // User.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "User.h" 10 | 11 | @implementation User 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/Weather.h: -------------------------------------------------------------------------------- 1 | // 2 | // Weather.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | #import "BaseModel.h" 11 | @interface Weather : BaseModel 12 | @property(nonatomic,strong) NSString* clouds;// "broken clouds", 13 | @property(nonatomic,strong) NSString* weatherCondition;// "haze", 14 | @property(nonatomic,strong) NSString* observation;// "KGRY 120720Z 19019KT 6SM HZ BKN026 BKN032 25/20 A3009 RMK A01 WIND DATA UNRELIABLE", 15 | @property(nonatomic,strong) NSNumber* windDirection;// 190, 16 | @property(nonatomic,strong) NSString* ICAO;// "KGRY", 17 | @property(nonatomic,strong) NSString* cloudsCode;// "BKN", 18 | @property(nonatomic,strong) NSNumber* lng;// -90.45, 19 | @property(nonatomic,strong) NSNumber* temperature;// "25", 20 | @property(nonatomic,strong) NSNumber* dewPoint;// "20", 21 | @property(nonatomic,strong) NSString* weatherConditionCode;// "HZ", 22 | @property(nonatomic,strong) NSNumber* windSpeed;// "19", 23 | @property(nonatomic,strong) NSNumber* humidity;// 73, 24 | @property(nonatomic,strong) NSString* stationName;// "GREEN CANYON 338", 25 | @property(nonatomic,strong) NSDate* datetime;// "2012-11-12 07;//20;//00", 26 | @property(nonatomic,strong) NSNumber* lat;// 27.633333333333333 27 | @end 28 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/Weather.m: -------------------------------------------------------------------------------- 1 | // 2 | // Weather.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "Weather.h" 10 | 11 | @implementation Weather 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/_City.h: -------------------------------------------------------------------------------- 1 | // 2 | // Location.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | #import 11 | #import "BaseManagedObjectModel.h" 12 | 13 | @interface _City : BaseManagedObjectModel 14 | 15 | @property (nonatomic, retain) NSString * toponymName; 16 | @property (nonatomic, retain) NSString * name; 17 | @property (nonatomic, retain) NSNumber * lat; 18 | @property (nonatomic, retain) NSNumber * lng; 19 | @property (nonatomic, retain) NSNumber * geonameId; 20 | @property (nonatomic, retain) NSString * countryCode; 21 | @property (nonatomic, retain) NSString * countryName; 22 | @property (nonatomic, retain) NSString * fcl; 23 | @property (nonatomic, retain) NSString * fcode; 24 | + (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_; 25 | @end 26 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/_City.m: -------------------------------------------------------------------------------- 1 | // 2 | // Location.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "_City.h" 10 | 11 | 12 | @implementation _City 13 | 14 | @dynamic toponymName; 15 | @dynamic name; 16 | @dynamic lat; 17 | @dynamic lng; 18 | @dynamic geonameId; 19 | @dynamic countryCode; 20 | @dynamic countryName; 21 | @dynamic fcl; 22 | @dynamic fcode; 23 | + (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_ { 24 | NSParameterAssert(moc_); 25 | return [NSEntityDescription insertNewObjectForEntityForName:@"City" inManagedObjectContext:moc_]; 26 | } 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/_Photo.h: -------------------------------------------------------------------------------- 1 | // 2 | // _Photo.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | #import "BaseManagedObjectModel.h" 12 | 13 | @interface _Photo : BaseManagedObjectModel 14 | 15 | @property (nonatomic, retain) NSNumber * photoId; 16 | @property (nonatomic, retain) NSString * thumbUrl; 17 | @property (nonatomic, retain) NSString * medUrl; 18 | @property (nonatomic, retain) NSString * largeUrl; 19 | 20 | @end 21 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/_Photo.m: -------------------------------------------------------------------------------- 1 | // 2 | // _Photo.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "_Photo.h" 10 | 11 | 12 | @implementation _Photo 13 | 14 | @dynamic photoId; 15 | @dynamic thumbUrl; 16 | @dynamic medUrl; 17 | @dynamic largeUrl; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/_User.h: -------------------------------------------------------------------------------- 1 | // 2 | // _User.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | #import "BaseManagedObjectModel.h" 12 | 13 | @interface _User : BaseManagedObjectModel 14 | 15 | @property (nonatomic, retain) NSNumber * userId; 16 | @property (nonatomic, retain) NSString * name; 17 | @property (nonatomic, retain) NSString * email; 18 | @property (nonatomic, retain) NSString * password; 19 | 20 | @end 21 | -------------------------------------------------------------------------------- /RepositoryPattern/Models/_User.m: -------------------------------------------------------------------------------- 1 | // 2 | // _User.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "_User.h" 10 | 11 | 12 | @implementation _User 13 | 14 | @dynamic userId; 15 | @dynamic name; 16 | @dynamic email; 17 | @dynamic password; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /RepositoryPattern/RPAppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPAppDelegate.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "RPIDbUnitOfWork.h" 11 | 12 | extern id dbUnitOfWork; 13 | @interface RPAppDelegate : UIResponder 14 | @property (strong, nonatomic) UIWindow *window; 15 | @end 16 | -------------------------------------------------------------------------------- /RepositoryPattern/RPAppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPAppDelegate.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "RPAppDelegate.h" 10 | #import "RPCoreDataUnitOfWork.h" 11 | #import "User.h" 12 | #import "Photo.h" 13 | #import "RPCityViewController.h" 14 | 15 | @implementation RPAppDelegate 16 | 17 | 18 | @synthesize window = _window; 19 | 20 | id dbUnitOfWork; 21 | 22 | - (void) initializeRepository{ 23 | dbUnitOfWork = [RPCoreDataUnitOfWork sharedInstance]; 24 | } 25 | 26 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 27 | { 28 | [self initializeRepository]; 29 | RPCityViewController *city = [[RPCityViewController alloc] initWithNibName:@"RPCityView" bundle:nil]; 30 | UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:city]; 31 | self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 32 | // Override point for customization after application launch. 33 | self.window.backgroundColor = [UIColor whiteColor]; 34 | [self.window setRootViewController:navigation]; 35 | [self.window makeKeyAndVisible]; 36 | return YES; 37 | } 38 | 39 | 40 | - (void)applicationWillResignActive:(UIApplication *)application 41 | { 42 | /* 43 | 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. 44 | 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. 45 | */ 46 | } 47 | 48 | - (void)applicationDidEnterBackground:(UIApplication *)application 49 | { 50 | /* 51 | 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. 52 | If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 53 | */ 54 | } 55 | 56 | - (void)applicationWillEnterForeground:(UIApplication *)application 57 | { 58 | /* 59 | 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. 60 | */ 61 | } 62 | 63 | - (void)applicationDidBecomeActive:(UIApplication *)application 64 | { 65 | /* 66 | 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. 67 | */ 68 | } 69 | 70 | - (void)applicationWillTerminate:(UIApplication *)application 71 | { 72 | // Saves changes in the application's managed object context before the application terminates. 73 | [dbUnitOfWork saveChanges]; 74 | } 75 | @end 76 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Fake/RPFakeCityRepository.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPFakeCityRepository.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/13/12. 6 | // 7 | // 8 | 9 | #import "RPGenericRepository.h" 10 | #import "RPICityRepository.h" 11 | @interface RPFakeCityRepository : RPGenericRepository 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Fake/RPFakeCityRepository.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPFakeCityRepository.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/13/12. 6 | // 7 | // 8 | 9 | #import "RPFakeCityRepository.h" 10 | #import "City.h" 11 | @implementation RPFakeCityRepository 12 | - (void)getCityFeed:(void (^)(NSArray *))success fail:(void (^)(int, NSError *))fail{ 13 | NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:1]; 14 | for (int i = 0;i<50;i++) { 15 | City* city = [self create]; 16 | [city setName:[NSString stringWithFormat:@"Fake City %d",i]]; 17 | [result addObject:city]; 18 | } 19 | success(result); 20 | } 21 | @end 22 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Generic/RPGenericRepository.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPGenericRepository.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "RPIRepository.h" 11 | #import "RPIDbContext.h" 12 | 13 | @interface RPGenericRepository :NSObject{ 14 | id dbContext; 15 | Class modelClass; 16 | } 17 | - (id) initWithDbContext:(id) context withModel:(Class)modeClass; 18 | @end 19 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Generic/RPGenericRepository.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPGenericRepository.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "RPGenericRepository.h" 10 | 11 | @implementation RPGenericRepository 12 | 13 | - (id) initWithDbContext:(id) context withModel:(__unsafe_unretained Class)class{ 14 | self = [super init]; 15 | if (self) { 16 | dbContext= context; 17 | modelClass = class; 18 | } 19 | return self; 20 | } 21 | - (NSArray *)getAll{ 22 | return [dbContext getObjects:modelClass]; 23 | } 24 | 25 | - (id)create{ 26 | return [dbContext attachObject:modelClass]; 27 | } 28 | 29 | - (void)remove:(id)object{ 30 | [dbContext removeManagedObject:object]; 31 | } 32 | 33 | - (NSArray *)find:(NSString *)where{ 34 | return [dbContext find:[modelClass description] where:where]; 35 | } 36 | - (NSArray *)find:(NSString *)where take:(int) countItem{ 37 | return [dbContext find:[modelClass description] where:where take:countItem]; 38 | } 39 | - (NSArray *)find:(NSString *)where orderBy:(NSString *)orderByAttribute ascending:(BOOL)ascending{ 40 | return [dbContext find:[modelClass description] where:where orderBy:orderByAttribute ascending:ascending]; 41 | 42 | } 43 | - (NSArray *)find:(NSString *)where orderBy:(NSString *)orderByAttribute ascending:(BOOL)ascending take:(int)countItem{ 44 | return [dbContext find:[modelClass description] where:where orderBy:orderByAttribute ascending:ascending take:countItem]; 45 | } 46 | @end 47 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Generic/RPICityRepository.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPICityRepository.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | #import "RPIRepository.h" 11 | 12 | @protocol RPICityRepository 13 | - (void) getCityFeed:(void(^)(NSArray/*City*/ *cities))success fail:(void(^)(int statusCode, NSError *error))fail; 14 | @end 15 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Generic/RPIDbContext.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPIDbContext.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @protocol RPIDbContext 12 | - (NSArray*) getObjects:(Class)modelClass; 13 | - (id) attachObject:(Class) modelClass; 14 | - (void) removeManagedObject:(id) managedObject; 15 | - (void) saveChanges; 16 | - (void) asyncUpdateWithContext:(void(^)(NSManagedObjectContext *context))startUpdate completion:(void(^)())completion; 17 | 18 | - (NSArray*) find:(NSString*)objectName where:(NSString*)conditions; 19 | - (NSArray*) find:(NSString*)objectName where:(NSString*)conditions take:(int) countItem; 20 | - (NSArray*) find:(NSString*)objectName where:(NSString*)conditions orderBy:(NSString*)orderByAttribute ascending:(BOOL)ascending; 21 | - (NSArray*) find:(NSString*)objectName where:(NSString*)conditions orderBy:(NSString*)orderByAttribute ascending:(BOOL)ascending take:(int)countItem; 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Generic/RPIDbUnitOfWork.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPIDbUnitOfWork.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "RPIRepository.h" 11 | #import "RPICityRepository.h" 12 | #import "RPIWeatherRepository.h" 13 | 14 | @protocol RPIDbUnitOfWork 15 | @required 16 | /* Describe your repository property here */ 17 | // User repository for User model 18 | @property(nonatomic,strong,readonly) id userRepository; 19 | // Photo repository for Photo model 20 | @property(nonatomic,strong,readonly) id photoRepository; 21 | // City repository for City model 22 | @property(nonatomic,strong,readonly) id cityRepository; 23 | // Weather repository for Weather model 24 | @property(nonatomic,strong,readonly) id weatherRepository; 25 | 26 | - (void) saveChanges; 27 | + (id) sharedInstance; 28 | @end 29 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Generic/RPIRepository.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPIRepository.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @protocol RPIRepository 12 | 13 | @required 14 | - (id) create; 15 | - (NSArray*) getAll; 16 | - (void) remove:(id)object; 17 | 18 | - (NSArray*) find:(NSString*)where; 19 | - (NSArray*) find:(NSString *)where take:(int) countItem; 20 | - (NSArray*) find:(NSString*)where orderBy:(NSString*)orderByAttribute ascending:(BOOL)ascending; 21 | - (NSArray*) find:(NSString*)where orderBy:(NSString*)orderByAttribute ascending:(BOOL)ascending take:(int)countItem; 22 | @end 23 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Generic/RPIWeatherRepository.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPIWeatherRepository.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | #import "RPIRepository.h" 11 | 12 | @protocol RPIWeatherRepository 13 | - (void) getWeatherFeed:(void(^)(NSArray/*Weather*/ *weather))success fail:(void(^)(int statusCode, NSError *error))fail; 14 | @end 15 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Generic/RPIWeatherRepository.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPIWeatherRepository.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "RPIWeatherRepository.h" 10 | 11 | @implementation RPIWeatherRepository 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Implements/RPCityRepository.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPCityRepository.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | #import "RPGenericRepository.h" 11 | #import "RPICityRepository.h" 12 | @interface RPCityRepository : RPGenericRepository 13 | 14 | @end 15 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Implements/RPCityRepository.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPCityRepository.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "RPCityRepository.h" 10 | #import "City.h" 11 | @implementation RPCityRepository 12 | - (void)getCityFeed:(void (^)(NSArray *))success fail:(void (^)(int, NSError *))fail{ 13 | 14 | RPHTTPClient *client = [RPHTTPClient sharedInstance]; 15 | 16 | NSString *api = @"citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo"; 17 | 18 | [client getPath:api 19 | parameters:nil 20 | success:^(AFHTTPRequestOperation *operation, id responseObject) { 21 | // Asynchronous update to Database without blocking UI 22 | [dbContext asyncUpdateWithContext:^(NSManagedObjectContext *backgroundContext) { 23 | // The background context is separate context used to saved to DB, 24 | // this context will not affect to ui context which used to display UI elements 25 | id responseCities = [responseObject objectForKey:@"geonames"]; 26 | for (NSDictionary *responseCity in responseCities) { 27 | // Insert new object to background context 28 | City *city = [City insertInManagedObjectContext:backgroundContext]; 29 | [city updateWithDictionary:responseCity]; 30 | } 31 | } completion:^{ 32 | // Reflect to UI when update finish. 33 | NSArray *cities = [self getAll]; 34 | success(cities); 35 | }]; 36 | 37 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 38 | int statusCode = [[operation response] statusCode]; 39 | fail(statusCode,error); 40 | }]; 41 | 42 | // Return saved objects to display as real time as possible 43 | id savedCities = [self getAll]; 44 | success(savedCities); 45 | } 46 | @end 47 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Implements/RPCoreDataContext.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPDataContext.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | #import "RPIDbContext.h" 12 | 13 | @interface RPCoreDataContext : NSObject{ 14 | NSManagedObjectContext *_foregroundObjectContext; 15 | NSManagedObjectContext *_backgroundObjectContext; 16 | NSManagedObjectModel *_managedObjectModel; 17 | NSPersistentStoreCoordinator *_persistentStoreCoordinator; 18 | } 19 | @end 20 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Implements/RPCoreDataContext.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPDataContext.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "RPCoreDataContext.h" 10 | #import "RPNSManagedObjectContext+Queryable.h" 11 | #import "User.h" 12 | @implementation RPCoreDataContext 13 | 14 | dispatch_queue_t background_save_queue(void); 15 | 16 | static dispatch_queue_t coredata_background_save_queue; 17 | 18 | dispatch_queue_t background_save_queue() 19 | { 20 | if (coredata_background_save_queue == NULL) 21 | { 22 | coredata_background_save_queue = dispatch_queue_create("com.coredata.backgroundsaves", 0); 23 | } 24 | return coredata_background_save_queue; 25 | } 26 | 27 | 28 | #pragma mark - Utils 29 | -(NSMutableArray *)searchObjects:(NSString*)entityName 30 | predicate:(NSPredicate*)predicate 31 | sortKey:(NSString*)sortKey 32 | sortAscending:(BOOL)sortAscending { 33 | 34 | NSFetchRequest *request = [[NSFetchRequest alloc] init]; 35 | NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:_foregroundObjectContext]; 36 | [request setEntity:entity]; 37 | 38 | if(predicate != nil) { 39 | [request setPredicate:predicate]; 40 | } 41 | 42 | if(sortKey != nil) { 43 | NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending]; 44 | NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 45 | [request setSortDescriptors:sortDescriptors]; 46 | } 47 | 48 | NSError *error; 49 | NSMutableArray *mutableFetchResults = [[_foregroundObjectContext executeFetchRequest:request error:&error] mutableCopy]; 50 | return mutableFetchResults; 51 | } 52 | 53 | -(NSMutableArray *)getObjects:(NSString*)entityName sortKey:(NSString*)sortKey sortAscending:(BOOL)sortAscending { 54 | return [self searchObjects:entityName 55 | predicate:nil 56 | sortKey:sortKey 57 | sortAscending:sortAscending]; 58 | } 59 | 60 | -(void)removeAllEntities:(NSString*)entityName { 61 | 62 | NSFetchRequest * allEntities = [[NSFetchRequest alloc] init]; 63 | [allEntities setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:_foregroundObjectContext]]; 64 | [allEntities setIncludesPropertyValues:NO]; //only fetch the managedObjectID 65 | 66 | NSError * error = nil; 67 | NSArray * entities = [_foregroundObjectContext executeFetchRequest:allEntities error:&error]; 68 | for (NSManagedObject * entity in entities) { 69 | [_foregroundObjectContext deleteObject:entity]; 70 | } 71 | } 72 | 73 | - (NSURL *)applicationDocumentsDirectory 74 | { 75 | return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 76 | } 77 | 78 | - (void)saveContext 79 | { 80 | NSError *error = nil; 81 | NSManagedObjectContext *managedObjectContext = _foregroundObjectContext; 82 | if (managedObjectContext != nil) 83 | { 84 | if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) 85 | { 86 | /* 87 | Replace this implementation with code to handle the error appropriately. 88 | 89 | 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. 90 | */ 91 | NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 92 | abort(); 93 | } 94 | } 95 | } 96 | 97 | 98 | #pragma mark - Protocol implementation 99 | - (NSArray*)getObjects:(Class)modelClass{ 100 | return [self getObjects:[modelClass description] sortKey:nil sortAscending:FALSE]; 101 | } 102 | - (id)attachObject:(Class)modelClass{ 103 | return [NSEntityDescription insertNewObjectForEntityForName:[modelClass description] inManagedObjectContext:_foregroundObjectContext]; 104 | } 105 | 106 | - (void)removeManagedObject:(id)managedObject{ 107 | [_foregroundObjectContext deleteObject:managedObject]; 108 | } 109 | 110 | - (void)saveChanges{ 111 | [self saveContext]; 112 | } 113 | 114 | - (void)asyncUpdateWithContext:(void (^)(NSManagedObjectContext *context))startUpdate completion:(void (^)())completion{ 115 | 116 | startUpdate(_backgroundObjectContext); 117 | 118 | NSError *error = nil; 119 | if (_backgroundObjectContext != nil) 120 | { 121 | if ([_backgroundObjectContext hasChanges] && ![_backgroundObjectContext save:&error]) 122 | { 123 | NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 124 | abort(); 125 | } 126 | } 127 | if (completion) 128 | { 129 | dispatch_async(dispatch_get_main_queue(), completion); 130 | } 131 | 132 | } 133 | 134 | - (NSArray *)find:(NSString *)objectName where:(NSString *)conditions{ 135 | NSArray* result = [[[_foregroundObjectContext ofType:objectName] 136 | where:conditions] toArray]; 137 | return result; 138 | 139 | } 140 | 141 | - (NSArray *)find:(NSString *)objectName where:(NSString *)conditions take:(int)countItem{ 142 | NSArray* result = [[[[_foregroundObjectContext ofType:objectName] 143 | where:conditions] take:countItem] toArray]; 144 | return result; 145 | } 146 | 147 | - (NSArray *)find:(NSString *)objectName where:(NSString *)conditions orderBy:(NSString *)orderByAttribute ascending:(BOOL)ascending{ 148 | if (ascending) { 149 | NSArray* result = [[[[_foregroundObjectContext ofType:objectName] 150 | where:conditions] 151 | orderBy:orderByAttribute] toArray]; 152 | return result; 153 | } 154 | else{ 155 | NSArray* result = [[[[_foregroundObjectContext ofType:objectName] 156 | where:conditions] 157 | orderByDescending:orderByAttribute] toArray]; 158 | return result; 159 | } 160 | } 161 | - (NSArray *)find:(NSString *)objectName where:(NSString *)conditions orderBy:(NSString *)orderByAttribute ascending:(BOOL)ascending take:(int)countItem{ 162 | if (ascending) { 163 | NSArray* result = [[[[[_foregroundObjectContext ofType:objectName] 164 | where:conditions] 165 | orderBy:orderByAttribute] 166 | take:countItem] 167 | toArray]; 168 | return result; 169 | } 170 | else{ 171 | NSArray* result = [[[[[_foregroundObjectContext ofType:objectName] 172 | where:conditions] 173 | orderByDescending:orderByAttribute] 174 | take:countItem] 175 | toArray]; 176 | return result; 177 | } 178 | } 179 | 180 | 181 | #pragma mark - Core Data stack 182 | /** 183 | Returns the managed object model for the application. 184 | If the model doesn't already exist, it is created from the application's model. 185 | */ 186 | - (NSManagedObjectModel *) createManagedObjectModel 187 | { 188 | if (_managedObjectModel != nil) 189 | { 190 | return _managedObjectModel; 191 | } 192 | NSURL *modelURL = [[NSBundle mainBundle] URLForResource:kCoreDataModelName withExtension:@"momd"]; 193 | _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 194 | return _managedObjectModel; 195 | } 196 | 197 | /** 198 | Returns the persistent store coordinator for the application. 199 | If the coordinator doesn't already exist, it is created and the application's store added to it. 200 | */ 201 | - (NSPersistentStoreCoordinator *) createPersistentStoreCoordinator 202 | { 203 | if (_persistentStoreCoordinator != nil) 204 | { 205 | return _persistentStoreCoordinator; 206 | } 207 | 208 | NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:kSqlLiteDbName]; 209 | 210 | NSError *error = nil; 211 | _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_managedObjectModel]; 212 | 213 | if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) 214 | { 215 | /* 216 | Replace this implementation with code to handle the error appropriately. 217 | 218 | 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. 219 | 220 | Typical reasons for an error here include: 221 | * The persistent store is not accessible; 222 | * The schema for the persistent store is incompatible with current managed object model. 223 | Check the error message to determine what the actual problem was. 224 | 225 | 226 | If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. 227 | 228 | If you encounter schema incompatibility errors during development, you can reduce their frequency by: 229 | * Simply deleting the existing store: 230 | [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] 231 | 232 | * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 233 | [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 234 | 235 | Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. 236 | 237 | */ 238 | [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]; 239 | 240 | //NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 241 | //abort(); 242 | } 243 | 244 | return _persistentStoreCoordinator; 245 | } 246 | 247 | /** 248 | Returns the managed object context for the application. 249 | If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. 250 | */ 251 | - (void) createManagedObjectContext 252 | { 253 | if (_foregroundObjectContext != nil) 254 | { 255 | return; 256 | } 257 | 258 | [self createManagedObjectModel]; 259 | 260 | NSPersistentStoreCoordinator *coordinator = [self createPersistentStoreCoordinator]; 261 | if (coordinator != nil) 262 | { 263 | _foregroundObjectContext = [[NSManagedObjectContext alloc] init]; 264 | [_foregroundObjectContext setPersistentStoreCoordinator:coordinator]; 265 | 266 | _backgroundObjectContext = [[NSManagedObjectContext alloc] init]; 267 | [_backgroundObjectContext setPersistentStoreCoordinator:coordinator]; 268 | 269 | [_foregroundObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy]; 270 | [_backgroundObjectContext setMergePolicy:NSOverwriteMergePolicy]; 271 | 272 | } 273 | } 274 | 275 | 276 | 277 | - (id) init{ 278 | self = [super init]; 279 | if (self) { 280 | [self createManagedObjectContext]; 281 | } 282 | return self; 283 | } 284 | @end 285 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Implements/RPCoreDataUnitOfWork.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPUnitOfWork.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "RPIDbUnitOfWork.h" 11 | #import "RPIDbContext.h" 12 | @interface RPCoreDataUnitOfWork : NSObject{ 13 | id dbContext; 14 | } 15 | 16 | @end 17 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Implements/RPCoreDataUnitOfWork.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPUnitOfWork.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "RPCoreDataUnitOfWork.h" 10 | #import "RPGenericRepository.h" 11 | #import "RPCoreDataContext.h" 12 | #import "RPICityRepository.h" 13 | #import "RPCityRepository.h" 14 | #import "RPFakeCityRepository.h" 15 | #import "RPWeatherRepository.h" 16 | #import "User.h" 17 | #import "Photo.h" 18 | #import "City.h" 19 | 20 | @implementation RPCoreDataUnitOfWork 21 | static id _sharedObject; 22 | 23 | -(id) init{ 24 | if (_sharedObject) { 25 | return _sharedObject; 26 | } 27 | else{ 28 | self = [super init]; 29 | if (self) { 30 | dbContext = [[RPCoreDataContext alloc] init]; 31 | } 32 | return self; 33 | } 34 | } 35 | 36 | + (id)sharedInstance{ 37 | static dispatch_once_t onceToken; 38 | dispatch_once(&onceToken, ^{ 39 | _sharedObject = [[RPCoreDataUnitOfWork alloc] init]; 40 | }); 41 | return _sharedObject; 42 | } 43 | 44 | - (id) userRepository{ 45 | return [[RPGenericRepository alloc] initWithDbContext:dbContext withModel:[User class]]; 46 | } 47 | 48 | - (id) photoRepository{ 49 | return [[RPGenericRepository alloc] initWithDbContext:dbContext withModel:[Photo class]]; 50 | } 51 | 52 | - (id) cityRepository{ 53 | /* 54 | return implemented repository 55 | */ 56 | return [[RPCityRepository alloc] initWithDbContext:dbContext withModel:[City class]]; 57 | /* 58 | return Fake Repository 59 | */ 60 | //return [[RPFakeCityRepository alloc] initWithDbContext:dbContext withModel:[City class]]; 61 | } 62 | 63 | - (id) weatherRepository{ 64 | return [[RPWeatherRepository alloc] init]; 65 | } 66 | 67 | - (void)saveChanges{ 68 | [dbContext saveChanges]; 69 | } 70 | @end 71 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Implements/RPWeatherRepository.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPWeatherRepository.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "RPGenericRepository.h" 10 | #import "RPIWeatherRepository.h" 11 | @interface RPWeatherRepository : RPGenericRepository 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Implements/RPWeatherRepository.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPWeatherRepository.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "RPWeatherRepository.h" 10 | #import "Weather.h" 11 | 12 | @implementation RPWeatherRepository 13 | 14 | - (void)getWeatherFeed:(void (^)(NSArray *))success fail:(void (^)(int, NSError *))fail{ 15 | RPHTTPClient *client = [RPHTTPClient sharedInstance]; 16 | NSString *api = @"weatherJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo"; 17 | [client getPath:api 18 | parameters:nil 19 | success:^(AFHTTPRequestOperation *operation, id responseObject) { 20 | NSArray *items = [responseObject objectForKey:@"weatherObservations"]; 21 | NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:1]; 22 | // Just fetch items without insert to DB 23 | for (NSDictionary *item in items) { 24 | Weather *weather = [[Weather alloc] init]; 25 | [weather updateWithDictionary:item]; 26 | [result addObject:weather]; 27 | } 28 | success(result); 29 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 30 | int statusCode = [[operation response] statusCode]; 31 | fail(statusCode,error); 32 | }]; 33 | } 34 | @end 35 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Supports/RPHTTPClient.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPHTTPClient.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "AFHTTPClient.h" 10 | 11 | @interface RPHTTPClient : AFHTTPClient 12 | + (RPHTTPClient*) sharedInstance; 13 | @end 14 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Supports/RPHTTPClient.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPHTTPClient.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "RPHTTPClient.h" 10 | #import "AFJSONRequestOperation.h" 11 | 12 | @implementation RPHTTPClient 13 | #define APIURL @"http://api.geonames.org/" 14 | static RPHTTPClient *_sharedObject; 15 | 16 | - (id)init{ 17 | if (_sharedObject) { 18 | return _sharedObject; 19 | } 20 | else{ 21 | self = [super initWithBaseURL:[NSURL URLWithString:APIURL]]; 22 | [self setDefaultHeader:@"Accept" value:@"application/json"]; 23 | [self setParameterEncoding:AFJSONParameterEncoding]; 24 | [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; 25 | return self; 26 | } 27 | } 28 | 29 | + (RPHTTPClient *)sharedInstance{ 30 | static dispatch_once_t onceToken; 31 | dispatch_once(&onceToken, ^{ 32 | _sharedObject = [[RPHTTPClient alloc] init]; 33 | }); 34 | return _sharedObject; 35 | } 36 | 37 | @end 38 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Supports/RPNSManagedObjectContext+Queryable.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSManagedObjectContext+Queryable.h 3 | // ios-queryable 4 | // 5 | // Created by Marty on 2012-11-07. 6 | // Copyright (c) 2012 Marty. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | 13 | @interface IQueryable : NSObject 14 | 15 | -(id)initWithType:(NSString*)type context:(NSManagedObject*)theContext; 16 | 17 | -(NSArray*) toArray; 18 | 19 | -(IQueryable*)orderBy:(NSString*)fieldName; 20 | 21 | -(IQueryable*)orderByDescending:(NSString*)fieldName; 22 | 23 | -(IQueryable*)skip:(int)numberToSkip; 24 | 25 | -(IQueryable*)take:(int)numberToTake; 26 | 27 | -(id)first; 28 | 29 | -(id)firstOrDefault; 30 | 31 | -(IQueryable*) where:(NSString*)condition; 32 | 33 | @end 34 | 35 | 36 | @interface NSManagedObjectContext (Queryable) 37 | 38 | -(IQueryable*)ofType:(NSString*)typeName; 39 | 40 | @end 41 | 42 | -------------------------------------------------------------------------------- /RepositoryPattern/Repositories/Supports/RPNSManagedObjectContext+Queryable.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSManagedObjectContext+Queryable.m 3 | // ios-queryable 4 | // 5 | // Created by Marty on 2012-11-07. 6 | // Copyright (c) 2012 Marty. All rights reserved. 7 | // 8 | 9 | #import "RPNSManagedObjectContext+Queryable.h" 10 | 11 | @implementation NSManagedObjectContext (Queryable) 12 | 13 | -(IQueryable*) ofType:(NSString*)typeName 14 | { 15 | return [[IQueryable alloc] initWithType:typeName context:self]; 16 | } 17 | 18 | @end 19 | 20 | 21 | @interface IQueryable() 22 | 23 | @property (strong) NSManagedObjectContext* context; 24 | @property (strong) NSArray* sorts; 25 | @property (strong) NSArray* whereClauses; 26 | 27 | @property int skipCount; 28 | @property int takeCount; 29 | @property (strong) NSString* type; 30 | 31 | @end 32 | 33 | 34 | @implementation IQueryable 35 | 36 | @synthesize takeCount; 37 | @synthesize skipCount; 38 | @synthesize sorts; 39 | @synthesize whereClauses; 40 | @synthesize context; 41 | @synthesize type; 42 | 43 | -(id)initWithType:(NSString *)entityType context:(NSManagedObjectContext*)theContext 44 | { 45 | self = [super init]; 46 | if(self != nil) 47 | { 48 | self.type = entityType; 49 | self.context = theContext; 50 | self.takeCount = INT32_MAX; 51 | self.skipCount = 0; 52 | } 53 | 54 | return self; 55 | } 56 | 57 | -(id)initWithType:(NSString*)entityType context:(NSManagedObjectContext*)theContext take:(int)newTake skip:(int)newSkip sorts:(NSArray*)newSorts whereClauses:(NSArray*)newWhereClauses 58 | { 59 | self = [super init]; 60 | if(self != nil) 61 | { 62 | self.type = entityType; 63 | self.context = theContext; 64 | self.takeCount = newTake; 65 | self.skipCount = newSkip; 66 | self.sorts = newSorts; 67 | self.whereClauses = newWhereClauses; 68 | } 69 | 70 | return self; 71 | } 72 | 73 | -(NSArray*)toArray 74 | { 75 | if(self.takeCount <= 0) 76 | return [[NSArray alloc] init]; 77 | 78 | int skip = MAX(self.skipCount, 0); 79 | 80 | NSError* error = nil; 81 | 82 | NSEntityDescription *entityDescription = [NSEntityDescription 83 | entityForName:self.type 84 | inManagedObjectContext:self.context]; 85 | 86 | NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init]; 87 | [fetchRequest setEntity:entityDescription]; 88 | 89 | fetchRequest.sortDescriptors = self.sorts; 90 | 91 | [fetchRequest setFetchOffset:skip]; 92 | [fetchRequest setFetchLimit:self.takeCount]; 93 | 94 | if(self.whereClauses != nil) 95 | fetchRequest.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:self.whereClauses]; 96 | 97 | NSArray* results = [self.context executeFetchRequest:fetchRequest error:&error]; 98 | return results; 99 | } 100 | 101 | -(NSArray*)add:(id)object toArray:(NSArray*)array 102 | { 103 | NSMutableArray* a = [NSMutableArray arrayWithArray:array]; 104 | return [a arrayByAddingObject:object]; 105 | } 106 | 107 | -(IQueryable*) orderBy:(NSString*)fieldName 108 | { 109 | NSSortDescriptor* descriptor = [[NSSortDescriptor alloc] initWithKey:fieldName ascending:true]; 110 | NSArray* newSorts = [self add:descriptor toArray:self.sorts]; 111 | 112 | IQueryable* q = [[IQueryable alloc] initWithType:self.type context:self.context take:self.takeCount skip:self.skipCount sorts:newSorts whereClauses:self.whereClauses]; 113 | return q; 114 | } 115 | 116 | -(IQueryable*) orderByDescending:(NSString*)fieldName 117 | { 118 | NSSortDescriptor* descriptor = [[NSSortDescriptor alloc] initWithKey:fieldName ascending:false]; 119 | NSArray* newSorts = [self add:descriptor toArray:self.sorts]; 120 | 121 | IQueryable* q = [[IQueryable alloc] initWithType:self.type context:self.context take:self.takeCount skip:self.skipCount sorts:newSorts whereClauses:self.whereClauses]; 122 | return q; 123 | } 124 | 125 | -(IQueryable*) skip:(int)numberToSkip 126 | { 127 | IQueryable* q = [[IQueryable alloc] initWithType:self.type context:self.context take:self.takeCount skip:numberToSkip sorts:self.sorts whereClauses:self.whereClauses]; 128 | 129 | return q; 130 | } 131 | 132 | -(IQueryable*) take:(int)numberToTake 133 | { 134 | IQueryable* q = [[IQueryable alloc] initWithType:self.type context:self.context take:numberToTake skip:self.skipCount sorts:self.sorts whereClauses:self.whereClauses]; 135 | 136 | return q; 137 | } 138 | 139 | -(IQueryable*)where:(NSString*)condition 140 | { 141 | NSPredicate* predicate = [NSPredicate predicateWithFormat:condition]; 142 | NSArray* newWheres = [self add:predicate toArray:self.whereClauses]; 143 | 144 | IQueryable* q = [[IQueryable alloc] initWithType:self.type context:self.context take:self.takeCount skip:self.skipCount sorts:self.sorts whereClauses:newWheres]; 145 | 146 | return q; 147 | } 148 | 149 | -(id)first 150 | { 151 | id result = [self firstOrDefault]; 152 | if(!result) 153 | [NSException raise:@"The source sequence is empty" format:@""]; 154 | 155 | return result; 156 | } 157 | 158 | -(id)firstOrDefault 159 | { 160 | IQueryable* q = [[IQueryable alloc] initWithType:self.type context:self.context take:1 skip:self.skipCount sorts:self.sorts whereClauses:self.whereClauses]; 161 | 162 | NSArray* results = [q toArray]; 163 | if(results.count > 0) 164 | return [results objectAtIndex:0]; 165 | else 166 | return nil; 167 | } 168 | 169 | @end -------------------------------------------------------------------------------- /RepositoryPattern/RepositoryPattern-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | ${PRODUCT_NAME} 9 | CFBundleExecutable 10 | ${EXECUTABLE_NAME} 11 | CFBundleIconFiles 12 | 13 | CFBundleIdentifier 14 | com.ducn.${PRODUCT_NAME:rfc1034identifier} 15 | CFBundleInfoDictionaryVersion 16 | 6.0 17 | CFBundleName 18 | ${PRODUCT_NAME} 19 | CFBundlePackageType 20 | APPL 21 | CFBundleShortVersionString 22 | 1.0 23 | CFBundleSignature 24 | ???? 25 | CFBundleVersion 26 | 1.0 27 | LSRequiresIPhoneOS 28 | 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /RepositoryPattern/RepositoryPattern-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header for all source files of the 'RepositoryPattern' target in the 'RepositoryPattern' project 3 | // 4 | 5 | #import 6 | 7 | #ifndef __IPHONE_3_0 8 | #warning "This project uses features only available in iOS SDK 3.0 and later." 9 | #endif 10 | 11 | #ifdef __OBJC__ 12 | #import 13 | #import 14 | #import 15 | #import 16 | #import "AFHTTPRequestOperation.h" 17 | #import "RPAppDelegate.h" 18 | #import "RPIDbUnitOfWork.h" 19 | #import "RPHTTPClient.h" 20 | #endif 21 | 22 | // Core data stuff 23 | #define kCoreDataModelName @"RepositoryPattern" 24 | #define kSqlLiteDbName @"RepositoryPattern.sqlite" -------------------------------------------------------------------------------- /RepositoryPattern/Resource/RepositoryPattern.xcdatamodeld/.xccurrentversion: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | _XCCurrentVersionName 6 | RepositoryPattern.xcdatamodel 7 | 8 | 9 | -------------------------------------------------------------------------------- /RepositoryPattern/Resource/RepositoryPattern.xcdatamodeld/RepositoryPattern.xcdatamodel/contents: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /RepositoryPattern/Views/City/RPCityView.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1536 5 | 11G63 6 | 2840 7 | 1138.51 8 | 569.00 9 | 10 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 11 | 1926 12 | 13 | 14 | IBProxyObject 15 | IBUITableView 16 | IBUIView 17 | 18 | 19 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 20 | 21 | 22 | PluginDependencyRecalculationVersion 23 | 24 | 25 | 26 | 27 | IBFilesOwner 28 | IBCocoaTouchFramework 29 | 30 | 31 | IBFirstResponder 32 | IBCocoaTouchFramework 33 | 34 | 35 | 36 | 274 37 | 38 | 39 | 40 | 274 41 | {320, 548} 42 | 43 | 44 | _NS:9 45 | 46 | 3 47 | MQA 48 | 49 | YES 50 | IBCocoaTouchFramework 51 | YES 52 | 1 53 | 0 54 | YES 55 | 44 56 | 22 57 | 22 58 | 59 | 60 | {{0, 20}, {320, 548}} 61 | 62 | 63 | 64 | 65 | 3 66 | MQA 67 | 68 | 2 69 | 70 | 71 | 72 | 73 | IBUIScreenMetrics 74 | 75 | YES 76 | 77 | 78 | 79 | 80 | 81 | {320, 568} 82 | {568, 320} 83 | 84 | 85 | IBCocoaTouchFramework 86 | Retina 4 Full Screen 87 | 2 88 | 89 | IBCocoaTouchFramework 90 | 91 | 92 | 93 | 94 | 95 | 96 | view 97 | 98 | 99 | 100 | 3 101 | 102 | 103 | 104 | tableView 105 | 106 | 107 | 108 | 21 109 | 110 | 111 | 112 | dataSource 113 | 114 | 115 | 116 | 15 117 | 118 | 119 | 120 | delegate 121 | 122 | 123 | 124 | 16 125 | 126 | 127 | 128 | 129 | 130 | 0 131 | 132 | 133 | 134 | 135 | 136 | -1 137 | 138 | 139 | File's Owner 140 | 141 | 142 | -2 143 | 144 | 145 | 146 | 147 | 1 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 4 156 | 157 | 158 | 159 | 160 | 161 | 162 | RPCityViewController 163 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 164 | UIResponder 165 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 166 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 167 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 168 | 169 | 170 | 171 | 172 | 173 | 21 174 | 175 | 176 | 177 | 178 | RPCityViewController 179 | UIViewController 180 | 181 | tableView 182 | UITableView 183 | 184 | 185 | tableView 186 | 187 | tableView 188 | UITableView 189 | 190 | 191 | 192 | IBProjectSource 193 | ./Classes/RPCityViewController.h 194 | 195 | 196 | 197 | 198 | 0 199 | IBCocoaTouchFramework 200 | YES 201 | 3 202 | 1926 203 | 204 | 205 | -------------------------------------------------------------------------------- /RepositoryPattern/Views/City/RPCityViewCell.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPCityViewCell.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | #import "City.h" 11 | @interface RPCityViewCell : UITableViewCell{ 12 | IBOutlet UILabel *cityName; 13 | } 14 | @property(nonatomic,assign) City *city; 15 | - (void)bindData; 16 | @end 17 | -------------------------------------------------------------------------------- /RepositoryPattern/Views/City/RPCityViewCell.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPCityViewCell.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "RPCityViewCell.h" 10 | 11 | @implementation RPCityViewCell 12 | 13 | - (id)initWithCoder:(NSCoder *)aDecoder{ 14 | self = [super initWithCoder:aDecoder]; 15 | return self; 16 | } 17 | - (void)bindData{ 18 | cityName.text = self.city.name; 19 | } 20 | @end 21 | -------------------------------------------------------------------------------- /RepositoryPattern/Views/City/RPCityViewCell.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1536 5 | 11G63 6 | 2840 7 | 1138.51 8 | 569.00 9 | 10 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 11 | 1926 12 | 13 | 14 | IBProxyObject 15 | IBUILabel 16 | IBUITableViewCell 17 | 18 | 19 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 20 | 21 | 22 | PluginDependencyRecalculationVersion 23 | 24 | 25 | 26 | 27 | IBFilesOwner 28 | IBCocoaTouchFramework 29 | 30 | 31 | IBFirstResponder 32 | IBCocoaTouchFramework 33 | 34 | 35 | 36 | 292 37 | 38 | 39 | 40 | 256 41 | 42 | 43 | 44 | 292 45 | {{25, 11}, {280, 21}} 46 | 47 | 48 | _NS:9 49 | NO 50 | YES 51 | 7 52 | NO 53 | IBCocoaTouchFramework 54 | Label 55 | 56 | 1 57 | MCAwIDAAA 58 | darkTextColor 59 | 60 | 61 | 3 62 | MQA 63 | 64 | 0 65 | 66 | 1 67 | 17 68 | 69 | 70 | Helvetica 71 | 17 72 | 16 73 | 74 | NO 75 | 76 | 77 | {320, 43} 78 | 79 | 80 | 81 | _NS:11 82 | 83 | 3 84 | MCAwAA 85 | 86 | NO 87 | YES 88 | 4 89 | YES 90 | IBCocoaTouchFramework 91 | 92 | 93 | {320, 44} 94 | 95 | 96 | 97 | _NS:9 98 | IBCocoaTouchFramework 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | cityName 107 | 108 | 109 | 110 | 11 111 | 112 | 113 | 114 | 115 | 116 | 0 117 | 118 | 119 | 120 | 121 | 122 | -1 123 | 124 | 125 | File's Owner 126 | 127 | 128 | -2 129 | 130 | 131 | 132 | 133 | 6 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 7 142 | 143 | 144 | 145 | 146 | 147 | 148 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 149 | UIResponder 150 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 151 | RPCityViewCell 152 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 153 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 154 | 155 | 156 | 157 | 158 | 159 | 11 160 | 161 | 162 | 163 | 164 | RPCityViewCell 165 | UITableViewCell 166 | 167 | cityName 168 | UILabel 169 | 170 | 171 | cityName 172 | 173 | cityName 174 | UILabel 175 | 176 | 177 | 178 | IBProjectSource 179 | ./Classes/RPCityViewCell.h 180 | 181 | 182 | 183 | 184 | 0 185 | IBCocoaTouchFramework 186 | YES 187 | 3 188 | 1926 189 | 190 | 191 | -------------------------------------------------------------------------------- /RepositoryPattern/Views/Weather/RPWeatherView.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1536 5 | 11G63 6 | 2840 7 | 1138.51 8 | 569.00 9 | 10 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 11 | 1926 12 | 13 | 14 | IBProxyObject 15 | IBUITableView 16 | IBUIView 17 | 18 | 19 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 20 | 21 | 22 | PluginDependencyRecalculationVersion 23 | 24 | 25 | 26 | 27 | IBFilesOwner 28 | IBCocoaTouchFramework 29 | 30 | 31 | IBFirstResponder 32 | IBCocoaTouchFramework 33 | 34 | 35 | 36 | 274 37 | 38 | 39 | 40 | 274 41 | {320, 548} 42 | 43 | 44 | _NS:9 45 | 46 | 3 47 | MQA 48 | 49 | YES 50 | IBCocoaTouchFramework 51 | YES 52 | 1 53 | 0 54 | YES 55 | 44 56 | 22 57 | 22 58 | 59 | 60 | {{0, 20}, {320, 548}} 61 | 62 | 63 | 64 | 65 | 3 66 | MQA 67 | 68 | 2 69 | 70 | 71 | 72 | 73 | IBUIScreenMetrics 74 | 75 | YES 76 | 77 | 78 | 79 | 80 | 81 | {320, 568} 82 | {568, 320} 83 | 84 | 85 | IBCocoaTouchFramework 86 | Retina 4 Full Screen 87 | 2 88 | 89 | IBCocoaTouchFramework 90 | 91 | 92 | 93 | 94 | 95 | 96 | view 97 | 98 | 99 | 100 | 12 101 | 102 | 103 | 104 | tableView 105 | 106 | 107 | 108 | 13 109 | 110 | 111 | 112 | dataSource 113 | 114 | 115 | 116 | 14 117 | 118 | 119 | 120 | delegate 121 | 122 | 123 | 124 | 15 125 | 126 | 127 | 128 | 129 | 130 | 0 131 | 132 | 133 | 134 | 135 | 136 | 1 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | -1 145 | 146 | 147 | File's Owner 148 | 149 | 150 | -2 151 | 152 | 153 | 154 | 155 | 3 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | RPWeatherViewController 164 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 165 | UIResponder 166 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 167 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 168 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 169 | 170 | 171 | 172 | 173 | 174 | 15 175 | 176 | 177 | 178 | 179 | RPWeatherViewController 180 | UIViewController 181 | 182 | tableView 183 | UITableView 184 | 185 | 186 | tableView 187 | 188 | tableView 189 | UITableView 190 | 191 | 192 | 193 | IBProjectSource 194 | ./Classes/RPWeatherViewController.h 195 | 196 | 197 | 198 | 199 | 0 200 | IBCocoaTouchFramework 201 | YES 202 | 3 203 | 1926 204 | 205 | 206 | -------------------------------------------------------------------------------- /RepositoryPattern/Views/Weather/RPWeatherViewCell.h: -------------------------------------------------------------------------------- 1 | // 2 | // RPWeatherCell.h 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import 10 | #import "Weather.h" 11 | @interface RPWeatherViewCell : UITableViewCell{ 12 | IBOutlet UILabel *lbstatus; 13 | } 14 | @property(nonatomic,assign) Weather *weather; 15 | - (void) bindData; 16 | @end 17 | -------------------------------------------------------------------------------- /RepositoryPattern/Views/Weather/RPWeatherViewCell.m: -------------------------------------------------------------------------------- 1 | // 2 | // RPWeatherCell.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 11/12/12. 6 | // 7 | // 8 | 9 | #import "RPWeatherViewCell.h" 10 | 11 | @implementation RPWeatherViewCell 12 | 13 | - (void)bindData{ 14 | lbstatus.text = self.weather.stationName; 15 | } 16 | 17 | @end 18 | -------------------------------------------------------------------------------- /RepositoryPattern/Views/Weather/RPWeatherViewCell.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1536 5 | 11G63 6 | 2840 7 | 1138.51 8 | 569.00 9 | 10 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 11 | 1926 12 | 13 | 14 | IBProxyObject 15 | IBUILabel 16 | IBUITableViewCell 17 | 18 | 19 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 20 | 21 | 22 | PluginDependencyRecalculationVersion 23 | 24 | 25 | 26 | 27 | IBFilesOwner 28 | IBCocoaTouchFramework 29 | 30 | 31 | IBFirstResponder 32 | IBCocoaTouchFramework 33 | 34 | 35 | 36 | 292 37 | 38 | 39 | 40 | 256 41 | 42 | 43 | 44 | 292 45 | {{20, 11}, {280, 21}} 46 | 47 | 48 | _NS:9 49 | NO 50 | YES 51 | 7 52 | NO 53 | IBCocoaTouchFramework 54 | Label 55 | 56 | 1 57 | MSAwIDAAA 58 | 59 | 60 | 3 61 | MQA 62 | 63 | 0 64 | 65 | 1 66 | 17 67 | 68 | 69 | Helvetica 70 | 17 71 | 16 72 | 73 | NO 74 | 75 | 76 | {320, 43} 77 | 78 | 79 | 80 | _NS:11 81 | 82 | 3 83 | MCAwAA 84 | 85 | NO 86 | YES 87 | 4 88 | YES 89 | IBCocoaTouchFramework 90 | 91 | 92 | {320, 44} 93 | 94 | 95 | 96 | _NS:9 97 | IBCocoaTouchFramework 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | lbstatus 106 | 107 | 108 | 109 | 8 110 | 111 | 112 | 113 | 114 | 115 | 0 116 | 117 | 118 | 119 | 120 | 121 | -1 122 | 123 | 124 | File's Owner 125 | 126 | 127 | -2 128 | 129 | 130 | 131 | 132 | 3 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 4 141 | 142 | 143 | 144 | 145 | 146 | 147 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 148 | UIResponder 149 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 150 | RPWeatherViewCell 151 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 152 | com.apple.InterfaceBuilder.IBCocoaTouchPlugin 153 | 154 | 155 | 156 | 157 | 158 | 8 159 | 160 | 161 | 162 | 163 | RPWeatherViewCell 164 | UITableViewCell 165 | 166 | lbstatus 167 | UILabel 168 | 169 | 170 | lbstatus 171 | 172 | lbstatus 173 | UILabel 174 | 175 | 176 | 177 | IBProjectSource 178 | ./Classes/RPWeatherViewCell.h 179 | 180 | 181 | 182 | 183 | 0 184 | IBCocoaTouchFramework 185 | YES 186 | 3 187 | 1926 188 | 189 | 190 | -------------------------------------------------------------------------------- /RepositoryPattern/en.lproj/InfoPlist.strings: -------------------------------------------------------------------------------- 1 | /* Localized versions of Info.plist keys */ 2 | 3 | -------------------------------------------------------------------------------- /RepositoryPattern/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // RepositoryPattern 4 | // 5 | // Created by Duc Ngo on 8/17/12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | #import "RPAppDelegate.h" 12 | 13 | int main(int argc, char *argv[]) 14 | { 15 | @autoreleasepool { 16 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([RPAppDelegate class])); 17 | } 18 | } 19 | --------------------------------------------------------------------------------