Share screenshot to facebook/twitter using cocos2d-x on IOS - cocos2d-x

I am porting my game from cocos2d (obj-c) to cocos2d-x 2.x (c++) but i am really struggling with getting the social features to work. Is it possible in any way to use the code below which works flawless in native objective-c and cocos2d.
Take screenshot
- (UIImage*) takeScreenShot
{
[CCDirector sharedDirector].nextDeltaTimeZero = YES;
CGSize winSize = [CCDirector sharedDirector].winSize;
CCLayerColor* blankLayer = [CCLayerColor layerWithColor:ccc4(255, 255, 255, 0) width:winSize.width height:winSize.height];
blankLayer.position = ccp(winSize.width/2, winSize.height/2);
CCRenderTexture* rtx = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];
[rtx begin];
[blankLayer visit];
//[[[CCDirector sharedDirector] runningScene] visit];
[layer_main visit];
[rtx end];
return [rtx getUIImage];
}
Post on facebook
- (void)share_score_facebook: (id) sender{
if (SYSTEM_VERSION_LESS_THAN(#"6.0")){
[AppVariables showAlert:#"Outdated iOS" message:#"You must have atleast iOS 6.0 to use the social features.\nPlease update to a newer iOS."];
return;
}
[[CCDirector sharedDirector] pause];
[[CCDirector sharedDirector] stopAnimation];
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
UIImage * screenshot = [self takeScreenShot];
SLComposeViewController *faceBookPost = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[faceBookPost setInitialText:[NSString stringWithFormat:#"Game on! Just scored %d on Game. Can you Beat it?",total_score]];
[faceBookPost addImage:screenshot];
[faceBookPost addURL:[NSURL URLWithString:#"URL_HERE"]];
[[app navController] presentViewController:faceBookPost animated:YES completion:nil];
faceBookPost.completionHandler = ^(SLComposeViewControllerResult result)
{
[[CCDirector sharedDirector] resume];
[[CCDirector sharedDirector] startAnimation];
[[app navController] dismissViewControllerAnimated:YES completion:nil];
};
}

You can compile any Objective-C code with cocos2d-x, but you need modify your code to adapt for cocos2d-x API. You want to take a screenshot and post it to Facebook, right? How about using the following instead of your Objective-C code?
Cocos2d-x v3.2-alpha0 Released! - Added utils::captureScreen to take screeshot
v3.2-alpha0 ccUtils.cpp seems it is able to work on earlier version of cocos2d-x
Screw - aims to bring native Facebook SDK functionalities to cocos2d-x

Related

Phaser HTML5 app cannot play sound after porting by Phonegap Cloud Build

This's a simple Phaser audio example. It works well on my Android web browser. However, it's muted after porting to Android app by Phonegap cloud build.
I know how to play sound (and loop) in Phonegap app (How to loop a audio in phonegap?) but don't know how to apply it into the Phaser JS framework.
Here's the ported app. I can install and run it but without sound. Do I miss something or Phonegap Cloud Build does support the WebAudio in Phaser JS?
https://build.phonegap.com/apps/1783695/
My config.xml is:
<?xml version="1.0" encoding="UTF-8" ?>
<widget id="com.phaser.phasersound" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
<name>Phaser sound complete</name>
<description>
Phaser sound phonegap
</description>
<gap:plugin name="org.apache.cordova.media" />
<icon src="icon.png" />
<preference name="splash-screen-duration" value="1"/>
<!--
If you do not want any permissions to be added to your app, add the
following tag to your config.xml; you will still have the INTERNET
permission on your app, which PhoneGap requires.
-->
<preference name="permissions" value="none"/>
</widget>
The source code is: (I changed the local audio files from local to github links to run on code snippet)
var game = new Phaser.Game(600, 800, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });
function preload() {
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
//have the game centered horizontally
game.scale.pageAlignHorizontally = true;
game.scale.pageAlignVertically = true;
game.stage.backgroundColor = '#414040';
// I changed the local audio files from local to github links to run on code snippet
/*
game.load.audio('explosion', 'assets/audio/SoundEffects/explosion.mp3');
game.load.audio('sword', 'assets/audio/SoundEffects/sword.mp3');
game.load.audio('blaster', 'assets/audio/SoundEffects/blaster.mp3');
*/
game.load.audio('explosion', 'https://raw.githubusercontent.com/nguoianphu/phaser-sound-complete-phonegap/master/www/assets/audio/SoundEffects/explosion.mp3');
game.load.audio('sword', 'https://raw.githubusercontent.com/nguoianphu/phaser-sound-complete-phonegap/master/www/assets/audio/SoundEffects/sword.mp3');
game.load.audio('blaster', 'https://raw.githubusercontent.com/nguoianphu/phaser-sound-complete-phonegap/master/www/assets/audio/SoundEffects/blaster.mp3');
}
var explosion;
var sword;
var blaster;
var text;
var text1;
var text2;
var text3;
function create() {
var style = { font: "65px Arial", fill: "#52bace", align: "center" };
text = game.add.text(game.world.centerX, 100, "decoding", style);
text.anchor.set(0.5);
explosion = game.add.audio('explosion');
sword = game.add.audio('sword');
blaster = game.add.audio('blaster');
// Being mp3 files these take time to decode, so we can't play them instantly
// Using setDecodedCallback we can be notified when they're ALL ready for use.
// The audio files could decode in ANY order, we can never be sure which it'll be.
game.sound.setDecodedCallback([ explosion, sword, blaster ], start, this);
}
var keys;
function start() {
text.text = 'Press 1, 2 or 3';
var style = { font: "48px Arial", fill: "#cdba52", align: "center" };
text1 = game.add.text(game.world.centerX, 250, "Blaster: Stopped", style);
text1.anchor.set(0.5);
text2 = game.add.text(game.world.centerX, 350, "Explosion: Stopped", style);
text2.anchor.set(0.5);
text3 = game.add.text(game.world.centerX, 450, "Sword: Stopped", style);
text3.anchor.set(0.5);
explosion.onStop.add(soundStopped, this);
sword.onStop.add(soundStopped, this);
blaster.onStop.add(soundStopped, this);
keys = game.input.keyboard.addKeys({ blaster: Phaser.Keyboard.ONE, explosion: Phaser.Keyboard.TWO, sword: Phaser.Keyboard.THREE });
keys.blaster.onDown.add(playFx, this);
keys.explosion.onDown.add(playFx, this);
keys.sword.onDown.add(playFx, this);
// And for touch devices you can also press the top, middle or bottom of the screen
game.input.onDown.add(onTouch, this);
}
function onTouch(pointer) {
var b = game.height / 3;
if (pointer.y < b)
{
playFx(keys.blaster);
}
else if (pointer.y > b * 2)
{
playFx(keys.sword);
}
else
{
playFx(keys.explosion);
}
}
function playFx(key) {
switch (key.keyCode)
{
case Phaser.Keyboard.ONE:
text1.text = "Blaster: Playing";
blaster.play();
break;
case Phaser.Keyboard.TWO:
text2.text = "Explosion: Playing";
explosion.play();
break;
case Phaser.Keyboard.THREE:
text3.text = "Sword: Playing";
sword.play();
break;
}
}
function soundStopped(sound) {
if (sound === blaster)
{
text1.text = "Blaster: Complete";
}
else if (sound === explosion)
{
text2.text = "Explosion: Complete";
}
else if (sound === sword)
{
text3.text = "Sword: Complete";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.4.4/phaser.js"></script>
UPDATE 2015-12-01
Here is my completed source code. It has both .mp3 and .ogg sound files. You can play them on Android native browser (tested on 4.4.4 Samsung E5).
Source: https://github.com/nguoianphu/phaser-sound-complete-phonegap
Here is the ported app on Phonegap. It can display the screen but can't play sounds.
https://build.phonegap.com/apps/1783695/builds
You are trying to play the audio with the webview library. It is likely using the HTML5 API for audio or webaudio. If it is neither of these, then you need to ask the author.
Next, it is not best practice to use external source (http:). Your assests (javascript, css, audio files, etc) should live on the device. If you load files from the web, then the sound quality could be poor (or the audio may not play at all - see whitelist below). Load from the device.
Android 4.4.4 is Kitkat. The standard webview library was exchanged for the chromium version. This means your audio library might be confused about this or you need to give the library knowledge about this library. This also means your code may not work on devices before 4.4.4. (Mostly, because you cannot test it.)
The link you point to is likely using the core media plugin, even though they dont say so. In addition, the post is over 3 years old. Many thing have changed since them. NOTE: you have installed the media plugin in your config.xml. This is likely why your loop works.
You should start over. You've made many errors. In addition, to all that you have, You will need to implement the whitelist plugin (if you are going to import files, or talk to the network).
FIRST TRY this sample app - example plays on Android and iOS. You can download the Android version and test it. The iOS version requires I have your UUID compiled in.
There are 16 audio plugins you can choose from. I know a few do real time audio playback and have better control than the "core" plugin.
You should read:
Top Mistakes by Developers new to Cordova/Phonegap - read the bold sentences.
HOW TO apply the Cordova/Phonegap the whitelist system
HOWTO Core Plugins Setup
Phonegap--Generic-Boilerplate7 - just wrote this. It works.
Phonegap Demo Apps
Phonegap-Media-Test - source code for the example that plays on Android and iOS. You can download the Android version and test it.
UPDATE: 2015-12-01 - 2am Previously, I had forgotten to add a wild-card (*) to the CSP meta tag. I am now including this. This meta tag should be added to the header of the index.html file that is playing the audio.
NOTE YOUR APP IS NOW INSECURE. IT IS UP TO YOU TO SECURE YOUR APP.
<meta http-equiv="Content-Security-Policy"
content="default-src *;
style-src * 'self' 'unsafe-inline' 'unsafe-eval';
script-src * 'self' 'unsafe-inline' 'unsafe-eval';">
UPDATE: 2015-12-01 - 3pm
#Tuan, I've applied all the fixes as outlined in
HOW TO apply the Cordova/Phonegap the whitelist system
HOWTO Core Plugins Setup
Phonegap--Generic-Boilerplate7 - just wrote this. It works.
The audio is now working on my Android LG Leon/Android 5.1.1
Truthfully, I would never do this on my own, but your code had enough working that after I tested it on my firefox(v34) browser, I was fairly certain it would work.
UPDATE: 2016-04-15
The code has been removed. Ask in the comments, if you need code.
There should be enough code in place for you to work off of.
- Code
- Working Android App
- Phonegap Build Documentation

How to add UIViewcontroller to a spritebuilder cocos2d 3.x project?

same as the title above. Please provide helpful link if possible. Googled it but did not find anything regarding Spritebuilder and uiviewcontroller integration. As it is needed for me to set up Google Analytics screen tag method inside viewDidLoad() method.
Thanks
This code will allow you to present UIViewController above your CCScene.
MyViewController *vc=[[MyViewController alloc]initWithNibName:#"MyViewController" bundle:nil];
UIViewController *rootViewController=[UIApplication sharedApplication].keyWindow.rootViewController;
if (!rootViewController) {
//some devices have no root view controller so... this code fix the issue
[[CCDirector sharedDirector]presentModalViewController:vc animated:YES];
}else{
[rootViewController presentViewController:vc animated:NO completion:nil];
}

FacebookLikeView crashing all the time iOS

I've been using the FacebookLikeView classes in a lot of apps to enable Facebook profile liking within apps. Recently the code has started crashing in every app I've put it in. The Facebook app is setup correctly and everything. This is the line it is giving an EXC_BAD_ACCESS on:
else if ([fbEvent isEqualToString:#"xfbml.render"] && [_delegate respondsToSelector:#selector(facebookLikeViewDidRender:)])
[_delegate facebookLikeViewDidRender:self];
And it's being implemented like so:
_facebook = [[Facebook alloc] initWithAppId:fbAppID andDelegate:self];
self.facebookLikeView = [[FacebookLikeView alloc]init];
[self.facebookLikeView setFrame:CGRectMake(117, 140, 82, 19)];
self.facebookLikeView.delegate = self;
self.facebookLikeView.href = [NSURL URLWithString:user];
self.facebookLikeView.layout = #"button_count";
self.facebookLikeView.showFaces = NO;
[self.facebookLikeView load];
You should set your facebookLikeView to nil in your dealloc method or viewdidunload method

What is the proper way to unload views in iOS 6 in a memory warning (Apple doc flaw)?

In iOS 6, viewWillUnload and viewDidUnload are deprecated and UIViewControllers no longer unload views that are not visible on screen during a memory warning. The View Controller Programming Guide has an example of how to manually restore this behavior.
Here is the code sample:
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Add code to clean up any of your own resources that are no longer necessary.
if ([self.view window] == nil)
{
// Add code to preserve data stored in the views that might be
// needed later.
// Add code to clean up other strong references to the view in
// the view hierarchy.
self.view = nil;
}
}
Below the code sample is the following note:
The next time the view property is accessed, the view is reloaded
exactly as it was the first time.
There is an obvious flaw here. If a view controller that has not loaded its view receives a memory warning it will load its view in the line if ([self.view window] == nil) and then proceed to clean up and release it again. At best, this is inefficient. At worst, it makes the memory conditions worse if a complex view hierarchy and supporting data are loaded. I verified this behavior in the iOS simulator.
I can certainly code around this but seems odd for Apple docs to have such an error. Am I missing something?
The correct check in a view controller for the view being loaded and on screen is:
if ([self isViewLoaded] && [self.view window] == nil)
My full solution in iOS 6 to have a view controller unload views and cleanup similar to iOS 5 is the following:
// will not be called in iOS 6, see iOS docs
- (void)viewWillUnload
{
[super viewWillUnload];
[self my_viewWillUnload];
}
// will not be called in iOS 6, see iOS docs
- (void)viewDidUnload
{
[super viewDidUnload];
[self my_viewDidUnload];
}
// in iOS 6, view is no longer unloaded so do it manually
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
if ([self isViewLoaded] && [self.view window] == nil) {
[self my_viewWillUnload];
self.view = nil;
[self my_viewDidUnload];
}
}
- (void)my_viewWillUnload
{
// prepare to unload view
}
- (void)my_viewDidUnload
{
// the view is unloaded, clean up as normal
}

ActionScript / AIR - Determine Device Profile At Runtime?

i'm developing an application for both desktop and mobile devices and would like to use the same code base for each build.
i want to employ cacheAsBitmapMatrix on some of my display objects, but cacheAsBitmapMatrix throws an error if it's included in an AIR application with a device profile other than mobileDevice or extendedMobileDevice.
something like the following would be ideal:
if (cacheAsBitmapMatrix.isSupported)
myDisplayObject.cacheAsBitmapMatrix = new Matrix();
update using try/catch:
try {myDisplayObject.cacheAsBitmapMatrix = new Matrix();}
catch(error:Error) {}
finally {myDisplayObject.cacheAsBitmap = true;}
update:
except for television profiles, this should work as well to distinguish between mobile and desktop:
//Resoslve Profile
if (Capabilities.os.indexOf("Windows") > -1 || Capabilities.os.indexOf("Mac") > -1 || Capabilities.os.indexOf("Linux") > -1)
trace("Desktop Profile");
else
trace("Mobile Profile");
update 2:
it seems the easiest way, and perhaps the most common way to determine the profile at runtime is to call:
NativeWindow.isSupported;
from the flash.display.NativeWindow documentation:
AIR profile support: This feature is
supported on all desktop operating
systems, but is not supported on
mobile devices or AIR for TV devices.
You can test for support at run time
on desktop devices using the
NativeWindow.isSupported property. See
AIR Profile Support for more
information regarding API support
across multiple profiles.
update 3:
while testing this on the BlackBerry PlayBook simulator, NativeWindow was supported. i haven't tested this on the device to know if it's was just supported on the simulator or not. i've since started using the following to determine the difference between mobile and desktop profiles:
if (
(Capabilities.os.toLowerCase().indexOf("mac") == -1) &&
(Capabilities.os.toLowerCase().indexOf("windows") == -1) &&
(Capabilities.os.toLowerCase().indexOf("linux") == -1)
)
deviceIsMobile = true;
This document specifies device capabilities for different profiles. Since cacheAsBitmapMatrix has no availability getter listed, you'll need to check it yourself once. It must be easy to do with try/catch block.
Edit: I'll try to illustrate what I meant under "check once":
public class Capabilities2
{
private static var cacheAsBitmapMatrixChecked:Boolean;
private static var cacheAsBitmapMatrixStatus:Boolean;
public static function get cacheAsBitmapMatrixIsSupported():Boolean
{
if (cacheAsBitmapMatrixChecked) return cacheAsBitmapMatrixStatus;
var test:Sprite = new Sprite();
try
{
text.cacheAsBitmapMatrix = new Matrix();
cacheAsBitmapMatrixStatus = true;
}
catch (error:Error)
{
cacheAsBitmapMatrixStatus = false;
}
cacheAsBitmapMatrixChecked = true;
return cacheAsBitmapMatrixStatus;
}
}
Get current profile might be cleaner solution, but I don't know how to do it. Another 'idea': using document above, test capabilities and deduce profile from results, like in Einstein riddle :)
For runtime checking if your application is on mobile or on web you can also use "Capabilities.playerType"
if (Capabilities.playerType == "Desktop") {
trace ("running on mobile");
}
else {
trace ("running on web");
}