听说了一些比较流氓的的需求,其中就有iOS的定时定位。可以实现任意时间对用户的定位,只有用户不主动杀死该程序。利用了类似于歌曲后台播放时,只用你不主动切断程序,程序就会一直运行。
首先、导入AVFoundation.framework库。AVFoundation是一个可以用来使用和创建基于时间的视听媒体的框架,它提供了一个能使用基于时间的视听数据的详细级别的Objective-C接口。
<pre><code>
//在AppDelegate中导入头文件。当进入后台后可调用。
#import <AVFoundation/AVFoundation.h> //可以就行类似于音乐播放的操作。
#import <CoreLocation/CoreLocation.h> //必须使用系统的地图定位功能
</code></pre>
在info.plist 加入如下:

```
//声明全局属性,方便操作。
@property (strong, nonatomic)CLLocationManager *locationManager; //
@property (assign, nonatomic)BOOL isLogation; //判断是否定位
@property (assign, nonatomic) CGFloat deviceLevel; //记录电量
@property (strong, nonatomic) NSTimer *myTimer; //定时器
```
利用懒加载,可防止多次的初始化
```
#pragma mark --------懒加载----------
- (CLLocationManager *)locationManager {
if (!_locationManager) {
_locationManager = [[CLLocationManager alloc] init];
//取得用户授权 不管应用是否在前台运行,都可以获取用户授权;
[_locationManager requestAlwaysAuthorization];
//定位服务,每隔多少米定位一次;
_locationManager.distanceFilter = 100;
//定位的精确度,越高越耗电
_locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
//指定代理
_locationManager.delegate = self;
_locationManager.pausesLocationUpdatesAutomatically = NO; //该模式是抵抗ios在后台杀死程序设置,iOS会根据当前手机使用状况会自动关闭某些应用程序的后台刷新,该语句申明不能够被暂停,但是不一定iOS系统在性能不佳的情况下强制结束应用刷新
}
return _locationManager;
}
```
在didFinishLaunchingWithOptions就行定位与定时器的初始化。
```
//确保后台运行
NSError *error1 = nil;
NSError *error2 = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error1];
[[AVAudioSession sharedInstance] setActive:YES error:&error2];
self.isLogation = [CLLocationManager locationServicesEnabled];
NSLog(@"%.2f",[self getCurrentBatteryLevel]);
//是否可定位
if (self.isLogation) {
_myTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(startLocation) userInfo:nil repeats:YES];
[self.myTimer setFireDate:[NSDate distantFuture]]; //先暂停定时器,当应用程序进入后台后再打开。这可根据需求进行修改。
}else {
NSLog(@"洗洗睡吧");
}
```
在程序进入后台后可进行后台定位操作applicationDidEnterBackground
```
//开启不停歇定位
UIApplication *app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier identifier;
identifier = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (identifier != UIBackgroundTaskInvalid) {
identifier = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (identifier != UIBackgroundTaskInvalid) {
identifier = UIBackgroundTaskInvalid;
}
});
});
if (self.isLogation) {
[self.myTimer setFireDate:[NSDate distantPast]];
}else { //用过未开启定位服务;
NSLog(@"洗洗睡吧");
}
```
需要如下方法
```
#pragma mark -------定时器代理方法------
- (void)startLocation {
if ([self getCurrentBatteryLevel]>0.4f) {
//开始定位
[self.locationManager startUpdatingLocation];
}else {
[self.myTimer invalidate];
self.myTimer = nil; }
}
#pragma mark -------地图代理方法--------
//实时获取的定位信息 代理方法会被多次执行
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray*)locations {
if (locations.count) {
//获取最新位置
CLLocation *location = locations.lastObject;
NSString *str = [NSString stringWithFormat:@"%.2f:%.2f",location.coordinate.latitude,location.coordinate.longitude];
NSLog(@"%@",str);
[self.locationManager stopUpdatingLocation];
}
}
//定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
if ([error code] == kCLErrorDenied) {
NSLog(@"定位被拒绝");
}
if ([error code] == kCLErrorLocationUnknown) {
NSLog(@"定位失败 = %@", error);
}
}
#pragma mark -------判断电量------------
- (CGFloat)getCurrentBatteryLevel {
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
return [UIDevice currentDevice].batteryLevel;
}
```
#[点击链接,参考方法2](http://www.jianshu.com/p/8595a271b3fe)
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决
我是ruby的新手,我认为重新构建一个我用C#编写的简单聊天程序是个好主意。我正在使用Ruby2.0.0MRI(Matz的Ruby实现)。问题是我想在服务器运行时为简单的服务器命令提供I/O。这是从示例中获取的服务器。我添加了使用gets()获取输入的命令方法。我希望此方法在后台作为线程运行,但该线程正在阻塞另一个线程。require'socket'#Getsocketsfromstdlibserver=TCPServer.open(2000)#Sockettolistenonport2000defcommandsx=1whilex==1exitProgram=gets.chomp
print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上
当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#
当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab
我想知道使用fork{}从Rails应用程序“后台”处理是否是个好主意...从我收集到的fork{my_method;Process#setsid}实际上做了它应该做的事情。1)创建另一个具有不同PID的进程2)不中断调用过程(例如它继续w/o等待fork完成)3)执行子进程直到它完成..这很酷,但这是个好主意吗?fork到底在做什么?它会在内存中创建我的整个railsmongrel/passenger实例的重复实例吗?如果是这样那就太糟糕了。或者,它是否以某种方式在不消耗大量内存的情况下完成。我的最终目标是取消我的后台守护进程/队列系统,转而支持这些进程的fork(主要是发送电子邮件
我需要将目录中的一堆文件上传到S3。由于上传所需的90%以上的时间都花在了等待http请求完成上,所以我想以某种方式同时执行其中的几个。Fibers能帮我解决这个问题吗?它们被描述为解决此类问题的一种方法,但我想不出在http调用阻塞时我可以做任何工作的任何方法。有什么方法可以在没有线程的情况下解决这个问题? 最佳答案 我没有使用1.9中的纤程,但是1.8.6中的常规线程可以解决这个问题。尝试使用队列http://ruby-doc.org/stdlib/libdoc/thread/rdoc/classes/Queue.html查看文