2012-07-03 50 views
3

我目前正在編寫一個使用XML文檔檢索數據的應用程序(我正在使用libxml2.2.7.3)。我將它設置爲加載本地XML文件(在xCode中的項目中,以及所有其他項目文件)。我發現我希望能夠編輯這個XML文件,然後在應用程序上進行即時更新。我取從XML文檔中的數據是這樣的:下載iPhone上的XML文件,存儲並使用它

NSArray *dagensRetList = [self getAllItems:@"//dagensret" fileName:@"dagensret.xml"]; 

我以爲來解決這個問題的最簡單的方法是將下載的XML文件每當有該文件的可用的新版本從網絡服務器是我提供了(在每個應用程序啓動/點擊刷新按鈕,它會從服務器下載新文件 - 也許讓它檢查他們是否有相同的標籤(weekNumber,這是一個丹麥編碼的應用程序))

所以我想關於什麼是最方便的下載文件的方式,我應該保持這種獲取數據的方式,還是將文檔保存在服務器上更明智些,然後他們會直接從第e服務器每次? (但它可能會使用很多流量,但它是我的學校的產品,所以用戶基數將在1200左右,但不是每個人都在使用智能手機)

如何下載文件一個網絡服務器,然後保持它緩存?

回答

5

如果用戶無法連接到服務器,您一定要將該文件緩存在設備上。

像這樣的東西應該讓你開始:

// Create a URL Request and set the URL 
NSURL *url = [NSURL URLWithString:@"http://google.com"] 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

// Display the network activity indicator 
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 

// Perform the request on a new thread so we don't block the UI 
dispatch_queue_t downloadQueue = dispatch_queue_create("Download queue", NULL); 
dispatch_async(downloadQueue, ^{ 

    NSError* err = nil; 
    NSHTTPURLResponse* rsp = nil; 

    // Perform the request synchronously on this thread 
    NSData *rspData = [NSURLConnection sendSynchronousRequest:request returningResponse:&rsp error:&err]; 

    // Once a response is received, handle it on the main thread in case we do any UI updates 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     // Hide the network activity indicator 
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 

     if (rspData == nil || (err != nil && [err code] != noErr)) { 
      // If there was a no data received, or an error... 
     } else { 
      // Cache the file in the cache directory 
      NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
      NSString* path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"init.xml"]; 

      [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; 
      [data writeToFile:path atomically:YES]; 

      // Do whatever else you want with the data... 
     } 
    }); 
}); 
+0

非常感謝!謝謝@pdesantis! – mikkeljuhl

+0

如果我能給你一千分,我會的。謝謝! –

相關問題