如何在iCloud中为UIDocument进行增量编写?

时间:2014-01-29 09:05:34

标签: ios iphone objective-c icloud uidocument

我在iCloud无处不在的容器中有UIDocument,我需要在保存文档时将数据附加到文件中。我根据UIDocument文档覆盖了readFromURL::writeContents:::::方法:

-(BOOL) writeContents:(id)contents toURL:(NSURL*)url forSaveOperation:(UIDocumentSaveOperation)saveOperation originalContentsURL:(NSURL*)originalContentsURL error:(NSError *__autoreleasing *)outError
{
    NSFileCoordinator* coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:self];
    NSError* error = nil;
    [coordinator coordinateWritingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
        NSData* data = contents; //correct, non-empty NSData

        ///[data writeToFile:newURL :] works, but overwrite original file

        NSOutputStream* stream =[[NSOutputStream alloc] initWithURL:newURL append:YES];
        if (stream)
        {
            NSInteger written = [stream write:data.bytes maxLength:data.length];
            if (written != data.length)
            {
                //failed here, written == -1
                NSLog(@"Write data to UIDocument failed: %@, error: %@", newURL, stream.streamError);
            }
        }
        else
        {
            NSLog(@"Write data to iCloudDocument failed: %@", newURL);
        }
    }];

    if (error)
    {
        NSLog(@"Coordinated write failed %@, error: %@", url, error);
        *outError = error;
    }

    return error == nil;
}

Accessor块具有不同的newURL,例如:

url: file:///private/var/mobile/Library/Mobile%20Documents/XXXXXXX~com~test~test/test.doc

newURL: file:///private/var/mobile/Applications/5631D484-7661-4E9E-A342-B25297FC0E18/tmp/(A%20Document%20Being%20Saved%20By%20test%20)/test.doc

[stream write::]失败,因为newURL文件不存在且我无法附加数据,只创建包含所有文档内容的文件。

文档编辑代码:

NSURL* url = [self.containerURL URLByAppendingPathComponent:kCloudDocumentName];

MyDocument* document = [[MyDocument alloc] initWithFileURL:url];
[document openWithCompletionHandler:^(BOOL success) {
    if (success)
    {
        //update some document data
        [self updateData:document completion:nil];

        [document closeWithCompletionHandler:^(BOOL success) {
            //failed here!
        }];

    }
}];

MyDocument存在于url无处不在的容器中,且文档处于正常状态。

在这种情况下如何进行增量写作?怎么了?

1 个答案:

答案 0 :(得分:0)

更改UIDocumnet中的数据后,您可以使用:

-[UIDocumnet saveToURL:UIDocumnet.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:nil];

不确定,它是对还是没有,但它适用于我的应用程序。如果这是错的,请告诉我某人。

您可能需要在UIDocumnet的子类中覆盖此方法:

- (id) contentsForType:(NSString *)typeName error:(NSError **)outError