ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
dispatch_semaphore_t sem;
NSMutableData *alldata;
}
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
sem = dispatch_semaphore_create(0);
alldata = [[NSMutableData alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[alldata appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
dispatch_semaphore_signal(sem);
}
- (IBAction)clicked:(id)sender {
//run clickThread function in a separate thread
[self performSelectorInBackground:@selector(clickThread) withObject:nil];
}
- (void) makeconnection:(NSString*)url {
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:url]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void) clickThread {
NSLog(@"making connection with google");
//NSURLConnection will only work if it is run on the main thread
[self performSelectorOnMainThread:@selector(makeconnection:) withObject:@"http://www.google.com" waitUntilDone:NO];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
NSLog(@"google done");
NSLog(@"%@", [[NSString alloc] initWithData:alldata encoding:NSUTF8StringEncoding]);
NSLog(@"making connection with yahoo");
sem = dispatch_semaphore_create(0);
alldata = [[NSMutableData alloc] init];
[self performSelectorOnMainThread:@selector(makeconnection:) withObject:@"http://www.yahoo.com" waitUntilDone:NO];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
NSLog(@"yahoo done");
NSLog(@"%@", [[NSString alloc] initWithData:alldata encoding:NSUTF8StringEncoding]);
}
@end