URL会话无法延迟执行

时间:2017-06-05 04:47:58

标签: ios objective-c xcode url

我正在请求一个URL会话,但在从URL获取数据之前,我的程序继续执行而不会获取给我一个错误的数据。 那么如何延迟执行直到会话结束或如何执行会话然后继续代码?

- (IBAction)submitb:(id)sender{
if(_otptf.text==self.otpStr && _otptf.text>0){
    NSString *post = [NSString stringWithFormat:@"phone=%@,otp=%@",self.stri1,self.stri];
    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/otp_verify.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) {
        [NSTimer scheduledTimerWithTimeInterval: 2.0
                                         target: self
                                       selector:@selector(onTick:)
                                       userInfo: nil repeats:NO];
        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(@"Req:%@",requestReply);
        NSLog(@"requestReply: %@", jsonDict);
        self.tmpv=[jsonDict valueForKey:@"sucess"] ;
        self.strv=self.tmpv;
        NSLog(@"tmp storage inside block:%@",self.tmpv);
        [NSTimer scheduledTimerWithTimeInterval: 2.0
                                         target: self
                                       selector:@selector(onTick:)
                                       userInfo: nil repeats:NO];
    }] resume];
   // [self performSegueWithIdentifier:<#(nonnull NSString *)#> sender:<#(nullable id)#>]
   //[self stats];
   // dispatch_async(dispatch_get_main_queue(), ^{
    [NSTimer scheduledTimerWithTimeInterval: 2.0
                                     target: self
                                   selector:@selector(onTick:)
                                   userInfo: nil repeats:NO];
      //  [self performSegueWithIdentifier:@"b2" sender:self];
    [self stats];
    //});
}

提前感谢您的建议!!

0 个答案:

没有答案