ORCHAN's Blog

Do it,damn it!


  • 首页

  • 归档

  • 标签

Core-Plot绘图边距问题

发表于 2016-10-25   |  

1


默认四边的内边距都为20.0f。


1. 内边距

1
2
3
4
5
6
7
8
9
10
11
// 基于xy轴的图表创建
CPTXYGraph *graph=[[CPTXYGraph alloc] initWithFrame:_hostView.bounds];

// 使宿主视图的hostedGraph与CPTGraph关联
_hostView.hostedGraph = graph;

// 设置内边距:默认 20.0f
graph.paddingLeft = CPTFloat(0);
graph.paddingTop = CPTFloat(200);
graph.paddingRight = CPTFloat(0);
graph.paddingBottom = CPTFloat(0);

CPTGraphHostingView 的背景色为蓝色,plotAreaFrame 绘图区域背景色为黄色

2

2. 绘图边距

1
2
3
4
graph.plotAreaFrame.paddingLeft   = CPTFloat(0);
graph.plotAreaFrame.paddingTop = CPTFloat(200);
graph.plotAreaFrame.paddingRight = CPTFloat(0);
graph.plotAreaFrame.paddingBottom = CPTFloat(0);

3

设置绘图边距只会改变绘图图形的大小

–

4

改变状态栏样式

发表于 2016-03-26   |   分类于 StatusBar   |  
  • 两种状态栏样式:
    1

  • 要改变状态栏的样式,需要在UIViewController中重载如下方法:

1
2
3
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
  • 这个方法不能直接调用,需要在改变样式的地方调用如下方法:
1
2
3
4
- (void)viewWillAppear:(Bool)animated {
[super viewWillAppear:animated];
[self setNeedsStatusBarAppearanceUpdate];
}

显示隐藏

  • 在控制器中重载如下方法:
1
2
3
- (Bool)prefersStatusBarHidden {
return YES;
}

同样不可以直接调用,需要调用这个方法使其生效:[self setNeedsStatusBarAppearanceUpdate]。

动画效果

  • 两种动画效果:UIStatusBarAnimationFade、UIStatusBarAnimationSlide
  • 在控制器中重载如下方法:
1
2
3
- (UIStatusBarAnimation)preferredStatusBarUpdatedAnimation {
return UIStatusBarAnimationSlide;
}

重载了这个方法还没有动画效果先,需要把[self setNeedsStatusBarAppearanceUpdate]放在block中执行。

1
2
3
4
[UIView animateWithDuration:0.3 
animations:^{
[self setNeedsStatusBarAppearanceUpdate];
}];

iOS指纹密码鉴定

发表于 2016-03-02   |   分类于 Authentication   |  

iPhone指纹/密码鉴定

一、两种鉴定方式

LAPolicyDeviceOwnerAuthenticationWithBiometrics : 生物指纹识别。验证弹框有两个按钮,第一个是取消按钮,第二个按钮可以自定义标题名称(输入密码)。只有在第一次指纹验证失败后才会出现第二个按钮,这种鉴定方式的第二个按钮的功能自定义。前三次指纹验证失败,指纹验证框不再弹出。再次重新进入验证,还有两次验证机会,如果还是验证失败,TOUCH ID 被锁住不再继续弹出指纹验证框。以后的每次验证都将会弹出设备密码输入框直至输入正确的设备密码方可解除TOUCH ID锁。


LAPolicyDeviceOwnerAuthentication: 生物指纹识别或系统密码验证。如果TOUCH ID 可用,且已经录入指纹,则优先调用指纹验证。其次是调用系统密码验证,如果没有开启设备密码,则不可以使用这种验证方式。指纹识别验证失败三次将弹出设备密码输入框,如果不进行密码输入。再次进来还可以有两次机会验证指纹,如果都失败则TOUCH ID被锁住,以后每次进来验证都是调用系统的设备密码直至输入正确的设备密码方可解除TOUCH ID锁。


二、鉴权错误信息类型

1. 验证(指纹/密码)不能开启的错误信息:

  • LAErrorPasscodeNotSet : 设备密码未设置
  • LAErrorTouchIDNotAvailable : TOUCH ID不可用
  • LAErrorTouchIDNotEnrolled : 指纹未录入
  • LAErrorTouchIDLockout : TOUCH ID被锁定
  • LAErrorAppCancel : APP调用了- (void)invalidate方法使 LAContext失效
  • LAErrorInvalidContext : 实例化的LAContext对象失效,再次调用evaluation...方法则会弹出此错误信息

2. 其他错误信息:

  • LAErrorAuthenticationFailed : 鉴定失败
  • LAErrorUserCancel : 用户取消
  • LAErrorUserFallback : 用户选择输入密码
  • LAErrorSystemCancel : 系统取消(如:另外一个应用进入前台)

三、Show code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
- (void)authentication
{
// 初始化上下文对象
LAContext* context = [[LAContext alloc] init];

NSError* error = nil;
NSString* result = @"需要您的支付进行支付";
context.localizedFallbackTitle = @"快捷支付";
NSLog(@"data before authentication = %@",[context evaluatedPolicyDomainState]);

// 首先使用canEvaluatePolicy 判断设备支持状态
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
// 支持指纹验证
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
if (success) {
//验证成功,主线程处理UI
NSLog(@"验证成功...");
NSLog(@"data after authentication = %@",[context evaluatedPolicyDomainState]);
}else{
NSLog(@"%@",error.localizedDescription);
switch (error.code) {
case LAErrorSystemCancel:
{
NSLog(@"Authentication was cancelled by the system");
//切换到其他APP,系统取消验证Touch ID
break;
}
case LAErrorUserCancel:
{
NSLog(@"Authentication was cancelled by the user");
//用户取消验证Touch ID
break;
}
case LAErrorUserFallback:
{
NSLog(@"User selected to enter custom password");
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//用户选择输入密码,切换主线程处理
}];
break;
}
case LAErrorAuthenticationFailed:
{
NSLog(@"Authentication Failed");
break;
}
case LAErrorTouchIDLockout:
{
NSLog(@"TOUCH ID is locked out");
break;
}
case LAErrorAppCancel:
{
NSLog(@"app cancle the authentication");
break;
}
case LAErrorInvalidContext:
{
NSLog(@"context is invalidated");
break;
}
default:
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//其他情况,切换主线程处理
}];
break;
}
}
}
}];
}else {
NSLog(@"%@",error.localizedDescription);
//不支持指纹识别,LOG出错误详情
switch (error.code) {
case LAErrorTouchIDNotEnrolled:
{
NSLog(@"TouchID is not enrolled");
break;
}
case LAErrorPasscodeNotSet:
{
NSLog(@"A passcode has not been set");
break;
}
default:
{
NSLog(@"TouchID not available");
break;
}
}
}
}

a1


第一次进来验证,第二行的文字 需要您的指纹进行支付 可以自定,此时第二个按钮隐藏,第一次验证失败后才显示。


a2


第一次指纹验证失败,第二个按钮(标题自定义,默认为:输入密码)显示出来,第一种验证方式的此按钮功能自定,第二种验证方式的此按钮点击会调用设备密码输入框。


a3


设备密码输入框


避免键盘遮挡

发表于 2016-03-01   |   分类于 monitorKeyboardNotification   |  

避免键盘遮挡以及隐藏键盘

很多时候在用户输入时弹出键盘都会阻挡到UI的显示,因此我们应该监听键盘弹出的通知以作UI的位置调整。

键盘的通知

  • UIKeyboardWillShowNotification
  • UIKeyboardDidShowNotification
  • UIKeyboardWillHideNotification
  • UIKeyboardDidHideNotification
  • UIKeyboardDidChangeFrameNotification
  • UIKeyboardWillChangeFrameNotification

键盘通知的字典内容分析

1. 监听键盘即将改变Frame的通知

1
2
3
4
5
6
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
NSDictionary *keyboardInfo = notification.userInfo;
NSLog(@"keyboardInfo is %@",keyboardInfo);
}

2. 通知内容分析

1
2
3
4
5
6
7
8
9
10
2016-02-18 14:17:02.843 test[1304:463755] keyboardInfo is {
UIKeyboardAnimationCurveUserInfoKey = 7; // 动画执行的节奏(速度)
UIKeyboardAnimationDurationUserInfoKey = "0.25";// 键盘弹出/隐藏所需的时间
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 0}}"; // 键盘的边界(Bound)
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 667}"; // 弹出前的中点
UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 667}"; // 弹出后的中点
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 0}}"; // 弹出前的 Frame
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 0}}"; // 弹出后的 Frame
UIKeyboardIsLocalUserInfoKey = 1;
}

动画调整View的Y值

根据通知接收的字典得到弹出后键盘的Y值以及键盘弹出的时间来调整View的Y值以避免被遮挡。

View调整的Y值 = 键盘弹出后的Y值 - 屏幕高度

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)keyboardFramWillChange:(NSNotification *)notification {
NSDictionary *keyboardInfo = notification.userInfo;
NSLog(@"keyboardInfo is %@",keyboardInfo);

// 键盘弹出所需要的时间
CGFloat animationTime = [keyboardInfo[UIKeyboardAnimationDurationUserInfoKey]floatValue];
// 键盘弹出后的 Frame
CGRect keyboardFrame = [keyboardInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
// 动画调整 View 的 Y值
[UIView animateWithDuration:animationTime animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, keyboardFrame.origin.y - SCREENHEIGHT);
}];
}

点击空白地方隐藏键盘

1
2
3
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.textField endEditing:YES];
}

定制 ReturnKey 来隐藏键盘或者跳到下一个 textField

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 1. 遵守 `UITextFieldDelegate` 协议
// 2. 设置 `textField` 的 `delegate` 为当前控制器
// 3. 设置协议的方法:`- (BOOL)textFieldShouldReturn:(UITextField *)textField`

[self.textField1 setDelegate:self];
// Returnkey设置为`next`
[self.textField1 setReturnKeyType:UIReturnKeyNext];
// 根据文本输入框有无字符时自动开启关闭 `Returnkey`
[self.textField1 setEnablesReturnKeyAutomatically:YES];

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self.textFeild1 resignFirstResponder];
// [self.textFeild1 becomeFirstResponder];
return YES;
}

Masonry使用总结

发表于 2016-02-22   |   分类于 Masonry, Autolayout   |  

一、Masonry简介

Masonry是一个轻量级的布局框架,适用于iOS以及OS X。它用简洁的语法对官方的AutoLayout进行了封装。 Masonry有它自己的一套框架用来描述NSLayoutConstraints布局的DSL,提高了约束代码的简洁性与可读性。
Masonry现处于bugfix only状态,将不再有功能性的更新。会有更多的开发者加入Swift阵营,推荐使用Swift写的Snapkit框架来布局。

snapkit


二、导入Masonry框架

  1. 使用Cocoapods来导入框架,在使用到该框架的文件中添加主头文件:#import <Masonry/Masonry.h>。
  • 可以参考这篇文章来配置使用Cocoapods – > Cocoapods的安装和使用
  1. 使用直接拖拽的方式拉入框架文件夹,在使用到该框架的文件中添加主头文件:#import "Masonry.h"。

三、Masonry的特性

  1. MASViewAttribute
    |MASViewAttribute |NSLayoutAttribute
    |:—-: |:—-:
    |MASViewAttribute |NSLayoutAttribute
    |view.mas_left |NSLayoutAttributeLeft
    |view.mas_right |NSLayoutAttributeRight
    |view.mas_top |NSLayoutAttributeTop
    |view.mas_bottom |NSLayoutAttributeBottom
    |view.mas_leading |NSLayoutAttributeLeading
    |view.mas_trailing |NSLayoutAttributeTrailing
    |view.mas_width |NSLayoutAttributeWidth
    |view.mas_height |NSLayoutAttributeHeight
    |view.mas_centerX |NSLayoutAttributeCenterX
    |view.mas_centerY |NSLayoutAttributeCenterY
    |view.mas_baseline |NSLayoutAttributeBaseline

  2. 简化前缀的宏定义

  • 为了增加代码的可读性这里有两个简化代码的宏:#define MAS_SHORTHAND和#define MAS_SHORTHAND_GLOBALS
  • MAS_SHORTHAND:只要在导入Masonry主头文件之前定义这个宏, 那么以后在使用Masonry框架中的属性和方法的时候, 就可以省略mas_前缀
  • MAS_SHORTHAND_GLOBALS:只要在导入Masonry主头文件之前定义这个宏,那么就可以让equalTo函数接收基本数据类型, 内部会对基本数据类型进行包装
    注意:这两个宏如果想有效使用,必须要在添加Masonry头文件之前导入进去。在没有增加宏`MAS_SHORTHAND_GLOBALS时,下面这句是会报错的。
    make.top.equalTo(42); –> make.top.equalTo([NSNumber numberWithInt:42]);

四、Masonry约束添加步骤

  1. 自定义UIView。
  2. 将自定义的UIView添加到父视图上。
  3. 添加约束

五、Masonry的具体使用

对一个控件添加约束条件要最终满足可以确定这个空间的大小和位置,否则会报错缺少约束,当然也要避免约束冲突。下面对View1的左右上下(位置)都进行约束,并没有对其大小进行约束,但是可根据上述约束自动设置View1的大小。

1. 创建一个View,左右上下空出10个像素

1
UIView *view1 = [[UIView alloc]init];

view1.backgroundColor = [UIColor greenColor];

[self.view addSubview:view1];

UIEdgeInsets padding = UIEdgeInsetsMake(150, 30, 30, 30);

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view.mas_top).with.offset(padding.top);
make.left.equalTo(self.view.mas_left).with.offset(padding.left);
make.bottom.equalTo(self.view.mas_bottom).with.offset(-padding.bottom);
make.right.equalTo(self.view.mas_right).with.offset(-padding.right);
}];

// 一句代码代替上面的多行
//    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(150, 30, 30, 30));
//    }];

2. 使用Priority属性来做简单的动画

.priority allows you to specify an exact priority

.priorityHigh equivalent to UILayoutPriorityDefaultHigh

.priorityMedium is half way between high and low

.priorityLow equivalent to UILayoutPriorityDefaultLow

  • 优先级约束一般放在一个控件约束的最后面,下面看示例。
    1
    // 红色View
    UIView *redView = [[UIView alloc]init];
    redView.backgroundColor = [UIColor redColor];
    [self.view addSubview:redView];
    
    // 蓝色View
    self.blueView = [[UIView alloc]init];
    self.blueView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:self.blueView];
    
    // 黄色View
    UIView *yellowView = [[UIView alloc]init];
    yellowView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:yellowView];
    
    // ---红色View--- 添加约束
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(self.view.mas_left).with.offset(20);
    make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(-80);
    make.height.equalTo([NSNumber numberWithInt:50]);
    }];
    
    // ---蓝色View--- 添加约束
    [self.blueView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(redView.mas_right).with.offset(40);
    make.bottom.width.height.mas_equalTo(redView);
    }];
    
    // ---黄色View--- 添加约束
    [yellowView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(self.blueView.mas_right).with.offset(40);
    make.right.mas_equalTo(self.view.mas_right).with.offset(-20);
    make.bottom.width.height.mas_equalTo(redView);
    
    // 优先级设置为250,最高1000(默认)
    make.left.mas_equalTo(redView.mas_right).with.offset(20).priority(250);
    }];

Masonry动画1

1
// 点击屏幕移除蓝色View
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.blueView removeFromSuperview];
[UIView animateWithDuration:1.0 animations:^{
[self.view layoutIfNeeded];
}];
}

Masonry动画2

解:这里的三个View的宽度是根据约束自动推断设置的,对黄色的View设置了一个与红色View有关的priority(250)的优先级,它同时有对蓝色View有个最高的优先级约束(make.left.mas_equalTo(self.blueView.mas_right).with.offset(40);)。当点击屏幕是,我将蓝色View移除,此时第二优先级就是生效。

3. Masonry官方Demo之Basic

basic1

basic2

1
- (void)testBasic
{
int padding = 15;

UIView *greenView = [[UIView alloc]init];
[self.view addSubview:greenView];
greenView.backgroundColor = [UIColor greenColor];

UIView *redView = [[UIView alloc]init];
[self.view addSubview:redView];
redView.backgroundColor = [UIColor redColor];

UIView *blueView = [[UIView alloc]init];
[self.view addSubview:blueView];
blueView.backgroundColor = [UIColor blueColor];

// 对 绿色View 进行约束
[greenView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.view.mas_left).with.offset(padding); // X

make.top.mas_equalTo(self.view.mas_top).with.offset(padding); // Y
make.bottom.mas_equalTo(blueView.mas_top).with.offset(-padding);// Y --> 推断出 Height

make.width.mas_equalTo(redView); // Width == 红色View(它推断出Width)
}];

// 对 红色View 进行约束
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(greenView.mas_right).with.offset(padding); // X
make.right.mas_equalTo(self.view.mas_right).with.offset(-padding);// X --> 推断出 Width

make.bottom.and.height.mas_equalTo(greenView); // Y & Height == 绿色View(它推断出 Height&Y)
}];

// 对 蓝色View 进行约束
[blueView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.view.mas_left).with.offset(padding); // X
make.right.mas_equalTo(self.view.mas_right).with.offset(-padding); // X --> 推断出 Width

make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(-padding); // Y

make.height.mas_equalTo(greenView); // 注意1:Height == 绿色View(它推断出Height)
}];
}

总结:对绿色View约束了距离左边的距离(即确定了X值),约束了距离顶部和底部蓝色View的距离(这里有个坑需要注意,很多人会认为约束了这两个就能推断出Height,其实是错误的。除非蓝色View添加一个约束让它们俩高度相同,否则即便知道了它们俩间距和分别对顶部和底部的距离,也不知道红色View和蓝色View高度如何。)

口诀:谁推断出大小位置(一或多),与其有约束关系的View的大小位置(一或多)向它看齐。

4. Masonry的更新约束 mas_updateConstraints

Alternatively if you are only updating the constant value of the constraint you can use the convience method mas_updateConstraints instead of mas_makeConstraints

创建一个按钮,约束好它的位置(居中,宽高等于100且小于屏幕宽高值)。每次点击一次这个按钮,其宽高将增大一定的倍数,最终其宽高等于屏幕宽高时将不再变化。

1
@interface ViewController ()
@property (nonatomic, strong) UIButton *growingButton;
@property (nonatomic, assign) CGFloat scacle;
@end
1
- (void)createGrowingButton {
self.growingButton = [UIButton buttonWithType:UIButtonTypeSystem];

[self.growingButton setTitle:@"点我放大" forState:UIControlStateNormal];

self.growingButton.layer.borderColor = UIColor.greenColor.CGColor;

self.growingButton.layer.borderWidth = 3;

[self.growingButton addTarget:self action:@selector(onGrowButtonTaped:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:self.growingButton];
self.scacle = 1.0;

[self.growingButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.mas_equalTo(self.view);

// 初始宽、高为100,优先级最低
make.width.height.mas_equalTo(100 * self.scacle);

// 最大放大到整个view
make.width.height.lessThanOrEqualTo(self.view);
}];    
}
1
- (void)onGrowButtonTaped:(UIButton *)sender {
self.scacle += 1.0;

// 告诉self.view约束需要更新
[self.view setNeedsUpdateConstraints];

// 调用此方法告诉self.view检测是否需要更新约束,若需要则更新,下面添加动画效果才起作用

[self.view updateConstraintsIfNeeded];

[UIView animateWithDuration:0.3 animations:^{
[self.view layoutIfNeeded];
}];
}
1
#pragma mark - updateViewConstraints
// 重写该方法来更新约束
- (void)updateViewConstraints {
[self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) {
// 这里写需要更新的约束,不用更新的约束将继续存在
// 不会被取代,如:其宽高小于屏幕宽高不需要重新再约束
make.width.height.mas_equalTo(100 * self.scacle);
}];

[super updateViewConstraints];
}

更新约束

5. Masonry的重写约束 mas_remakeConstraints

Creates a MASConstraintMaker with the callee view. Any constraints defined are added to the view or the appropriate superview once the block has finished executing. All constraints previously installed for the view will be removed.

创建一个按钮,约束好其位置(与屏幕上左右的距离为0,与屏幕底部距离为350),点击按钮后全屏展现(即与屏幕底部距离为0)。

1
@property (nonatomic, strong) UIButton *growingButton;
@property (nonatomic, assign) BOOL isExpanded;
1
- (void)createExpandButton {
self.isExpanded = NO;
self.growingButton = [UIButton buttonWithType:UIButtonTypeSystem];
[self.growingButton setTitle:@"点我展开" forState:UIControlStateNormal];
self.growingButton.layer.borderColor = UIColor.greenColor.CGColor;
self.growingButton.layer.borderWidth = 3;
self.growingButton.backgroundColor = [UIColor redColor];
[self.growingButton addTarget:self action:@selector(onGrowButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.growingButton];
[self.growingButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(0);
make.left.right.mas_equalTo(0);
make.bottom.mas_equalTo(-350);
}];
}
1
#pragma mark - updateViewConstraints
- (void)updateViewConstraints {
// 这里使用update也能实现效果
// remake会将之前的全部移除,然后重新添加
__weak __typeof(self) weakSelf = self;
[self.growingButton mas_remakeConstraints:^(MASConstraintMaker *make) {
// 这里重写全部约束,之前的约束都将失效
make.top.mas_equalTo(0);
make.left.right.mas_equalTo(0);
if (weakSelf.isExpanded) {
make.bottom.mas_equalTo(0);
} else {
make.bottom.mas_equalTo(-350);
}
}];
[super updateViewConstraints];
}
1
- (void)onGrowButtonTaped:(UIButton *)sender {
self.isExpanded = !self.isExpanded;
if (!self.isExpanded) {
[self.growingButton setTitle:@"点我展开" forState:UIControlStateNormal];
} else {
[self.growingButton setTitle:@"点我收起" forState:UIControlStateNormal];
}
// 告诉self.view约束需要更新
[self.view setNeedsUpdateConstraints];
// 调用此方法告诉self.view检测是否需要更新约束,若需要则更新,下面添加动画效果才起作用
[self.view updateConstraintsIfNeeded];

[UIView animateWithDuration:0.3 animations:^{
[self.view layoutIfNeeded];
}];
}
  • mas_remakeConstraints和 mas_updateConstraints 的区别在于前者重新对视图进行了约束(抛弃了之前的约束),后者是更新约束条件(保留未更新的约束,如:这次更新了对 height 的约束,其他对X&Y以及宽的约束不变)。

重写约束1

重写约束2

6. Masonry的比例使用 multipliedBy

使用multipliedBy必须是对同一个控件本身,如果修改成相对于其它控件会出导致Crash。

1
UIView *topView = [[UIView alloc]init];
[topView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:topView];

UIView *topInnerView = [[UIView alloc]init];
[topInnerView setBackgroundColor:[UIColor greenColor]];
[topView addSubview:topInnerView];

UIView *bottomView = [[UIView alloc]init];
[bottomView setBackgroundColor:[UIColor orangeColor]];
[self.view addSubview:bottomView];

UIView *bottomInnerView = [[UIView alloc]init];
[bottomInnerView setBackgroundColor:[UIColor blueColor]];
[bottomView addSubview:bottomInnerView];

[topView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.mas_equalTo(0);
make.height.mas_equalTo(bottomView);
}];

[topInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.mas_equalTo(0);
make.width.mas_equalTo(topInnerView.mas_height).multipliedBy(3);
make.center.mas_equalTo(topView);
}];

[bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.bottom.right.mas_equalTo(0);
make.height.mas_equalTo(topView);
make.top.mas_equalTo(topView.mas_bottom);
}];

[bottomInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.bottom.mas_equalTo(bottomView);
make.height.mas_equalTo(bottomInnerView.mas_width).multipliedBy(3);
make.center.mas_equalTo(bottomView);
}];

multiply

iOS音频播放的几种方式

发表于 2016-02-22   |   分类于 systemMusicPlayer, audioPlayer   |  

一、使用AVAudioPlayer播放音乐

1. Background Modes

打开后台模式的音乐播放,或者在info.plist文件中添加Required Background Modes键,其值是App plays audio or streams audio/video using AirPlay

Background Modes

2. 添加后台播放代码

1
2
3
4
5
AVAudioSession *session = [AVAudioSession sharedInstance];

[session setActive:YES error:nil];

[session setCategory:AVAudioSessionCategoryPlayback error:nil];

3. 播放指定的音频文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 1.获取要播放音频文件的URL
NSURL *fileURL = [[NSBundle mainBundle]URLForResource:@"王力宏-流泪手心" withExtension:@".mp3"];

// 2.创建 AVAudioPlayer 对象
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];

// 3.打印歌曲信息
NSString *msg = [NSString stringWithFormat:@"音频文件声道数:%ld\n 音频文件持续时间:%g",self.audioPlayer.numberOfChannels,self.audioPlayer.duration];
NSLog(@"%@",msg);

// 4.设置循环播放
self.audioPlayer.numberOfLoops = -1;
self.audioPlayer.delegate = self;

// 5.开始播放
[self.audioplayer play];

二、使用System Sound Services播放音频

利用System Sound Services只能播放一些很小的提示或警告音频,它存在诸多限制,例如:声音长度不能超过30秒,不能控制进度,格式支持少等。

1. 注册音频文件

调用 AudioServicesCreateSystemSoundID(CFURLRef inFileURL,SystemSoundID *outSystemSoundID) 该函数的第一个参数代表音频文件的URL(可通过NSURL转换成CFURLRef),第二个参数代表注册音频文件的SystemSoundID。

2. 在音频播放完执行某些操作

调用AudioServicesAddSystemSoundCompletion()函数为制定SystemSoundID注册Callback函数。

3. 播放音频

调用AudioServicePlaySystemSound函数或者AudioServicePlayAlertSound(调用系统振动功能)。

4. 实战

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#import "FKViewController.h"
static void completionCallback(SystemSoundID mySSID)
{
// Play again after sound play completion
AudioServicesPlaySystemSound(mySSID);
}
@implementation ViewController
// 音频文件的ID
SystemSoundID ditaVoice;

- (void)viewDidLoad
{
[super viewDidLoad];
// 1. 定义要播放的音频文件的URL
NSURL *voiceURL = [[NSBundle mainBundle]URLForResource:@"CleanDidFinish" withExtension:@"aiff"];

// 2. 注册音频文件(第一个参数是音频文件的URL 第二个参数是音频文件的SystemSoundID)
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(voiceURL),&ditaVoice);

// 3. 为crash播放完成绑定回调函数
AudioServicesAddSystemSoundCompletion(ditaVoice,NULL,NULL,(void*)completionCallback,NULL);

// 4. 播放 ditaVoice 注册的音频 并控制手机震动
AudioServicesPlayAlertSound(ditaVoice);

// AudioServicesPlaySystemSound(ditaVoice);
// AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); // 控制手机振动
}

使用System Sound Services需要AudioToolbox框架的支持,需要导入其主头文件:#import<AudioToolbox/AudioToolbox.h>


三、使用MPMusicPlayerController控制本机音乐播放

对控制内置音乐库播放状态以及媒体信息的获取进行了封装,主要用于公司手环端蓝牙发送指令控制手机音乐播放以及在手环荧幕上显示歌曲名称。
下面介绍一下用法:

  1. 包含我封装的头文件 #import "BackgroundMusic.h"
  2. 遵守协议:achieveMusicInfoDelegate
  3. 初始化:
1
@property (nonatomic,strong) BackgroundMusic *musicController;
self.musicController = [[BackgroundMusic alloc]init];
self.musicController.delegate = self; // 设置当前控制器为代理

4. 监听媒体曲目的改变:

1
// 在 - (void)viewDidLoad 方法中调用以下方面
[self.musicController monitorMediaItem];

// 实现代理方法
- (void)achieveachieveMusicInfo:(NSString *)songName andPlaybackStatus:(int)playStatus
{
if (1 == playStatus) {
NSLog(@"正在播放音乐中...");
}else if(0 == playStatus){
NSLog(@"音乐暂停中...");
}else{
NSLog(@"播放状态未知...");
}

NSLog(@"歌曲信息:%@",songName);
}

5. 播放控制

1
// 控制音乐播放、暂停
[self playOrPause];

// 下一曲
[self next];

  • 使用MPMusicPlayerController实例化对象来播放内置音乐库的媒体文件,有以下两种类方法来实例化对象:
  • MPMusicPlayerController *playController = [MPMusicPlayerController systemMusicPlayer];
    说明:播放内置媒体库项目取代用户目前播放状态(如果是用网易云音乐或QQQ音乐在播放歌曲)
  • MPMusicPlayerController *playController = [MPMusicPlayerController applicationMusicPlayer];
    说明:播放该应用内的歌曲,不影响本机自带音乐播放器的状态。

1. 判断有没有正在播放的媒体项目

  • 返回NSNotFound表示empty queue or an infinite playlist
1
if ([self.playController indexOfNowPlayingItem] == NSNotFound) {
return YES;
}else{
return NO;
}

2. 创建媒体队列

  • 根据query创建媒体队列,创建成功后可以条用play来播放(默认播放第 index = 0 首曲目)
1
/**
*  设置媒体播放队列
*/
- (void)createMediaQuery
{
// Creates a media query that matches music items and that groups and sorts collections by song name.
self.query = [MPMediaQuery songsQuery];

// Sets a music player’s playback queue based on a media query.
[self.playController setQueueWithQuery:self.query];
}

3. 获取正在播放的媒体曲目的信息

  • 可以由nowPlayingItem取得一系列正在播放的曲目的详细信息:
    1
    @property (nonatomic, readonly) MPMediaEntityPersistentID 
    @property (nonatomic, readonly) MPMediaType mediaType 
    @property (nonatomic, readonly) NSString *title 
    @property (nonatomic, readonly) NSString *albumTitle 
    @property (nonatomic, readonly) MPMediaEntityPersistentID 
    @property (nonatomic, readonly) NSString *artist 
    @property (nonatomic, readonly) MPMediaEntityPersistentID 
    @property (nonatomic, readonly) NSString *albumArtist 
    ...
1
/**
*  获取媒体信息
*/
- (void)obtainMusicInfo
{
MPMediaItem *currentItem = [self.playController nowPlayingItem];
NSString *artist = [currentItem valueForProperty:MPMediaItemPropertyArtist];
NSString *songName = [currentItem valueForProperty:MPMediaItemPropertyTitle];

self.musicInfo = [NSString stringWithFormat:@"%@-%@",artist,songName];
}

4. 监听播放媒体项目的通知

  • 监听此通知可以在播放曲目发生改变时(如:下一曲、上一曲)作出动作。
1
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(updateMusicInfo)
name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:nil];

[self.playController beginGeneratingPlaybackNotifications];

基于百度地图SDK记录运动轨迹

发表于 2016-02-22   |   分类于 mapTrack, BaiduMap   |  

一、 前期准备工作

首先需要登录百度开放平台下载iOS地图SDK(内含开发者文档、框架以及Demo示例),推荐下载全新Framework形式的静态库,配置更加简单方便,具体看下图:
百度开放平台

framework静态库


1. 新建Xcode工程

File->New->Project->Single View Application,填写好相关信息完成工程建立。
新建工程


2. 获取Bundle Identifier

通过project->target->general可以看到本应用的Bundle Identifie,我们正是需要这串字符串去百度开发平台申请一个Key用于百度地图的调用。
Bundle Identifie


3. 申请key

登录百度开放平台后,点击右上角的API控制台进入申请key的界面,点击创建应用,在“安全码”处填入你的应用的Bundle Identifie,具体信息填写请看下图:
申请key信息填写图1
申请key信息填写图2


4. 导入框架配置工程

第一步 、引入BaiduMapAPI.framework
百度地图SDK提供了模拟器和真机两种环境所使用的framework,分别存放在libs/Release-iphonesimulator和libs/Release-iphoneos文件夹下,开发者可根据需要使用真机或模拟器的包,如果需同时使用真机和模拟器的包,可以使用lipo命令将设备和模拟器framwork包中的BaiduMapAPI文件合并成一个通用的文件,命令如下:

1
lipo -create Release-iphoneos/BaiduMapAPI.framework/BaiduMapAPI Release-iphonesimulator/BaiduMapAPI.framework/BaiduMapAPI -output Release-iphoneos/BaiduMapAPI.framework/BaiduMapAPI

此时Release-iphoneos文件夹下的BaiduMapAPI.framework即可同时用于真机和模拟器。将所需的BaiduMapAPI.framework拷贝到工程所在文件夹下。在TARGETS->Build Phases-> Link Binary With Libaries中点击+按钮,在弹出的窗口中点击“Add Other”按钮,选择BaiduMapAPI.framework文件添加到工程中。
注:静态库中采用ObjectC++实现,因此需要您保证您工程中至少有一个.mm后缀的源文件(您可以将任意一个.m后缀的文件改名为.mm),或者在工程属性中指定编译方式,即将Xcode的Project -> Edit Active Target -> Build -> GCC4.2 - Language -> Compile Sources As设置为Objective-C++。

第二步、引入所需的系统库
百度地图SDK中提供了定位功能和动画效果,v2.0.0版本开始使用OpenGL渲染,因此您需要在您的Xcode工程中引入CoreLocation.framework和QuartzCore.framework、OpenGLES.framework、
SystemConfiguration.framework、CoreGraphics.framework、
Security.framework。添加方式:在Xcode的Project -> Active Target ->Build Phases ->Link Binary With Libraries,添加这几个framework即可。

第三步、环境配置
在TARGETS->Build Settings->Other Linker Flags中添加-ObjC。

第四步、引入mapapi.bundle资源文件
如果使用了基础地图功能,需要添加该资源,否则地图不能正常显示
mapapi.bundle中存储了定位、默认大头针标注View及路线关键点的资源图片,还存储了矢量地图绘制必需的资源文件。如果您不需要使用内置的图片显示功能,则可以删除bundle文件中的image文件夹。您也可以根据具体需求任意替换或删除该bundle中image文件夹的图片文件。
方法:选中工程名,在右键菜单中选择Add Files to “工程名”…,从BaiduMapAPI.framework||Resources文件中选择mapapi.bundle文件,并勾选“Copy items if needed”复选框,单击Add按钮,将资源文件添加到工程中。

第五步、引入头文件
在使用SDK的类引入头文件:

1
#import <BaiduMapAPI/BMapKit.h>//引入所有的头文件
#import <BaiduMapAPI/BMKMapView.h>//只引入所需的单个头文件

–引用自百度开放平台iOS SDK环境配置


5. 初始化 BMKMapManager

  • 在AppDelegate.m 中添加 BMKMapManager的定义:

    1
    @interface AppDelegate ()<BMKGeneralDelegate>
    
    @property (nonatomic,strong) BMKMapManager *mapManager;
    
    @end
  • 遵守 BMKGeneralDelegate 实现其两个代理方法,目的是为了得知本应用是否联网成功、授权成功:

    1
    - (void)onGetNetworkState:(int)iError
    {
    if (0 == iError) {
    NSLog(@"联网成功");
    }
    else{
    NSLog(@"onGetNetworkState %d",iError);
    }
    
    }
    
    - (void)onGetPermissionState:(int)iError
    {
    if (0 == iError) {
    NSLog(@"授权成功");
    }
    else {
    NSLog(@"onGetPermissionState %d",iError);
    }
    }

BMKGeneralDelegate.h

  • 在AppDelegate.m文件中添加对BMKMapManager的初始化,并填入申请的授权Key,示例如下:
    1
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 要使用百度地图先实例化 BMKMapManager
    self.mapManager = [[BMKMapManager alloc]init];
    
    // 如果要关注网络及授权验证事件,请设定 generalDelegate 参数
    BOOL ret = [self.mapManager start:@"OjYbYha0YULmuLPaHT9wxxx" generalDelegate:self];
    if (!ret) {
    NSLog(@"manager start failed");
    }
    return YES;
    }

二、实战记录运动轨迹

一条完整的运动轨迹是由一组地理位置坐标数组描点连线构成的,我们需要实时监测用户位置的变更,将最新的符合限定条件的地位位置数据存放到数据中,调用SDK中的画折线方法绘制运动轨迹。


1. 初始化工作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@interface ViewController () <BMKMapViewDelegate, BMKLocationServiceDelegate>

/** 记录上一次的位置 */
@property (nonatomic, strong) CLLocation *preLocation;

/** 位置数组 */
@property (nonatomic, strong) NSMutableArray *locationArrayM;

/** 轨迹线 */
@property (nonatomic, strong) BMKPolyline *polyLine;

/** 百度地图View */
@property (nonatomic,strong) BMKMapView *mapView;

/** 百度定位地图服务 */
@property (nonatomic, strong) BMKLocationService *bmkLocationService;
@end

@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];

// 初始化百度位置服务
[self initBMLocationService];

// 初始化地图窗口
self.mapView = [[BMKMapView alloc]initWithFrame:self.view.bounds];

// 设置MapView的一些属性
[self setMapViewProperty];

[self.view addSubview:self.mapView];
}
@end
  • 初始化MapView后设置其一些属性:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    /**
    * 设置 百度MapView的一些属性
    */

    - (void)setMapViewProperty
    {
    // 显示定位图层
    self.mapView.showsUserLocation = YES;

    // 设置定位模式
    self.mapView.userTrackingMode = BMKUserTrackingModeNone;

    // 允许旋转地图
    self.mapView.rotateEnabled = YES;

    // 显示比例尺
    self.bmkMapView.showMapScaleBar = YES;
    self.bmkMapView.mapScaleBarPosition = CGPointMake(self.view.frame.size.width - 50, self.view.frame.size.height - 50);

    // 定位图层自定义样式参数
    BMKLocationViewDisplayParam *displayParam = [[BMKLocationViewDisplayParam alloc]init];
    displayParam.isRotateAngleValid = NO;//跟随态旋转角度是否生效
    displayParam.isAccuracyCircleShow = NO;//精度圈是否显示
    displayParam.locationViewOffsetX = 0;//定位偏移量(经度)
    displayParam.locationViewOffsetY = 0;//定位偏移量(纬度)
    displayParam.locationViewImgName = @"walk";
    [self.mapView updateLocationViewWithParam:displayParam];
    }
  • 百度定位服务的参数设置:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /**
    * 初始化百度位置服务
    */

    - (void)initBMLocationService
    {
    // 初始化位置百度位置服务
    self.bmkLocationService = [[BMKLocationService alloc] init];

    // 设置距离过滤,表示每移动10更新一次位置
    [BMKLocationService setLocationDistanceFilter:10];

    // 设置定位精度
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyBest];
    }

2. 开始定位

1
2
3
4
5
6
7
// 打开定位服务
[self.bmkLocationService startUserLocationService];

// 设置当前地图的显示范围,直接显示到用户位置
BMKCoordinateRegion adjustRegion = [self.mapView regionThatFits:BMKCoordinateRegionMake(self.bmkLocationService.userLocation.location.coordinate, BMKCoordinateSpanMake(0.02f,0.02f))];

[self.mapView setRegion:adjustRegion animated:YES];

只要遵守了BMKLocationServiceDelegate协议就可以获知位置更新的情况,需要实现下面几个代理方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 定位失败会调用该方法
*
* @param error 错误信息
*/

- (void)didFailToLocateUserWithError:(NSError *)error
{
NSLog(@"did failed locate,error is %@",[error localizedDescription]);
}

/**
* 用户位置更新后,会调用此函数
* @param userLocation 新的用户位置
*/

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
// 如果此时位置更新的水平精准度大于10米,直接返回该方法
// 可以用来简单判断GPS的信号强度
if (userLocation.location.horizontalAccuracy > kCLLocationAccuracyNearestTenMeters) {
return;
}
}

/**
* 用户方向更新后,会调用此函数
* @param userLocation 新的用户位置
*/

- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
// 动态更新我的位置数据
[self.mapView updateLocationData:userLocation];
}


3. 存储更新的用户地理位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 开始记录轨迹
*
* @param userLocation 实时更新的位置信息
*/

- (void)recordTrackingWithUserLocation:(BMKUserLocation *)userLocation
{
if (self.preLocation) {
// 计算本次定位数据与上次定位数据之间的距离
CGFloat distance = [userLocation.location distanceFromLocation:self.preLocation];
self.statusView.distanceWithPreLoc.text = [NSString stringWithFormat:@"%.3f",distance];
NSLog(@"与上一位置点的距离为:%f",distance);

// (5米门限值,存储数组画线) 如果距离少于 5 米,则忽略本次数据直接返回方法
if (distance < 5) {
return;
}
}

// 2. 将符合的位置点存储到数组中(第一直接来到这里)
[self.locationArrayM addObject:userLocation.location];
self.preLocation = userLocation.location;

// 3. 绘图
[self drawWalkPolyline];
}

4. 绘制轨迹线

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 绘制轨迹路线
*/

- (void)drawWalkPolyline
{
// 轨迹点数组个数
NSUInteger count = self.locationArrayM.count;

// 动态分配存储空间
// BMKMapPoint是个结构体:地理坐标点,用直角地理坐标表示 X:横坐标 Y:纵坐标
BMKMapPoint *tempPoints = new BMKMapPoint[count];

// 遍历数组
[self.locationArrayM enumerateObjectsUsingBlock:^(CLLocation *location, NSUInteger idx, BOOL *stop) {
BMKMapPoint locationPoint = BMKMapPointForCoordinate(location.coordinate);
tempPoints[idx] = locationPoint;
}
}];

//移除原有的绘图,避免在原来轨迹上重画
if (self.polyLine) {
[self.mapView removeOverlay:self.polyLine];
}

// 通过points构建BMKPolyline
self.polyLine = [BMKPolyline polylineWithPoints:tempPoints count:count];

//添加路线,绘图
if (self.polyLine) {
[self.mapView addOverlay:self.polyLine];
}

// 清空 tempPoints 临时数组
delete []tempPoints;

// 根据polyline设置地图范围
[self mapViewFitPolyLine:self.polyLine];
}

NSPredicate

发表于 2016-02-21   |   分类于 filter NSPredicate   |  

NSPredicate 是一个Foundation的类,用来定义逻辑条件约束的获取或内存中的过滤搜索,相当于SQL中的where用法。

1.集合中使用 NSPredicate

  • Foundation提供了Predicate来过滤NSArray、NSMutableArray、NSSet、NSMutableSet、NSDictionary等集合的方法。
  • NSArray&NSSet(不可变集合):通过filteredArrayUsingPredicate、filteredSetUsingPredicate:方法评估一个接收到的predicate来返回一个不可变集合。
  • NSMutableArray&NSMutableSet(可变集合):通过filterUsingPredicate:方法评估一个接收到的predicate来移除评估结果为FALSE的对象,这个可变数组将仅剩下符合要求的对象。同样地,也可以使用filteredArrayUsingPredicate、filteredSetUsingPredicate:方法来过滤返回一个符合要求的不可变集合。
  • NSDictionary:可以使用predicate来过滤分别过滤键值。

CodeSnippest:

1
2
3
4
5
6
7
8
9
10
11
NSMutableArray *mutArr = [NSMutableArray arrayWithObjects:@"bang",@"bing",@"jklb",@"dgjk",nil];
NSLog(@"before filter mutArr is %@",mutArr);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@",@"g"];

// 可变数组不会被改变,返回一个不可变数组
NSArray *arr = [mutArr filteredArrayUsingPredicate:predicate];
NSLog(@"after filter mutArr is %@,arr is %@",mutArr,arr);

// 可变数组被变更,只剩下符合条件的对象
[mutArr filterUsingPredicate:predicate];
NSLog(@"after filter mutArr is %@",mutArr);

2.谓词语法

  • 替换

%@ 是对值为字符串,数字或者日期的对象的替换值,%K 是key path的替换值

1
2
3
4
5
6
7
// 第一种写法
NSPredicate *bobPredicate = [NSPredicate predicateWithFormat:@"firstName = 'Bob'"];
NSPredicate *ageIs33Predicate = [NSPredicate predicateWithFormat:@"%K = %@", @"age", @33];

// 第二种写法
NSPredicate *bobPredicate = [NSPredicate predicateWithFormat:@"@"%K = %@",@"firstName",@"Bob""];
NSPredicate *ageIs33Predicate = [NSPredicate predicateWithFormat:@"age = 33"];

$VARIABLE_NAME是可以被NSPredicate -predicateWithSubstitutionVariables:替换的值。

1
2
3
NSMutableArray *mutArr = [NSMutableArray arrayWithObjects:@"bang",@"bing",@"jklb",@"dgjk",nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] $letter"];
NSLog(@"%@",[mutArr filteredArrayUsingPredicate:[predicate predicateWithSubstitutionVariables:@{@"letter":@"l"}]]);
  • 基本比较 :=(==)、<、>、<=(=<)、>=(=>)、!=(<>)、BETWEEN
1
2
3
NSArray *arr = @[@2,@3,@4,@5];
NSPredicate *arrPredicate = [NSPredicate predicateWithFormat:@"SELF BETWEEN {4,10}"];
NSLog(@"%@",[arr filteredArrayUsingPredicate:arrPredicate]);
  • 复合谓词 :AND(&&)、OR(||)、NOT(!)
1
2
3
NSArray *arr = @[@"kezhen",@"bole",@"Archae",@"arphan"];
NSPredicate *arrPredicate = [NSPredicate predicateWithFormat:@"(SELF BEGINSWITH %@) AND (SELF ENDSWITH %@)",@"b",@"e"];
NSLog(@"%@",[arr filteredArrayUsingPredicate:arrPredicate]);
  • 字符串比较相关:BEGINSWITH:以指定字符串开始;CONTAINS:包含指定字符串;ENDSWITH:以指定字符串结束;LIKE:左边表达式等于右边表达式,?匹配一个字符,*匹配0个或多个字符;MATCHES:左边的表达式根据ICU v3(更多内容请查看ICU User Guide for Regular Expressions)的regex风格比较,等于右边的表达式。
1
2
3
4
5
6
7
8
9
10
// LIKE
NSArray *arr = @[@"kezhen",@"bole",@"orchan",@"orphan"];
NSPredicate *arrPredicate = [NSPredicate predicateWithFormat:@"SELF LIKE %@",@"?rc*"];
NSLog(@"%@",[arr filteredArrayUsingPredicate:arrPredicate]);

// BETWEEN
NSArray *arr = @[@"kezhen",@"bole",@"Archae",@"arphan"];
NSString *regex = @"^A.+e$"; //以A开头,e结尾
NSPredicate *arrPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
NSLog(@"%@",[arr filteredArrayUsingPredicate:arrPredicate]);
  • 关系操作:ANY、ALL、NONE、IN

3.创建复合谓词

除了用复合谓词关键字连接组合多个谓词,还可以可用以下方法。

1
2
3
4
[NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"age > 25"], [NSPredicate predicateWithFormat:@"firstName = %@", @"Quentin"]]];

// 使用关键字连接组合多个谓词
[NSPredicate predicateWithFormat:@"(age > 25) AND (firstName = %@)", @"Quentin"];

4.Block谓词

block可以封装任意的计算,所以有一个查询类是无法以NSPredicate格式字符串形式来表达的(比如对运行时被动态计算的值的评估)。

1
2
3
4
NSPredicate *pre = [NSPredicate predicateWithBlock:^BOOL(id  _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
return [[evaluatedObject firstName] length] < 3;
}];
NSLog(@"firstName.length %@",[arr filteredArrayUsingPredicate:pre]);
  • 参考来源:
    NSPredicate - Mattt Thompson撰写、 Zihan Xu翻译、 发布于2013年7月15日

AVAudioSession Programming Guide

发表于 2016-02-21   |   分类于 AudioSession   |  

Defining an Audio Session

在你的应用中使用声音播放需要定义一个合适的audio session,它会配置你的应用的声音行为。例如

  • 是否让其他应用(音乐播放器)和你的应用声音进行混合
  • 来电或闹钟打断应用的声音播放应该如何恢复中断
  • 插拔耳机你的应用应该作何回应

当你的应用启动时,audio session的配置影响到所有音频的活动除了使用System Sounds Services API 播放的音频。你可以通过audio session查询到你应用所在的设备的硬件特性,例如:声道数量和采样率等。你可以激活和反激活你的audio session,系统也能够主动反激活你的audio session,例如来电和闹钟。

1.1 Audio Session Default Behavior

audio session有一些默认的行为:

  • 正在播放音视频时不可以进行录制
  • 应用声音播放跟随静音键的设置(静音键打开应用静音)
  • 应用声音跟随锁屏(锁频应用静音)
  • 应用声音独占播放(不允许其他应用与之混音)

以上的这些音频默认行为来自系统默认选择的AVAudioSessionCategorySoloAmbient。
在开发过程中,你可以采用上面这些默认的音频行为。不过,在以下几种情况你可以放心地忽略audio session的设置:

  • 你的应用播放声音使用System Sound Services or the UIKit playInputClick method,且没有使用音其他音频API。

    System Sound Services用于播放用户交互界面上的简短声音提示以及调用设备的震动功能。The UIKit playInputClick 方法让你在自定义的输入或键盘附件中播放标准的敲击声,它的音频行为由系统处理。

  • 你的应用根本没有使用到音频

在有其他音频行为需求下,不要使用默认的audio session。

1.2 Why a Default Audio Session Usually Isn’t What You Want

如果你没有实例化、配置以及清晰地使用你的audio session,你的应用则不能对音频线路改变或中断作出响应。
下面是一些演示默认音频行为的场景以及如何去改变它:

  • 场景1。你写了一个电子书应用。一个用户开始听《西游记》,不久设备自动锁屏了,应用也静音了。

    为了保证设备锁屏后依然能够正常播放声音,应该配置一个audio session支持播放并且在UIBackgroundModes中设置打开音频后台使用开关。

  • 场景2。你写了一个第一人称的射击游戏,使用了OpenAL-based sound effects。你提供了一个背景声音播放轨道,可以给用户播放音乐库的歌曲。当歌曲正在播放到一半时,你开炮射击了敌人的集中营,随之歌曲停止播放了。

    为了确保你的歌曲不会被打断,应该设置audio session允许被混音。使用AVAudioSessionCategoryAmbient或者修改AVAudioSessionCategoryPlayback来支持混音。(详情见Fine-Tuning category)。

  • 场景3。你写了一个流媒体音频应用,使用Audio Queue Services来播放。当一个用户在收听时,一个电话打进来了,正如我们所预料到的应用停止播放了。用户选择挂断电话,返回应用点击播放但不再响应。为了恢复播放,用户需要重启应用。

    为了能够优雅地处理音频队列的中断,设置合适的category并且监听AVAudioSessionInterruptionNotification。

1.3 Initializing Your Audio Session

在你的应用启动时系统就提供了一个audio session对象。然而,为了处理中断事件你必须实例化这个audio session。

1
2
// implicitly initializes your audio session
AVAudioSession *session = [AVAudioSession sharedInstance];

这个session代表被初始化的audio session,可以马上使用。当你使用AVAudioSession class’s interruption notifications或delegate protocols of the AVAudioPlayer and AVAudioRecorder classes处理中断时,苹果官方推荐对audio session进行隐式地初始化。

1.4 Adding Volume and Route Control

使用MPVolumeView类去为你的APP展示音量和线路控制。这个volume view提供了一个滑动条在应用内部控制音量,还提供了一个旋钮选择音频输出线路。当输出音频到内置扬声器时,苹果官方推荐通过AVAudioSessionPortOverride使用MPVolumeView route picker。

1.5 Responding to Remote Control Events

远程控制事件让用户控制应用的多媒体播放。如果你的应用播放音频或视频内容,你可能想要响应来自传输控件或外部附件的远程控制事件。iOS转换UIEvent对象的命令,传递事件到APP。APP把事件发送给第一响应者,如果第一响应者没有处理它们,将沿着响应链传递下去。你的APP一定要是“Now Playing”,否则不能响应事件。

1.6 Activating and Deactivating Your Audio Session

在你的APP启动时,系统将激活你的audio session。即使这样,苹果官方推荐在viewDidLoad方法中显式激活它,同时优先设置硬件偏好值。具体参照Setting Preferred Hardware Values代码,这可以测试是否激活成功。
下面展示如何激活APP的audio session

1
2
3
NSError *activationError = nil;
BOOL success = [[AVAudioSession sharedInstance] setActive: YES error: &activationError];
if (!success) { /* handle the error in activationError */ }

反激活则传递 NO 到 setActive 参数中。

在使用AVAudioPlayer对象播放声音或使用AVAudioRecorder对象录制音频的具体使用例子中,系统很关心在中断结束后audio session的重新激活。苹果官方推荐监听通知消息来重新激活audio session。如此,你可以确保重新激活成功,与此同时你可以更新应用的状态和UI。
大多数应用不需要显示地反激活audio session,如:VOIP、语音导航、录音的应用。

  • 要确保经常在后台运行的VOIP应用的audio session只有在处理通话时才是处于激活状态的。在后台等待处理电话通知时的audio session不应该被激活。
  • 设置为recording category应用的audio session只有在录制情况下才处于激活状态。在录制开始前和录制结束时,要确保你的应用的audio session是处于非激活状态来允许其他声音播放。

1.7 Checking Whether Other Audio Is Playing During App Launch

当用户启动APP的时候,或许设备正在播放音频。例如:当你启动应用时,设备音乐播放器在播放歌曲或浏览器在播放流媒体音频。如果你的应用是游戏,这种情况很明显。很多游戏有一个音乐声轨和一个音效轨道。在这种情况下,Sound in iOS Human Interface Guidelines 建议你音乐和游戏音效一起播放。检查otherAudioPlaying属性判断在你的应用启动时是否有其他音频正在播放。如果有其他音频正在播放,使你游戏应用的音乐声轨静音并且设置AVAudioSessionCategorySoloAmbientcategory。

1.8 Working with Inter-App Audio

在最基本的形式下,跨应用音频允许一个APP(节点APP)发送输出它的音频到另外一个APP(主APP)。也有可能是由主APP发送音频到节点APP,让节点APP来处理音频并返回结果给主APP。主APP需要有一个处于激活状态的audio session,然而节点APP只有在接收主APP输入时才需要一个处于激活状态的audio session。使用下面的指南来设置跨应用音频:

  • 为hostandnodeAPP的inter-app-audio授权。
  • 为hostAPP打开UIBackgroundModes的audio开关。
  • 为nodeAPP打开UIBackgroundModes的audio开关,当nodeAPP同时连接到一个inter-appaudio host时使用输入或输出线路。
  • 为host和nodeAPP设置AVAudioSessionCategoryOptionMixWithOthers。
  • 当nodeAPP同时连接到一个inter-appaudio host时,确保nodeAPP的audio session在接收来自系统的输入(或者发送音频输出)。

ORCHAN

ORCHAN

喜欢摄影,后期处理,捣鼓新奇数码产品

9 日志
8 分类
2 标签
© 2015 - 2016 ORCHAN
由 Hexo 强力驱动
主题 - NexT.Pisces