Search code examples
iosobjective-c-blocks

How to delay the execution of some lines


I have button click event. Inside that I am calling to another method inside another NSObject class. That method is calling to web service within a dispatch block. My button click even is like this

-(IBAction)Loging:(id)sender
{

NSString *strParam=[NSString stringWithFormat:@"userName=%@&password=%@&ipAddress=%@",@"admin",@"1234",@"127.0.0.1"];

NSString *str=[wb prepareURL:@"account/users?" :strParam :NO :YES :nil];
 NSLog(@"data array %@",dm.arrayData);
 NSLog(@"str========= %@",str);
}

My problem is like this. this arrayData and str printing as empty because those two lines get execute before that prepareURLfinish it's execution. I want to execute the later part after fully completed the prepareURL method. What would be the solution for this? If I should use blocks how can I write a block for that? Please help me.

Thanks

UPDATED

-(NSString *)prepareURL :(NSString *)appendString :(NSString *)bindedParams :(BOOL)isauthorized :(BOOL)isGet :(NSMutableDictionary *)jsonBody

 {

dm=[Datamanager sharedManager];
NSString *strToken=dm.strAuthToken;
NSString *strServerURL=[[[NSBundle mainBundle]infoDictionary] objectForKey:@"BaseURL"];
NSString *strfullURL=[NSString stringWithFormat:@"%@%@%@",strServerURL,appendString,bindedParams];
NSURL *url=[NSURL URLWithString:strfullURL];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

if (isauthorized) {

    [request addValue:[NSString stringWithFormat:@"Bearer %@", strToken] forHTTPHeaderField:@"Authorization"];
}

NSString *str=[self GetPostPreperation:request:isGet:jsonBody];

return str;



 }

And this is my GetPostPreperationmethod

-(NSString *)GetPostPreperation :(NSMutableURLRequest *)request :(BOOL)isGet :(NSMutableDictionary *)jsonBody


 {


 NSError *error=nil;
 __block NSString *strReturn;

if (isGet) {
     [request setHTTPMethod:@"GET"];
}

else
{
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
     NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonBody
                                                       options:NSJSONWritingPrettyPrinted error:&error];
    NSString *string = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"Json string %@",string);
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:jsonData];


}


dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
    NSError *error = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error: &error];
    NSString *string = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];


    NSLog(@"Response string %@",string);

    if (!error) {

        NSLog(@"No Error");

        NSError *jsonerror=nil;
        NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: returnData options: NSJSONReadingAllowFragments error: &jsonerror];

        if (!jsonArray) {
            NSLog(@"Error parsing JSON: %@", jsonerror);
            strReturn=[[NSString alloc] initWithFormat:@"%@",jsonerror];
        } else {

            dm=[Datamanager sharedManager];
            [dm.arrayData addObjectsFromArray:jsonArray];


            }

    }
    else
    {
        NSLog(@"Error %@",error);
        strReturn=[NSString stringWithFormat:@"%@",error];

    }

});


return strReturn;




  }

Solution

  • The best native class for api calls in iOS is NSURLSession right now.

    Using this class:

    -(NSString *)prepareURL :(NSString *)appendString :(NSString *)bindedParams :(BOOL)isauthorized :(BOOL)isGet :(NSMutableDictionary *)jsonBody completionHandler:(void(^)(NSData *data, NSURLResponse *response, NSError *error) ) completion{
       NSURLSession *session = [NSURLSession sharedSession];
       NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //request is your NSURLRequest object
        //use the data here to get your wanted result
        completion(data,response,error); //send data to calling class
        }];
        [task resume];
    }
    

    on how to use blocks you can refer this website