Thursday, August 4, 2016

Create an iMessage App in iOS 10_part2(end)

Next, add the following method to your class:
  1. func createStickerBrowser() {
  2.     let controller = MSStickerBrowserViewController(stickerSize: .large)
  3.      
  4.     addChildViewController(controller)
  5.     view.addSubview(controller.view)
  6.     controller.stickerBrowserView.backgroundColor = UIColor.blue()
  7.     controller.stickerBrowserView.dataSource = self  
  8.     view.topAnchor.constraint(equalTo: controller.view.topAnchor).isActive = true
  9.     view.bottomAnchor.constraint(equalTo: controller.view.bottomAnchor).isActive = true
  10.     view.leftAnchor.constraint(equalTo: controller.view.leftAnchor).isActive = true
  11.     view.rightAnchor.constraint(equalTo: controller.view.rightAnchor).isActive = true
  12. }
With this code, we create an instance of the MSStickerBrowserViewController class and add this as a child of the root view controller in addition to constraining it to the full available height and width.

Next, we need to implement the required MSStickerBrowserViewDataSource methods to provide the necessary sticker information. To do so, add the following methods to your code:
  1. func numberOfStickers(in stickerBrowserView: MSStickerBrowserView) -> Int {
  2.     return stickers.count
  3. }
  4. func stickerBrowserView(_ stickerBrowserView: MSStickerBrowserView, stickerAt index: Int) -> MSSticker {
  5.     return stickers[index]
  6. }
Lastly, so that all of our code is actually executed, replace your viewDidLoad method with the following:
  1. override func viewDidLoad() {
  2.     super.viewDidLoad()
  3.     loadStickers()
  4.     createStickerBrowser()
  5. }
Run your app just as we did earlier (remembering that you may have to swipe across to get to the right app), and once everything has finished loading you should see an identical screen to earlier except now with a blue background:


In this tutorial, we only loaded local sticker images into our custom application for simplicity. One of the main advantages to using a custom sticker application, however, is that you can load sticker images from a remote server and even, through the use of other view controllers before showing your MSStickerBrowserViewController, let your users create their own stickers.

4. Custom Applications

In the last part of this tutorial, we are going to create a very basic iMessage application in order to create a unique message.

If you want to follow along, open up Xcode and create another iMessage Application called MessageApp. Open up your MainInterface.storyboard file and in the view controller shown, remove the default label and add a stepper and button as shown:

Please note that for your iMessage app to appear correctly on all device sizes, you will need to implement auto layout in your interfaces. In this example, I have constrained the stepper to the centre of the view controller and the button to the bottom.

Next, open up the Attributes inspector with your stepper selected and change its minimum and maximum values to 0 and 10 respectively:


Next, open up the Assistant editor with your MessagesViewController.swift file to create and connect an outlet for your stepper and a touch up inside action for your button:
  1. @IBOutlet weak var stepper: UIStepper!
  2. @IBAction func didPress(button sender: AnyObject) {  
  3. }
Now it's time for us to write some code. Firstly, I need to introduce you to a few classes that are crucial when creating an iMessage app:
  • MSConversation: represents the currently open conversation. You can use this class in order to manipulate the conversation transcript, for example by inserting messages or getting the currently selected message.
  • MSMessage: represents a single message, whether created by you to insert into the conversation or already existing in the conversation.
  • MSMessageTemplateLayout: creates a message bubble for you to display your custom message in. As shown in the below image, this template layout has many properties and places for you to put your own content in order to customise your messages.


It is important to note that the space in the top left of this layout will be filled by your iMessage app's icon. Also, all of these properties are optional, and providing no caption strings at all will get rid of the bottom portion of the layout.

Still in your MessagesViewController.swift file, add the following method to your MessagesViewController class:
  1. func createImageForMessage() -> UIImage? {
  2.     let background = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
  3.     background.backgroundColor = UIColor.white()
  4.     let label = UILabel(frame: CGRect(x: 75, y: 75, width: 150, height: 150))
  5.     label.font = UIFont.systemFont(ofSize: 56.0)
  6.     label.backgroundColor = UIColor.red()
  7.     label.textColor = UIColor.white()
  8.     label.text = "\(Int(stepper.value))"
  9.     label.textAlignment = .center
  10.     label.layer.cornerRadius = label.frame.size.width/2.0
  11.     label.clipsToBounds = true 
  12.     background.addSubview(label)
  13.     background.frame.origin = CGPoint(x: view.frame.size.width, y: view.frame.size.height)
  14.     view.addSubview(background)    
  15.     UIGraphicsBeginImageContextWithOptions(background.frame.size, false, UIScreen.main().scale)
  16.     background.drawHierarchy(in: background.bounds, afterScreenUpdates: true)
  17.     let image = UIGraphicsGetImageFromCurrentImageContext()
  18.     UIGraphicsEndImageContext()
  19.     background.removeFromSuperview()    
  20.     return image
  21. }
With this method, we take the current value of the slider and put this in a circular label. We then render this label (and its containing parent view) into a UIImage object which we can attach to our message.

Next, replace your didPress(button:) method with the following code:
  1. @IBAction func didPress(button sender: AnyObject) {
  2.     if let image = createImageForMessage(), let conversation = activeConversation {
  3.         let layout = MSMessageTemplateLayout()
  4.         layout.image = image
  5.         layout.caption = "Stepper Value"
  6.         let message = MSMessage()
  7.         message.layout = layout
  8.         message.url = URL(string: "emptyURL")  
  9.         conversation.insert(message, completionHandler: { (error: NSError?) in
  10.             print(error)
  11.         })
  12.     }
  13. }
You will see that with this code, we firstly create the message layout and set the image and caption properties. Next, we create our MSMessage object to insert into the conversation.

Please note that for iMessage to process your custom message correctly, you must set a layout and url for your message. This url is intended to link to a web page of some sort where macOS users can also view your custom iMessage content. For this simple example, however, we just created a basic url from a string.

Lastly, we insert the message into the current active conversation. Calling this method does not actually send the message, though—instead it puts your message in the user's entry field so that they can press send themselves.

Build and run your new app once again, and you will see an interface similar to the following:


Once you press the Create Message button, you should then also see the message layout bubble shown in the entry field and available to send:


Conclusion

In this tutorial, I introduced you to the new Messages framework in iOS 10, which allows you to create sticker packs and applications to integrate with iMessage. We covered the basic classes you need to be aware of, including MSStickerBrowserViewController, MSConversation, MSMessage, and MSTemplateMessageLayout.

The Messages framework provides APIs to give you a large amount of control over your iMessage apps. For further reading, I would recommend checking out Apple's Messages Framework Reference.
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 Message Extension App Reskinning without Coding

iOS 10 & Swift 3: From Beginner to Paid Professional

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

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



No comments:

Post a Comment