iOS Store files if no internet, then send when internet present
I need to send data to the server. If no internet connection is present, I want to simply store this textual data into a "file" on the iOS file system.
Periodically we will check the internet connection, if we have 开发者_Python百科it we need to check if there are any files in the file system and how many, then I need to extract the data from the file and ship it to the server as normal. Then delete the file.
So what I don't know how to do:
1) Save text to a file in the local device file system
2) Check that file system if there are any files
3) Iterate through the files and extract the data from each one
4) Delete the file after the data hits the server
Thanks
The only place where you can save a file is in the application's documents directory. There is a separate one for each application.
1) You save files using NSFileManager
.
2) You also use NSFileManager
to check for files in the documents directory,
3) including iteration
4) and deletion.
You get the documents directory like this:
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
}
You save a file like this:
NSData *file = ...;
NSURL *fileURL = [applicationDocumentsDirectory
URLByAppendingPathComponent:@"filename"];
[file writeToURL:fileURL atomically:YES];
You get an array of directory contents for iteration like this:
NSArray *files = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:path error:NULL];
for (id file in files) {
/* do what you have to do */
}
Delete a file:
[[NSFileManager defaultManager] removeItemAtURL:fileURL];
- Many of the Foundation classes like NSString, NSData, and NSDictionary have methods that can write their contents directly to a file. (There are similar methods for reading.) There's also a ton of documentation provided with the iOS SDK. Start with the File System Programming Guide.
2-4. Take a look at NSFileManager, which lets you do all these things and more.
精彩评论