dimanche 2 novembre 2014

NSURLSession in a separate class cannot pass data to the ViewController


Vote count:

0




I'm learning the NSURLSession class and I wanted to create a separate class in my project with all the methods I use to retrieve data from a web service.


This is the header file, tclass.h



#import <Foundation/Foundation.h>

@interface tclass : NSObject

- (void)returnIP;
@property (nonatomic, strong) NSString *IP ;

@end


This is the implementation file, tclass.m



#import "tclass.h"

@implementation tclass

- (id)init {
self = [super init];
return self;
}

- (void)returnIP {
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:@"http://icanhazip.com/"]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
[self setIP:[NSString stringWithUTF8String:[data bytes]]];
}] resume];
}


@end


In my ViewController class, I firstly use the returnIP method to retrieve the data and to store it in a property then I update the UI, all of this using dispatch_async.



- (IBAction)butact:(id)sender {
tclass *t = [[tclass alloc]init];

[_round setHidden:NO];
[_round startAnimating];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
[t returnIP];
dispatch_async(dispatch_get_main_queue(), ^{
[_round stopAnimating];
[_round setHidden:NO];
[_lab setText:[t IP]];
});
});

}


My problem is that the IP property is not populated, and the UI update does not appear to be done even though I'm using the main queue to do it.


How can I accomplish this process?


Is my approach completely wrong?


Thanks for your help.



asked 29 secs ago







NSURLSession in a separate class cannot pass data to the ViewController

Aucun commentaire:

Enregistrer un commentaire