iOS objective c 从无法访问全局变量的服务器 NSUrl 检索数据

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

嗨,我是 iOS 的新手,我正在向服务器发出请求并获取手机号码,通过请求回复我能够获得 otp,但是当我从 seesion 中打印数据时在块内初始化,我得到 null

这是我的 .h 文件

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

这是我在 .m 文件中的 url 请求块

- (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;

}

这是我的打印日志

 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

块是额外的线程,所以你需要等待完成块,所以改变你的代码如下

如果你想访问外部的数据

 - (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;

}