blob: 1daa4b142ee21318febff28d5d68f5365b1ef188 [file] [log] [blame] [edit]
#import "ViewController.h"
#import "AppDelegate.h"
#import <Courier/Courier.h>
static NSString * const TestTaskGroup1 = @"TestTaskGroup1";
static NSString * const TestTaskGroup2 = @"TestTaskGroup2";
@interface ViewController ()
@property (nonatomic, strong) CRSessionController *sessionController;
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPMaximumConnectionsPerHost = 1;
configuration.URLCache = nil;
_sessionController = [CRSessionController sessionControllerWithConfiguration:configuration];
[_sessionController setReachabilityStatusChangeBlock:^(NetworkStatus status) {
if (status == NotReachable) {
NSLog(@"Not reachable!");
} else {
NSLog(@"Reachable!");
}
}];
[_sessionController startReachabilityMonitoring];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - IBAction
- (IBAction)startNetworkRequests:(id)sender {
for (NSInteger i = 0; i < 10; i++) {
BOOL even = i % 2;
if (even) {
[self startImageDownloadTaskInTaskGroup:TestTaskGroup1];
} else {
[self startImageDownloadTaskInTaskGroup:TestTaskGroup2];
}
}
}
- (IBAction)startNetworkRequestsOnAnotherThread:(id)sender {
for (NSInteger i = 0; i < 10; i++) {
BOOL even = i % 2;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
if (even) {
[self startImageDownloadTaskInTaskGroup:TestTaskGroup1];
} else {
[self startImageDownloadTaskInTaskGroup:TestTaskGroup2];
}
});
}
}
- (IBAction)stopNetworkRequests:(id)sender {
[self.sessionController cancelTasksInGroup:TestTaskGroup1];
[self.sessionController cancelTasksInGroup:TestTaskGroup2];
}
- (IBAction)nilSessionController:(id)sender {
@autoreleasepool {
[self.sessionController.session invalidateAndCancel];
self.sessionController = nil;
}
}
- (IBAction)printHasTasks:(id)sender {
NSLog(@"Has tasks %i", [self.sessionController hasTasksInGroup:TestTaskGroup1
withState:NSURLSessionTaskStateRunning]);
}
#pragma mark -
- (void)startImageDownloadTaskInTaskGroup:(NSString *)taskGroup {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://static.fjcdn.com/pictures/Space_03b120_799520.jpg"]];
NSURLSessionDataTask *task =
[self.sessionController dataTaskForRequest:request
taskGroup:taskGroup
completionHandler: ^(NSData *data,
NSURLResponse *response,
BOOL cachedResponse,
NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
}
if (response.cou_success) {
NSLog(@"Downloaded image!");
UIImage *image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = image;
});
}
else {
NSLog(@"Error: %li", response.cou_statusCode);
}
}];
[task resume];
}
@end