我想在调用applicationDidEnterBackground
时取消url连接。但我不知道如何在整个应用程序范围内保存连接。我在其他视图控制器中创建了一些url连接,但我想在AppDelegate
中取消它们。我怎么能这样做?
答案 0 :(得分:3)
您可以在类中UIApplicationDidEnterBackgroundNotification
添加观察者,以创建连接。试试这个:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
记得叫这个
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
在班级的dealloc
答案 1 :(得分:0)
我相信当您的应用进入后台时,您的NSURLConnections将会被杀死。
如果要跟踪所有NSURLConnections,您需要通过将它们添加到NSSet,NSArray或其他一些数据结构来自己跟踪它们,并循环关闭它们。您还可以拥有一个继承或组成NSURLConnection的类。此数据结构将处理将其自身添加到队列,并且您可以在应用程序退出时进行清理。
答案 2 :(得分:0)
最好在应用变为非活动状态之前停止连接,而不是 applicationDidEnterBackground 。
答案是使用通知:
-(void)init
{
//
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeConnection) name:UIApplicationWillResignActiveNotification object:nil];
//
}
-(void)closeConnections
{
// [urlConnection cancel];
}