搜索
您的当前位置:首页正文

那些 iOS 7 中容易被忽视的新特性总结

来源:二三娱乐

NSAttributedString

from HTMLs!”;    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};          NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding]    options:options documentAttributes:nil error:nil];        现在你可以在任意的UIKit对象上使用NSAttributedString 了,比如说是一个UILabel或是一个UITextField,见以下代码:      #import- (BOOL)saveCredentials:(NSError **)error {        SSKeychainQuery *query = [[SSKeychainQuery alloc] init];        query.password = @”MySecretPassword”;        query.service = @”MyAwesomeService”;        query.account = @”John Doe”;        query.synchronizable = YES;        return [query save:&error];    }          - (NSString *)savedPassword:(NSError **)error {        SSKeychainQuery *query = [[SSKeychainQuery alloc] init];        query.service = @”MyAwesomeService”;        query.account = @”John Doe”;        query.synchronizable = YES;        query.password = nil;        if ([query fetch:&error]) {            return query.password;        }        return nil; 注意:NSHTMLTextDocumentType 只是NSDocumentTypeDocumentAttribute key一种可能的值。你还可以使用NSPlainTextDocumentType,NSRTFTextDocumentType或是 NSRTFDTextDocumentType。你还可以从NSAttributedString中创建一个HTML字符串,如下:NSAttributedString *attrString; // from previous code NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};  NSData *htmlData = [attrString dataFromRange:NSMakeRange(0, [attrString length]) documentAttributes:options error:nil]; NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding]; 现在你估计在app中会更多的使用HTML了。15.使用原生的Base64Base64是使用ASCII码显示二进制数据的一种流行方法。直到现在,开发者还不得不使用开源的工具来编码解码Base64的内容。现在iOS7引入了以下四种新的NSData方法来操作Base64编码的数据:// From NSData.h  /* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized  as valid Base-64. */ - (id)initWithBase64EncodedString:(NSString *)base64String options:(NSDataBase64DecodingOptions)options;  /* Create a Base-64 encoded NSString from the receiver’s contents using the given options. */ - (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options;  /* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64. */ - (id)initWithBase64EncodedData:(NSData *)base64Data options:(NSDataBase64DecodingOptions)options;  /* Create a Base-64, UTF-8 encoded NSData from the receiver’s contents using the given options. */ - (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options; 这些方法可以帮助你轻易的将NSData对象转化为Base64,或者将Base64转化为NSData object。见以下的例子:NSData* sampleData = [@"Some sample data" dataUsingEncoding:NSUTF8StringEncoding];  NSString * base64String = [sampleData base64EncodedStringWithOptions:0]; NSLog(@”Base64-encoded string is %@”, base64String); // prints ”U29tZSBzYW1wbGUgZGF0YQ==”  NSData* dataFromString = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; NSLog(@”String is %@”,[NSString stringWithUTF8String:[dataFromString bytes]]); // prints ”String is Some sample data” 如果你需要支持iOS6或者更早以前的系统,你可以使用以下两个方法:/* These methods first appeared in NSData.h on OS X 10.9 and iOS 7.0. They are deprecated in the same releases in favor of the methods in theNSDataBase64Encodingcategory. However, these methods have existed for several releases, so they may be used for applications targeting releases prior to OS X 10.9 and iOS 7.0. */ - (id)initWithBase64Encoding:(NSString *)base64String; - (NSString *)base64Encoding; 16.使用UIApplicationUserDidTakeScreenshotNotification来检查截图在iOS7之前,像Snapshot或是Facebook Poke这样的app是使用一些很精巧的方法来检测用户是否有截图。然而,iOS7提供一个崭新的推送方 法:UIApplicationUserDidTakeScreenshotNotification。只要像往常一样订阅即可知道什么时候截图了。注意:UIApplicationUserDidTakeScreenshotNotification 将会在截图完成之后显示。现在在截图截取之前无法得到通知。希望苹果会在iOS8当中增加 UIApplicationUserWillTakeScreenshotNotification。17.实现多语言语音合成如果可以让app说话会不会很好呢?iOS7加入了两个新类:AVSpeechSynthesizer 以及AVSpeechUtterance。这两个类可以给你的app发声。很有意思不是吗?有多种语言可供选择——Siri不会说的语言也有,比如说巴西葡萄牙语。使用这两个类给app提供语言合成的功能非常简单。AVSpeechUtterance 代表你想说什么,如何说。AVSpeechSynthesizer 用来发出这些声音,见以下代码片段:AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init]; AVSpeechUtterance *utterance =  [AVSpeechUtterance speechUtteranceWithString:@"Wow, I have such a nice voice!"]; utterance.rate = AVSpeechUtteranceMaximumSpeechRate / 4.0f; utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"]; // defaults to your system language [synthesizer speakUtterance:utterance]; 18.使用了新的UIScreenEdgePanGestureRecognizer UIScreenEdgePanGestureRecognizer 继承自UIPanGestureRecognizer ,它可以让你从屏幕边界即可检测手势。使用新的手势识别器很简单,见以下:UIScreenEdgePanGestureRecognizer *recognizer = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action: @selector(handleScreenEdgeRecognizer:)]; recognizer.edges = UIRectEdgeLeft; // accept gestures that start from the left; we’re probably building another hamburger menu! [self.view addGestureRecognizer:recognizer]; 19.使用UIScrollViewKeyboardDismissMode实现了Message app的行为像Messages app一样在滚动的时候可以让键盘消失是一种非常好的体验。然而,将这种行为整合到你的app很难。幸运的是,苹果给UIScrollView添加了一个很好用的属性keyboardDismissMode,这样可以方便很多。现在仅仅只需要在Storyboard中改变一个简单的属性,或者增加一行代码,你的app可以和办到和Messages app一样的事情了。这个属性使用了新的UIScrollViewKeyboardDismissMode enum枚举类型。这个enum枚举类型可能的值如下:UIScrollViewKeyboardDismissModeNone        // the keyboard is not dismissed automatically when scrolling UIScrollViewKeyboardDismissModeOnDrag      // dismisses the keyboard when a drag begins UIScrollViewKeyboardDismissModeInteractive // the keyboard follows the dragging touch off screen, and may be  pulled upward again to cancel the dismiss 以下是让键盘可以在滚动的时候消失需要设置的属性:20.使用Core Image来检测眨眼以及微笑iOS给Core Image增加了两种人脸检测功能:CIDetectorEyeBlink以及CIDetectorSmile。这也就是说你现在可以在照片中检测微笑以及眨眼。以下是在app中使用它的方法:UIImage *image = [UIImage imageNamed:@"myImage"]; CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace                                          context:nil                                          options:@{CIDetectorAccuracy: CIDetectorAccuracyHigh}];  NSDictionary *options = @{ CIDetectorSmile: @YES, CIDetectorEyeBlink: @YES };  NSArray *features = [detector featuresInImage:image.CIImage options:options];  for (CIFaceFeature *feature in features) {    NSLog(@”Bounds: %@”, NSStringFromCGRect(feature.bounds));      if (feature.hasSmile) {    NSLog(@”Nice smile!”);    } else {    NSLog(@”Why so serious?”);    }    if (feature.leftEyeClosed || feature.rightEyeClosed) {    NSLog(@”Open your eyes!”);    } } 21.给UITextView增加了链接现在在iOS添加你自己的Twitter账户更加简单了,现在你可以给一个NSAttributedString增加链接了,然后当它被点击的时候唤起一个定制的action。首先,创建一个NSAttributedString然后增加给它增加一个NSLinkAttributeName 属性,见以下:NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@”This is an example by @marcelofabri_”]; [attributedString addAttribute:NSLinkAttributeName                          value:@"username://marcelofabri_"                          range:[[attributedString string] rangeOfString:@”@marcelofabri_”]];    NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor],                                  NSUnderlineColorAttributeName: [UIColor lightGrayColor],                                  NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};  // assume that textView is a UITextView previously created (either by code or Interface Builder) textView.linkTextAttributes = linkAttributes; // customizes the appearance of links textView.attributedText = attributedString; textView.delegate = self; 这样就可以让链接在文本中显示。然而,你也可以控制当链接被点击的时候会发生什么,实现这个可以使用UITextViewDelegate协议的新的shouldInteractWithURL方法,就像这样:- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {    if ([[URL scheme] isEqualToString:@”username”]) {        NSString *username = [URL host];        // do something with this username        // …        return NO;    }    return YES; // let the system open this URL } 现在这些新功能就介绍完了。

Top