Я пробовал приведенный ниже код, но [self performSelector:handler withObject:data afterDelay:0]
в функции синхронизации не вызывает методы handler1
или handler2
, даже когда я передаю обработчики из метода initWithType
. Обработчик не обнуляется. Я уже проверил это.
Может кто-нибудь сказать мне, что идет не так?
- (instancetype)initWithType:(NSInteger *)Handler
{
switch(Handler)
{
case 0:
[self sync:@selector(handler1:) withURL:SyncURL];
break;
case 1:
[self sync:@selector(handler2:) withURL:SyncURL];
break;
default:
break;
}
-(void)sync : (SEL) handler withURL:(NSString *)str1{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
if(networkStatus==NotReachable)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Connection can't be established " delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
return;
}
else{
NSData *poststring=[syncString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSMutableData *data = [NSMutableData data];
[data appendData:poststring];
NSString * postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[data length]];
NSMutableURLRequest * request =[[NSMutableURLRequest alloc] init];
NSString *ad_user;
NSString *ad_password;
NSString *ad_params;
ad_user = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
ad_password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
NSString *password = [Utility URLEncodeStringFromString:ad_password];
ad_params = [[NSString alloc] initWithFormat:@"ad_user=%@&ad_password=%@",ad_user,password];
NSString *str = [[NSString alloc] initWithFormat:@"%@?&%@",str1,ad_params];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",str]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setTimeoutInterval:240];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:data];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error!=NULL)
{
NSLog(@"error=%@",error.localizedDescription);
}
else
{
[self performSelector:handler withObject:data afterDelay:0];
}
}];
[task resume];
}
}
-(void)handler1:(id )data{
//lines of code to execute
}
-(void)handler2:(id )data{
//lines of code to execute
}