Showing posts with label Objective-C. Show all posts
Showing posts with label Objective-C. Show all posts

Monday, January 16, 2017

Dismiss Keyboard When Tapping Outside UITextField

A quick way to dismiss keyboard when tapping outside a UITextField can be done as follows.
- (void)viewDidLoad {
    ...
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] 
                                       initWithTarget:self.view 
                                               action:@selector(endEditing:)]];
    ...
}

The same can be re-written with a selector method as follows.
- (void)viewDidLoad {
    ...
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] 
                                     initWithTarget:self
                                             action:@selector(hideKeyboard)];
    [self.view addGestureRegnizer:tap];
    ...
}

- (void)hideKeyboard {
    [self.view endEditing:YES];
}

Friday, January 13, 2017

Async Request using dataTaskWithRequest

Here is a simple example of Async Request using [NSURLSession dataTaskWithURL].

- (void) asyncDemo1 { NSURL *url = [NSURL URLWithString:@"https://mysite.com/sampleData.json"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable taskError) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ // ----- Place background thread operations here ----- // dispatch_async(dispatch_get_main_queue(), ^(void){ // ----- Place async UI update, etc here ----- // if(taskError){ NSLog(@"taskError is %@", [taskError localizedDescription]); } else{ NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } }); }); }]; [task resume]; }