Search code examples
iosobjective-cxcodensurl

iOS objective c retrieving data from server NSUrl not able to access to global variable


hi I am new to iOS and I am giving request to server and getting top to the mobile number and through request reply I am able to get the otp but when I print the data out of the seesion which is initialised inside block I am getting null

this is my .h file

#import <UIKit/UIKit.h>. 
@interface OtpViewController : UIViewController
@property (nonatomic,strong) NSString *str;
@property (strong,nonatomic) NSString *tmp;
@property(weak,nonatomic) NSString *requestReply ;
@end

this is my url request block in .m file

- (IBAction)submitb:(id)sender
{
if (_mobiletf.text && _mobiletf.text.length >0 )
{
    /* not empty - do something */
    NSString *post = [NSString stringWithFormat:@"phone=%@",_mobiletf.text];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    //  Next up, we read the postData's length, so we can pass it along in the request.
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    // Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://www.sitesandflats.com/send_otp.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];
    NSLog(@"the data Details is %@", post);
    //   And finally, we can send our request, and read the reply by creating a new NSURLSession:
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
         //   NSError *error;
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
            NSLog(@"requestReply: %@", jsonDict);
            self.tmp=[jsonDict valueForKey:@"otp"] ;
            self.str=self.tmp;
            NSLog(@"tmp storage inside block:%@",self.tmp);

            [self performSelector:@selector(updateStatus) withObject:nil afterDelay:1.0];
           // NSLog(@"requestReply: %@", jsonDict);

            //self.tmp=[jsonDict valueForKey:@"otp"] ;
            //self.str=self.tmp;
            //NSLog(@"tmp storage inside block:%@",self.tmp);
    }] resume];
    //self.str=self.tmp;
    NSLog(@" storage:%@",self.str);
    NSLog(@"tmp storage:%@",self.tmp);
    [ self performSegueWithIdentifier:@"b1" sender:self];

}
else
{
    /* what ever */
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
        message:@"Please check your input!!."
        delegate:self
        cancelButtonTitle:@"OK"
        otherButtonTitles:nil];
    [alert show];
}
}

-(void)updateStatus{
NSLog(@" storage:%@",self.str);
NSLog(@"tmp storage:%@",self.tmp);
 // [ self performSegueWithIdentifier:@"b1" sender:self];


}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable    id)sender
{
VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
loadCtr.otpStr =self.tmp;
loadCtr.mobileStr = _mobiletf.text;

}

this is my print log

 2017-06-01 12:44:08.813 MenuBar[2750:135123] the data Details is phone=9047038606
2017-06-01 12:44:08.829 MenuBar[2750:135123] 9047038606
2017-06-01 12:44:08.835 MenuBar[2750:135123]  storage:(null)
2017-06-01 12:44:08.836 MenuBar[2750:135123] tmp storage:(null)
2017-06-01 12:44:10.122 MenuBar[2750:135162] requestReply: {
otp = 552749;
success = 1; 
}
2017-06-01 12:44:10.122 MenuBar[2750:135162] tmp storage inside block:552749

Solution

  • block is the additional thread , so you need to wait for completion block, so change your code like below

    if you want to acces the data in outside

     - (IBAction)submitb:(id)sender
    {
    if (_mobiletf.text && _mobiletf.text.length >0 )
    {
        /* not empty - do something */
        NSString *post = [NSString stringWithFormat:@"phone=%@",_mobiletf.text];
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        //  Next up, we read the postData's length, so we can pass it along in the request.
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
        // Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:@"http://www.sitesandflats.com/send_otp.php"]];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:postData];
        NSLog(@"the data Details is %@", post);
        //   And finally, we can send our request, and read the reply by creating a new NSURLSession:
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
             //   NSError *error;
                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
                NSLog(@"requestReply: %@", jsonDict);
                self.tmp=[jsonDict valueForKey:@"otp"] ;
                self.str=self.tmp;
                NSLog(@"tmp storage inside block:%@",self.tmp);
    
                [self updateStatus];
    
        }] resume];
    
    
    }
    else
    {
        /* what ever */
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
            message:@"Please check your input!!."
            delegate:self
            cancelButtonTitle:@"OK"
            otherButtonTitles:nil];
        [alert show];
    }
    }
    
    -(void)updateStatus{
    NSLog(@" storage:%@",self.str);
    NSLog(@"tmp storage:%@",self.tmp);
    dispatch_async(dispatch_get_main_queue(), ^{
        [ self performSegueWithIdentifier:@"b1" sender:self];
    });
    
     }
    
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable    id)sender
    {
    VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
    loadCtr.otpStr =self.tmp;
    loadCtr.mobileStr = _mobiletf.text;
    
    }