Skip to content

Instantly share code, notes, and snippets.

@jamiebullock
Created March 20, 2017 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiebullock/0a792a4ba6dbc95e3fb2c2acfe695050 to your computer and use it in GitHub Desktop.
Save jamiebullock/0a792a4ba6dbc95e3fb2c2acfe695050 to your computer and use it in GitHub Desktop.
Test for Cocoa connecting to a remote URL
#import <Foundation/Foundation.h>
@interface SimpleURL : NSObject {
NSURLSession *session;
}
-(void)connect:(NSString *)url;
-(void)handleResponse:(NSURLResponse *)response;
@end
@implementation SimpleURL
- (instancetype)init
{
self = [super init];
if (self)
{
//session = [NSURLSession sharedSession];
}
return self;
}
-(void)handleResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
// NSLog(@"response status code: %ld", (long)[httpResponse statusCode]);
}
-(void)connect:(NSString *)url
{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
session = [NSURLSession sharedSession];
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: url] cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 60.0];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:req completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error){
if (error)
{
[self handleResponse:response];
dispatch_semaphore_signal(semaphore);
}
else {
[self handleResponse:response];
dispatch_semaphore_signal(semaphore);
}
}];
[dataTask resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
@end
int main(int argc, const char * argv[])
{
SimpleURL *simple = [[SimpleURL alloc] init];
double count = 0.0;
int iterations = 100;
NSString *url = @"https://s3.amazonaws.com";
for (int i = 0; i < iterations; ++i)
{
NSLog(@"****** Running test %d ******", i);
NSDate *start = [NSDate date];
[simple connect:url];
NSTimeInterval timeInterval = [start timeIntervalSinceNow];
NSLog(@"Time: %f", fabs(timeInterval));
count += timeInterval;
}
NSLog(@"AVERAGE: %f", fabs(count) / (double)iterations);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment