Flying Butterfly – Swift Tutorial Series – User Touch Handling & Conclusion- Part 7 of 7 (event-handler used : touchesEnded(_:withEvent:))

Here’s  the completed project in action – Your butterfly in all its glory!

Important Note: This the last post in the Flying Butterfly Series. on using Swift language to develop apps. If you’ve just begun with the series, I recommend that you start with its first post “Flying Butterfly – Part 1 of 7 – Swift Tutorial Series on Layers, Transforms, Animation, Delegates and Event Handling” here.

So far we have been successful in creating a butterfly which flies from its starting position to its destination.  Upon reaching its final position it sits there with its wings fluttering. There is a label “Touch Me” that becomes visible and urges the user to tap the butterfly. In order to make the whole app interactive let us now incorporate touch handling. When the butterfly is tapped by the user, it starts its journey again from its starting position. For this we use touchesEnded(_:withEvent:) method to handle the user’s touch. The method is defined in the view controller as shown below:

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        //Check if butterfly is touched by the user
        if(containerLyr.animationKeys() != nil){
            println("Touched in motion")
            return
        }
        //Butterfly is not in motion and has reached its destination, check if user has touched the butterfly
        var touch:UITouch = touches.anyObject() as UITouch
        var touchPt:CGPoint = touch.locationInView(self.view)
        if( CGRectContainsPoint(containerLyr.frame, touchPt)){
            //User tapped on the buttefly so start its animation again
            println("Making the butterfly fly again from start")
            
            startButterflyAnimation_Realistic()
            
            //Hide the prompt as the butterfly has started moving again
            lblTouchMe.hidden = true
        }
    }

The first thing that we do in the method is to check whether our butterfly is in flight or not. For this we check if there is any animation attached to the container of the butterfly. If yes, then the method just returns and we not do anything further. Remember when we made the butterfly fly from its start position to the end position we attached a keyframe animation to the containerLyr (Please refer to the previous post).  If it is flying then we do not do anything as we would like the butterfly to complete its journey and only when it is sitting on the flowers we would like to respond to the user’s touch.

Once we are sure that the butterfly in not in motion (it is sitting) we process the user touch. We check if touch has really happened on the butterfly. If yes then we call the startButterflyAnimation_Realistic() method, which starts the flight animation of the butterfly afresh. When the butterfly starts to fly again, it is also the time to hide the “Touch Me” label. Now our butterfly not only flies in its full glory but also responds to the user’s touch.

Conclusion:

This brings us to the end of the 7-Part Flying Butterfly Series. This series of Swift Tutorials has helped us achieve the following:

1. Enabled us to use Swift as the programming language to create an interactive iOS application.
2. Demonstrated how to use the different classes/delegate methods/constructs available in the Swift programming language.
3. Helped us understand how to create and when to apply the two different kinds of animations: CABasicAnimation and CAKeyframeAnimation
4. Made us appreciate the power of transforms.
5. Helped us determine how to use paths to our convenience, whether for drawing shapes or for using paths to fine tune our animations.
6. Enabled us to understand how to fine-tune our code to make our demos look more realistic. In this series, we saw how we made the fluttering of the wings of the butterfly and its flight animation more realistic.
7. Demonstrated when and how we must use the animation delegate method to our convenience. We learned how to handle the ending of the different animations that we have to incorporate in our apps from time to time.
8. Learned how user involvement can be brought in by using interactivity in our apps through touch event-handling.

All work and no play makes Jack and Jill dull kids! So take a break and if you love playing games do visit and try my games & apps at: https://itunes.apple.com/us/artist/grouchy-gremlins/id567639930

Goodbye and happy experimenting!

You can download the complete project as a zip file here .

— §§§ —

 

iOS trainings for corporates & companies india | iOS games and applications development Delhi NCR Noida Gurgaon India | mobile apps development india | iPhone iPad games & apps development in Delhi NCR Noida Gurgaon | Xcode iOS trainings and courses in swift for corporates & companies | ios application development in swift objective C India | iPhone iPad based game development in Gurgaon Noida Delhi NCR India | iPhone & iPad Application development in India | iOS trainings courses workshops in swift programming in India at Delhi NCR Noida Gurgaon | Apple development training courses Delhi NCR Gurgaon Noida | iPhone app and game development courses workshops in swift | iPhone & iPad games for eLearning | iOS apps and games development courses & trainings in Delhi NCR Noida Gurgaon India | games and apps developer & producer india | iOS app development trainings in Noida Gurgaon Delhi NCR | iPhone development trainings & classes in swift & objective C | Indian iOS Games and apps developers

 

Advertisements

Flying Butterfly – Swift Tutorial Series – Making Butterfly Flight Realistic – Part 6 of 7 (classes/methods used : CAKeyFrameAnimation, animationDidStop(_:finished:))

Important Note: This post is 6th in the series of posts on using Swift language to develop apps. If you’ve just begun with the series, I recommend that you start with its first post “Flying Butterfly – Part 1 of 7 – Swift Tutorial Series on Layers, Transforms, Animation, Delegates and Event Handling” here.

In my last post we made our butterfly fly from the bottom left corner of the screen to the top right corner but the movement didn’t appear to be realistic. Butterflies do not move in straight lines. Instead they flit about. In order to move our butterfly on a non-linear (curvilinear) path, our CABasicAnimation class would not help us much. We will have to take the help of CAKeyframeAnimation class which has a path property. This property allows us to define a path, so for our butterfly we can create a curvilinear path using UIBezierPath class methods (or CGPath methods). Once the path property of CAKeyframeAnimation is set, the object on which the animation is applied, animates along the set path.

Flying Butterfly Tutorial Series -Part 6 - Realistic Animation of Flight - CAKeyframeAnimation and delegate example

In order to make the flight of our butterfly realistic, let us replace the function call to method startButterflyAnimation() with startButterflyAnimation_Realistic() in the createButterflyAssemblyAndAnimate() method of the view controller. The startButterflyAnimation_Realistic() is defined in the view controller file as below.

func startButterflyAnimation_Realistic(){
        lblTouchMe.hidden = true//hide the touch me label when the animation begin
        
        var duration:CGFloat = 6.0//it takes 6 sec for the butterfly to fly from bottom left to top right
        
        var bPath:UIBezierPath = UIBezierPath()
        bPath.moveToPoint(startPosition)
        
        //We would like the butterfly to move in a curve instead of a straight line (take two arbitrary control points)
        bPath.addCurveToPoint(endPosition, controlPoint1: CGPointMake(200, 10), controlPoint2: CGPointMake(450, 550))
        
        var kfAni:CAKeyframeAnimation = CAKeyframeAnimation(keyPath:"position")
        kfAni.path = bPath.CGPath
        kfAni.duration = Double(duration)
        kfAni.autoreverses = false
        kfAni.fillMode = kCAFillModeForwards
        
        kfAni.repeatCount = 1
        kfAni.removedOnCompletion = true
        kfAni.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        kfAni.delegate = self
        
        //set the value of key "key_containerLyr" as containerLyr object as we will be using it in the animation handling (in animation delegate method)
        kfAni.setValue(containerLyr, forKey: "key_containerLyr")
        containerLyr.addAnimation(kfAni, forKey: "container_Ani")
}

In this method we create an instance of UIBezierPath and use its methods to draw a curve. We use the method addCurveToPoint(_:controlPoint1:controlPoint2:) to draw a curve which defines the flight of the butterfly. The first parameter of the function is supplied with the value of the variable endPostion (which specifies the final destination of the butterfly). We take two arbitrary control points as we want the path to be a curve. You can experiment with different values of controlPoint1 and controlPoint2 to arrive at differently curved paths. While you are experimenting you would be amazed to find that some paths (based on the control points values) will even go beyond the end point and finally loop back to reach end point. This also sometimes happen with butterflies (Every once in a while, a butterfly goes a little beyond its destination and then swirls back to reach its final position). I recommend you play with different values of the two control points to see your butterfly move differently. It’s quite a visual treat.

Another thing to note in the above method is that we have assigned “self” to the delegate property of the animation. We’ve also added a key “key_containerLyr” to the animation which has containerLyr as its value. When the flight animation ends we also set the butterfly to its final position and transform. These two aspects are taken care of by the animation delegate which gets modified as below.


override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
        var cLyr = anim.valueForKey("key_containerLyr") as? CALayer;//returns an optional - a nil(no value or when cast fails) or CALayer
        if(cLyr != nil){
            if(cLyr === containerLyr){
                //Butterfly has reached the final position
                CATransaction.begin()
                CATransaction.setDisableActions(true)
                containerLyr.position = endPosition//final postioin
                containerLyr.transform = CATransform3DMakeRotation(CGFloat(M_PI/6), 0.0, 0.0, 1.0)
                CATransaction.commit()
                //Show prompt as butterfly is not in animation
                lblTouchMe.hidden = false
            }
        }
        else{
            //Set random duration and spread for the butterfly wings and start the fluttering action again
            var duration:CGFloat = 0.70/2 + 0.10 * CGFloat(arc4random_uniform(9))
            var spread:CGFloat = 0.40 + 0.04 * CGFloat(arc4random_uniform(11))
            startRightWingAnimationWithDuration(duration, withSpread: spread)
            startLeftWingAnimationWithDuration(duration, withSpread: spread)
        }
}

The if block of the animation delegate (ab0ve,) is responsible for what happens when the butterfly (the containerLyr) finishes its flying animation. (The else block is responsible for handling the fluttering animation of the wings which was covered in Part 4). The first thing which we do in this method is get the value of the key “key_containerLyr” set for the animation earlier in startButterflyAnimation_Realistic() method. We cast the value returned to a CALayer instance using the as? operator which returns an optional CALayer instance.(If you are wondering what as? is, and how to use it please refer to my post on optionals here.)

In the next line we check whether the instance returned is not nil. If it is not nil then we use identity operator (===) to check if the CALayer instance is indeed containerLyr. Once we are sure of this we proceed to set the final position of the butterfly to its end position and transform. This is also the time to display the “Touch Me” label which prompts the user to tap the butterfly. (I’ll discuss Touch Handling in my Part 7 of this series – the next post)

Now if we run the project, we see that our butterfly flies in a realistic manner. It starts from the lower left corner of the screen, flits around with its wings fluttering, and finally perches on the flowers at the top right corner of the screen. The label prompts the user to tap the butterfly as the butterfly patiently waits for the user to tap her.

In our next post we will use event handling to handle the user touch.

You can download the project as a zip file here (Part 6).

— §§§ —

 

iOS apps and games development courses & trainings in Delhi NCR Noida Gurgaon India | games and apps developer & producer india | iPhone iPad based game development in Gurgaon Noida Delhi NCR India | iPhone development trainings & classes in swift & objective C | iOS app development trainings in Noida Gurgaon Delhi NCR | iPhone & iPad Application development in India | ios application development in swift objective C India | Xcode iOS trainings and courses in swift for corporates & companies | iOS games and applications development Delhi NCR Noida Gurgaon India | iOS trainings courses workshops in swift programming in India at Delhi NCR Noida Gurgaon | iPhone & iPad games for eLearning | iPhone app and game development courses workshops in swift | iOS trainings for corporates & companies india | mobile apps development india | Apple development training courses Delhi NCR Gurgaon Noida | Indian iOS Games and apps developers | iPhone iPad games & apps development in Delhi NCR Noida Gurgaon

 

Flying Butterfly – Swift Tutorial Series -Making Butterfly Fly – Part 5 of 7 (class used: CABasicAnimation)

Important Note: This post is 5th in the series of posts on using Swift language to develop apps. If you’ve just begun with the series, I recommend that you start with its first post “Flying Butterfly – Part 1 of 7 – Swift Tutorial Series on Layers, Transforms, Animation, Delegates and Event Handling” here.

In the previous post our butterfly had just started fluttering its wings but to experience a butterfly in its full glory we must make it fly. In this post, our butterfly will fly from one point to another. Currently the butterfly is positioned at the lower left corner of the screen and to ensure that it covers the maximum distance we will make it fly to the top right corner of the screen. If you recall my 2nd post in the series, we had declared two constants: startPosition (150, 825) – where she currently is, and endPosition (650,150) – where she’s headed.

To make the butterfly move, we add the following lines of code below startLeftWingAnimationWithDuration(_:withSpread:) method of the view controller.

The code makes a call to the method startButteflyAnimation(), which is defined in the view controller file. So let us see what is happening inside the method.

    //---- Start Butterfly flight animation -----
    //This makes the butterfly move from its current position to the top right corner of the screen
    func startButterflyAnimation(){
        containerLyr.transform = CATransform3DIdentity
        containerLyr.position = startPosition
        
        let dx = endPosition.x - startPosition.x
        let dy = endPosition.y - startPosition.y
        
        var fromTrans = CATransform3DConcat(CATransform3DMakeRotation(CGFloat(M_PI/6), 0.0, 0.0, 1.0),
            CATransform3DTranslate(containerLyr.transform, 0, 0, 0))
        
        var toTrans = CATransform3DConcat(CATransform3DMakeRotation(CGFloat(M_PI/6), 0.0, 0.0, 1.0),
            CATransform3DTranslate(containerLyr.transform, dx, dy, 0))
        
        
        var duration:CGFloat = 3.0 + 0.5 * CGFloat(arc4random_uniform(7))
        
        var ani = CABasicAnimation(keyPath: "transform");
        ani.fromValue = NSValue(CATransform3D: fromTrans);
        ani.toValue = NSValue(CATransform3D:toTrans);
        ani.duration = Double(duration);
        ani.autoreverses = false
        ani.fillMode = kCAFillModeForwards;
        
        ani.repeatCount = 1
        ani.removedOnCompletion = false;
        containerLyr.addAnimation(ani, forKey: "container_Ani");
    }

In this method we compute the two transforms (fromTrans and toTrans). These transforms define the start and end orientations of the butterfly. Since the butterfly moves from startPosition to endPosition, we calculate the difference in the x coordinates and the y coordinates of the two points and store the differences in their values in constants dx and dy. These values are used in the CATransform3DTranslate method used for moving the butterfly while calculating the value of toTrans.

Once both the transforms are computed, rest of the method defines an instance of CABasicAnimation and sets it properties. The fromValue and toValue properties are assigned the objects that are created from the above transforms using NSValue class. The repeatCount property of the animation is set to 1. This implies that the flight animation will run only once. This is because we would like our butterfly to start and end its flight at the top right corner. The top right portion of the background graphic shows some flowers. The animation is applied to the containerLyr, which contains the whole butterfly – its body and its two wings. So the journey of our butterfly ends when it goes to the top-right corner and sits on a flower. It also continues to flutter its wings while sitting. Later we will see that it waits there for user input and the prompt “Touch Me” becomes visible. (We will cover this in a later post)

Now our butterfly doesn’t just flutter its wings but also flies from one place to another. If we closely analyze  the flight of the butterfly it still looks slightly un-natural. The flight looks more like an airplane’s than a butterfly’s, as it flies from source to its destination in a straight line the way an air plane does. We all know that butterflies do not fly in straight lines. Their motion has an artistic feel brought about by wavy movements. This is why our current animation does not look realistic. I have a feeling that our butterfly might not be too happy with the way we’ve made it fly!

In my next post, I will cover how to make the flight of our butterfly look more realistic. That, I guess, will make everyone including the butterfly, a lot happier.

You can download the project as a zip file here (Part 5).

— §§§ —

 

iPhone iPad based game development in Gurgaon Noida Delhi NCR India | mobile apps development india | Apple development training courses Delhi NCR Gurgaon Noida | iOS app development trainings in Noida Gurgaon Delhi NCR | iPhone development trainings & classes in swift & objective C | ios application development in swift objective C India | Xcode iOS trainings and courses in swift for corporates & companies | Indian iOS Games and apps developers | iPhone app and game development courses workshops in swift | iOS trainings for corporates & companies india | iOS trainings courses workshops in swift programming in India at Delhi NCR Noida Gurgaon | iPhone iPad games & apps development in Delhi NCR Noida Gurgaon | iOS games and applications development Delhi NCR Noida Gurgaon India | iPhone & iPad Application development in India | games and apps developer & producer india | iPhone & iPad games for eLearning | iOS apps and games development courses & trainings in Delhi NCR Noida Gurgaon India

 

Flying Butterfly – Swift Tutorial Series -Realistic Fluttering of Wings – Part 4 of 7 (animation delegate method used: animationDidStop(_:finished:))

Important Note: This post is 4th in the series of posts on using Swift language to develop apps. If you’ve just begun with the series, I recommend that you start with its first post “Flying Butterfly – Part 1 of 7 – Swift Tutorial Series on Layers, Transforms, Animation, Delegates and Event Handling” here.

In the previous post we had brought the butterfly to life by animating its wings. However the fluttering of the wings looked very mechanical. In real world when a butterfly flutters its wings, the motion varies from time to time. Sometimes the fluttering of its wings becomes faster and when the butterfly wants to take a little rest or tires out it starts fluttering its wings slowly. Sometimes a butterfly spreads its wings more than usual and at times it spreads them less. In order to capture this kind of animation behavior we make use of the animation delegate method animationDidStop(_:finished:). When we created the right wing of the butterfly (refer to my previous post) we assigned “self” as the animation delegate for the animation. Now let us understand what must be done in animation delegate method.

We use animation delegate for two purposes. First, to bring about a realistic variation in the animation of the wings of the butterfly, and second, we use it for controlling the flight animation of the butterfly. I will cover the second part in a later post. Right now our focus is to bring about realism in the fluttering action of the butterfly. If you recall the function definition of the method startRightWingAnimationWithDuration(_:withSpread:) used for creating animation in the right wing, it has two parameters: duration and spread.(Refer to my previous post)

As per the animation configured in the methods, each animation lasts for 2 cycles and then it stops. The stopping of the animation of the right wing is captured by the animation delegate method and we use the same method to start the fluttering animation for both the wings again. However before we call the animation methods for each wing we randomly choose the duration and spread for the next cycle of animation for both the wings. This makes the fluttering action look more natural.

Let us look at the animation delegate method

override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
//Set random duration and spread for the butterfly wings and start the fluttering action again
var duration:CGFloat = 0.70/2 + 0.10 * CGFloat(arc4random_uniform(9));
var spread:CGFloat = 0.40 + 0.04 * CGFloat(arc4random_uniform(11));
startRightWingAnimationWithDuration(duration, withSpread: spread)
startLeftWingAnimationWithDuration(duration, withSpread: spread)
}

The animation delegate method captures what happens when the right wing animation stops. If we look at the first two lines of the implementation of the method, it defines two variables: duration & spread. The values of these variables are computed using arc4random_uniform(n) function. This gives random values for both the variables. Consequently we use these values in the two animation methods which are called to start the animation of the wings. So every time the two-cycle-animation for the wings end, a new animation cycle starts with new duration and spread values. This gives the random fluttering animation behavior to the wingsFlying Butterfly - Swift Tutorials Series Part 4 of 7. Realistic Animation of Wings Layers - Example Animation Delegate in iOS - ScreenshotAbove: Screenshot of the video – Download Video (1.5 MB)

So now the butterfly is not only continuously fluttering its wings but the fluttering action also changes pace (increases or decreases) from time to time. This is how butterflies actually flutter their wings in real world. Now all that remains to be done is to make our butterfly fly across the garden. I will cover this in my next post.

You can download the project as a zip file here (Part 4).

— §§§ —

 

iPhone app and game development courses workshops in swift | iOS apps and games development courses & trainings in Delhi NCR Noida Gurgaon India | games and apps developer & producer india | outsourcing ios games and apps development india | iPhone development trainings & classes in swift & objective C | iPhone iPad games & apps development in Delhi NCR Noida Gurgaon | ios application development in swift objective C India | Indian iOS Games and apps developers | iOS app development trainings in Noida Gurgaon Delhi NCR | iPhone & iPad games for eLearning | iPhone iPad based game development in Gurgaon Noida Delhi NCR India | outsourcing iphone ipad app development costs | Xcode iOS trainings and courses in swift for corporates & companies | iPhone & iPad Application development in India | iOS trainings for corporates & companies india | Apple development training courses Delhi NCR Gurgaon Noida | mobile apps development india | iOS games and applications development Delhi NCR Noida Gurgaon India | iOS trainings courses workshops in swift programming in India at Delhi NCR Noida Gurgaon

 

Flying Butterfly – Swift Tutorial Series -Animating the Wings – Part 3 of 7 (classes used: CATransform3D, CABasicAnimation)

Important Note: This post is 3rd in the series of posts on using Swift language to develop apps. If you’ve just begun with the series, I recommend that you start with the first post in the series “Flying Butterfly – Part 1 of 7 – Swift Tutorial Series on Layers, Transforms, Animation, Delegates and Event Handling” here.

In this post we will start with the butterfly that we created in the previous post (part 2 of 7) and bring it to life by making its wings flutter. We’ve all seen and admired the beauty of a butterfly fluttering its wings.

Screenshot-Flying Butterfly Tutorial Series Part 3 of 7 of Swift Programming Series Classes Used:CATransform3D,CABasicAnimation. An example iOS (iPhone/iPad) project

Let us first analyze the fluttering-behavior. There are two important points to note. First, when a butterfly opens and closes it wings while sitting, it performs the action in a certain time-duration. Second, the fluttering action involves spreading and then closing of the wings. In order to capture these two important aspects of a butterfly’s fluttering action we create a function with two parameters.

1. duration: The time it takes for the butterfly to open its wings wide apart from completely closed position (when both the wings are vertical to the body and together). It is measured in seconds and the datatype for this parameter is CGFloat.
2. spread: The span of the wings as they are drawn apart when the butterfly opens its wings. It is also defined as a CGFloat and its values vary from 0.0 to 1.0 (when the two wings are spread fully apart.)

In order to make the wings flutter we add the following code immediately below the section “Creating the Wings of the Butterfly”


//---- Start right wing flutter animation -----
startRightWingAnimationWithDuration(0.50, withSpread: 0.70)

//---- Start left wing flutter animation -----
startLeftWingAnimationWithDuration(0.50, withSpread: 0.70)

As you can see these are function calls to methods startRightWingAnimationWithDuration(_:withSpread:) and startLeftWingAnimationWithDuration(_:withSpread:) with same parameter values (duration = 0.5 seconds and spread = 0.70). It is important that the parameters supplied to both the wings should be the same. This is important as the movement of one wing mirrors the other. Now let us look at both the function definitions.

//Make butterfly's wing flutter
//Param: [duration] : duration of the animation
//Param: [spread] : how much the wing will turn (values: 0 (none) to 1.0 (max))
func startRightWingAnimationWithDuration(duration:CGFloat, withSpread spread:CGFloat){
var fromTrans = CATransform3DMakeRotation(CGFloat((-M_PI/2)*0.9), 0.0, 1.0, 0.0) //start at slightly less than 90 degrees (10% less)
var toTrans = CATransform3DMakeRotation(CGFloat(-M_PI/2) * CGFloat(1.0 - CGFloat(spread)), 0.0, 1.0, 0.0);//end transform depends on the spread

//Build the animation object
var ani = CABasicAnimation(keyPath: "transform");
ani.fromValue = NSValue(CATransform3D: fromTrans);
ani.toValue = NSValue(CATransform3D:toTrans);
ani.duration = Double(duration);
ani.fillMode = kCAFillModeForwards;
ani.autoreverses = true;

ani.repeatCount = 2
ani.removedOnCompletion = false;
ani.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut);
ani.delegate = self; // assgin delegate as self. We wish to handle this in the animation delegate
wingRightLyr.addAnimation(ani, forKey: "wing_R_Ani");
}

Here we use transforms to rotate the wing on its y axis. The rotation values range from slightly less than -90 degrees (actually 10% less than -90 degrees) to an angle computed by the value of the spread specified in the parameter at the time of calling. The later part of the method creates an instance of CABasicAnimation using the transform keyPath. Other properties of the animation are defined so that the wing flutters continuously. However, we limit the repeatCount to 2. We also assign animation delegate to this animation (self is assigned to the delegate property of the animation). This implies that we will have to define animationDidStop(_:finished:) delegate method in the view controller file. This will be covered in my next post.

Now let’s look at the method used to make the left wing flutter, and how it is different from the method used for making the right wing flutter.

func startLeftWingAnimationWithDuration(duration:CGFloat, withSpread spread:CGFloat){
//we use scale transform to flip the wing in x direcation as both wings are mirror images of eachother
var fromTrans = CATransform3DMakeRotation(CGFloat((-M_PI/2)*0.9), 0.0, 1.0, 0.0)
fromTrans = CATransform3DConcat(fromTrans, CATransform3DMakeScale(-1, 1, 1));

var toTrans = CATransform3DMakeRotation(CGFloat(-M_PI/2) * CGFloat(1.0 - CGFloat(spread)), 0.0, 1.0, 0.0);
toTrans = CATransform3DConcat(toTrans, CATransform3DMakeScale(-1, 1, 1));

var ani = CABasicAnimation(keyPath: "transform");
ani.fromValue = NSValue(CATransform3D: fromTrans);
ani.toValue = NSValue(CATransform3D:toTrans);
ani.duration = Double(duration);
ani.autoreverses = true;
ani.fillMode = kCAFillModeForwards;

ani.repeatCount = 2
ani.removedOnCompletion = false;
ani.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut);
//no need to set delegate as the right wing delegate handles both the wings (wings always flutter together)
wingLeftLyr.addAnimation(ani, forKey: "wing_L_Ani");
}

Looking at both the methods carefully we see that they are almost identical except for two things. The transforms used in the left wing have additional scaling involved and the method does not assign any delegate to the animation. If we look at the previous post (part 2 of this swift tutorial series), we concluded it by creating left wing on top of the right wing. Since both the wings point in opposite direction when in open position and are mirror images of each other we need to scale the left wing in x direction by a factor of -1 (flip it left). Since left wing has anchor point at (0.0, 0.5), after the scale transform, both the wings are now exactly the way two wings of butterfly should be positioned on its body. In this method we do not assign any delegate as we know that both the wings move together and the delegate of the animation assigned in right wing method will help animate both the wings.

Now our butterfly has come alive with the fluttering of the wings. At this point in our project, both the wings flutter for 2 complete cycles and then they stop. This, of course, is something that we don’t want. Instead we would like the butterfly to flutter its wings continuously. If that was all that we wanted, we could have assigned Float.infinity to the repeatCount property of the animations and our job would have been done. But in order to make flutter of the wings look realistic we need to do a little bit more. This is why we assigned animation delegate to the animation in the right wing animation method. The action that happens after the animation stops is taken care of by the delegate method, which I will cover in my next post. The delegate method will help us make the fluttering of the wings look realistic.

You can download the project as a zip file here (Part 3).

 

— §§§ —

 

iPhone app and game development courses workshops in swift | iOS apps and games development courses & trainings in Delhi NCR Noida Gurgaon India | games and apps developer & producer india | iPhone development trainings & classes in swift & objective C | iPhone iPad games & apps development in Delhi NCR Noida Gurgaon | ios application development in swift objective C India | Indian iOS Games and apps developers | iOS app development trainings in Noida Gurgaon Delhi NCR | iPhone & iPad games for eLearning | iPhone iPad based game development in Gurgaon Noida Delhi NCR India | Xcode iOS trainings and courses in swift for corporates & companies | iPhone & iPad Application development in India | iOS trainings for corporates & companies india | Apple development training courses Delhi NCR Gurgaon Noida | mobile apps development india | iOS games and applications development Delhi NCR Noida Gurgaon India | iOS trainings courses workshops in swift programming in India at Delhi NCR Noida Gurgaon

 

The Grey Market for iPhone 6s / iPhone 6s Plus, Smartphone Market and iPhone’s Market Share in India

iPhone 6s & iPhone 6s Plus expected to be available in Indian grey markets within 2 days of its launch in the US

The desire to show off their newest Apple-acquisition is paramount in the affluent, tech-savvy Indian. The grey market is already deluged with orders for the new iPhone 6s and iPhone 6s Plus. Everyone seems to be hankering for the new rose gold model, which is most in demand. Perhaps, the new rose-gold color would help them show it off to their friends, telling them that they have the newest iPhone without actually spelling it out.

According to the Economic Times, the financial Indian Daily both iPhone 6s and iPhone 6s Plus are expected to go on sale in India by October 11-15. The daily said that the grey market is so active that one would be able to get a new iPhone 6s within 2 days of the launch in the US. It is reported that those who wish to admire their prized possession well ahead of its India-launch will have to cough up nothing less than $1300 (INR 1 lakh or Indian Rupees 1,00,000) but then going by the grey market order-book it is a small price to pay. This seems to be quite an irony especially when the per capita income of India is barely $118.68/year (Rs 7,378.17/year) but then income-disparities in India aren’t the topic of this post.

Smart Phones Market in India

In terms of sales volumes, Samsung is the market leader with around 25% market share with Micromax trailing behind with 15%. The third largest player is Intex with 10% market share. Considering that the Apple iPhones are not available below $500 price point, in terms of volume they have a miniscule 2% of the market share.

In terms of value, the premium smartphone segment ( Rs 30000+) has always seen Apple as the dominant player so far. However, for the first time, in Jan-April quarter of 2015, Samsung has taken over Apple. Now Samsung’s market share, by value, stands at 46% as compared to Apple’s 42%. Samsung has been able to achieve this due to increase in sales of its Galaxy S6 and Galaxy S6 Edge models. They have also leveraged their distribution network which is much stronger than Apple’s. Now online sales have also become an important channel for distribution.

For the financial year ending September 30, 2014, Apple was able to sell 1 million iPhones in India. Interestingly, 75% of the sales came from the latest iPhone models: iPhone 6 and iPhone 6 Plus. As of April 30, 2015 Apple has already crossed 1 million units and is expected to touch 2 million by the end of September 2015. This will be 100% increase in its sales. This is a tremendous growth but then Apple also has a small base of 1 million as compared to more than 100 million smartphones which are expected to be sold in India in 2015.

According to IDC in the second quarter of 2015, 26.5 million units of smartphones were shipped to India as compared to 18.4 million last year. This translates to phenomenal 44% growth. As compared to this the whole mobile phone industry saw only 59.4 million units shipped vis-a-vis  63.2 million units shipped in the same quarter last year. This is actually a 6% contraction. This clearly shows that Indians are moving towards smartphones from low-end mobile phones. Also, there is a world-wide trend of falling smartphones prices. As compared to last year the average selling price of a smartphone has decreased by 12%.

Still, as compared to overall world sales of iPhone units, India’s contribution is minuscule but it is one of the larges growing segments. Apple seems to have recognized this growth potential and this year we can expect it to be more aggressive in implementing its marketing and distribution.

iPhone 6s / iPhone 6s Plus, iPad Pro (with Smart Keyboard), Apple Pencil, new Apple TV launched by Tim Cook

The September announcement from Apple was a much awaited event both by the developers and the users. Speculations that were rife about iPhone 6s and iPad were put to rest by Apple CEO Tim Cook when he addressed the gathering at the Bill Graham Civic Auditorium on September 9, 2015. He introduced a new iPad from Apple called iPad Pro. He also released the latest iPhones, iPhone 6s and iPhone 6s Plus, saying “no product is more about innovation than the iPhone.”

Here are the salient features and specifications of the products that Apple launched in September 2015:

iPhone 6s & iPhone 6s Plus

  • New Models: iPhone 6s and iPhone 6s Plus
  • 3D Touch Technology: Now the surface of the new iPhones are pressure sensitive and it can detect between a light press and a firmer press using the 3D Touch. (For developers: these new gestures are called Peek and Pop respectively). A light press can give the user some cursory information and if she desires the details, a firmer press will do the job.
  • Camera: The main camera is now 12 MegaPixels (enhanced from previous 8 MP,) and the front-facing FaceTime HD camera now has 5 MegaPixels.
  • Live Photos: Live Photos is a technology that helps capture photos which could be shown with a slight animation. According to Phil Schiller, Sr. VP Apple, says “users just take photos like normal, but a new icon will capture 1.5 seconds before and after pictures.”
  • Colors: A new color rose-gold was launched. Now iPhone will be available in silver, gold, rose gold and space grey.
  • New iPhone Upgrade Program: This let users get a new iPhone every single year for $32 a month.
  • Pricing: The price for iPhone 6s is  $199  while iPhone 6s Plus will cost $299.
  • Pre-Ordering/Sale: Pre-ordering begins on September 12 and sales in the US start on Sep 25.

iPad Pro

  • Model Name: iPad Pro
  • Screen Size: 12.9 inches diagonally
  • Display: 5.6 million pixels more than in the 15” retina display Macbook Pro
  • Thickness: (6.9 mm vs 6.1 mm (when compared with the regular 9.7 inch iPad.)
  • Weight: 1.57 lb vs 1.54 lb (when compared with the iPad 1.)
  • Resolution: 2732 x 2048
  • Enhanced Battery Life: 10 Hrs
  • New Processor: A faster A9 64 bit chip
  • Price: 32 GB will cost $799

Apple Pencil:

Apple also introduced Apple Pencil, a stylus which will work with iOS and will be available for $99. Apple Pencil could be extremely helpful to artists and illustrators for drawing, as it will enable them to use different pressure levels for freehand drawing.

Smart Keyboard:

Apple also introduced a new Smart Keyboard for typing on the iPad. This is very similar to the Microsoft Surface. The keyboard will be available for $169 and it will be 3.2 mm thick. Here is link that compares Microsoft Surface with  iPad Pro with Smart Keyboard.

iPad Pro, Apple Pencil and Smart Keyboard will go on sale in November 2015.

Partnership with Microsoft:

Apple pencil will work seamlessly with MS Office applications like MSWord and MSPowerpoint.

New Apple TV

According to Tim Cook “The future of TV is apps”.  Some interesting features of the new Apple TV are:

  • Faster chip for processing
  • Bluetooth 4.0 remote
  • Volume and TV power controls
  • Full charge can last for upto three months (with Lightning connector for recharging).
  • Siri can be used for searching and playing films and TV Programs
  • Apple Music will be integrated into the tvOS
  • Games will be available for Apple TV
  • Redesigned remote can used for advanced gaming features
  • Developers can develop apps for tvOS, which is based on iOS
  • Netflix, HBO and Hulu Apps will be available as well
  • Price: 32 GB will cost $149 and 64GB model will cost $199

 

Other things that were part of the announcement were the launch of the new iPad Mini 4 and the news of Apple’s collaboration with French high-fashion & clothing manufacturer Hermes. Collaboration with Hermes brought more excitement to the Apple Watch, as both Apple and Hermes will work together to create new Bands & watch-faces that are more colorful and stylish.

iOS 9 will be the new operating system available in the new devices. The old devices will be able to upgrade to iOS 9 September 16 onwards.


The launch of Apple Pencil reminds me of a line which Apple’s founder Steve Jobs said while announcing iPhone to the world in 2007, he said:

“Nobody wants a stylus.”

It will be interesting to watch how Tim Cook’s decision to include a stylus and collaborate with Microsoft plays out.

Flying Butterfly – Part 2 of 7 – Swift Tutorial Series -Creating the Butterfly ( classes used: CALayer, CAShapeLayer, UIBezierPath )

Important Note: This post is 2nd in the series of posts on using Swift language to develop apps. If you’ve just begun with the series, I recommend that you start with its first post “Flying Butterfly – Part 1 of 7 – Swift Tutorial Series on Layers, Transforms, Animation, Delegates and Event Handling“.

In this post we will create the Butterfly. Our butterfly will consist of three parts – two wings which are mirror images of each other and a body in center from where the wings originate. All the three body-parts will be encased in a container, and together they’ll constitute the butterfly. We will use CALayer class to create instance of the container and the body. Since the wings will be drawn using UIBezierPath methods we will use instances of CAShapeLayer for the wings. Let us look how our butterfly will look at the end of this post.

Screenshot for Flying Butterfly - Swift Tutorial Series - Part 2 Example Project for iOS (iPhone / iPad)

This is how the object hierarchy for the Butterfly goes:

The Butterfly

Container (CALayer)
->Body (CALayer)
->Right Wing (CAShapeLayer)
->Left Wing (CAShapeLayer)

We need to target the container, the left and right wing in our code later, this is why we declare three variables corresponding to them in the swift file. The beauty of Swift is that it has only one file (as compared to the .m and .h files of Objective C). We will not be targeting the body of the butterfly so we do not associate any variable with it. Additionally we need to program the flight of the butterfly (which we will cover in later posts) from a starting position (lower left of the screen) to the end position (top right of the screen). Therefore we declare two constants to define those points. This is how the properties/outlets declaration section of the file looks.

//MARK:PROPERTIES / OUTLETS
var containerLyr:CALayer! //container layer for butterfly consisting of wings and body
var wingRightLyr:CALayer! //right wind of the butterfly
var wingLeftLyr:CALayer! //left wing of the butterfly

@IBOutlet weak var lblTouchMe:UILabel! //label which prompts the user to touch the butterfly

let startPosition:CGPoint = CGPointMake(150, 825)
let endPosition:CGPoint = CGPointMake(650, 150)

Creating the container

This container will house all the parts of the butterfly – the two wings and the body. When we wish to move the entire butterfly we can easily do it by moving this container. The container is a rectangle with height equal to the wing’s height and its width is twice the wing’s width (as there are two wings). We start inside the viewDidLoad method by declaring a variable which will contain the size of a single wing:
var wingSize:CGSize = CGSize(width: 120, height: 180);

//---- Create Butterfly Container -----
 containerLyr = CALayer();
 containerLyr.bounds = CGRectMake(0, 0, wingSize.width * 2, wingSize.height);
 containerLyr.position = startPosition;
 containerLyr.transform = CATransform3DMakeRotation(CGFloat(M_PI/6), 0.0, 0.0, 1.0);
 self.view.layer .addSublayer(containerLyr);

We first place the butterfly container at the start position. Next, we use a transform to rotate the container by 30 degrees clockwise as we want the butterfly to look towards the top-right.

Creating the Body

Body of the butterfly is a longish rectangle which has its edges curved. The left and the right wing will be placed at the center of the body. In the viewDidLoad method of the view controller add the following lines after “Create Butterfly Container” section.

//---- Create Butterfly body and position it in the container -----
var lyrB = createButterflyBodyWithSize(CGSizeMake(10,120));
lyrB.position = CGPointMake(containerLyr.frame.size.width/2, containerLyr.frame.size.height/2 - 10);
containerLyr.addSublayer(lyrB);

The first line calls the function createButterflyBodyWithSize(_:). This creates a body, the size of which is passed as a parameter. The function returns a CALayer object which is then added as a sublayer of the container layer. It is positioned almost at the center of the container.

func createButterflyBodyWithSize(bodySize:CGSize) ->CALayer{
//Create body of the butterfly (a rectangle) with given size
var bodyLyr = CALayer();
bodyLyr.bounds = CGRectMake(0, 0, bodySize.width, bodySize.height);
bodyLyr.backgroundColor = UIColor(red: 25/255.0, green: 65/255.0, blue: 145/255.0, alpha: 0.9).CGColor;// dark blue color
bodyLyr.cornerRadius = bodySize.width/2; //this will make longish rectangles top and bottom edges curve and it will look like long tube now
return bodyLyr;

}

Creating the Wings of the Butterfly

We create the right and the left wings of the butterfly by adding the following code in the viewDidLoad method of the view controller after “Create Butterfly Body and Position it in the container” section.

//---- Create Butterfly's right wing and position it in the container -----
wingRightLyr = createWingWithSize(wingSize);
wingRightLyr.position = CGPointMake(containerLyr.frame.size.width/2, containerLyr.frame.size.height/2);
containerLyr.addSublayer(wingRightLyr);

//---- Create Butterfly's left wing and position it in the container -----
wingLeftLyr = createWingWithSize(wingSize);
wingLeftLyr.position = CGPointMake(containerLyr.frame.size.width/2, containerLyr.frame.size.height/2);
containerLyr.addSublayer(wingLeftLyr);

Both the sub-sections above make a call to the method createWingWithSize(_:), which is defined in the file. Both the wings are placed at the center of the container and then added as sublayers of the container layer. Let’s quickly understand what is going inside the wing creation function. Each wing is an instance of CAShapeLayer. We selected CAShapeLayer because we wanted to create a wing by drawing (using a UIBezierPath). This path is later converted to CGPath and assigned to the path property of the shape layer. If you look at the path drawing functions we not only create the wing geometry but also create two circles on each wing. The wings are of orange color (fillColor) and the stroke (strokeColor) used is of red color. It’s important to note that we have altered the anchor point to (0.0,0.5) from the default (0.5,0.5). This is so because we are going to place the wings along the body as they actually sprout from a butterfly’s body, and they are placed exactly at the center of the container.

func createWingWithSize(wingSize:CGSize) ->CAShapeLayer{

var w:CGFloat = wingSize.width; //width of the buttefly's wing
var h:CGFloat = wingSize.height; //height of the butterfly's wing

//Create a shape layer and set its properties: bounds, anchor point, fill color and stroke color
var wingLyr = CAShapeLayer();
wingLyr.bounds = CGRectMake(0, 0, w, h);
wingLyr.anchorPoint = CGPointMake(0.0, 0.5); //anchor point of butterfly wing is at left (horizontally) and center (vertically)
wingLyr.fillColor = UIColor(red: 250/255.0, green: 185/255.0, blue: 95/255.0, alpha: 0.9).CGColor; //orangish color
wingLyr.strokeColor = UIColor(red: 244/255.0, green: 66/255.0, blue: 96/255.0, alpha: 0.8).CGColor;//reddish color
wingLyr.lineWidth = 2.0;//stroke width

//Create buttefly's wing geometry using UIBezierPath
var bPath:UIBezierPath = UIBezierPath();

//Create the geometry of the wings
bPath.moveToPoint(CGPointMake(0, h/4));
bPath.addLineToPoint(CGPointMake(w/3, 0));
bPath.addLineToPoint(CGPointMake(w, 0));
bPath.addLineToPoint(CGPointMake(w, h/3));
bPath.addLineToPoint(CGPointMake(2*w/3, h/2));
bPath.addLineToPoint(CGPointMake(w, 2*h/3));
bPath.addLineToPoint(CGPointMake(w, h));
bPath.addLineToPoint(CGPointMake(w/3, h));
bPath.addLineToPoint(CGPointMake(0, 2*h/3));
bPath.closePath();

//Draw two circles on the wings
bPath.moveToPoint(CGPointMake(w/2 + w/5, h/4));
bPath.addArcWithCenter(CGPointMake(w/2, h/4), radius:CGFloat(w/5), startAngle:CGFloat(0), endAngle:CGFloat(M_PI*2), clockwise:true)
bPath.closePath();

bPath.moveToPoint(CGPointMake(w/2 + w/8, 3*h/4));
bPath.addArcWithCenter(CGPointMake(w/2, 3*h/4), radius:CGFloat(w/8), startAngle:CGFloat(0), endAngle:CGFloat(M_PI*2), clockwise:true);
bPath.closePath();

//Assign path to the path property of the shape layer
wingLyr.path = bPath.CGPath;

return wingLyr;
}

This post completes the creation of the whole butterfly. Now the butterfly is placed at the lower left portion of the screen and has a dark blue body with two orange wings. However, as of now, the wings are placed one above the other and have not yet started fluttering.(please refer to the screenshot above) In my next post I will cover how to animate these wings. This will bring our butterfly to life.

You can download the project as a zip file here (Part 2).

— §§§ —

 

mobile apps development india | iOS app development training in Delhi NCR Noida Gurgaon | iPhone & iPad Application development in India | iPhone iPad based game development in Delhi NCR Noida Gurgaon India | games and apps developer & producer india | iPhone & iPad games for eLearning | iOS games and applications development Delhi NCR Noida Gurgaon India | iPhone development training & classes in swift & objective C | iPhone app and game development courses workshops in swift | iOS training for corporates & companies india | iOS trainings courses workshops in swift programming at Delhi NCR Noida Gurgaon | Apple development training courses Delhi NCR Nodia Gurgaon | Xcode iOS trainings and courses in swift for corporates & companies| Indian iOS Games and apps developers | iOS apps and games development courses & trainings in Delhi NCR Noida Gurgaon India

 

Flying Butterfly – Part 1 of 7 – Swift Tutorial Series on Layers, Transforms, Animation, Delegates and Event Handling

The Genesis of the Flying Butterfly

Since its launch in June 2014,  Swift programming language has caught the attention of the  programmers world-wide. Swift incorporates the best features from various programming languages and then some. This is how Apple’s own  documentation describes Swift.

“Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works.”

In past I have used Objective C as well as C in the development of my games and apps. For the last one year I have been using Swift and its features never cease to amaze me. The genesis of this tutorial series was the need to illustrate the use of various classes, methods and constructs used in Cocoa-based applications, by developing a small interactive app using Swift as the programming language (and not Objective C).  Hence the Flying Butterfly.  I hope those programmers who are either learning to master Swift or trying to migrate from Objective C to Swift, will find this series of posts useful.

This is a long tutorial which will spread across different posts and will demonstrate the application of the following classes, methods, delegates, event handlers and other programming constructs using Swift.

Here is the video of the Flying Butterfly that shows the output of our programming efforts in this tutorial. (The video opens in a new window. File Name: Output-Flying-Butterfly-Swift-Tutorial-Series.mov (size approx. 6.5 MB))

Classes/Methods/Handlers used in the tutorial

The major classes, methods, event handlers which will be used in this tutorial are:

  • CALayer
  • CAShapeLayer
  • CATransform3D
  • CABasicAnimation
  • CAKeyframeAnimation
  • animationDidStop(_:,finished:) (animation delegate)
  • touchesEnded(_:withEvent:) (touch handling )

Brief Description of the Flying Butterfly

We will start this tutorial by constructing a butterfly. The butterfly will comprise two wings and a body. This will be followed by making the wings flutter. While the butterfly is fluttering its wings we will also make it fly from lower left part of the screen to the top right corner where it finally sits on the flowers. When the butterfly is at its destination and sitting on the flowers, the app will show a prompt “Touch Me” to the user to tap it. Tapping the sitting butterfly will make it repeat the flying animation again from the lower right corner of the screen. Our objective will be to make fluttering of the wings and the flight of the butterfly as realistic as possible. You can watch the butterfly in its complete action in this video. Here is a screen- shot of the video taken somewhere in the middle of the butterfly’s flight.

Screenshot for Flying Butterfly - Swift Tutorial Series on Layers, Transforms, Animation, Delegates and Event Handling for iOS (iPhone / iPad)

This tutorial assumes that you already know how to create a single view application in Swift. We are using iPad as our target device for this tutorial, however,  the project can be modified to be used for both iPhone and iPad. So go ahead and create a  project and name it Flying Butterfly. Once you have created it, ViewController.swift is the file where we will be writing our code. Open Main.storyboard file and in Utilities area navigate to File Inspector (cmd+optn+1). In Interface Builder Document section deselect Use Auto Layout and when the prompt for “Using Size Classes Requires Auto Layout” comes up on screen, select iPad for “Keep size class data for:” and then press “Disable Size Classes” button. This will make the view of the view controller match the dimensions of iPad’s Screen (768×1024). Import the background image (download it here) into the project and place it inside the main view as the background image view. Also drag a label to the view and create an outlet for it in the view controller with name lblTouchMe. ( @IBOutlet weak var lblTouchme:UILabel!). Link the label on the storyboard to this outlet and you are good to go.

Next post onwards we will dive into programming and bring in the various constructs and classes mentioned above. In the meantime if you are not very comfortable using Swift as the programming language then before starting with these tutorials I recommend that you boot up with the basics of Swift.

In Part 2 this series, we will start creating the butterfly.

You can download the project as a zip file here (Part 1).
 

— §§§ —

 
 

iPhone & iPad games for eLearning | iPhone & iPad Application development in India | mobile apps development india | Xcode iOS trainings and courses in swift for corporates & companies | Indian iOS Games and apps developers | iOS app development training in Delhi NCR Noida Gurgaon | iOS trainings courses workshops in swift programming at Delhi NCR Noida Gurgaon | iPhone iPad based game development in Delhi NCR Noida Gurgaon India | Apple development training courses Delhi NCR Nodia Gurgaon | iOS games and applications development Delhi NCR Noida Gurgaon India | games and apps developer & producer india | iOS apps and games development courses & trainings in Delhi NCR Noida Gurgaon India | iOS training for corporates & companies india | iPhone app and game development courses workshops in swift | iPhone development training & classes in swift & objective C

 

Playing with Layers in Swift with Playgrounds – A Tutorial / Example for Rapid Prototyping

Introduction:

Interactive Playgrounds is one of the best gifts from Apple to iOS/OSX developers. Learning Swift using Playgrounds is fun. Playgrounds do not require any simulator or any engine to get started and when a Playground file is opened or created it renders/shows the results instantaneously. Before Playgrounds, in order to test a small code we had to create an application, write code in the view controller file, and then test it on a device or a simulator. With Playgrounds all that has been a thing a past. Playgrounds are very helpful in situations were we need to test a code for which we must make frequent changes and constantly review its output.

Normal testing takes longer and at times becomes frustrating. For example if we are drawing a complex shape which uses arc related drawing methods of a UIBezierPath or CGPath, it becomes a chore to run a small code fragment again and again to test it in the simulator. With Interactive Playgrounds at our disposal, it happens in a breeze. Playgrounds can be effectively used to complement the training sessions where audience retention is directly related to immediate visual feedback. Playgrounds are also very effective for doing rapid prototyping or demonstrating proof-of-concepts. Once we are satisfied with the results, the same code can be ported to a project and used as it is. A developer has to just write a line of code and it executes instantaneously and results are available to view and evaluate.

According to Apple-

Playgrounds let you:
*Share curriculum to teach programming with beautiful text and interactive code.
*Design a new algorithm and watch its results every step of the way.
*Create new tests and verify they work before promoting into your test suite.
*Experiment with new APIs to hone your Swift coding skills.
*Turn your experiments into documentation with example code that runs within the playground.

Here is a screen-shot of the Playground window (explained later) which shows the code on the left-hand side and the rendered view on the right-hand side. (Click to view the bigger image)

Screenshot of Apple Swift Playground in Action used for rapid prototyping testing code for iOS / OSX - Examples and Tutorials

Getting Started With Playgrounds

Starting a playground is even simpler than creating a project in XCode. To create a playground file, you can do any of the either select the “Get Started with Playground” option from the “Welcome to XCode” window or  if XCode is already open, select the New submenu from the File Menu, then select the Playground option (File->New->Playground). Once the file is created the left pane is available to write your code.

If you are working with views, it’s a good idea to render them. For doing this we have to import XCPlayground (insert “import XCPlayground” after “importUIKit” statement.) This is important as we use function XCPShowView(“ViewIdentifierString”, viewVariable) to show the view we create in the playground. The best thing about playground is that we have to call this function only once after the view is created. All other code written after this function call executes and updates the view automatically. In order to show the rendered view in our playground window we have open the assistant editor. So navigate to the View menu and open Assistant Editor (View->Assistant Editor->Show Assistant Editor). If you don’t do  this you may be left wondering why playground is not showing the results.

The first thing you should do in a playground is to create a view of the desired size, background color etc., and then call the function XCPShowView. This function has two parameters. The first parameter is a string which helps you identify your view in the assistant editor and the second parameter is the variable which holds the view. This view is your drawing area and whenever you are creating a sub-view or a sub-layer – they all go inside this view.

My Heart Beats For You! – A Playground Example for playing with Layers

I have created a playground example which uses three objects of different layer classes – CALayer, CAShapeLayer and CATextLayer. First, let us look at the rendered view:

Playing with Layers - An Example of Interactive Playground in IOS for drawing paths / shapes

Here is an overview of what we do in this example:

1. We create a view with muave background and then call XCPShowView function to render it.
2. Then we create a CALayer object (boxLyr) which acts as the container layer. This box has a red thick border.
3. Then we create a CAShapeLayer object (heartLyr). We create a shape of heart using UIBezierPath methods.

Testing this code again and again was a necessity and doing the same in a normal iOS project would have been a real pain. I had to change the control points many times over to arrive at the correct shape of the heart. Each time the playground rendered the output shape with great ease.

Once the drawing is over we convert UIBezierPath to CGPath and assign it to the path property of the heart layer. We also give some shadow to the heart so that it floats over the box. Here is the code for creating path for the heart shape:

//---Create Path for drawing the Heart---
var path = UIBezierPath()
//Move to Drawing Point
path.moveToPoint(CGPointMake(heartW/2, 120))
//Upper-Right Curve
path.addQuadCurveToPoint(CGPointMake(heartW * 0.9, 150), controlPoint: CGPointMake(heartW * 0.8, 0))
//Lower-Right Curve
path.addQuadCurveToPoint(CGPointMake(heartW/2, heartH * 0.9), controlPoint: CGPointMake(heartW, 320))
//Lower-Left Curve
path.addQuadCurveToPoint(CGPointMake(heartW * 0.1, 150), controlPoint: CGPointMake(0,320))
//Upper-Left Curve
path.addQuadCurveToPoint(CGPointMake(heartW/2, 120), controlPoint: CGPointMake(heartW * 0.2, 0))
//Assign CGPath
heartLyr.path = path.CGPath
//Add as sublayer of boxLyr
boxLyr.addSublayer(heartLyr)

4. Then we create a text layer with text “My Heart Beats for You!”. This text is in white and is placed over the heart. It is rotated by 15 degrees counter-clockwise.

 

If you are interested in playing with the code in the file to see its effect on the view, download the playground file here.

— §§§ —

 

iPhone & iPad Application development in India | iPhone & iPad games for eLearning | iOS training for corporates & companies india | mobile apps development india | iOS apps and games development courses & trainings in Delhi NCR Noida Gurgaon India | iPhone development training & classes in swift & objective C | Xcode iOS trainings and courses in swift for corporates & companies | Apple development training courses Delhi NCR Nodia Gurgaon | iOS games and applications development Delhi NCR Noida Gurgaon India | iOS app development training in Delhi NCR Noida Gurgaon | iPhone app and game development courses workshops in swift | games and apps developer & producer india | iOS trainings courses workshops in swift programming at Delhi NCR Noida Gurgaon | iPhone iPad based game development in Delhi NCR Noida Gurgaon India | Indian iOS Games and apps developers