文档章节

IOS 后台不断网处理

S
 Snaiper
发布于 2016/02/25 16:31
字数 1394
阅读 161
收藏 0

后台不断网处理  地图服务

//

//  AppDelegate.m

//  networkdemo

//

//  Created by siteview on 16/2/1.

//  Copyright © 2016年 数据结构. All rights reserved.

//

 

#import "AppDelegate.h"

#import

 

 

@interface AppDelegate ()

{

    CLLocationManager * locationManager;

}

 

@property (assign, nonatomic) UIBackgroundTaskIdentifier bgTask;

 

@property (strong, nonatomic) dispatch_block_t expirationHandler;

@property (assign, nonatomic) BOOL jobExpired;

@property (assign, nonatomic) BOOL background;

 

@end

 

@implementation AppDelegate

 

 

 

 

 

 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error//当定位服务不可用出错时,系统会自动调用该函数

{

 

    if ( [error code] == kCLErrorDenied ) {

       

       

        //服务未打开

    }

 

 

}

 

 

 

 

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations//当用户位置改变时,系统会自动调用,这里必须写一点儿代码,否则后台时间刷新不管用

{

 

    CLLocation * loc = [locations  lastObject];

    float  latitudeMe = loc.coordinate.latitude;

    float  longtitudeMe= loc.coordinate.longitude;

}

 

 

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

   

//    __weak__typeof__(self)  weakself = self;

   

    __weak  __typeof(&*self) weakSelf = self;

   

//   

//    __weak __typeof(&*self)weakSelf = self;

//   

//    // 我之前一直这么写的

//    __weak __typeof(self) weakSelf = self;

//    // 或者这么写

//    __weak XxxViewController *weakSelf = self;

//    // 或者这么写

//    __weak id weakSelf = self;

//   

    UIApplication* app = [UIApplication sharedApplication];

    self.expirationHandler = ^{

   

        [app  endBackgroundTask:weakSelf.bgTask];

        weakSelf.bgTask = UIBackgroundTaskInvalid;

        weakSelf.bgTask = [app beginBackgroundTaskWithExpirationHandler:weakSelf.expirationHandler];

        weakSelf.jobExpired = YES;

        while ( weakSelf.jobExpired )

        {

           

            //等待180s循环进程的结束;

            [NSThread  sleepForTimeInterval:1];

           

        }

        [weakSelf startBackgroundTask];

       

    };

 

   

//    [self monitorBateryStateInBackground];

 

    locationManager = [[CLLocationManager alloc] init];

    locationManager.delegate = self;

   

    // Override point for customization after application launch.

    return YES;

}

 

 

//进入后台之后执行的任务

- (void) startBackgroundTask

{

    NSLog(@" 重新启动任务 ");

   

    //开始长时间运行任务

    dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) , ^{

       

           NSLog(@" 重新新启动任务");

        int  count = 0;

        BOOL  NoticeoBackground = false;  //只通知一次标志位

        BOOL  FlushBackgroundTime = false; //只通知一次标志位

        locationManager.distanceFilter = kCLDistanceFilterNone;

        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;

       

       

        while ( self.background && !self.jobExpired )

        {

            //进入后台运行

            [NSThread  sleepForTimeInterval:1];

            count++;

            if( count > 2 ) //每60s进行一次开启定位,刷新后台

            {

               

                count = 0;

                [locationManager startUpdatingLocation];  //60s之后开启位置服务

                NSLog(@"开启位置服务");

                [NSThread  sleepForTimeInterval:1];

                [locationManager stopUpdatingLocation];

                NSLog(@"停止位置服务");

                FlushBackgroundTime = false;

            }

        }

       

    });

   

   

    for(  int i=0;  i<100000; i++ )

    {

       

        NSString *  pathString = @"http://pics.sc.chinaz.com/files/pic/pic9/201601/apic18410.jpg";

        NSURL  * url = [NSURL URLWithString:pathString];

        NSURLRequest  * request = [[NSURLRequest alloc] initWithURL:url cachePolicy:0 timeoutInterval:30000];

        NSURLResponse * response =  [[NSURLResponse alloc] init];

        NSData  *   data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

        UIImage * image = [[UIImage alloc] initWithData:data];

        NSLog(@"image:  %@",image);

       

        [NSThread sleepForTimeInterval:1];

    }

 

}

 

 

- (void) monitorBateryStateInBackground

{

    self.background = YES;

    [self startBackgroundTask];

}

 

 

- (void)applicationWillResignActive:(UIApplication *)application {

    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

}

 

 

//进入后台

- (void)applicationDidEnterBackground:(UIApplication *)application {

 

   

    self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:self.expirationHandler];

    NSLog(@"进入后台");

    [self monitorBateryStateInBackground];

   

 

}

 

- (void)applicationWillEnterForeground:(UIApplication *)application {

 

   

   

   

   

   

}

 

 

 

//从后台进入前台

- (void)applicationDidBecomeActive:(UIApplication *)application

{

 

   

   

    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    [locationManager stopUpdatingLocation];

    self.background = NO;

   

   

}

 

- (void)applicationWillTerminate:(UIApplication *)application {

    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    // Saves changes in the application's managed object context before the application terminates.

    [self saveContext];

}

 

#pragma mark - Core Data stack

 

@synthesize managedObjectContext = _managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

 

- (NSURL *)applicationDocumentsDirectory {

    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.siteview.zemeng.networkdemo" in the application's documents directory.

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}

 

- (NSManagedObjectModel *)managedObjectModel {

    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.

    if (_managedObjectModel != nil) {

        return _managedObjectModel;

    }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"networkdemo" withExtension:@"momd"];

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}

 

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.

    if (_persistentStoreCoordinator != nil) {

        return _persistentStoreCoordinator;

    }

   

    // Create the coordinator and store

   

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"networkdemo.sqlite"];

    NSError *error = nil;

    NSString *failureReason = @"There was an error creating or loading the application's saved data.";

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        // Report any error we got.

        NSMutableDictionary *dict = [NSMutableDictionary dictionary];

        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";

        dict[NSLocalizedFailureReasonErrorKey] = failureReason;

        dict[NSUnderlyingErrorKey] = error;

        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];

        // Replace this with code to handle the error appropriately.

        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

        abort();

    }

   

    return _persistentStoreCoordinator;

}

 

 

- (NSManagedObjectContext *)managedObjectContext {

    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)

    if (_managedObjectContext != nil) {

        return _managedObjectContext;

    }

   

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (!coordinator) {

        return nil;

    }

    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

    [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    return _managedObjectContext;

}

 

#pragma mark - Core Data Saving support

 

- (void)saveContext {

    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

    if (managedObjectContext != nil) {

        NSError *error = nil;

        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

            // Replace this implementation with code to handle the error appropriately.

            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

            abort();

        }

    }

}

 

@end

 

 

另外一个人的后台多任务

IOS系统本身支持多任务,但是苹果出于对电量的控制,当用户按下home键后,切到后台的app一般就被系统pend了;前面提到一般,就说明还有不一般的app,到底是什么类型的app,这里不做说明。如何让一般的app可以在后台永久的运行呢?办法就是将一般的app处理成苹果允许后台运行的“不一般”的app。

我这里有两个办法:

1、使用一个无声的音频文件,当app切换到后台后就开始无限循环播放。这样你的app就永远在后台活着了,你在后台想做什么,都可以。

2、循环向系统申请“任务时间片“,也能保证你的app就永远在后台活着。

 

对比而言,第二种办法较为妥当(第一种可能被来电或者其他播放软件打断)。下面是操作代码:

 

在你app的程序代理实现文件中添加红色显示的代码(验证下吧,添加个定时器,看看是不是切换到后台后永远跑着)

 

 

 #import "MQLAppDelegate.h"

 

@interface MQLAppDelegate ()

 

//时间片标识begin

@property UIBackgroundTaskIdentifier newtaskID;

@property UIBackgroundTaskIdentifier oldtaskID;

//时间片标识end

 

@end

 

@implementation MQLAppDelegate

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    //时间片标识begin

    self.newtaskID = self.oldtaskID = UIBackgroundTaskInvalid;

    //时间片标识end

    

    return YES;

}

 

- (void)applicationDidEnterBackground:(UIApplication *)application {

 

    //时间片标识begin

    self.newtaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

    

    if (self.newtaskID != UIBackgroundTaskInvalid && self.oldtaskID != UIBackgroundTaskInvalid)

    {

        [[UIApplication sharedApplication] endBackgroundTask: self.oldtaskID];

    }

    self.oldtaskID = self.newtaskID;

    //时间片标识end

}

 

- (void)applicationWillEnterForeground:(UIApplication *)application

{

    //时间片标识begin

    if (self.oldtaskID != UIBackgroundTaskInvalid) {

        

        [[UIApplication sharedApplication] endBackgroundTask: self.oldtaskID];

        self.oldtaskID = UIBackgroundTaskInvalid;

    }

    //时间片标识end

}

 

 

@end 

© 著作权归作者所有

S
粉丝 13
博文 100
码字总数 135194
作品 0
深圳
私信 提问
iOS按钮倒计时在进入后台不继续计时的处理

iOS程序进入后台后十分钟之内就会被系统kill掉,我想要程序进入后台后仍然运行计时功能,怎么解决呢? 方法一:可以使用记录开始时间和获取当前时间的时间差进行处理 还是直接上代码: 下面的...

云上飞飞
2018/07/06
0
0
iDev 全平台开发者大会 2016,评论抢赠票

即日起参与评论即有机会获得免费/优惠赠票,抢到前十楼即可获免费票一张,十楼之后评论者可获优惠购票码,请参与盖楼活动后私信@Alaise ,活动11月3号截止 2016 年 11月 5-6 日,iDev 全平台...

Alaise
2016/09/27
770
4
iDev 全平台开发者大会 2016,评论抢赠票

即日起参与评论即有机会获得免费/优惠赠票,抢到前十楼即可获免费票一张,十楼之后评论者可获优惠购票码,请参与盖楼活动后私信@Alaise ,活动11月3号截止 2016 年 11月 5-6 日,iDev 全平台...

Alaise
2016/09/27
0
0
关于Android流畅度不如iOS的几点看法

网上一名据称是前谷歌实习生的人透露了一些关于Android系统硬件加速的内幕。据称,在 Android3.0和4.0之前,并没有完整的硬件加速。他们一直在通过硬件加速绘制某些UI元素,并称效果并不像他...

虫虫
2011/12/17
21.3K
28
首届中国iOS应用开发大赛作品提交通道已开启

  据科技传媒网8月10日消息: 首届中国iOS应用开发大赛自6月初启动报名以来,受到了全国高校学生、iOS开发从业者和业余开发者的关注和青睐,大赛报名工作正如火如荼进行中,目前在官网完成...

守护灬小伦
2016/08/10
98
0

没有更多内容

加载失败,请刷新页面

加载更多

cmd命令与dos指令

bat命令学习 基础部分: 一、基础语法: 1.批处理文件是一个“.bat”结尾的文本文件,这个文件的每一行都是一条DOS命令。可以使用任何文本文件编辑工具创建和修改。 2.批处理是一种...

WinkJie
14分钟前
0
0
折叠手机适配布局

CSS Grid 设备相关参数 媒体查询 Chrome进行调试,创建相应的模拟机

lilugirl
44分钟前
2
0
Knative Eventing 中如何实现 Registry 事件注册机制

摘要: 在最新的 Knative Eventing 0.6 版本中新增了 Registry 特性, 为什么要增加这个特性, 该特性是如何实现的。针对这些问题,希望通过本篇文章给出答案。 背景 作为事件消费者,之前是...

阿里云云栖社区
48分钟前
1
0
安装 jemalloc for mysql

前言: Jemalloc 是BSD的提供的内存分配管理 安装依赖 $ yum install -y gcc$ yum install autoconf -y 安装 jemalloc $ git clone https://github.com/jemalloc/jemalloc$ cd jema......

Linux_Anna
58分钟前
3
0
linux下ctrl+c中止不了

有一台centos7的服务器,ctrl+c无效,并且tail -f也无效,只能关掉终端或者crtl+z放入后台再删掉,但是ping的时候使用ctrl+c是有效果的。 出现这种情况的原因可能是因为有人要使用ruby安装r...

gaolongquan
今天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部