在创建文件后立即显示存折:计时问题

时间:2014-09-06 20:51:52

标签: ios

我正在通过php脚本在服务器上创建存折,并希望立即在我的应用程序中显示它。有时候不能显示存折,因为php脚本还没有写完文件,而代码却继续尝试阅读存折。

这是我的代码:

[request setURL:[NSURL URLWithString:@"https://adress/passbook/makePassbook.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *myConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if (myConnection) {
        // Show Passbook
               ....
        NSData *passData = [NSData dataWithContentsOfURL:urlAdress];
        NSError* error = nil;
        PKPass *newPass = [[PKPass alloc] initWithData:passData
                                         error:&error];
       if (error!=nil) {
           // Show error message
       }

       PKAddPassesViewController *addController =
       [[PKAddPassesViewController alloc] initWithPass:newPass];

       addController.delegate = self;
       [self presentViewController:addController
                   animated:YES
                 completion:nil];
}

检查存折文件是否已完成并准备好PKAddPassesViewController的好方法。我想暂停应用程序大约一秒钟,但我认为应该有一个更优雅的解决方案。

1 个答案:

答案 0 :(得分:0)

发布的代码会创建一个连接,但不会运行它。然后它同步向Web服务发出请求。尝试运行NSURLConnection asynch ...

// ...your code to setup the request
[request setHTTPBody:postData];

// change the UI to tell the user that the app is busy

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    // change the UI back to not busy
    if (!error) {
        NSError *passError;
        PKPass *newPass = [[PKPass alloc] initWithData:data error:&passError];
        // your code continues here...
    }
}];