Friday, August 12, 2016

SpriteKit From Scratch: Advanced Techniques and Optimizations_part 2 (end)


3. The Animation Loop

Before each frame of your game renders, SpriteKit executes a series of processes in a particular order. This group of processes is referred to as the animation loop. These processes account for the actions, physics properties, and constraints that you have added to your scene.

If, for whatever reason, you need to run custom code in between any of these processes, you can either override some specific methods in your SKScene subclass or specify a delegate that conforms to the SKSceneDelegate protocol. Note that, if you assign a delegate to your scene, the class' implementations of the following methods are not invoked.

The animation loop processes are as follows:

Step 1
The scene calls its update(_:) method. This method has a single NSTimeInterval parameter, which gives you the current system time. This time interval can be useful as it allows you to calculate the time it took for your previous frame to render.

If the value greater than 1/60th of a second, your game is not running at the smooth 60 frames per second (FPS) that SpriteKit aims for. This means that you may need to change some aspects of your scene (for example, particles, number of nodes) to reduce its complexity.

Step 2
The scene executes and calculates the actions you have added to your nodes and positions them accordingly.

Step 3
The scene calls its didEvaluateActions() method. This is where you can perform any custom logic before SpriteKit continues with the animation loop.

Step 4
The scene performs its physics simulations and changes your scene accordingly.

Step 5
The scene calls its didSimulatePhysics() method, which you can override with the didEvaluateActions() method.

Step 6
The scene applies the constraints that you have added to your nodes.

Step 7
The scene calls its didApplyConstraints() method, which is available for you to override.

Step 8
The scene calls its didFinishUpdate() method, which you can also override. This is the final method you can change your scene in before its appearance for that frame is finalized.

Step 9
Finally, the scene renders its contents and updates its containing SKView accordingly.

It is important to note that, if you use a SKSceneDelegate object rather than a custom subclass, each method gains an extra parameter and changes its name slightly. The extra parameter is an SKScene object, which allows you to determine which scene the method is being run in relation to. The methods defined by the SKSceneDelegate protocol are named as follows:
  • update(_:forScene:)
  • didEvaluateActionsForScene(_:)
  • didSimulatePhysicsForScene(_:)
  • didApplyConstraintsForScene(_:)
  • didFinishUpdateForScene(_:)
Even if you don't use these methods to make any changes to your scene, they can still be very useful for debugging. If your game consistently lags and the frame rate drops at a particular moment in your game, you could override any combination of the above methods and find the time interval between each one being called. This allows you to accurately find whether it is specifically your actions, physics, constraints, or graphics that are too complex for your game to run at 60 FPS.

4. Performance Best Practices

Batch Drawing
When rendering your scene, SpriteKit, by default, runs through the nodes in your scene's children array and draws them on to the screen in the same order as they are in the array. This process is also repeated and looped for any child nodes a particular node might have.

Enumerating through child nodes individually means that SpriteKit executes a draw call for each node. While for simple scenes this method of rendering does not significantly impact performance, as your scene gains more nodes this process becomes very inefficient.

To make rendering more efficient, you can organize the nodes in your scene into distinct layers. This is done through the zPosition property of the SKNode class. The higher a node's zPosition is, the "closer" it is to the screen, which means that it is rendered on top of other nodes in your scene. Likewise, the node with the lowest zPosition in a scene appears at the very "back" and can be overlapped by any other node.

After organizing nodes into layers, you can set an SKView object's ignoreSiblingOrder property to true. This results in SpriteKit using the zPosition values to render a scene rather than the order of the children array. This process is far more efficient as any nodes with the same zPosition are batched together into a single draw call rather than having one for each node.

It is important to note that the zPosition value of a node can be negative if needed. The nodes in your scene are still rendering in order of increasing zPosition.

Avoid Custom Animations
Both the SKAction and SKConstraint classes contain a large number of rules you can add to a scene to create animations. Being part of the SpriteKit framework, they are optimized as much as they possibly can be and also fit in perfectly with SpriteKit's animation loop.

The wide array of actions and constraints provided to you allow for almost any possible animation you could want. For these reasons, it is recommended that you always utilize actions and constraints in your scenes to create animations rather than performing any custom logic elsewhere in your code.

In some cases, especially if you are needing to animate a reasonably large group of nodes, physics force fields may also even be able to produce the result you want. Force fields are even more efficient as they are calculated alongside the rest of SpriteKit's physics simulations.

Bit Masks
Your scenes can be optimized even more by using only the appropriate bit masks for nodes in your scene. In addition to being crucial for physics collision detection, bit masks also determine how regular physics simulations and lighting affect the nodes in a scene.

For any pair of nodes in a scene, regardless of whether or not they will ever collide, SpriteKit monitors where they are relative to each other. This means that, if left with the default masks with all bits enabled, SpriteKit is keeping track of where each node is in your scene compared to every other node. You can greatly simplify SpriteKit's physics simulations by defining appropriate bit masks so that only the relationships between nodes that can potentially collide are tracked.

Likewise, a light in SpriteKit only affects a node if the logical AND of their category bit masks is a non-zero value. By editing these categories, so that only the most important nodes in your scene are affected by a particular light, you can greatly reduce the complexity of a scene.

Conclusion

You should now know how you can further optimize your SpriteKit games by using more advanced techniques, such as texture atlases, batch drawing, and optimized bit masks. You should also be comfortable with saving and loading scenes to give your players a better overall experience.

Throughout this series, we have looked through a lot of the features and functionality of the SpriteKit framework in iOS, tvOS, and OS X. There are even more advanced topics beyond the scope of this series, such custom OpenGL ES and Metal shaders as well as physics fields and joints.
Written by Davis Allie

If you found this post interesting, follow and support us.
Suggest for you:

Complete Beginners Guide to iOS Development - Build 10 Apps

The Complete iOS 10 Developer - Build Real Apps with Swift 3

Swift 3 and iOS 10 The Final Course Learn to Code like a Pro

Thursday, August 11, 2016

SpriteKit From Scratch: Advanced Techniques and Optimizations_part1

Introduction

In this tutorial, the fifth and final installment of the SpriteKit From Scratch series, we look at some advanced techniques you can use to optimize your SpriteKit-based games to improve performance and user experience.

This tutorial requires that you are running Xcode 7.3 or higher, which includes Swift 2.2 and the iOS 9.3, tvOS 9.2, and OS X 10.11.4 SDKs. To follow along, you can either use the project you created in the previous tutorial or download a fresh copy from GitHub.

The graphics used for the game in this series can be found on GraphicRiver. GraphicRiver is a great source for finding artwork and graphics for your games.

1. Texture Atlases

In order to optimize the memory usage of your game, SpriteKit provides the functionality of texture atlases in the form of the SKTextureAtlas class. These atlases effectively combine the textures you specify into a single, large texture that takes up less memory than the individual textures on their own.

Luckily, Xcode can create texture atlases very easily for you. This is done in the same asset catalogs that are used for other images and resources in your games. Open your project and navigate to the Assets.xcassets asset catalog. At the bottom of the left sidebar, click the + button and select the New Sprite Atlas option.

As a result, a new folder is added to the asset catalog. Click the folder once to select it and click again to rename it. Name it Obstacles. Next, drag the Obstacle 1 and Obstacle 2 resources into this folder. You can also delete the blank Sprite asset that Xcode generates if you want to, but that is not required. When completed, your expanded Obstacles texture atlas should look like this:


It's now time to use the texture atlas in code. Open MainScene.swift and add the following property to the MainScene class. We initialize a texture atlas using the name we entered in our asset catalog.
  1. let obstaclesAtlas = SKTextureAtlas(named: "Obstacles")
While not required, you can preload the data of a texture atlas into memory before it is used. This allows your game to eliminate any lag that might occur when loading the texture atlas and retrieving the first texture from it. Preloading a texture atlas is done with a single method and you can also run a custom code block once the loading has completed.

In the MainScene class, add the following code at the end of the didMoveToView(_:) method:
  1. override func didMoveToView(view: SKView) {     
  2.     ...     
  3.     obstaclesAtlas.preloadWithCompletionHandler { 
  4.         // Do something once texture atlas has loaded
  5.     }
  6. }
To retrieve a texture from a texture atlas, you use the textureNamed(_:) method with the name you specified in the asset catalog as a parameter. Let's update the spawnObstacle(_:) method in the MainScene class to use the texture atlas we created a moment ago. We fetch the texture from the texture atlas and use it to create a sprite node.
  1. func spawnObstacle(timer: NSTimer) {
  2.     if player.hidden {
  3.         timer.invalidate()
  4.         return
  5.     }
  6.     let spriteGenerator = GKShuffledDistribution(lowestValue: 1, highestValue: 2)
  7.     let texture = obstaclesAtlas.textureNamed("Obstacle \(spriteGenerator)")
  8.     let obstacle = SKSpriteNode(texture: texture)
  9.     obstacle.xScale = 0.3
  10.     obstacle.yScale = 0.3 
  11.     let physicsBody = SKPhysicsBody(circleOfRadius: 15)
  12.     physicsBody.contactTestBitMask = 0x00000001
  13.     physicsBody.pinned = true
  14.     physicsBody.allowsRotation = false
  15.     obstacle.physicsBody = physicsBody 
  16.     let center = size.width/2.0, difference = CGFloat(85.0)
  17.     var x: CGFloat = 0
  18.     let laneGenerator = GKShuffledDistribution(lowestValue: 1, highestValue: 3)
  19.     switch laneGenerator.nextInt() {
  20.     case 1:
  21.         x = center - difference
  22.     case 2:
  23.         x = center
  24.     case 3:
  25.         x = center + difference
  26.     default:
  27.         fatalError("Number outside of [1, 3] generated")
  28.     }     
  29.     obstacle.position = CGPoint(x: x, y: (player.position.y + 800))
  30.     addChild(obstacle)     
  31.     obstacle.lightingBitMask = 0xFFFFFFFF
  32.     obstacle.shadowCastBitMask = 0xFFFFFFFF
  33. }
Note that, if your game takes advantage of On-Demand Resources (ODR), you can easily specify one or more tags for each texture atlas. Once you have successfully accessed the correct resource tag(s) with the ODR APIs, you can then use your texture atlas just like we did in the spawnObstacle(_:) method. You can read more about On-Demand Resources in another tutorial of mine.

2. Saving and Loading Scenes

SpriteKit also offers you the ability to easily save and load scenes to and from persistent storage. This allows players to quit your game, have it relaunched at a later time, and still be up to the same point in your game as they were before.

The saving and loading of your game is handled by the NSCoding protocol, which the SKScene class already conforms to. SpriteKit's implementation of the methods required by this protocol automatically allow for all of the details in your scene to be saved and loaded very easily. If you want to, you can also override these methods to save some custom data along with your scene.

Because our game is very basic, we are going to use a simple Bool value to indicate whether the car has crashed. This shows you how to save and load custom data that is tied to a scene. Add the following two methods of the NSCoding protocol to the MainScene class.
  1. // MARK: - NSCoding Protocol 
  2. required init?(coder aDecoder: NSCoder) {
  3.     super.init(coder: aDecoder)
  4.     let carHasCrashed = aDecoder.decodeBoolForKey("carCrashed") 
  5.     print("car crashed: \(carHasCrashed)")
  6. } 
  7. override func encodeWithCoder(aCoder: NSCoder) {
  8.     super.encodeWithCoder(aCoder) 
  9.     let carHasCrashed = player.hidden
  10.     aCoder.encodeBool(carHasCrashed, forKey: "carCrashed")
  11. }
If you are unfamiliar with the NSCoding protocol, the encodeWithCoder(_:) method handles the saving of your scene and the initializer with a single NSCoder parameter handles the loading.

Next, add the following method to the MainScene class. The saveScene() method creates an NSData representation of the scene, using the NSKeyedArchiver class. To keep things simple, we store the data in NSUserDefaults.
  1. func saveScene() {
  2.     let sceneData = NSKeyedArchiver.archivedDataWithRootObject(self)
  3.     NSUserDefaults.standardUserDefaults().setObject(sceneData, forKey: "currentScene")
  4. }
Next, replace the implementation of didBeginContactMethod(_:) in the MainScene class with the following:
  1. func didBeginContact(contact: SKPhysicsContact) {
  2.     if contact.bodyA.node == player || contact.bodyB.node == player {
  3.         if let explosionPath = NSBundle.mainBundle().pathForResource("Explosion", ofType: "sks"),
  4.             let smokePath = NSBundle.mainBundle().pathForResource("Smoke", ofType: "sks"),
  5.             let explosion = NSKeyedUnarchiver.unarchiveObjectWithFile(explosionPath) as? SKEmitterNode,
  6.             let smoke = NSKeyedUnarchiver.unarchiveObjectWithFile(smokePath) as? SKEmitterNode {
  7.              
  8.             player.removeAllActions()
  9.             player.hidden = true
  10.             player.physicsBody?.categoryBitMask = 0
  11.             camera?.removeAllActions()
  12.              
  13.             explosion.position = player.position
  14.             smoke.position = player.position
  15.              
  16.             addChild(smoke)
  17.             addChild(explosion)
  18.              
  19.             saveScene()
  20.         }
  21.     }
  22. }
The first change made to this method is editing the player node's categoryBitMask rather than removing it from the scene entirely. This ensures that upon reloading the scene, the player node is still there, even though it is not visible, but that duplicate collisions are not detected. The other change made is calling the saveScene() method we defined earlier once the custom explosion logic has been run.

Finally, open ViewController.swift and replace the viewDidLoad() method with the following implementation:
  1. override func viewDidLoad() {
  2.     super.viewDidLoad() 
  3.     let skView = SKView(frame: view.frame) 
  4.     var scene: MainScene?
  5.     if let savedSceneData = NSUserDefaults.standardUserDefaults().objectForKey("currentScene") as? NSData,
  6.        let savedScene = NSKeyedUnarchiver.unarchiveObjectWithData(savedSceneData) as? MainScene {
  7.         scene = savedScene 
  8.     } else if let url = NSBundle.mainBundle().URLForResource("MainScene", withExtension: "sks"),
  9.               let newSceneData = NSData(contentsOfURL: url),
  10.               let newScene = NSKeyedUnarchiver.unarchiveObjectWithData(newSceneData) as? MainScene {
  11.         scene = newScene
  12.     } 
  13.     skView.presentScene(scene)
  14.     view.insertSubview(skView, atIndex: 0) 
  15.     let left = LeftLane(player: scene!.player)
  16.     let middle = MiddleLane(player: scene!.player)
  17.     let right = RightLane(player: scene!.player) 
  18.     stateMachine = LaneStateMachine(states: [left, middle, right])
  19.     stateMachine?.enterState(MiddleLane)
  20. }
When loading the scene, we first check to see if there is saved data in the standard NSUserDefaults. If so, we retrieve this data and recreate the MainScene object using the NSKeyedUnarchiver class. If not, we get the URL for the scene file we created in Xcode and load the data from it in a similar manner.

Run your app and run into an obstacle with your car. At this stage, you don't see a difference. Run your app again, though, and you should see that your scene has been restored to exactly how it was when you just crashed the car.
Written  by Davis Allie

If you found this post interesting, follow and support us.
Suggest for you:

iOS 10 Projects: Build Amazing Apps with Apple's Newest iOS

iOS 10 & Swift 3: From Beginner to Paid Professional

Complete Beginners Guide to iOS Development - Build 10 Apps

The Complete iOS 10 Developer - Build Real Apps with Swift 3

Swift 3 and iOS 10 The Final Course Learn to Code like a Pro

Tuesday, August 9, 2016

Data Validation With Core Data: Common Constraints

No matter what persistence framework an application uses, the developer decides what is stored in the application's persistent store. This also means that the developer is in charge of validating the data before it is inserted into the persistent store.

If your application uses Core Data for persisting data, then you are in luck. The framework has a number of APIs for validating objects before they are persisted to disk. In this tutorial, I show you what options Core Data offers developers for validating objects.

1. Project Setup

The best way to learn is by doing. Open Xcode and create a new project based on the Single View Application template.

Name the project Validation and set Language to Swift. Check Use Core Data at the bottom and click Next.


2. Populate Data Model

Open Validation.xcdatamodeld, create a new entity, and name it User. Add the following attributes to the User entity:
  • first of type String
  • last of type String
  • email of type String
  • age of type Integer 16
Create another entity, name it Note, and add the following attributes to the entity:
  • title of type String
  • contents of type String
  • createdAt of type Date
A user can have many notes and a note can belong to only one user. This means that we need to add a To Many relationship to the User entity with the Note entity as the destination. We also need to add a To One relationship to the Note entity with the User entity as the destination and notes as the inverse relationship. This is what that looks like in Xcode's data model editor.



3. Constraining Attributes

Common constraints can be defined in the data model. Let me show you how this works. Open Validation.xcdatamodeld and select the User entity. Select the email attribute and open the Data Model Inspector on the right.


In the Validation section, you can set the minimum and maximum length of the attribute. You can even enter a regular expression the value of the attribute must match in order to be valid. The Data Model Inspector also adds the ability to set a default value, which is convenient for required attributes.

This brings us to the most obvious constraint for attributes, their optionality. By unchecking the Optional checkbox at the top, you tell Core Data that the attribute must have a value for it to be valid.

If an object doesn't pass validation, Core Data throws an error if a save operation is performed. It goes without saying that Core Data doesn't allow invalid objects to be pushed to the application's persistent store.

If you select the age attribute of the User entity, you will notice that the Validation section looks slightly different. Because the age attribute is of type Integer 16, you can set a minimum and a maximum value for the attribute. You can also define a default value.


Select the createdAt attribute of the Note entity and open the Data Model Inspector. Note that you can specify a minimum and a maximum date as well as a default date.


The most important downside of constraints defined in the data model is the lack of dynamism. For example, if you want to constrain an attribute of type Date to values based on the current date, then you need to implement custom validation in code. We take a look at how that works later.

4. Constraining Relationships

Relationships are not very different from attributes. They too can be constrained. A relationship can be optional or required. The count of a To Many relationship can be constrained to a minimum and a maximum value. Select the notes attribute of the User entity and open the Data Model Inspector. The count of the notes relationship can have a minimum and a maximum value.


Having the ability to add constraints to a data model is a powerful concept and it is nice to know that this is built into the Core Data framework.

5. Validating Objects

Select the User entity and mark every attribute as required by unchecking the Optional checkbox in the Data Model Inspector. Select the age attribute and set the minimum value to 0 and the maximum value to 120. Set the attribute's default value to 21.


Open AppDelegate.swift and update application(_:didFinishLaunchingWithOptions:) as shown below. We create an instance of the User entity and populate its attributes. Note that we set the age attribute to a value that exceeds the maximum value we specified in the data model. We can ask the managed object whether it is valid for insertion into the persistent store by invoking validateForInsert(). Because this method is throwing, we wrap it in a do-catch statement.
  1. func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  2.     if let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: self.managedObjectContext) {
  3.         // Create Managed Object
  4.         let user = NSManagedObject(entity: entity, insertIntoManagedObjectContext: self.managedObjectContext)
  5.         // Populate Managed Object
  6.         user.setValue(140, forKey: "age")
  7.         user.setValue("Bart", forKey: "first")
  8.         user.setValue("Jacobs", forKey: "last")
  9.         user.setValue("me@icloud.com", forKey: "email") 
  10.         do {
  11.             try user.validateForInsert() 
  12.         } catch {
  13.             let validationError = error as NSError
  14.             print(validationError)
  15.         } 
  16.     } 
  17.     return true
  18. }
If you run the application in the simulator or on a physical device, you should see the following error in the console.
  1. Error Domain=NSCocoaErrorDomain Code=1610 "The operation couldn’t be completed. (Cocoa error 1610.)" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x7fef63611dd0> (entity: User; id: 0x7fef63613eb0 <x-coredata:///User/t8C45E95D-D8C3-4900-82FA-BC313D53D5882> ; data: {
  2.     age = 140;
  3.     email = "me@icloud.com";
  4.     first = Bart;
  5.     last = Jacobs;
  6.     notes =     (
  7.     );
  8. }), NSValidationErrorValue=140, NSValidationErrorKey=age, NSLocalizedDescription=The operation couldn’t be completed. (Cocoa error 1610.)}
The error is pretty clear about what is wrong with the managed object. Even though the localized description is a bit vague, the error indicates the value of the age attribute isn't meeting the constraints we defined in the data model.

It is possible that multiple validation errors were thrown during validation. Let me show you what that looks like. To avoid migration issue, delete the application from simulator. Revisit the data model and select the last attribute of the User entity. Open the Data Model Inspector on the right and uncheck Optional to make the attribute required.

Open AppDelegate.swift and remove the line in which we set the last name of the User record.
  1. user.setValue("Jacobs", forKey: "last")
Run the application again and inspect to output in the console.
  1. Error Domain=NSCocoaErrorDomain Code=1560 "(null)" UserInfo={NSDetailedErrors=(
  2.     "Error Domain=NSCocoaErrorDomain Code=1610 \"The operation couldn\U2019t be completed. (Cocoa error 1610.)\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x7feab8419690> (entity: User; id: 0x7feab84196f0 <x-coredata:///User/tD1D0A3BA-7F23-41A7-9567-5C1A30D6A0132> ; data: {\n    age = 140;\n    email = \"me@icloud.com\";\n    first = Bart;\n    last = nil;\n    notes =     (\n    );\n}), NSValidationErrorValue=140, NSValidationErrorKey=age, NSLocalizedDescription=The operation couldn\U2019t be completed. (Cocoa error 1610.)}",
  3.     "Error Domain=NSCocoaErrorDomain Code=1570 \"The operation couldn\U2019t be completed. (Cocoa error 1570.)\" UserInfo={NSValidationErrorKey=last, NSLocalizedDescription=The operation couldn\U2019t be completed. (Cocoa error 1570.), NSValidationErrorObject=<NSManagedObject: 0x7feab8419690> (entity: User; id: 0x7feab84196f0 <x-coredata:///User/tD1D0A3BA-7F23-41A7-9567-5C1A30D6A0132> ; data: {\n    age = 140;\n    email = \"me@icloud.com\";\n    first = Bart;\n    last = nil;\n    notes =     (\n    );\n})}"
  4. )}
The userInfo dictionary of the error object contains an array of errors that inform us what went wrong during validation. Understand that the same errors are thrown if you try to save a managed object that doesn't pass validation.

Conclusion

Data validation is a key aspect of data persistence. You need to make sure that the data you insert into the persistent store is valid. In other words, the data you insert needs to conform to the requirements you define in the data model and your application code.
Written by Bart Jacobs

If you found this post interesting, follow and support us.
Suggest for you:


Monday, August 8, 2016

Data Validation With Core Data: Advanced Constraints

In the previous tutorial, you learned how to define common constraints in the data model. In this tutorial, I show you how you can define more advanced constraints in code.

1. Project Setup

Download the project we created in the previous tutorial from GitHub and open it in Xcode. Open AppDelegate.swift and update the implementation of application(_:didFinishLaunchingWithOptions) as shown below.
  1. func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  2.     if let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: self.managedObjectContext) {
  3.         // Create Managed Object
  4.         let user = NSManagedObject(entity: entity, insertIntoManagedObjectContext: self.managedObjectContext)
  5.         // Populate Managed Object
  6.         user.setValue(44, forKey: "age")
  7.         user.setValue("Bart", forKey: "first")
  8.         user.setValue("Jacobs", forKey: "last")
  9.         user.setValue("me@icloud.com", forKey: "email") 
  10.         do {
  11.             try user.validateForInsert()
  12.         } catch {
  13.             let validationError = error as NSError           
  14.            print(validationError)
  15.         }         
  16.     }   
  17.     return true
  18. }


If you run the application in the simulator or on a physical device, no errors should be thrown. In other words, the managed object we create in application(_:didFinishLaunchingWithOptions) passes validation for insertion into the application's persistent store.

2. Subclassing NSManagedObject

To validate the value of an attribute in code, we need to create an NSManagedObject subclass. Choose New > File... from Xcode's File menu and select the Core Data > NSManagedObject subclass template from the list of templates.


Select the data model of the project and check the entities for which you want to create an NSManagedObject subclass.



Check Use scalar properties for primitive data types, tell Xcode where you want to save the files for the subclasses, and click Create.


3. Property Validation

To validate the property of an entity, you implement a method that takes the following format, validate<PROPERTY>(_:). The method should be a throwing method. If the validation fails, an error is thrown, notifying Core Data that the value for the property is invalid.

In the example below, I have implemented a validation method for the first property of the User entity. Add the following snippet to User.swift.
  1. import CoreData
  2. import Foundation 
  3. class User: NSManagedObject { 
  4.     let errorDomain = "UserErrorDomain" 
  5.     enum UserErrorType: Int {
  6.         case InvalidFirst
  7.     } 
  8.     func validateFirst(value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {
  9.         var error: NSError? = nil; 
  10.         if let first = value.memory as? String {
  11.             if first == "" {
  12.                 let errorType = UserErrorType.InvalidFirst
  13.                 error = NSError(domain: errorDomain, code: errorType.rawValue, userInfo: [ NSLocalizedDescriptionKey : "The first name cannot be empty." ] )
  14.             } 
  15.         } else {
  16.             let errorType = UserErrorType.InvalidFirst
  17.             error = NSError(domain: errorDomain, code: errorType.rawValue, userInfo: [ NSLocalizedDescriptionKey : "The first name cannot be blank." ] )
  18.         }
  19.         if let error = error {
  20.             throw error
  21.         }
  22.     }
  23.  
  24. }
The validation method accepts one parameter of type AutoreleasingUnsafeMutablePointer<AnyObject?>. What is that? Don't let the type of the parameter scare you. As the name of the type indicates, the AutoreleasingUnsafeMutablePointerr structure is a mutable pointer. It points to an object reference. We can access the value to which the pointer points through its memory property.

As I mentioned a moment ago, the validateFirst(_:) method is throwing. If the value that is handed to us isn't valid, we throw an error. By throwing an error, we inform Core Data that the managed object is invalid.

In the next example, I implement a validation method for the email property of the User class. We make use of a regular expression to validate the value of the email property.
  1. func validateEmail(value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {
  2.     var error: NSError? = nil
  3.     if let email = value.memory as? String {
  4.         let regex = "^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$"
  5.         let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
  6.         if !predicate.evaluateWithObject(email) {
  7.             let errorType = UserErrorType.InvalidEmail
  8.             error = NSError(domain: errorDomain, code: errorType.rawValue, userInfo: [ NSLocalizedDescriptionKey : "The email address is invalid." ] )
  9.         }
  10.     } else {
  11.         let errorType = UserErrorType.InvalidEmail
  12.         error = NSError(domain: errorDomain, code: errorType.rawValue, userInfo: [ NSLocalizedDescriptionKey : "The email address is invalid." ] )
  13.     } 
  14.     if let error = error {
  15.         throw error
  16.     }
  17. }
Even though you can modify the value of the property in a validation method, Apple strongly discourages this. If you modify the value that is handed to you in a validation method, memory management may go haywire. With that in mind, the data validation flow becomes very simple. Validate the value of the property and throw an error if it is invalid. It is that simple.

Modify the values of the attributes in application(_:didFinishLaunchingWithOptions) and run the application in the simulator. If the values you entered are invalid, an error should be thrown.

4. Object Validation

The NSManagedObject class exposes three additional hooks subclasses can override for data validation:
  1. validateForInsert()
  2. validateForUpdate()
  3. validateForDelete()
These methods are invoked by Core Data on the managed object before inserting, updating, or deleting the corresponding record in the persistent store. Each of these methods is throwing. If an error is thrown, the corresponding insert, update, or delete is aborted.

Even though the benefit these hooks have over the property validation methods we discussed earlier may not be immediately obvious, they are invaluable in several scenarios. Imagine that a user record cannot be deleted as long as it has one or more note records associated with it. In that case, you can override the validateForDelete() method in the User class.
  1. override func validateForDelete() throws {
  2.     try super.validateForDelete()
  3.  
  4.     var error: NSError? = nil
  5.  
  6.     if let notes = notes {
  7.         if notes.count > 0 {
  8.             let errorType = UserErrorType.OneOrMoreNotes
  9.             error = NSError(domain: errorDomain, code: errorType.rawValue, userInfo: [ NSLocalizedDescriptionKey : "A user with notes cannot be deleted.." ] )
  10.         }
  11.     }
  12.  
  13.     if let error = error {
  14.         throw error
  15.     }
  16. }
Note that we use the override keyword and invoke the validateForDelete() implementation of the superclass at the top. If the user record is tied to one or more note records, an error is thrown, preventing the user record from being deleted.

5. Which Option Should You Use?

Data validation is an important aspect of every application that works with data. Core Data provides developers with several APIs for implementing data validation. But you may be wondering which option, or options, to use in your application.

This depends on your preference and the requirements of the project. For a simple data model with common constraints, the options the data model offers may be sufficient. That said, some developers prefer to keep validation logic in the model classes, that is, in the NSManagedObject subclasses. The advantage is that the logic for a particular model class is located in one place.

For more complex validation logic, custom validation methods for properties or the validateForInsert(), validateForUpdate(), and validateForDelete() hooks are recommended. They add power and flexibility to object validation and you also have the benefit that the model layer includes the validation logic.

It is important to understand that data validation consists of two aspects, the logic for data validation and when data validation should be performed. The model layer is in charge of data validation. The controller is in charge of deciding when data validation should be performed, for example, when the user taps a button to create an account. This is a subtle but important difference.

Last but not least, avoid putting data validation logic in the controller layer. It unnecessarily clutters up the controllers of your project and it usually leads to code duplication.

Conclusion

Core Data makes data validation easy and straightforward. The data model helps you with common constraints, but the framework also exposes several more advanced APIs for custom data validation.
Written by Bart Jacobs

If you found this post interesting, follow and support us.
Suggest for you:



Saturday, August 6, 2016

Rapid, Interactive Prototyping With Xcode Playgrounds_part2 (end)

4. Modifying Variables in the Playground

Let's now change the back faces of the cards from solid red to an image, specifically b.png in the Resources folder. Add the following line to the bottom of the playground.
  1. gc.backImage = UIImage(named: "b")!
After a second or two, you'll see that the back sides of the cards have changed from plain red to a cartoon hand.

Let's now try to alter the padding property, which we assigned a default value of 20 in Game.swift. The space between the cards should increase as a result. Add the following line to the bottom of the playground:
  1. gc.padding = 75
Wait for the live view to refresh and see that ... nothing has changed.

5. A Brief Detour

To understand what is going on, you have to keep in mind that entities, such as view controllers and their associated views, have a complex life cycle. We are going to focus on the latter, that is, views. Creating and updating of a view controller's view is a multistage process. At specific points in the life cycle of the view, notifications are issued to the UIViewController, informing it of what is going on. More importantly, the programmer  can hook into these notifications by inserting code to direct and customize this process.

The loadView() and viewDidAppear(_:) methods are two methods we used to hook into the view life cycle. This topic is somewhat involved and beyond the scope of this discussion, but what matters to us is that the code in the playground, after the assignment of the view controller as the playground's liveView, is executed some time between the call to viewWillAppear(_:) and the call to viewDidAppear(_:). You can verify this by modifying some property in the  playground and add print statements to these two methods to display the value of this property.

The issue with the value of padding not having the expected visual effect is that, by that time, the view and its subviews have already been laid out. Keep in mind that, whenever you make a change to the code, the playground is rerun from the beginning. In that sense, this issue isn't specific to playgrounds. Even if you were developing code to run on the simulator or on a physical device, often times you would need to write additional code to ensure that the change in a property's value has the desired effect on the view's appearance or content.

You might ask why we were able to change the value of the backImage property and see the result without doing anything special. Observe that the backImage property is actually used for the first time in viewDidAppear(_:), by which time it has already picked up its new value.

6. Observing Properties and Taking Action

Our way to deal with this situation will be to monitor changes to the value of padding and resize/reposition the view and subviews. Fortunately, this is easy to do with Swift's handy property observing feature. Start by uncommenting the code for the resetGrid() method in Game.swift:
  1. // (7): reset grid
  2. func resetGrid() {
  3.     view.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
  4.     for v in view.subviews {
  5.         if let card = v as? Card {
  6.             card.center = centerOfCardAt(card.x, card.y)
  7.         }
  8.     }
  9.      
  10. }
This method recomputes the position of the view's frame and that of each Card object based on the new values of viewWidth and viewHeight. Recall that these properties are computed based on the value of padding, which has just been modified.

Also, modify the code for padding to use the didSet observer whose body, as the name indicates, executes whenever we set the value of padding:
  1. // (1): public variables so we can manipulate them in the playground
  2. public var padding = CGFloat(20) {
  3.     didSet {
  4.         resetGrid()
  5.     }
  6. }
The resetGrid() method kicks in and the view is refreshed to reflect the new spacing. You can verify this in the playground.


It appears we were able to fix things quite easily. In reality, when I first decided I wanted to be able to interact with the padding property, I had to go back and make changes to the code in Game.swift. For example, I had to abstract out the Card center calculation in a separate function (centerOfCardAt(_:_:)) to cleanly and independently (re)compute the positions of the cards whenever they needed to be laid out.

Making computed properties for viewWidth and viewHeight also helped. While this kind of rewrite is something you should be prepared for as a trade-off of not doing much upfront design, it can be reduced with some forethought and experience.

7. Game Logic & Touch Interaction

It is now time to implement the game's logic and enable ourselves to interact with it through touch. Begin by uncommenting the firstCard property declaration in the GameController class:
  1. var firstCard: Card?
Recall that the logic of the game involves revealing two cards, one after the other. This variable keeps track of whether a card flip performed by the player is the first of the two or not.

Add the following method to the bottom of the GameController class, before the terminating curly brace:
  1. func handleTap(gr: UITapGestureRecognizer) {
  2.     let v = view.hitTest(gr.locationInView(view), withEvent: nil)!
  3.     if let card = v as? Card {
  4.         UIView.transitionWithView(
  5.             card, duration: 0.5,
  6.             options: .TransitionFlipFromLeft,
  7.             animations: {card.image = UIImage(named: String(card.tag))}) { // trailing completion handler:
  8.                 _ in
  9.                 card.userInteractionEnabled = false
  10.                 if let pCard = self.firstCard {
  11.                     if pCard.tag == card.tag {
  12.                         UIView.animateWithDuration(
  13.                             0.5,
  14.                             animations: {card.alpha = 0.0},
  15.                             completion: {_ in card.removeFromSuperview()})
  16.                         UIView.animateWithDuration(
  17.                             0.5,
  18.                             animations: {pCard.alpha = 0.0},
  19.                             completion: {_ in pCard.removeFromSuperview()})
  20.                     } else {
  21.                         UIView.transitionWithView(
  22.                             card,
  23.                             duration: 0.5,
  24.                             options: .TransitionFlipFromLeft,
  25.                             animations: {card.image = self.backImage})
  26.                         { _ in card.userInteractionEnabled = true }
  27.                         UIView.transitionWithView(
  28.                             pCard,
  29.                             duration: 0.5,
  30.                             options: .TransitionFlipFromLeft,
  31.                             animations: {pCard.image = self.backImage})
  32.                         { _ in pCard.userInteractionEnabled = true }
  33.                     }
  34.                     self.firstCard = nil
  35.                 } else {
  36.                     self.firstCard = card
  37.                 }
  38.         }
  39.     }
  40. }
That is a lengthy method. That is because it packs all the required touch handling, game logic as well as associated animations in one method. Let's see how this method does its work:

First, there is a check to ensure that the user actually touched a Card instance. This is the same as? construct that we used earlier.
If the user did touch a Card instance, we flip it over using an animation similar to the one we implemented earlier. The only new aspect is that we use the completion handler, which executes after the animation completes, to temporarily disable touch interactions for that particular card by setting the userInteractionEnabled property of the card. This prevents the player from flipping over the same card. Note the _ in construct that is used several times in this method. This is just to say that we want to ignore the Bool parameter that the completion handler takes.
We execute code based on whether the firstCard has been assigned a non-nil value using optional binding, Swift's familiar if let construct.
If firstCard is non-nil, then this was the second card of the sequence that the player turned over. We now need to compare the face of this card with the previous one (by comparing the tag values) to see whether we got a match or not. If we did, we animate the cards fading out (by setting their alpha to 0). We also remove these cards from the view. If the tags are not equal, meaning the cards don't match, we simply flip them back facing down and set userInteractionEnabled to true so that the user can select them again.
Based on the current value of firstCard, we set it to either nil or to the present card. This is how we switch the code's behavior between two successive touches.
Finally, uncomment the following two statements in the GameController's initializer that adds a tap gesture recognizer to the view. When the tap gesture recognizer detects a tap, the handleTap() method is invoked:
  1. let tap = UITapGestureRecognizer(target: self, action: #selector(GameController.handleTap(_:)))
  2. view.addGestureRecognizer(tap)
Head back to the playground's timeline and play the memory game. Feel free to decrease the large padding we assigned a bit earlier.

The code in handleTap(_:) is pretty much the unembellished version of what I wrote the first time. One might raise the objection that, as a single method, it does too much. Or that the code isn't object-oriented enough and that the card flipping logic and animations should be neatly abstracted away into methods of the Card class. While these objections aren't invalid per se, remember that quick prototyping is the focus of this tutorial and since we did not foresee any need to interact with this part of the code in the playground, we could afford to be a bit more "hack-ish".

Once we have something working and we decide we want to pursue the idea further, we would certainly have to give consideration to code refactoring. In other words, first make it work, then make it fast/elegant/pretty/...

8. Touch Handling In the Playground

While the main part of the tutorial is now over, as an interesting aside, I want to show you how we can write touch handling code directly in the playground. We will first add a method to the GameController class that allows us to peek at the faces of the cards. Add the following code to the GameController class, immediately after the handleTap(_:) method:
  1. public func quickPeek() {
  2.     for v in view.subviews {
  3.         if let card = v as? Card {
  4.             card.userInteractionEnabled = false
  5.             UIView.transitionWithView(card, duration: 1.0, options: .TransitionFlipFromLeft, animations: {card.image =  UIImage(named: String(card.tag))}) {
  6.                 _ in
  7.                 UIView.transitionWithView(card, duration: 1.0, options: .TransitionFlipFromLeft, animations: {card.image =  self.backImage}) {
  8.                     _ in
  9.                     card.userInteractionEnabled = true
  10.                 } 
  11.             }
  12.         }
  13.     }
  14. }
Suppose we want the ability to activate or deactivate this "quick peek" feature from within the playground. One way to do this would be to create a public Bool property in the GameController class that we could set in the playground. And of course, we would have to write a gesture handler in the GameController class, activated by a different gesture, that would invoke quickPeek().

Another way would be to write the gesture handling code directly in the playground. An advantage of doing it this way is that we could incorporate some custom code in addition to calling quickPeek(). This is what we will do next. Add the following code to the bottom of the playground:
  1. class LPGR {
  2.     static var counter = 0
  3.     @objc static func longPressed(lp: UILongPressGestureRecognizer) {
  4.         if lp.state == .Began {
  5.             gc.quickPeek()
  6.             counter += 1
  7.             print("You peeked \(counter) time(s).")
  8.         }
  9.     }
  10. } 
  11. let longPress = UILongPressGestureRecognizer(target: LPGR.self, action: #selector(LPGR.longPressed))
  12. longPress.minimumPressDuration = 2.0
  13. gc.view.addGestureRecognizer(longPress)
To activate the quick peek feature, we will use a long press gesture, that is, the player holds their finger on the screen for a certain amount of time. We use two seconds as the threshold.

For handling the gesture, we create a class, LPGR (long press gesture recognizer abbreviated), with a static variable property, counter, to keep track of how many times we peeked, and a static method longPressed(_:) to handle the gesture.

By using the static qualifier, we can avoid having to create an LPGR instance because the entities declared static are associated with the LPGR type (class) rather than with a particular instance.

Apart from that, there is no particular advantage to this approach. For complicated reasons, we need to mark the method as @objc to keep the compiler happy. Note the use of LPGR.self to refer to the type of the object. Also note that in the gesture handler, we check if the state of the gesture is .Began. This is because the long press gesture is continuous, that is, the handler would execute repeatedly as long as the user kept their finger on the screen. Since we only want the code to execute once per finger press, we do it when the gesture is first recognized.

The incrementing counter is the custom code that we introduced, which doesn't rely on functionality provided by the GameController class. You can view the output of the print(_:) function (after having peeked a couple of times) in the console at the bottom.


Conclusion

Hopefully, this tutorial has demonstrated an interesting example of rapid, interactive prototyping in Xcode playgrounds. Apart from the reasons for using playgrounds I mentioned earlier, you could think up other scenarios where they could be useful. For instance:
  • demonstrating prototype functionality to clients and letting them choose options and make customizations with live feedback and without having to dig into the nitty-gritty details of the code.
  • developing simulations, such as for physics, where students can play with some parameter values and observe how the simulation is affected. In fact, Apple has released an impressive playground that showcases their interactivity and the incorporation of physics via the UIDynamics API. I encourage you to check it out.
When using playgrounds for demonstration/teaching purposes such as these, you will probably want to make liberal use of the markup capabilities of playgrounds for rich text and navigation.

The Xcode team seems committed to improving playgrounds as new versions of the IDE are rolled out. The breaking news is that Xcode 8, currently in beta, will feature playgrounds for iPad. But, obviously, playgrounds are not meant to substitute the full blown Xcode IDE and the need to test on actual devices when developing a complete, functional app. Ultimately, they are just a tool to be used when it makes sense, but a very useful one.
Written  by Akiel Khan

If you found this post interesting, follow and support us.
Suggest for you:

iOS 10 Message Extension App Reskinning without Coding

iOS 10 Projects: Build Amazing Apps with Apple's Newest iOS

iOS 10 & Swift 3: From Beginner to Paid Professional

The Complete iOS 10 Developer - Build Real Apps with Swift 3

Swift 3 and iOS 10 The Final Course Learn to Code like a Pro

Master iOS 9 - 10 - Xcode 8 and Swift 3