viernes, 25 de enero de 2013

Sending mail inside the app with Cocos2D

First of all, I would like to say that if you are looking for a way of sending mails without using the Apple's mail composer you are not looking in the proper site. However I had the same purpose at the beginning, but I didn't want to deal directly with the SMTP protocol and I couldn't find any supported library.

Instead of a custom mail scene, you are going to have the Apple's standard mail composer. Something like that:


Implementing this is not difficult using MFMailComposeViewController, but with Cocos2D you have to pay attention at several points.

The general idea is simple: create the composer, check if it can send mails, set the delegate, fill the mail and tell the controller to show the composer.

So, the steps to follow are;

  1. Add the MessageUI framework to the project.
  2. Make your class implement MFMailComposeViewController.
  3. Instantiate the mail composer
  4. Check if the device can send the mail. This checks whether the iPhone Mail app is synchronized with an account or not. In this last case, you should break here and show an error.
  5. Set the delegate to self. Your class now must contain the method mailComposeController:didFinishWithResult:error:
  6. Fill the mail with the subject, recipients, body...
  7. Tell the UI view controller to show the composer


The main problems with Cocos2D are the animation and that you don't work with view controllers, instead you have scenes, layers, ...
For the first problem, it's as easy as pausing the director before showing the composer and resuming it after the mail is sent.
For the controller issue, I found in the cocos-2d forum a solution which involved creating a view controller and setting the view to the openGL view. That worked pretty fine with iOS5, but arise a uncaught exception when testing in iOS6. More than one view controller cannot be associated with the same view.

I finally got to the solution, take the view controller, stored in the appDelegate (it implies a little modification in the appDelegate class), and use it to show the mail view.

Finally, the code should be like that:
Remark. All of this is assuming that you are working with cocos2d 1.x. This is reasonable assumption since the new version in cocos2d is quite recent, it has several changes from the older version and doesn't support iOS <4 or iPhone <3GS.
With Cocos2d 2.x and this documentation, I suppose (I haven't tried it yet) that the problem is no more there, because our SharedDirector will be itself our view controller (we don't need to ask the AppDelegate nor create the rootViewController variable)


No hay comentarios:

Publicar un comentario