问题
No matter what I try, this isn't working...
I am trying to use UIDocument
to save my (text) files locally. When I create a file (i.e. it isn't loaded), it saves fine. However, if I load my file by opening it and then save it, it simply won't save.
EDIT: I try to save my documents when the app enters the background. However, it seems that the app actually "finishes saving" the documents when I enter the foreground. Is my app not allowed to save documents while in the background?
I've checked my URLs and they're all valid.
Here is the code for making the document from scratch:
document = [[MyDocumentClass alloc] initWithFileURL:fileURL];
fileURL
was made previously.
When loading I don't open or create it, I simply save it when the user quits the app.
If the file already exists on disk:
Here is the code for opening:
[document openWithCompletionHandler:^(BOOL success){
if (!success) {
NSLog(@"FAILED TO OPEN DOCUMENT");
}
// Code to handle document's data
}];
And for saving:
[document saveToURL:[NSURL fileURLWithPath:path] forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success){
if (!success || document.documentState == UIDocumentStateSavingError) {
NSLog(@"FAILED TO CLOSE DOCUMENT");
}
}];
My document encodes and provides its data correctly in contentsForType: error:
, given that it saves correctly when first being created.
I don't get any errors in handleError: userInteractionPermitted:
Any ideas?
N.B. I save my data in applicationDidEnterBackground:
And the completion handler for saveToURL: forSaveOperation: completionHandler:
is never called...
回答1:
Did you test it on simulator ? Be car full as the save is not promised to be done immediately ! if you test on simulator, try this : install app on simulator, stop debuting session, open app on simulator, edit and save your document, close the app, reopen your app and check if your doc was saved - if yes fine !. PS with simulator when you stop debuting you probably interrupt the process of saving in background (but we don't know when the system perform this).
Hop this help
回答2:
Have you first created the document somewhere?
For example, for creating:
[document saveToURL:[NSURL fileURLWithPath:path] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
if (!success || document.documentState == UIDocumentStateSavingError) {
NSLog(@"FAILED TO CLOSE DOCUMENT");
}
}];
and for overwriting:
[document saveToURL:[NSURL fileURLWithPath:path] forSaveOperation: UIDocumentSaveForOverwriting completionHandler:^(BOOL success){
if (!success || document.documentState == UIDocumentStateSavingError) {
NSLog(@"FAILED TO CLOSE DOCUMENT");
}
}];
回答3:
Thank you Armand DOHM for your help. It turns out that the saving was suspended until my app entered the foreground, since I was saving when the user presses the home button. This question seemed to fix the problem: Question
来源:https://stackoverflow.com/questions/22332165/uidocument-not-saving