我正在将 JSON 文档从我的应用程序上传到 Web 上的服务器,我能够成功完成此操作。但是,我现在需要做的是检测何时没有 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 方法中检测并向用户发出警报,提示他们没有连接,以及他们是否想在本地保存文档?
最佳答案
查看可达性框架/库。
tonymillion 制作了 Apple 提供的一个不错的版本,该版本已被改编为使用 ARC 并增加了对 block 的支持。 github 上的自述文件还解释了如何订阅连接更改的通知:)
关于ios - iOS上传JSON文档时需要检测app无法连接服务器的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14088491/