2014-09-06 71 views
0

我正在通過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的好方法。我想暫停應用程序一秒左右,但我認爲應該有一個更優雅的解決方案。

回答

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... 
    } 
}];