2012-03-12 9 views
13

我正在使用NSFileManagerstartDownloadingUbiquitousItemAtURL將文件從iCloud下載到本地副本(在本例中本地還沒有該文件的副本)。我似乎無法找到這個過程的回調。我需要回調告訴我的應用程序,請求的文件已完成下載(到本地副本),所以其他任務可以開始讀取文件的內容並做些什麼。iCloud:回調NSFileManager的startDownloadingUbiquitousItemAtURL?

我可以檢查是否下載文件。但它會不斷參與投票。有沒有辦法做到這一點,而不需要設置一個計時器來輪詢呢?

回答

28

我相信這種方法打算與基於Apple's documentation的文件協調器一起使用。所以,你需要使用一個文件協調員像這樣:

NSURL *itemURL = nil; // this is the URL you want to read from 

__block NSData *data = nil; 
NSError *error = nil; 
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil]; 
[coordinator coordinateReadingItemAtURL:itemURL options:0 error:&error byAccessor:^(NSURL *newURL) { 
    data = [NSData dataWithContentsOfURL:newURL]; 
}]; 

這將是同步的,但是,如果你想異步地做一些事情,你可以使用塊像這樣:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    // read info from the URL using the code above 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     // handle data read from the URL 
    }); 
}); 
+1

NSFileCoordinator中的方法在同步模式下工作得很漂亮。我還需要在我的項目的後期階段的異步版本 - 投票贊成!謝謝。 – user523234 2012-03-19 21:36:38

+0

@SpaceDog你是100%的權利。我一直在處理這些API,坦率地說,糟糕透了。 – mattsven 2015-08-27 19:54:12

+3

Apple創建的API可以分爲兩類:1)吸引人的地方,混淆爲地獄,模糊,不完整和不良記錄,以及2)被通過的人。沒有一個設計良好的API。不要誤會我的意思。我喜歡蘋果公司的產品,但與開發人員和API有關的蘋果公司並不是擁有高標準認知的蘋果公司。反之。 – SpaceDog 2015-08-27 22:09:49

-1

要正確地上傳到iCloud你也需要類似這樣的東西(任何其他都沒有工作:|)

NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]; 

    NSString *FileNS = @"myfile.dat"; 
    NSURL *FileURL = [[ubiq URLByAppendingPathComponent:@"Documents"] URLByAppendingPathComponent:FileNS ]; 


    BYTE *data = NULL;//Put your file data in here 
    int FileSize = 0;//replace with your file size 
    NSData *myData = [[NSData alloc] initWithBytes:data length:FileSize]; 
    [myData writeToFile:[FileURL path] atomically:YES]; 
+0

op要求下載,不能上傳 – SpaceDog 2015-09-24 14:40:15