OSX Command Line Read StdIn

1
2
3
4
5
6
func readStdIn() -> String {
let stdIn = NSFileHandle.fileHandleWithStandardInput()
let inputData = stdIn.availableData
let string = NSString(data: inputData, encoding: NSUTF8StringEncoding)!
return string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
}

Layer-Backed

1
2
3
4
5
6
7
8
//layer-backed view = false
-(void) drawRect

//layer-backed view = true
//wantsUpdateLayer = true
-(BOOL) wantsUpdateLayer
//wantsUpdateLayer = false
- (void)drawRect:(NSRect)dirtyRect

Layer-Backed Views

By default, AppKit views are not backed by Core Animation layers; layer-backing support has been integrated into AppKit retroactively. But while you never have to worry about this with UIKit, with AppKit there are decisions to make. AppKit differentiates between layer-backed and layer-hosting views, and layer backing can be turned on and off on a per-view-tree basis.

The most straightforward approach to enable layer backing is to set the wantsLayer property to YES on the window’s content view. This will cause all views in the window’s view tree to have their own backing layers, so there’s no need to repeatedly set this property on each individual view. This can be done in code or simply in Interface Builder’s View Effects Inspector.

In contrast to iOS, on the Mac you should treat the backing layers as an implementation detail. This means you should not try to interact with the layers directly, as AppKit owns those layers. For example, on iOS you could simply say:
SELECT ALL

1
self.layer.backgroundColor = [UIColor redColor].CGColor;

But in AppKit, you shouldn’t touch the layer. If you want to interact with the layer in such ways, then you have to go one step further. Overriding NSView’s wantsUpdateLayer method to return YES enables you to change the layer’s properties. If you do this though, AppKit will no longer call the view’s drawRect: method. Instead, updateLayer will be called during the view update cycle, and this is where you can modify the layer.

bash history

1
2
3
4
5
6
7
8
9
10
11
12
history
history n
history -n
history | grep xx
!n Expand to command with history number "n".
!-n Expand to command that was "n" number of commands before the current command in history.
!xxx execute the last command which start with xxx
!?xxx? execute the last command which contain "xxx"
!! Expand to the last command

touch /etc/hello
sudo !!

ctrl-R search bash

监听全局事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyUpMask 
handler:^(NSEvent * _Nonnull event) {
[self handleEvent:event];
}];

-(BOOL) handleEvent:(NSEvent *) event{
const NSUInteger kNotAlt = NSAlternateKeyMask | NSShiftKeyMask | NSCommandKeyMask;
if ((event.modifierFlags & NSControlKeyMask) != 0
&&
((event.modifierFlags & kNotAlt) == 0)
&&
[event.charactersIgnoringModifiers isEqualToString:@"x"]) {
.....

// 激活app
[NSApp activateIgnoringOtherApps:YES];
return YES;
}
return NO;
}

AVAuthorizationStatus Camera

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
- (IBAction)goToCamera{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized){
        [self popCamera];
    } else if(authStatus == AVAuthorizationStatusNotDetermined) {
        NSLog(@"%@", @"Camera access not determined. Ask for permission.");
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo 
        completionHandler:^(BOOL granted){
            if(granted) {
                NSLog(@"Granted access to %@", AVMediaTypeVideo);
                [self popCamera];
            } else {
                NSLog(@"Not granted access to %@", AVMediaTypeVideo);
                [self camDenied];
            }
        }];
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        // My own Helper class is used here to pop a dialog in one simple line.
        [Helper popAlertMessageWithTitle:@"Error" 
        alertText:@"You've been restricted from using the camera on this device. 
        Without camera access this feature won't work. Please 
        contact the device owner so they can give you access."];
    } else {
        [self camDenied];
    }
}

Swift 2.2 changelog

  • ++ and – are deprecated
  • Traditional C-style for loops are deprecated
  • Arrays and other slice types now have removeFirst()
  • You can now compare tuples
  • Tuple splat syntax is deprecated
  • More keywords can be used as argument labels
  • var parameters have been deprecated
  • Renamed debug identifiers: #line, #function, #file
  • Stringified selectors are deprecated
  • Compile-time Swift version checking
1
2
3
4
5
#if swift(>=2.2)
print("Running Swift 2.2 or later")
#else
print("Running Swift 2.1 or earlier")
#endif

UIView rotate Infinite

1
2
3
4
5
6
7
8
9
10
11
12
13
#import <QuartzCore/QuartzCore.h> 
- (void) spinAnimationOnView:(UIView*)view
duration:(CGFloat)duration
rotations:(CGFloat)rotations
repeat:(float)repeat; {
CABasicAnimation *animation;
animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 * rotations * duration ];
animation.duration = duration;
animation.cumulative = YES;
animation.repeatCount = repeat;
[view.layer addAnimation:animation forKey:@"rotationAnimation"];
}

CIFilter

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
+(void) adjustImage:(UIImage *) image container:(UIImageView *) iv{
CIImage *beginImage = [CIImage imageWithCGImage:image.CGImage];
CIFilter * filter = [CIFilter filterWithName:@"CIColorControls"];
[filter setValue:beginImage forKey:kCIInputImageKey];

NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];

// 亮度 10 -1---1
float lightPercent = [[ud objectForKey:@"Light"] floatValue];
float lightValue = -1 + 2*lightPercent;


// 对比度 -11 0---4
float contrastPercent = [[ud objectForKey:@"Contrast"] floatValue];
float contrastValue = 0 + 4*contrastPercent;

// 饱和度 0---2
float bhdPercent = [[ud objectForKey:@"Temp"] floatValue];
float bhdValue = 0 + 2*bhdPercent;

[filter setValue:@(lightValue) forKey:@"inputBrightness"];
[filter setValue:@(contrastValue)forKey:@"inputContrast"];
[filter setValue:@(bhdValue) forKey:@"inputSaturation"];

// 得到过滤后的图片
CIImage *outputImage = [filter outputImage];
// // 转换图片, 创建基于GPU的CIContext对象
// CIContext *context = [CIContext contextWithOptions: nil];
// CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];
UIImage *newImg = [UIImage imageWithCIImage:outputImage];
// // 显示图片
[iv setImage:newImg];
// // 释放C对象
// CGImageRelease(cgimg);

}

ios 截屏保存到UIImage

1
2
3
4
5
CGSize imageSize = [[UIScreen mainScreen] bounds].size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
[[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();