后台运行定位,音频,网络电话
大家都知道我们的程序在后台运行的时间是10分钟,10分钟后便会停止。但是像实时定位,播放音频,以及网络电话这些功能我们需要在后台持续运行。那么我们就要进行相应的设置。
下面具体的例子以定位为例
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface BackgroundTrackerViewController : UIViewController<CLLocationManagerDelegate>
@property(nonatomic, retain) CLLocationManager *locationManager;
@property(nonatomic, retain) UIButton *startTrackingButton;
@property(nonatomic, retain) UILabel *alertLabel;
- (void)startTracking:(id)sender;
#import "BackgroundTrackerViewController.h"
@interface BackgroundTrackerViewController ()
@end
@implementation BackgroundTrackerViewController
@synthesize locationManager,startTrackingButton,alertLabel;
//开始跟踪
- (void)startTracking:(id)sender
{
[locationManager startUpdatingLocation];
}
-(void)start:(id)sender
{
// [locationManager startUpdatingLocation];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.view.backgroundColor=[UIColor grayColor];
self.startTrackingButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
startTrackingButton.frame=CGRectMake(0, 200, 100, 50);
[startTrackingButton addTarget:self action:@selector(startTracking:) forControlEvents:UIControlEventTouchUpInside];
[startTrackingButton setTitle:@"startTracking" forState:UIControlStateNormal];
[self.view addSubview:startTrackingButton];
self.alertLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 50)];
self.alertLabel.backgroundColor=[UIColor orangeColor];
self.alertLabel.hidden=YES;
self.alertLabel.text=@"无法找到位置";
[self.view addSubview:alertLabel];
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
//Only applies when in foreground otherwise it is very significant changes
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];//要求的精确度
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D currentCoordinates = newLocation.coordinate;
[alertLabel setText:@"Location Has been found"];
[alertLabel setHidden:NO];
NSLog(@"Entered new Location with the coordinates Latitude: %f Longitude: %f", currentCoordinates.latitude, currentCoordinates.longitude);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"Unable to start location manager. Error:%@", [error description]);
[alertLabel setHidden:NO];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
作者:陈杭州
优质内容筛选与推荐>>长按二维码向我转账
受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。
已发送
发送中
微信扫一扫
关注该公众号