当 iphone 连接到互联网时调用应用程序并在服务器上上传数据

Posted

技术标签:

【中文标题】当 iphone 连接到互联网时调用应用程序并在服务器上上传数据【英文标题】:invoke the app and upload data on server when iphone is connected to internet 【发布时间】:2015-07-24 08:52:08 【问题描述】:

我正在制作一个 ios 应用程序,我需要从用户那里获取一些数据并将它们上传到服务器上。但有时互联网连接将不可用 那时候 。所以我想当我的设备连接到互联网时,我的应用程序会将数据发送到服务器

【问题讨论】:

看看可达性。 【参考方案1】:

您可以使用可达性来实现它。它有很多方法可以检查互联网可用性或者您也可以从 Apple 获取示例代码。 关注这个网址:https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.htmle

每当网络状态发生变化reachabilityChanged调用,您可以在reachabilityChanged方法中检查互联网是否可用。

@interface ViewController ()

 @property (nonatomic) Reachability *hostReachability;

@end

- (void)viewDidLoad 
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

 self.hostReachability = [Reachability reachabilityForInternetConnection];
 [self.hostReachability startNotifier];


// 当网络状态发生变化时由 Reachability 调用,

(void)reachabilityChanged:(NSNotification *)notification 
    NetworkStatus networkStatus = [self.hostReachability currentReachabilityStatus];

    if (networkStatus == NotReachable) 
        //no internet connection
    
    else 
        //internet available send your code to server
    

【讨论】:

【参考方案2】:

您可以使用第三方库可达性类。并在 ViewWillAppear 中编写代码。

 Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    );

else 
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"Please check Your Internet connection" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alert show];

【讨论】:

以上是关于当 iphone 连接到互联网时调用应用程序并在服务器上上传数据的主要内容,如果未能解决你的问题,请参考以下文章

未捕获的错误:连接到数据库时调用未定义的函数 mysqli_connect() [重复]

如何用 Objective-C 判断 iPhone 是不是连接到 wifi 网络?

当我们执行以下操作时,您的应用程序在运行 iOS 11.1 并连接到 IPv6 网络的 iPad 和 iPhone 上崩溃:

使用 NEHotspotConfigurationManager 连接到没有互联网的 wifi

iPhone 应用程序连接到离线网络中的服务器

如何在iphone中单击按钮时调用url