来源:nshipster.cn 发布时间:2014-07-06 阅读次数:2152

随便去问任何人,他们都会告诉你WWDC2014是近年来最为激动的回忆。 整个大会没有发布任何新硬件,它是一次史无前例的软件开发者盛宴!

  仅是iOS 8和OS X Yosemite的发布就能让2014成为苹果平台划时代的一年,加上Extension,Continuity,SpriteKit 改进,iOS SceneKit,Metal,HealthKit,Local Authentication和全新的照片框架。更不用说,Xcode和Interface Builder的明显改观,重新设计的iTunes Connect,TestFlight,崩溃报告和CloudKit。当然还有oh yeah-Swift。

  更棒的是?苹果放松了她的保密协定,也就是说我们可以现在就公开讨论这些崭新的玩具!

  这周,我们将拨开iOS 8的云雾,探讨一些所有人都应该知道新API。

从现在开始NSHipster讲主要使用Swift写样历代吗。夏天结束之前,我们希望能将全部的现存代码转换为Swift,并且提供可以切换语言的选项。

 NSProcessInfo -isOperatingSystemAtLeastVersion

  忘记[[UIDevice currentDevice] systemVersion]和NSFoundationVersionNumber吧, 现在可以用NSProcessInfo -isOperatingSystemAtLeastVersion来确定系统版本。

1
2
3
4
import Foundation
 
let yosemite = NSOperatingSystemVersion(majorVersion: 10, minorVersion: 10, patchVersion: 0)
NSProcessInfo().isOperatingSystemAtLeastVersion(yosemite) // false

  值得注意的是,在做兼容性测试的时候还是应该使用SomeClass.class或respondsToSelector:。 Swift和C中的编译器宏可以用来根据不同生成配置和目标来选择代码。

 新的NSFormatter子类

  Foundation中严重缺失的一项功能就是不能处理重量和长度单位转换。在iOS 8和OS X Yosemite中,引进了三个新类NSEnergyFormatter,NSMassFormatter和NSLengthFormatter来弥补这一缺失。

这使得NSFormatter子类的数量翻了一倍, 之前只有NSNumberFormatter,NSDateFormatter和NSByteCountFormatter。

  虽然这些都是Foundation的子类,但是它们主要都是在HealthKit当中使用。

  NSEnergyFormatter

  NSEnergyFormatter使用焦作为能量的原始单位,当处理健康信息时,则使用卡.

1
2
3
4
5
let energyFormatter = NSEnergyFormatter()
energyFormatter.forFoodEnergyUse = true
 
let joules = 10_000.0
println(energyFormatter.stringFromJoules(joules)) // "2.39 Cal"

  NSMassFormatter

  虽然质量是物质存在的基本单位, 在HealthKit中,它主要指的是身体重量.

1
2
3
let massFormatter = NSMassFormatter()
let kilograms = 60.0
println(massFormatter.stringFromKilograms(kilograms)) // "132 lb"

  NSLengthFormatter

  NSFormatter的最后一个新子类是NSLengthFormatter. 我们可以把它想象为MKDistanceFormatter的加强版。

1
2
3
let lengthFormatter = NSLengthFormatter()
let meters = 5_000.0
println(lengthFormatter.stringFromMeters(meters)) // "3.107 mi"

 CMPedometer

  沿着iOS 8的健康路线, CMStepCounter被重新设计了. CMPedometer作为它的改良版本不仅可以即时获取离散的点数据,并且可以同时跟踪脚步和距离,甚至计算总共爬了多少级楼梯。

  M7芯片真是功能强大.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import CoreMotion
 
let lengthFormatter = NSLengthFormatter()
let pedometer = CMPedometer()
pedometer.startPedometerUpdatesFromDate(NSDate(), withHandler: { <span id="9_nwp" style="width: auto; height: auto; float: none;"><a id="9_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=47&ch=0&di=128&fv=20&is_app=0&jk=6ffe5dec0d9071f6&k=data&k0=data&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=f671900dec5dfe6f&ssp2=1&stid=0&t=tpclicked3_hc&td=1922429&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F4675%2Ehtml&urlid=0" target="_blank" mpid="9" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">data</span></a></span>, error in
    if !error {
        println("Steps Taken: <span class="MathJax_Preview">\(<span id="0_nwp" style="width: auto; height: auto; float: none;"><a id="0_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=47&ch=0&di=128&fv=20&is_app=0&jk=6ffe5dec0d9071f6&k=data&k0=data&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=f671900dec5dfe6f&ssp2=1&stid=0&t=tpclicked3_hc&td=1922429&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F4675%2Ehtml&urlid=0" target="_blank" mpid="0" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">data</span></a></span>.numberOfSteps)")
 
        let distance = data.distance.doubleValue
        println("Distance: \)</span><script type="math/tex">data.numberOfSteps)")
 
        let distance = data.distance.doubleValue
        println("Distance: </script>lengthFormatter.stringFromMeters(distance))")
 
        let time = data.endDate.timeIntervalSinceDate(data.startDate)
        let speed = distance / time
        println("Speed: <span class="MathJax_Preview">\(lengthFormatter.stringFromMeters(speed)) / s")
    }
})</span>

 CMAltimeter

  在支持的设备上,CMAltimeter可以让CMPedometer的floorsAscended,floorsDescended数据更加精准:

1
2
3
4
5
6
7
8
9
10
import CoreMotion
 
let altimeter = CMAltimeter()
if CMAltimeter.isRelativeAltitudeAvailable() {
    altimeter.startRelativeAltitudeUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { <span id="8_nwp" style="width: auto; height: auto; float: none;"><a id="8_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=47&ch=0&di=128&fv=20&is_app=0&jk=6ffe5dec0d9071f6&k=data&k0=data&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=f671900dec5dfe6f&ssp2=1&stid=0&t=tpclicked3_hc&td=1922429&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F4675%2Ehtml&urlid=0" target="_blank" mpid="8" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">data</span></a></span>, error in
        if !error {
            println("Relative Altitude: \(data.relativeAltitude)")
        }
    })
}

 CLFloor

  CLFloor的引入展示了苹果进军室内导航的宏伟计划,楼层信息将扮演着重要的角色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import CoreLocation
 
class LocationManagerDelegate: NSObject, CLLocationManagerDelegate {
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
        let location: CLLocation? = locations[0] as? CLLocation
        if let floor: CLFloor? = location?.floor {
            println("Current Floor: $$floor?.level)")
        }
    }
}
 
let manager = CLLocationManager()
manager.delegate = LocationManagerDelegate()
manager.startUpdatingLocation()

 HKStatistics

  作为一个框架,HealthKit包含着大量的子类和常量。要想全部理解,HKStatistics是一个很好的开始。

  HealthKit管理着所有的生理信息,例如:心率,卡路里摄入量,血氧等等,并且通过统一的API聚合在一起。

  下面这个例子演示了如何从一天的连续数据中,挖掘和获取单独的数据:

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
import HealthKit
 
let collection: HKStatisticsCollection? = ...
let statistics: HKStatistics? = collection!.statisticsForDate(NSDate())
for item: AnyObject in statistics!.sources {
    if let source = item as? HKSource {
        if let quantity: HKQuantity = statistics!.sumQuantityForSource(source) {
            if quantity.isCompatibleWithUnit(HKUnit.gramUnitWithMetricPrefix(.Kilo)) {
                let massFormatter = NSMassFormatter()
                let kilograms = quantity.doubleValueForUnit(HKUnit.gramUnitWithMetricPrefix(.Kilo))
                println(massFormatter.stringFromKilograms(kilograms))
            }
 
            if quantity.isCompatibleWithUnit(HKUnit.meterUnit()) {
                let lengthFormatter = NSLengthFormatter()
                let meters = quantity.doubleValueForUnit(HKUnit.meterUnit())
                println(lengthFormatter.stringFromMeters(meters))
            }
 
            if quantity.isCompatibleWithUnit(HKUnit.jouleUnit()) {
                let energyFormatter = NSEnergyFormatter()
                let joules = quantity.doubleValueForUnit(HKUnit.jouleUnit())
                println(energyFormatter.stringFromJoules(joules))
            }
        }
    }
}

  NSHipster将会在未来探讨更多的HealthKit,敬请关注!

 NSStream +getStreamsToHostWithName

  在许多方面,WWDC 2014也是苹果查漏补遗的一年,比如给NSStream添加了新的initializer(再也不用调用CFStreamCreatePairWithSocketToHost了),这就是:+[NSStream getStreamsToHostWithName:port:inputStream:outputStream:]

1
2
3
4
5
6
7
var inputStream: NSInputStream?
var outputStream: NSOutputStream?
 
NSStream.getStreamsToHostWithName(hostname: "nshipster.com",
                                      port: 5432,
                               inputStream: &inputStream,
                              outputStream: &outputStream)

 NSString -localizedCaseInsensitiveContainsString

  这又是一个NSString小而实用的修缮:

1
2
3
4
let string: NSString = "Café"
let substring: NSString = "É"
 
string.localizedCaseInsensitiveContainsString(substring) // true

 CTRubyAnnotationRef

  好吧,此Ruby非彼Ruby. . 这是用来给亚洲文字添加注音符号的.

1
2
3
4
5
6
7
8
9
10
@import CoreText;
 
NSString *kanji = @"猫";
NSString *hiragana = @"ねこ";
 
CFStringRef furigana[kCTRubyPositionCount] =
    {(__bridge CFStringRef)hiragana, NULL, NULL, NULL};
 
CTRubyAnnotationRef ruby =
    CTRubyAnnotationCreate(kCTRubyAlignmentAuto, kCTRubyOverhangAuto, 0.5, furigana);

  无可否认的是,文档中并没有很清晰的描述具体如何将它整合进入你剩下的CoreText中,但是结果如下:

  猫ねこ

 新的日历识别符

  iOS 8和OS X中这些新的日历识别符使得Fundation跟上了CLDR的步伐:

  • NSCalendarIdentifierCoptic: 亚历山大日历, 科普特正教使用.
  • NSCalendarIdentifierEthiopicAmeteMihret: 埃塞俄比亚日历, Amete Mihret
  • NSCalendarIdentifierEthiopicAmeteAlem: 埃塞俄比日历, Amete Alem
  • NSCalendarIdentifierIslamicTabular: 一个简单的伊斯兰星历.
  • NSCalendarIdentifierIslamicUmmAlQura: 沙特阿拉伯伊斯兰日历.

 NSURLCredentialStorage

  自从去年NSURLSession的引入之后,Foundation的URL载入系统并没有太大的改变。但是,新的NSURLCredentialStorage可以让你更加方便地以移步,非闭包的方式获取和存储密码。

1
2
3
4
5
6
7
8
9
10
11
import Foundation
 
let session = NSURLSession()
let task = session.<span id="4_nwp" style="width: auto; height: auto; float: none;"><a id="4_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=47&ch=0&di=128&fv=20&is_app=0&jk=6ffe5dec0d9071f6&k=data&k0=data&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=f671900dec5dfe6f&ssp2=1&stid=0&t=tpclicked3_hc&td=1922429&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F4675%2Ehtml&urlid=0" target="_blank" mpid="4" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">data</span></a></span>TaskWithURL(NSURL(string: "http://nshipster.com"), completionHandler: { data, response, error in
    // ...
})
 
let protectionSpace = NSURLProtectionSpace()
NSURLCredentialStorage.getCredentialsForProtectionSpace(protectionSpace: protectionSpace, task: task, completionHandler: { credentials in
    // ...
})

 kUTTypeToDoItem

  在比较过最新的API之后,你可能会注意到大量的新UTI常量。其中,kUTTypeToDoItem引起了我的注意:

1
2
3
import MobileCoreServices
 
kUTTypeToDoItem // "public.to-do-item"

  作为一个公共类型,iOS和OS X现在提供了统一的方式让App之间共享任务。如果你碰巧正在开发一个任务管理工具,正确的整合好这个系统类型应该成为你的首要任务。

 kCGImageMetadataShouldExcludeGPS

  许多用户完全不知道他们用手机拍摄的大部分照片都包含了GPS元数据。更是有数不清的人因为这一个小细节泄露了自己的隐私。

  最新的图片I/O框架中加入了一个新的选项CGImageDestination:kCGImageMetadataShouldExcludeGPS让你方便的控制是否包含GPS元数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@import UIKit;
@import ImageIO;
@import MobileCoreServices;
 
UIImage *image = ...;
NSURL *fileURL = [NSURL fileURLWithPath:@"/path/to/output.jpg"];
NSString *UTI = kUTTypeJPEG;
NSDictionary *options = @{
                          (__bridge id)kCGImageDestinationLossyCompressionQuality: @(0.75),
                          (__bridge id)kCGImageMetadataShouldExcludeGPS: @(YES),
                          };
 
CGImageDestinationRef imageDestinationRef =
CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL,
                                (__bridge CFStringRef)UTI,
                                1,
                                NULL);
 
CGImageDestinationAddImage(imageDestinationRef, [image CGImage], (__bridge CFDictionaryRef)options);
CGImageDestinationFinalize(imageDestinationRef);
CFRelease(imageDestinationRef);

 WTF_PLATFORM_IOS

  #define WTF_PLATFORM_IOS已经从JavaScriptCore中移除.

 WKWebView

  UIWebView已死. WKWebView万岁.

  WKWebView提供了Safari级别的性能,并且在UIWebView的基础上提供了更多的配置选项:

1
2
3
4
5
6
7
8
9
10
11
import WebKit
 
let preferences = WKPreferences()
preferences.javaScriptCanOpenWindowsAutomatically = false
 
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
 
let webView = WKWebView(frame: self.view.bounds, configuration: configuration)
let request = NSURLRequest(URL: NSURL(string: "http://nshipster.com"))
webView.loadRequest(request)

 NSQualityOfService

  线程这个概念已经在苹果框架中被系统性的忽略。这对于开发者而言是件好事。

  沿着这个趋势,NSOperation中新的qualityOfService的属性取代了原来的threadPriority。通过它可以推迟那些不重要的任务,从而让用户体验更加流畅。

  NSQualityOfService枚举定义了以下值:

  • UserInteractive:和图形处理相关的任务,比如滚动和动画。
  • UserInitiated:用户请求的任务,但是不需要精确到毫秒级。例如,如果用户请求打开电子邮件App来查看邮件。
  • Utility:周期性的用户请求任务。比如,电子邮件App可能被设置成每五分钟自动检查新邮件。但是在系统资源极度匮乏的时候,将这个周期性的任务推迟几分钟也没有大碍。
  • Background:后台任务,用户可能并不会察觉对这些任务。比如,电子邮件App对邮件进行引索以方便搜索。

  Quality of Service将在iOS 8和OS X Yosemite中广泛的应用,所以留意所有能利用它们的机会。

 LocalAuthentication

  最后,最令人期待的iOS 8新功能之一:LocalAuthentication。自从iPhone 5S加入TouchID,开发者就对它的应用前景垂涎三尺。

  想象一下,只要有CloudKit和LocalAuthentication,创建新账号的烦恼讲不复存在。只需要扫描一下你的手就搞定了!

  LocalAuthentication以LAContext的方式工作,验证声明的规格,然后返回是否验证成功。整个过程中,用户的生物信息都被安全的储存在硬件当中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
LAContext *context = [[LAContext alloc] init];
NSError *error = nil;
 
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
                         error:&error])
{
    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
            localizedReason:NSLocalizedString(@"...", nil)
                      reply:^(BOOL success, NSError *error) {
        if (success) {
            // ...
        } else {
            NSLog(@"%@", error);
        }
    }];
} else {
    NSLog(@"%@", error);
}

  虽然这些天每个人都在讨论Swift,但是作为一个开发者你更应该关注的是这些iOS 8和OS X Yosemite的新API。它们可以让你实实在在的_做_一些事。

  如果你想接着探索,dive into the iOS 7.1 to 8.0 API diffs可以让你领会这些变化的重要性。当然,4000多的新API,很多只是细微的改变或者将方法改为属性,但是,它们值得拥有!

iOS 8 新特性介绍的更多相关文章

  1. Xcode9新特性介绍-中文篇

    背景: Xcode 9 新特性介绍: 1.官方原文介绍链接 2.Xcode9 be ta 2 官方下载链接 本文为官方介绍翻译而来,布局排版等都是按照官方布局来的. 与原文相比,排版上基本还是熟悉的配 ...

  2. dubbox新特性介绍

    dubbx是当当网对原阿里dubbo2.x的升级,并且兼容原有的dubbox.其中升级了zookeeper和spring版本,并且支持restfull风格的远程调用. dubbox git地址:  h ...

  3. Hadoop3.0新特性介绍,比Spark快10倍的Hadoop3.0新特性

    Hadoop3.0新特性介绍,比Spark快10倍的Hadoop3.0新特性 Apache hadoop 项目组最新消息,hadoop3.x以后将会调整方案架构,将Mapreduce 基于内存+io+ ...

  4. jdk7和8的一些新特性介绍

    jdk7和8的一些新特性介绍 本文是我学习了解了jdk7和jdk8的一些新特性的一些资料,有兴趣的大家可以浏览下下面的内容. 官方文档:http://www.oracle.com/technetwor ...

  5. ArcGIS 10.3 for Desktop新特性介绍

    ArcGIS 10.3是一个完整公布的ArcGIS平台,它包含新的产品(ArcGIS Pro),针对10.2版本号产品进行了功能增强和稳定性的改进. ArcGIS 10.3 for Server新特性 ...

  6. php7函数,声明,返回值等新特性介绍

    使用 ... 运算符定义变长参数函数 (PHP 5 >= 5.6.0, PHP 7) 现在可以不依赖 func_get_args(), 使用 ... 运算符 来实现 变长参数函数. functi ...

  7. webpack 4.0.0-beta.0 新特性介绍

    webpack 可以看做是模块打包机.它做的事情是:分析你的项目结构,找到JavaScript模块以及其它的一些浏览器不能直接运行的拓展语言(Scss,TypeScript等),并将其打包为合适的格式 ...

  8. iOS 9应用开发教程之iOS 9新特性

    iOS 9应用开发教程之iOS 9新特性 iOS 9开发概述 iOS 9是目前苹果公司用于苹果手机和苹果平板电脑的最新的操作系统.该操作系统于2015年6月8号(美国时间)被发布.本章将主要讲解iOS ...

  9. MyBatis 3.5.2 新特性介绍

    1.MyBatis 最新版本 3.5.2 发布 MyBatis最新版本是:3.5.2,发布时间是:2019年7月15日 2.MyBatis 3.5.2 新特征介绍 我们知道,MyBatis 是支持定制 ...

随机推荐

  1. r画饼图

    原始图样: library(ggplot2) dt = data.frame(A = c(2, 7, 4, 10, 1), B = c('B','A','C','D','E')) p = ggplot ...

  2. Python:基本运算、基本函数(包括复数)、Math模块、NumPy模块

    基本运算 x**2 : x^2 若x是mat矩阵,那就表示x内每个元素求平方 inf:表示正无穷 逻辑运算符:and,or,not 字典的get方法 a.get(k,d) 1 1 get相当于一条if ...

  3. 重点:怎样正确的使用QThread类(注:包括推荐使用QThread线程的新方法QObject::moveToThread)

    背景描述: 以前,继承 QThread 重新实现 run() 函数是使用 QThread唯一推荐的使用方法.这是相当直观和易于使用的.但是在工作线程中使用槽机制和Qt事件循环时,一些用户使用错了.Qt ...

  4. TCP/IP和Socket的关系

    要写网络程序就必须用Socket,这是程序员都知道的.而且,面试的时候,我们也会问对方会不会Socket编程?一般来说,很多人都会说,Socket编程基本就是listen,accept以及send,w ...

  5. glob函数 循环遍历子目录下的文件

    <?php foreach (glob("ueditor\php\upload\image\*\*.png") as $filename) { echo "$fil ...

  6. tornado 重定向404

    方法一: 一度喜欢tornado的我, 一直在尝试寻找自定义404的方法,恰巧在看tornaod的mvc结构的时候看到了解决办法 方法之巧妙令人从心底佩服.后来我克隆一份到自己的github以作备份. ...

  7. 不可将布尔变量直接与 TRUE、FALSE 或者 1、0 进行比较

    不可将布尔变量直接与 TRUE.FALSE 或者 1.0 进行比较. 根据布尔类型的语义,零值为“假”(记为 FALSE),任何非零值都是“真”(记为 TRUE). TRUE 的值究竟是什么并没有统一 ...

  8. 利用CMake和OpenCV源代码生成Visual Studio工程

    OpenCV1.0版本有windows,linux之分,笔者曾经一直使用Opencv1.0.这个版本在下载,安装之后,在 \OpenCV\_make文件夹下面已经存在了一个opencv.dsw的工程文 ...

  9. iOS 图文混排 (Swift版)

    // 0> 图片附件 let attachment = NSTextAttachment() attachment.image = #imageLiteral(resourceName: &qu ...

  10. 10046事件sql_trace跟踪

    查看 sql 执行计划的方法有许多种, 10046 事件就是其中的一种. 与其他查看 sql 执行计划不同, 当我们遇到比较复杂的 sql 语句, 我们可以通过 10046 跟踪 sql 得到执行计划 ...