I was trying the below code but [self performSelector:handler withObject:data afterDelay:0]
in the sync function does not call the handler1
or handler2
methods, even when I'm passing the handlers from initWithType
method. The handler is not going null I have already checked that.
Can someone please tell me what is going wrong?
- (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
}
I found a fix.
i used performSelector:withObject:
like @skyylex suggested. also i changed the type of handler from SEL to NSString and did this [self performSelector:(NSSelectorFromString(handler)) withObject:data];
it worked.