【问题标题】:iOS Send data via Internet when connection is enableiOS 启用连接时通过 Internet 发送数据
【发布时间】:2014-01-05 23:55:06
【问题描述】:

我正在开发一款无需连接即可运行的应用。用户可以插入一些数据,当应用程序检测到 Internet 连接已启用时,它必须发送这些数据。

互联网连接可以是WIFI或运营商连接。

我该怎么做?我发现了一个叫做“可达性”的东西,但我不确定。

应用必须支持 iOS6 和 iOS7

【问题讨论】:

  • 您知道如何准备数据并在有互联网连接时发送数据吗?
  • 是的,例如,用户写入一个uitextfield,我使用CoreData保存文本,

标签: ios networking reachability


【解决方案1】:

问题:

您想知道您的应用程序如何通知您用户 iOS 设备中的网络变化,以便您可以在互联网连接可用时将数据发送到您的服务器。

解决方案:

正如您在帖子中提到的,您已经找到了Reachability 类,只需导入它,然后找到您的AppDelegate.m 文件并在您的didFinishLaunchingWithOptions: 方法中添加以下代码

// This sets up a notification system for internet connections
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(checkNetworkStatus:) 
                                             name:kReachabilityChangedNotification object:nil];

// Set up Reachability
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];   

请注意我们希望在通知更改时调用的选择器checkNetworkStatus:,这就是我们现在要做的:

// This method is called called whenever there is a change in network status
- (void)checkNetworkStatus:(NSNotification *)notice {

    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];

    if(internetStatus == NotReachable)
    {
        NSLog(@"The internet is down. So don't do anything");
        break;
    }
    else if((internetStatus == ReachableViaWiFi) || (internetStatus == ReachableViaWWAN))
    {
        NSLog(@"The internet is working via WIFI OR via a cellular network, Thus");
        NSLog(@"Call your method in this code block to send the data to your server");
        [self sendApplicationPreparedData];
        break;            
    }
}

只有当网络发生变化时,从 Reachability 发送的通知才会调用 checkNetworkStatus,并且当存在活动的 Internet 连接时,将调用名为 sendApplicationPreparedData 的自定义方法。

-(void)sendApplicationPreparedData{
    //Your code that is responsible for sending your application data to your server
}

【讨论】:

  • 如果我们在应用程序中使用可达性,它会在每次有互联网连接时发出通知,即使应用程序没有运行。
  • BalaChandra,当我发送数据并且我没有更多数据时,可以移除观察者的更好近似?当用户插入数据(无连接)时,我将其存储并再次添加观察者??
  • @BalaChandra 不,是的,虽然你不能在后台持续检查互联网连接,但是你可以做一些有趣的事情,比如在 iOS 7 中使用苹果新的 Background Fetch API 下载数据。
  • @BalaChandra 继续。如果从用户按下按钮时没有互联网连接,您也许可以存储一个名为 ShouldSendDataWhenInternetAvailable 的布尔值,对于长变量名很抱歉;)然后每当调用通知方法时,如果该布尔值是设置为 true 然后您从通知方法发送数据。然后将布尔值设置为 false,这样您就不会发送多个请求。
  • @BalaChandra 请参考我的第三条评论,我已经回答了这个问题。似乎您无法在后台持续检查互联网连接,但我相信您可以在 ios 7 中为您的应用程序安排任务,您需要对为后台任务注册您的设备进行一些研究,以便您可以调用一个方法快速检查是否有可用的互联网连接。
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
相关资源
最近更新 更多