我正在将我的应用程序中的 JSON 文档上传到网络上的服务器,并且我能够成功地做到这一点。但是,我现在需要做的是检测何时没有 WiFi 或 3G 连接,并通过警报提示用户应用程序无法连接,然后让他们选择将 JSON 文档另存为.plist 文件在本地。
这是我到目前为止的代码:
这是我将 JSON 文档上传到服务器的方法:
- (void) sendJsonDoc:(NSString *)jDoc {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myWebsite.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
[request setValue:[NSString stringWithFormat:@"%d", [jDoc length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[jDoc dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSLog(@"%d", code);
}
这是我为了将 JSON 文档在本地保存为 plist 文件而拥有的代码:
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"jsonDoc.plist"];
// If the file doesn't exist in the Documents Folder, copy it.
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"jsonDoc" ofType:@"plist"];
[fileManager copyItemAtPath:sourcePath toPath:path error:nil];
}
// Load the Property List.
NSString *loadJSON = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
如何在我的 sendJsonDoc 方法中检测到没有连接并向用户发出警报,提示他们没有连接,以及他们是否想在本地保存文档?