IOS 8 APIs that developers should know but are slightly vague (1)

Source: Internet
Author: User
Tags republican calendar

IOS 8 APIs that developers should know but are slightly vague (1)

No matter whether you ask anyone, they will tell you that WWDC2014 is the most exciting thing for them in recent days. Without hardware release information, it is entirely about software and developer tools.

The announcement of iOS 8 and OS X Yosemite in 2014 will make the apple platform the most leadership platform this year. The scalability and continuity of iOS, SpriteKit enhancements and SceneKit, as well as Metal, Game HealthKit, homeKit, Local Authentication and a new photo frame. Not to mention the compelling Xcode and Interface Builder. The improved iTunes Connect, TestFlight, Crash Reports and CloudKit, and Swift!

Are you still complaining? Apple has generously relaxed its confidentiality measures for new technologies, which means that we can now discuss the shiny new things.

This week, we will discuss the features listed below and share some of the vague APIs that everyone in iOS 8 should know.

From now on, NSHipster will mainly use Swift to write sample code, and occasionally use Objective-C. At the end of summer, we hope that all existing code samples can be transplanted to Swift, so as to quickly switch between languages.

# NSProcessInfo-isOperatingSystemAtLeastVersion ##

Forget [[UIDevice currentDevice] systemVersion] And NSFoundationVersionNumber. Here is a new method for determining the current operating system in the Code: NSProcessInfo-isOperatingSystemAtLeastVersion

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

But remember, to test the compatibility test), SomeClass. class or respondsToSelector is a better option to check the operating system version. The macros of C and Swift compilers can

It is used to compile the source based on the target configuration with conditions. Target-based build configuration, the macros compiled by C or Swift can compile the source code conditionally)

# New NSFormatter subclass ##

The most serious deficiency in the Foundation framework is the ability to process quantity units, such as quality and length. In iOS 8 and OS X Yosemite, three new classes are introduced: NSEnergyFormatter, NSMassFormatter, and NSLengthFormatter. This effectively doubles the number of NSFormatter sub-classes in the Foundation framework, previously limited to NSNumberFormatter, NSDateFormatter, and NSByteCountFormatter.

Although these new formatting classes are part of the Foundation framework, they are mainly used in HealthKit.

# NSEnergyFormatter ##

The NSEnergyFormatter uses jiao and calories as the formatting units of energy. Jiao is the unit used during exercise and the unit of calories in nutrition.

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

# NSMassFormatter ##

Although it is the basic unit of material existence, mass mainly refers to the user's weight in HealthKit. However, there is another sentence: Yes, Mass and weight are different, but in the program, this is not a science course, so don't be so peatchy !)

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

# NSLengthFormatter ##

To improve the new NSFormatter, another subclass is NSLengthFormatter. Think of it as a more useful version of MKDistanceFormatter, which has more unit options and format setting options.

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

# CMPedometer ##

In the last release, CMStepCounter made more stringent improvements than before, allowing users to query discrete data points in a timely manner and track users' steps and distances, it even calculates the number of stairs a user climbs.

Surprisingly, the M7 chip is competent for this task.

 
 
  1. import CoreMotion 
  2.  
  3. let lengthFormatter = NSLengthFormatter() 
  4. let pedometer = CMPedometer() 
  5. pedometer.startPedometerUpdatesFromDate(NSDate(), withHandler: { data, error in 
  6.     if !error { 
  7.         println("Steps Taken: \(data.numberOfSteps)") 
  8.  
  9.         let distance = data.distance.doubleValue 
  10.         println("Distance: \(lengthFormatter.stringFromMeters(distance))") 
  11.  
  12.         let time = data.endDate.timeIntervalSinceDate(data.startDate) 
  13.         let speed = distance / time 
  14.         println("Speed: \(lengthFormatter.stringFromMeters(speed)) / s") 
  15.     } 
  16. })

# CMAltimeter ##

On supported devices, CMPedometer can use CMAltimeter to expand the floorsAscended/floorsDescended statistics to obtain more precise vertical distance:

 
 
  1. import CoreMotion 
  2.  
  3. let altimeter = CMAltimeter() 
  4. if CMAltimeter.isRelativeAltitudeAvailable() { 
  5.     altimeter.startRelativeAltitudeUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { data, error in 
  6.         if !error { 
  7.             println("Relative Altitude: \(data.relativeAltitude)") 
  8.         } 
  9.     }) 

# CLFloor ##

CLFloor is a new API in iOS 8. The new features in CoreMotion reflect Apple's ambitious indoor navigation program. This information will play an important role in the localization navigation application.

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

# HKStatistics ##

As a framework, HealthKit involves a wide range, including many new classes and constants. Understanding the possibility of HKStatistics makes a good start for developers.

HealthKit manages biological data from all your devices in a unified API and can track and summarize multiple pieces of biological data in a powerful way, such as heart rate, calorie intake, and aerobic output.

The following example shows how to group and interpret data for one day:

 
 
  1. import HealthKit 
  2.  
  3. let collection: HKStatisticsCollection? = ... 
  4. let statistics: HKStatistics? = collection!.statisticsForDate(NSDate()) 
  5. for item: AnyObject in statistics!.sources { 
  6.     if let source = item as? HKSource { 
  7.         if let quantity: HKQuantity = statistics!.sumQuantityForSource(source) { 
  8.             if quantity.isCompatibleWithUnit(HKUnit.gramUnitWithMetricPrefix(.Kilo)) { 
  9.                 let massFormatter = NSMassFormatter() 
  10.                 let kilograms = quantity.doubleValueForUnit(HKUnit.gramUnitWithMetricPrefix(.Kilo)) 
  11.                 println(massFormatter.stringFromKilograms(kilograms)) 
  12.             } 
  13.  
  14.             if quantity.isCompatibleWithUnit(HKUnit.meterUnit()) { 
  15.                 let lengthFormatter = NSLengthFormatter() 
  16.                 let meters = quantity.doubleValueForUnit(HKUnit.meterUnit()) 
  17.                 println(lengthFormatter.stringFromMeters(meters)) 
  18.             } 
  19.  
  20.             if quantity.isCompatibleWithUnit(HKUnit.jouleUnit()) { 
  21.                 let energyFormatter = NSEnergyFormatter() 
  22.                 let joules = quantity.doubleValueForUnit(HKUnit.jouleUnit()) 
  23.                 println(energyFormatter.stringFromJoules(joules)) 
  24.             } 
  25.         } 
  26.     } 

NSHipster will cover more HealthKit functions in the future, so stay tuned!

# NSStream + getStreamsToHostWithName ##

From many aspects, Apple fixed many shortcomings on WWDC 2014. Some minor things, such as adding the missing NSStream initializer, instead of relying on the clumsy bridge CFStreamCreatePairWithSocketToHost call. This is + [NSStream getStreamsToHostWithName: port: inputStream: outputStream:]

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

# NSString-localizedCaseInsensitiveContainsString ##

For example, the following is a "small and solid fix", a simpler NSString method:

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

# CTRubyAnotationRef ##

If you are an attach to linguistics and text formatting, the new content of CoreText framework may make you get up and cheer.

... Oh, right. However, this Ruby is not what you think of Ruby. It is used to show the character pronunciation in some Asian scripts.

 
 
  1. @ Import CoreText;
  2.  
  3. NSString * kanji = @ "cat ";
  4. NSString * hiragana = @ "strongswan ";
  5.  
  6. CFStringRef furigana [kCTRubyPositionCount] =
  7. {(_ Bridge CFStringRef) hiragana, NULL };
  8.  
  9. CTRubyAnnotationRef ruby =
  10. CTRubyAnnotationCreate (kCTRubyAlignmentAuto, kctrubyoverhangautomatic, 0.5, furigana );

It is undeniable that the document does not fully describe how to accurately merge this part into the remaining CoreText painting calls, but the results may look like this:

Zookeeper

Cat

# New Calendar identifier ##

What is cool than Ruby comments? The new calendar identifier is added to iOS 8 and OS X Yosemite. This update updates the Foundation framework to the latest CLDR version. However, from the perspective of NSHipsters, French Republican Calendar still has its own highlights.

New Calendar identifier:

-NSCalendarIdentifierCoptic: Also known as Alexander calendar, which was previously used by Coptic Orthodox Church.

-NSCalendarIdentifierEthiopicAmeteMihret: Ethiopian calendar, Amete Mihret, about October 8)

-NSCalendarIdentifierEthiopicAmeteAlem: calendar of Ethiopia, before and after Amete Alem 5493 BC)

-NSCalendarIdentifierIslamicTabular: A simple table of Islamic calendars, which is used in the astronomical age of Thursday, July 15, 622 AD.

-NSCalendarIdentifierIslamicUmmAlQura: the Islamic Umm Qura calendar used in Saudi Arabia. It is calculated based on astronomy, rather than table behavior.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.