Thứ Hai, 22 tháng 6, 2015

My WWDC Experience and How I Got the WWDC Scholarship

Editor’s note: This is a guest post by Stasy Meclazcke. Stasy is a 17 year old iOS app developer and designer. He started programming when was 12 years old. When he was 16, he started to learn iOS programming and build iOS apps. Since then he has published more than five apps on the App Store. He recently won the student scholarship from Apple and got an opportunity to attend the WWDC 2015. We are happy to have him to share his experience at WWDC and on how he got the scholarship. If you plan to apply for the scholarship next year, I hope you will find the post useful. And my advice is: Start to learn Swift and build apps!

Enter Stasy Meclazcke.

This year, Apple asked students to make an app about themselves describing and showing their technical skills and what they did before and what they plan to do. Apple required that the app be mainly or solely written in Swift. I was able to transfer my knowledge of Objective-C into Swift pretty easily and made the app with ease.

wwdc-2015

What’s it like to attend WWDC

This year, 350 students won a scholarship to WWDC, compared to 200 from last year. The first event for the WWDC scholarship students occurred on the Sunday right before WWDC. This orientation started at 11:30 this year and was held at a hotel. It’s good to get there a little bit early so you won’t have to wait in line so long to get in. Once you are in, they serve food. There’s plenty to go around, and it’s pretty good compared to the food at WWDC. After that, you wait until the orientation presentation begins. Try to stay near the doors before the actual presentation starts if you want to have a good seat. During the presentation, some leaders at Apple talk to you about how Apple runs and some of the many ways you can get hired. After the presentation, you go out and talk with other students or people who work at Apple. Be sure to stay near the entrance or be on the lookout for Tim Cook. He came in and took pictures with many of the students. He would stay for less than an hour. Once Tim Cook left, they handed out WWDC 15 backpacks, which are only available to the scholarship winners. After that, people would start to leave (before 4:30 p.m., which is when it ends).

craig-myself

Right after the orientation, some people started lining up for the keynote at 5 p.m. Lining up at 10 p.m. will get you in the first 20 people though. If you want to have a good seat, it is a good idea to start lining up before 3-4 a.m. It would be cold at night, so remember to bring layers of clothes, a blanket, a chair or anything to keep you warm. While waiting, you would see companies hand out free stuff. I got some hand warmers and pizza.

At around 7 a.m., you start going in Moscone. It gets really packed, and everyone is pushing up against you. At this point, there will be people cheating and climbing over the rails to get on the other side near the door. Once through the door, you go up some escalators. They tell you not to run, but everyone does. Once up the first escalator, be sure to stay on the right side. The right side goes up the right escalators, which leads to the right side of Presidio. The best seats are at the front, to the right. The middle space at the front is reserved for the press and people who work for Apple. After you get up the first escalators, you will have to wait near the second escalators for around two hours. You can get some food and take some rest. After an hour of waiting at Presidio (and after you get seats), the keynote starts. Don’t leave your seat while waiting because someone may take it.

The keynote usually ends with a performance. After the keynote, you can have lunch at Moscone (which isn’t the best, but it’s edible). Then, the platform’s state of the union and Apple design awards starts. The Apple design awards are pretty interesting and fun to watch it live. That’s the events happened on Monday, the first day of WWDC. After the keynote, the beta softwares announced earlier at WWDC would become available for download. From Tuesday to Friday, you can either attend sessions or labs. Sessions are presentations about the new technologies presented at the keynote. Labs are hands-on sessions that you can get one-on-one advice from Apple’s engineer. You can ask pretty much anything related to iOS app or Mac app development. You should build some apps or continue working on apps that you have during WWDC, so you can attend as many labs as possible and get direct help from Apple. Sessions are live-streamed and stored online, so you can watch them later. Therefore, my advice is to spend as much time as possible on labs. The scholarship lounge is reserved for scholarship winners.

wwdc-labs
wwdc-lounge

This part of Moscone is on the third floor. It has many chairs and outlets in which to hang out. It also has a table with some food and soda. They pretty much had an unlimited supply of soda and food at the event at certain time. There are download stations with ethernet cables (some with USB adapters) which have incredibly fast speeds (900mbps up/down). You should get breakfast before 9 a.m. during the week. If you want to sign up for the User Interface Design Lab, make sure you should go to Moscone at 7 a.m. There are also many other things you can do in San Francisco during the week. There were events on the Facebook group for visiting tech companies such as Facebook and Twitter. From 6 p.m. to 9 p.m., the bash occurs. A popular band plays and the students get a private section on top of AMC. Some Apple executives hung out with us, including Craig Federighi.

Overall, it’s a rewarding experience.

fb-the-hacker-way

How I Got the WWDC Scholarship

To win a WWDC scholarship, it is important to be knowledgeable and resourceful in most technologies related to iOS or Mac. Apple wants you to use their latest technologies in your scholarship app. Since WWDC 14, it is important to use Swift, Apple’s new programming language, to build your app. Apple really wants this language to succeed so you should demonstrate how you are using it and what you’ve built with it. It is also important to create a couple of apps before crafting your scholarship app. One section of the app should consist of the apps or things you’ve made. You can check out my apps at aeip.github.io.

bizcard-app

If you need help creating your scholarship app, you can always ask for help. Simply search for programming tutorials (AppCoda is really good for this), or check out the issue you are experiencing on Stack Overflow (you can find pretty much anything related to iOS app development on Stack Overflow). If you already know Objective-C, it is pretty easy to learn Swift. If you don’t know Objective-C, you should start with Swift now. It’s easier and better for making iOS apps.

This is my WWDC experience. If you have any thoughts, feel free to share it with me by leaving a comment below.

Source : appcoda[dot]com
post from sitemap

Thứ Bảy, 20 tháng 6, 2015

How to Change the Language on iPhone & iPad

Change language on iPhone

The iPhone language is set during the initial setup of the device, defaulting to wherever region it was sold. But if you would like to change the language used on iPhone, you can do so at any time without resetting the device back to factory defaults, instead you’ll just need to turn to the settings in iOS.


Changing the language in iOS takes just a few seconds, you can set it to anything you want, which can be helpful if it was accidentally changed, you don’t understand the language currently in use, or perhaps because you’re learning a foreign language and you want greater immersion. Here’s what you’ll want to do:

  1. Open the Settings app then go to “General”
  2. Choose “Language & Region” and tap on ‘iPhone Language’*
  3. Select the language you wish to change the iPhone to, and confirm that you wish to change the iPhones language to the choice
  4. Wait a moment or two and iOS will switch to the new language

How to change the language used on iPhone

You can change the language on iPhone at any time using this option screen, and it’s the same for any other iOS device too, so if you wish to do so on an iPad or iPod touch the language setting will be in the same place.

* The default language options included directly on iPhone are for English, Spanish, German, Chinese (Simplified and Traditional), Japanese, Dutch, Italian, Japanese, Korean, Arabic, and additional languages can be downloaded if necessary. Choose “Other Languages” if the latter situation applies to you.

If you’re wondering, this is completely different from adding keyboard support to another language, which is another option for bilingual and multilingual users, though adding other language keyboards also allows for things like special character access on the iOS keyboard and of course, the popular Emoji keyboard.

By the way, if you’re adjusting language settings to help you learn another language or because you’re traveling, you may want to check out the rather amazing Word Lens app, which uses the iPhone camera to translate languages on the fly, it’s quite impressive. Adjusting the Maps language can also be helpful too.

Source : osxdaily[dot]com
post from sitemap

Thứ Tư, 17 tháng 6, 2015

A Beginner’s Guide to UIScrollView

In iOS, scroll views are used to view content that won’t fit entirely on the screen. Scroll views have two main purposes:

  • To let users drag the area of the content they want to display
  • To let users zoom in to or out of the displayed content using the pinch gestures

A common control used in iOS apps – UITableView – is a subclass of UIScrollView and provides a great way to view content that is larger than the screen.

In this tutorial, we’ll look at various aspects of UIScrollView, specifically, creating a scroll view programmatically and in Interface Builder, scrolling and zooming, working with insets and nested scroll views.

UIScrollView Guide

Before reading on, first download the resource file for the project which contains files we’ll use in the tutorial.

Creating Scroll Views Programmatically

Scroll views are created as any other view is, either programmatically or in Interface Builder. After that, only a small amount of additional configuration is required to achieve basic scrolling capabilities.

A scroll view is created and inserted into a controller or view hierarchy like any other view. There are only two additional steps required to complete the scroll view configuration:

  • You must set the contentSize property to the size of the scrollable content. This specifies the size of the scrollable area.
  • You must add a view or views that are displayed and scrolled by the scroll view. These view(s) provide the displayed content.

You can optionally configure any visual cues your application requires like vertical and horizontal scroll indicators, drag bouncing, zoom bouncing, and directional constraint of scrolling.

We’ll start off by creating a scroll view in code. Open the ScrollViewDemo project from the project files you downloaded. It contains a simple project with a single view controller in the storyboard that has been linked to the ScrollViewController class created in the project. I have also included an image named image.png which we’ll be using (photo coutesy of unsplash.com).

Open ScrollViewController.swift and add the following properties.

1
2
var scrollView : UIScrollView !
var imageView : UIImageView !

Modify viewDidLoad() as shown.

1
2
3
4
5
6
7
8
9
10
11
12
13
override func viewDidLoad ( ) {
     super . viewDidLoad ( )
        
     imageView = UIImageView ( image : UIImage ( named : "image.png" ) )
        
     scrollView = UIScrollView ( frame : view . bounds )
     scrollView . backgroundColor = UIColor . blackColor ( )
     scrollView . contentSize = imageView . bounds . size
     scrollView . autoresizingMask = UIViewAutoresizing . FlexibleWidth | UIViewAutoresizing . FlexibleHeight
        
     scrollView . addSubview ( imageView )
     view . addSubview ( scrollView )
}

The above creates a scroll view and an image view. The image view is set as a subview of the scroll view. contentSize sets the size of the scrollable region. We set it equal to the size of the image view (2000 x 1500). We set the scroll view’s background color to black so that the image can have a black backdrop. We set the scroll view’s autoresizingMask to .FlexibleWidth and .FlexibleHeight so that it readjusts its size when the device is rotated. Run the app and you should be able to scroll through and see the different parts of the image.

scroll view demo #1

When you ran the app, you might have noticed that the part of the image that was originally shown was its top left corner.

scroll view demo #2

This is because the scroll view’s bound origin is set to (0,0) which is at the top left corner. If you want to change the position of the content shown when the app launches, then you have to change the scroll views’s bound origin. Since setting this position is so common when working with scroll views, UIScrollView has a contentOffset property that you can change which will have the same effect as changing the bounds origin.

Paste the following statement after the line that sets the scroll view’s autoresizingMask.

1
scrollView . contentOffset = CGPoint ( x : 1000 , y : 450 )

Run the app again and you’ll see that the scroll view has moved to show a different part of the photo. So you can determine what is presented to the user when the view is loaded.

scroll view image demok

Zooming

We’ve added a scroll view which enables the user to scroll through a larger portion of content that’s too large for the screen. This is great, but it would be more useful if the user could zoom in and out of the view.

To support zooming, you must set a delegate for your scroll view. The delegate object must conform to the UIScrollViewDelegate protocol. That delegate class must implement the viewForZoomingInScrollView() method and return the view to zoom.

You should also specify the amount the user can zoom in and out. You do this by setting values of the scroll view’s minimumZoomScale and maximumZoomScale properties. Both of these are set to 1.0 by default.

Modify the ScrollViewController class definition as shown.

1
class ScrollViewController : UIViewController , UIScrollViewDelegate {

Then add the following function to the class.

1
2
3
func viewForZoomingInScrollView ( scrollView : UIScrollView ) -> UIView ? {
     return imageView
}

Then at the bottom of viewDidLoad() add the following.

1
2
3
4
scrollView . delegate = self
scrollView . minimumZoomScale = 0.1
scrollView . maximumZoomScale = 4.0
scrollView . zoomScale = 1.0

In the above code we set the zoomScale to 1.0 and specify the zoom factor for the minimum and maximum zooming. On running the app, it will start off with the same scale factor as previously shown(zoomScale of 1.0). When you pinch the view, you will be able to scroll it up and down to its maximum and minimum scale factors. We set a large number (4.0) for the maximumZoomScale, thus you can scale up the image to 4 times its size, which isn’t so good as the resulting image when scaled up to a size larger than the original will be blurry. We’ll change this in the next step back to its default of 1.0.

image03

In the above, we set the minimumZoomScale to 0.1 which results in a pretty small image that leaves a lot of blank space on the screen. In landscape mode, the empty space next to the image is even larger. We want to make the image ‘Aspect Fit’ the scroll view so that it takes up as much space on the scroll view as it can while still showing the full image.

image04

To do this we’ll calculate the mimimum scale factor by using the ratio of the scroll view and image view size.

First remove the following three statements from viewDidLoad().

1
2
3
scrollView . minimumZoomScale = 0.1
scrollView . maximumZoomScale = 4.0
scrollView . zoomScale = 1.0

Add the following function to the class. We get width and height ratios and pick the smaller of the two and set it as the minimum zoom scale. Notice I’ve remove the setting of the maximumZoomScale, so it will be set to its default of 1.0.

1
2
3
4
5
6
7
8
9
func setZoomScale ( ) {
     let imageViewSize = imageView . bounds . size
     let scrollViewSize = scrollView . bounds . size
     let widthScale = scrollViewSize . width / imageViewSize . width
     let heightScale = scrollViewSize . height / imageViewSize . height
        
     scrollView . minimumZoomScale = min ( widthScale , heightScale )
     scrollView . zoomScale = 1.0
}

Then call this at the end of viewDidLoad()

1
setZoomScale ( )

Also add the following so that the image scales right after the user tries to zoom in/out after a device orientation change.

1
2
3
override func viewWillLayoutSubviews ( ) {
     setZoomScale ( )
}

Run the app and now when you zoom out the image will take up as much space on the screen while being fully visible.

image05

From the images above, you notice that the scroll view’s content – the image – is positioned from the top left corner of the screen. We want this to be centered on the screen instead.

Add the following function to the class.

1
2
3
4
5
6
7
8
9
func scrollViewDidZoom ( scrollView : UIScrollView ) {
     let imageViewSize = imageView . frame . size
     let scrollViewSize = scrollView . bounds . size
        
     let verticalPadding = imageViewSize . height < scrollViewSize . height ? ( scrollViewSize . height - imageViewSize . height ) / 2 : 0
     let horizontalPadding = imageViewSize . width < scrollViewSize . width ? ( scrollViewSize . width - imageViewSize . width ) / 2 : 0
        
     scrollView . contentInset = UIEdgeInsets ( top : verticalPadding , left : horizontalPadding , bottom : verticalPadding , right : horizontalPadding )
}

This is called after every zoom action. It tells the delegate that the scroll view’s zoom factor changed. In the above code we calculate the padding/inset that will be applied on the sides of the image to center it. For the top and bottom values, we check if the image view’s height is smaller than the scroll view and if so set the padding to half the value of the difference between the two views, otherwise we set the value to 0. We do a similar thing for the horizontal padding. We then set the scroll view’s contentInset. This is the distance that the content view is inset from the enclosing scroll view.

Run the app and now the content should be centered when zoomed down to the minimum scale.

image06

Zooming by Tapping

The basic UIScrollView class supports the pinch-in and pinch-out gestures with a little amount of additional code. But supporting a richer zooming experience using tap detection will rquire more work.

The iOS Human Interface Guidlines defines a double-tap to zoom in and out. This however assumes some constraints: that the view has a single level of zoom (such as in the Photos application where a double tap zooms the content up to the maximum zoom scale and another tap zooms it down to the mimimum), or that successive double-taps will zoom to the maximum amount and, once reached, the next double-tap zooms back to the full-screen view. But some applications require a more flexible behavior when dealing with tap-to-zoom functionality, an example of this is the Maps application. Maps supports double-tap to zoom in, with additional double-taps zooming in further. To zoom out in successive amounts, Maps uses a two-finger touch, with the fingers close together, to zoom out in stages

In order for your application to support tap to zoom functionality, you implement the required touch handling in the class for which the UIScrollView delegate method viewForZoomingInScrollView() returns. That class will be responsible for tracking the number of fingers on the screen and the tap count. When it detects a single tap, a double tap, or a two-finger touch, it will respond accordingly. In the case of the double tap and two-finger touch, it should programmatically zoom the scroll view by the appropriate factor.

For our app, we’ll implement the double-tap to zoom up to maximum if it’s currently at the minimum zoom scale, otherwise the double-tap will zoom it down to the minimum, this is similar to what you get on the Photos app.

Add the following two functions to the class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func setupGestureRecognizer ( ) {
     let doubleTap = UITapGestureRecognizer ( target : self , action : "handleDoubleTap:" )
     doubleTap . numberOfTapsRequired = 2
     scrollView . addGestureRecognizer ( doubleTap )
}
    
func handleDoubleTap ( recognizer : UITapGestureRecognizer ) {
        
     if ( scrollView . zoomScale > scrollView . minimumZoomScale ) {
         scrollView . setZoomScale ( scrollView . minimumZoomScale , animated : true )
     } else {
         scrollView . setZoomScale ( scrollView . maximumZoomScale , animated : true )
     }
}

Then at the bottom of viewDidLoad() make the following call.

1
setupGestureRecognizer ( )

In the above code, we add a gesture recognizer to the scrollview, that recognizes when a user double taps on it. We then handle this by either zooming in or out depending on the current zoom level.

Run the app and you should be able to zoom in and out by double tapping.

Creating Scroll Views in Interface Builder

Implementing the scroll view similar to what we’ve done in Interface Builder is simpler than in code. These are the quick steps to get what we just built in code using storyboards.

In Main.storyboard, drag another view controller onto the canvas. Set it as the initial view controller by either dragging the Storyboard Entry Point arrow from the other view controller, or by selecting the new view controller and checking the Is Initial View Controller checkbox in the Attributes Inspector.

Add a Scroll View to the view controller’s view and pin all its edges so that it fills the screen.

image07

Then add an Image View to the Scroll View and pin all its edges to the scroll view.

image08

Remember that a scroll view needs to know its content size. When you set the image of the image view, its size will be used as the content size of the scroll view.

In Attributes Inspector, select image.png as the Image of the Image View. Resolve any Auto Layout issues by updating the frames. Run the app and you should have the same scrolling view we had in just a few set up steps and without writing a line of code. You can take a look at the Attributes Inspector, on selecting the Scroll View, to see what attributes you can set on it here. You can, for instance, set its minimum and maximum zoom scale.

For zooming, you’ll still need to implement the viewForZoomingInScrollView() delegate method as we did previously. We aren’t going to cover that here as it will just be a repetition of the last section. This means that if you need more features for your scroll view, you’ll still need to get into code.

Nested Scroll Views

It is possible to nest a scroll view inside another scroll view. This nesting can either be same directional or cross directional. For the code files for this part of the tutorial, use the NestedScrollViews starter project provided.

Same Directional Scrolling

Same-directional scrolling occurs when a UIScrollView that is a subview of a UIScrollView both scroll in the same direction. You can use this to add a section in your main scroll view’s view that contains additional separate data. You can also use same directional scroll views to achieve some UI effects like the parallax effect. In our demo app, we’ll use same directional scrolling and set different scrolling speeds for the two scroll views. This will result in a parallax effect of the views.

Open the storyboard file of the NestedScrollViews project, you should see a view controller with two sibling scroll views inside the main view. The scroll views have IDs of Background and Foreground. The Background scroll view has an image view with all its edges pinned to the scroll view with no padding. The image has been set to image.png. Both scroll views are pinned to the View with no padding.

In the Foreground scroll view, there are some labels added to it and a container view. The labels are only there so that we have a populated scroll view when we run the app. The container view will be used in the next section where we’ll look at cross directional scrolling. Incase you are wondering about the long size of the view controller, this is a setting you can set by selecting the view controller, going to the Size Inspector, changing its Simulated Size to Freeform and setting a size for this. In our case, I increased the height to 1,200. This is only to help you visually when you are working on your views and need more space on the view controller. It won’t affect the running app. It comes in handy when you are laying out elements that will likely be out of view when you first run the app, like the elements at the lower half of our scroll view.

image09

Since we already have the UI set up, creating the parallax effect will be quick. First run the app and note that the Foreground scrolls, but the Background remains stationary.

We’ll first create outlets for the two scroll views. Open the Assistant Editor and create an outlet for the Background scroll view named background and another for Foreground named foreground. You should have the following in ViewController.swift.

1
2
@ IBOutlet weak var background : UIScrollView !
@ IBOutlet weak var foreground : UIScrollView !

We’ll need to know when the foreground view is scrolled, so we can calculate the amount the background should scroll by and use this value to scroll it. We’ll use a UIScrollViewDelegate method for this.

Change the class declaration of ViewController as shown.

1
class ViewController : UIViewController , UIScrollViewDelegate {

Add the following to the bottom of viewDidLoad(). We only care about the foreground, so we wont set the background’s delegate.

1
foreground . delegate = self

Add the following function to the class.

1
2
3
4
5
6
7
8
func scrollViewDidScroll ( scrollView : UIScrollView ) {
        
     let foregroundHeight = foreground . contentSize . height - CGRectGetHeight ( foreground . bounds )
     let percentageScroll = foreground . contentOffset . y / foregroundHeight
     let backgroundHeight = background . contentSize . height - CGRectGetHeight ( background . bounds )
        
     background . contentOffset = CGPoint ( x : 0 , y : backgroundHeight * percentageScroll )
}

In the above code, we get the height of the foreground and calculate by how much the foreground has been scrolled. We then take this value and multiply it with the background’s height and use this in setting the background’s contentOffset which will result with the background moving a little bit faster than the foreground, each time the foreground is scrolled. Run the app and you’ll see the parallax effect created by this.

sv01

Cross Directional Scrolling

Cross-directional scrolling occurs when a scroll view that is a subview of another scroll view scrolls at a 90 degree angle. We’ll create this next.

In the NestedScrollViews project, you’ll notice a container view in the Foreground scroll view. This is where our horizontal scroll view will go.

Add a view controller to the Interface Builder canvas. With this view controller selected, go to the Size Inspector and change its Simulated Size to Freeform and set its height to 128. 128 is the size of our container view, so we set this as the size of the simulated view so we can better see how the scroll view will eventually look like. The view controller will look as shown.

image10

Drag a scroll view to this view controller and pin its edges as shown.

image11

Then add a view to the scroll view and set its size in the Size Inspector to 70×70. Place it to the left of the scroll view. Duplicate it to create other similar views and spread them out on the scroll view. You don’t have to be accurate about the spacing. Below you can see what I have at this point. I changed the Background Color of the views to light gray so that they are more distinct.

image12

Select the leftmost view and pin it to the top and left. Also add constraints for the height and width.

image13

Select the view on the furthest right side and pin its top and right, and add constraints to its width and height.

image14

In the Document Outline. Select the Scroll View and go to Editor > Resolve Auto Layout Issues > All Views > Add Missing Constraints. This will add constraints to the other views. Run the app and you should be able to scroll vertically like before, but on the container view, you will be able to scroll through the content horizontally. In the example below, I set the Background Color of the view controller’s view to Clear Color.

scroll view demo

That brings us to the end of this tutorial. We didn’t cover everything about scroll views, but I hope the article helps you when you’re getting started with scroll views. For more on the topic, you can read more in the Scroll View Programming Guide.

For reference, you can download both completed project files here.

Source : appcoda[dot]com
post from sitemap

Chủ Nhật, 14 tháng 6, 2015

Add a New Person to a Group Message on iPhone

Messages

Group messaging is a great feature that makes conversations with multiple people much easier, but what if you want to add someone else to an existing group chat from iOS? No sweat, you can quickly add a new contact (or several) to a group message conversation from your iPhone or iPad with a few easy steps.


You’ll obviously need to be in the Messages app to do this, and you’ll want to have an preexisting group conversation going that you can add a new person to. Here’s how this works to bring about a new contact to a group chat:

  1. From any existing Group Message, tap the “Details” button in the upper right corner
  2. Details button in group Chat Messages

  3. Under the names of people included in the Group chat, tap on the “+ Add Contact” button
  4. Add a contact to the group chat in Messages app of iOS

  5. Tap on a contact to add that user to the group message
  6. Adding this person to a group conversation in Messages for iOS

  7. Tap “Done” or repeat as necessary to add additional users to the group chat

Once a person is added they’ll be included in all future conversations as long as they’re in the group, unless they leave the group chat themselves or you remove them. When you send a new message to the group, that new person will be now be added to those future message threads (and no, they can not see the prior messages and conversation).

Of course if you’re on the receiving end of this and you’ve been added to a group chat that you don’t really care to be a part of at some point, you can always opt to mute the group conversation and all messages pertaining to it or simply leave the group chat yourself.

Adding contacts to a group conversation like this is kind of like a text based conference call, use it the next time you’re trying to arrange plans or converse with multiple people at once, it’s great.

Source : osxdaily[dot]com
post from sitemap

Thứ Sáu, 12 tháng 6, 2015

What’s New in Swift 2.0: A Brief Introduction

Editor’s note: This post is contributed by Maxime. He was recently awarded the WWDC scholarship to attend this year’s conference. We’re so happy to have him to share with us about the new features of Swift 2.

One year ago, Apple brought us Swift, a brand new programming language for both iOS and OS X. When it was first announced, just like other iOS developers, I was thrilled. Advertised as a fast and safe language, Swift has now grown to one of the most popular programming languages. As expected, the company introduced Swift 2 at WWDC this year. I am fortunate that I got an opportunity to attend the conference so I can share some updates on Swift.

We’re stepping on the gas this year with Swift 2. We think Swift is the next big programming language, the one we will all do application and systems programming on for 20 years to come. We think it should be everywhere and used by everyone.

Craig Federighi, Apple’s senior vice president of Software Engineering

What's new in Swift 2

We measure temperature in Celsius or Fahrenheit scale. At WWDC, we measure the popularity of a new feature in decibel. The two biggest applauses this year were when Apple announced UI testing support in Xcode 7 and Swift goes Open Source. If you missed the WWDC keynote or have been living under a rock lately, you read it right: Swift goes open source. This is a huge deal. Later this year, Apple will release Swift’s source code to the public, including the compiler and standard libraries, under an OSI-compliant license. Apple will also port the source code to Linux. Developers will be able to contribute to the development of the language and write programs on Linux using Swift. In fact, you’re encouraged to contribute to the development of the language.

Along with this exciting news, Swift 2 includes some new features such as improved error handling, protocol extensions and availability check. Let me give you a brief overview of the updates.

Error Handling

Sometimes things may go wrong. When a function fails, it’s always good to catch the error and understand why it fails. Swift version 1 lacked proper error handling model. In Swift 2, it comes with an exception-like model using try / throw / catch keywords.

Imagine you’re modelling a car engine. The engine can fail for the following reasons:

  • No fuel
  • Oil leakage
  • Low battery

In Swift, errors are represented by values of types conforming to the ErrorType protocol. In this case, you can create an enumeration that adopts ErrorType to model the error conditions:

1
2
3
4
5
enum CarEngineErrors : ErrorType {
     case NoFuel
     case OilLeak
     case LowBattery
}

To create a function that can throw an error, you use the throws keyword in its declaration. Here is an example:

1
2
func checkEngine ( ) throws {
}

To throw an error in the function, you use the throw statement. Here is a sample function that performs a simple check on the engine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let fuelReserve = 20 . 0
let oilOk = true
let batteryReserve = 0.0
 
func checkEngine ( ) throws {
     guard fuelReserve > 0.0 else {
         throw CarEngineErrors . NoFuel
     }
    
     guard oilOk else {
         throw CarEngineErrors . OilLeak
     }
    
     guard batteryReserve > 0.0 else {
         throw CarEngineErrors . LowBattery
     }
}

The guard keyword may be new to you. It is first introduced in Swift 2 to improve control flow. When the control reaches the guard statement, it first checks the condition. If the condition evaluates to false, the else part will be executed. In the above code, the function will throw an error if a certain condition is not met.

To call the throwing function, you put the try keyword in front of the call. Here is an example:

1
2
3
func startEngine ( ) {
     try checkEngine ( )
}

If you write the above code in Playgrounds, you will end up with an error as we haven’t handled the errors. The error handling model in Swift requires you to use a do-catch statement to catch all errors and handle them.

Here is a sample function that specifies what to do when an error is caught:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func startEngine ( ) {
     do {
         try checkEngine ( )
         print ( "Engine started" , appendNewline : true )
     } catch CarEngineErrors . NoFuel {
         print ( "No Fuel!" )
     } catch CarEngineErrors . OilLeak {
         print ( "Oil Leak!" )
     } catch CarEngineErrors . LowBattery {
         print ( "Low Battery!" )
     } catch {
         // Default
         print ( "Unknown reason!" )
     }
}

Each catch clause matches a particular error and you specify what to do in the body. In the above example, the batteryReserve variable is set to zero. In this case, the .LowBattery error is thrown when you call startEngine().

Try to set the value of batteryReserve to 1.0. In this case, no error is thrown and ‘Engine started’ is printed.

Similar to the switch statement, the error handling model in Swift 2 is exhaustive. You have to handle all the possible errors. This is why we need to include a catch clause without specifying a pattern.

If you want to learn more about error handling in Swift, I recommend you to go over the Apple Documentation.

No More println()

Something I noticed when writing this tutorial is the absence of the println() function. In Swift 2, we can only use print() to write something to the output. Apple has combined both println() and print() functions into one. If you want to output something with a newline, you can set the appendNewline parameter to true. Here is an example:

1
print ( "Engine started" , appendNewline : true )

Protocol Extensions

In the first release of Swift, you can use extensions to add new functionalities to an existing class, structure or enumeration. Swift 2 allows developers to apply extensions to protocol types. With Protocol Extensions, you can add functions or properties to all classes that conform to a certain protocol. The is useful when you want to extend the protocol’s functionality.

As an example, let’s create a new protocol called Awesome. The protocol can be implemented by any type that provides a way to return the awesomeness index of a particular object in percentage.

1
2
3
protocol Awesome {
     func awesomenessPercentage ( ) -> Float
}

Now we declare two classes that adopt our new protocol. Each class implements the required method of the Awesome protocol:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Dog : Awesome {
     var age : Int !
     func awesomenessPercentage ( ) -> Float {
         return 0.85
     }
}
 
class Cat : Awesome {
     var age : Int !
     func awesomenessPercentage ( ) -> Float {
         return 0.45
     }
}
 
let dog = Dog ( )
dog . awesomenessPercentage ( )
 
let cat = Cat ( )
cat . awesomenessPercentage ( )

If you instantiate the classes and call the awesomenessPercentage() method in Playground, you will see an output like this:

swift 2 protocol

Let’s say you want to extend the Awesome protocol to provide an awesomenessIndex property, which uses the result of the awesomenessPercentage() method to calculate the awesomeness index. You can write the code like this:

1
2
3
4
5
6
7
extension Awesome {
     var awesomenessIndex : Int {
         get {
             return Int ( awesomenessPercentage ( ) * 100 )
         }
     }
}

By creating an extension on the protocol, all classes that adopt the Awesome protocol automatically gain access to the awesomenessIndex property.

swift2-protocol-extension

This is really awesome, right?

Availability Checking

Every developer knows the struggle when building an app that supports multiple iOS versions. You always want to use the latest version of APIs, but sometimes this may cause errors when the app is run on older versions of iOS. Prior to Swift 2, there is no standard way to do availability check. As an example, the NSURLQueryItem class was only available since the release of iOS 8. If you use the class on older versions of iOS, you’ll end up with an error and probably causes an app crash. To prevent the error, you may perform the availability checking like this:

1
2
3
4
5
if NSClassFromString ( "NSURLQueryItem" ) != nil {
     // iOS 8 or up
} else {
     // Earlier iOS versions
}

This is one way to check if the class exists. Starting with Swift 2, it finally comes with built-in support for checking API availability. You can easily define an availability condition so that the block of code will only be executed on certain iOS versions. Here is an example:

1
2
3
4
5
6
7
8
if # available ( iOS 8 , * ) {
     // iOS 8 or up
     let queryItem = NSURLQueryItem ( )
    
} else {
     // Earlier iOS versions
    
}

do-while is now repeat-while

The classic do-while loop is now renamed to repeat-while. Here is an example:

1
2
3
4
5
var i = 0
repeat {
     i ++
     print ( i )
} while i < 10

Summary

I hope you enjoy reading this quick overview of Swift 2. There are so much (say, Markdown comment) I haven’t explored. You can further refer to this WWDC video to learn more about Swift 2. At the time of this writing, some companies are still using Objective-C as the primary programming language for iOS. Probably you’re still programming in Objective-C too. I firmly believe that Swift is the way to go. In fact, all major sessions at WWDC 2015 are in Swift. So if you haven’t started to learn Swift, now is the time to take action.

For reference, you can download the Playground file of this tutorial here. Make sure you use Xcode 7 to run the code as this is the only Xcode version that supports Swift 2.0. Xcode 7 is currently in beta. You can download it from Apple.

Source : appcoda[dot]com
post from sitemap