How to use GETURL in the class (AS3) - actionscript-3

I use this code but after publish when I open my file automatically 2 internet browser (www.example.com) are open
package {
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
public class bAEForm extends SimpleButton {
public function bAEForm() {
var url:String = "http://www.google.com";
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
variables.exampleSessionId = new Date().getTime();
variables.exampleUserLabel = "guest";
request.data = variables;
request.method = URLRequestMethod.POST;
navigateToURL(request);
}
}
}
I want, when I press my button then inter browser (www.example.com) should be open

if you want to navigate to URL when the button is clicked you code should something like this:
package {
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.events.MouseEvent;
public class bAEForm extends SimpleButton {
public function bAEForm() {
this.addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(event:MouseEvent)
{
var url:String = "http://www.google.com";
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
variables.exampleSessionId = new Date().getTime();
variables.exampleUserLabel = "guest";
request.data = variables;
request.method = URLRequestMethod.POST;
navigateToURL(request);
}
}
}
You can't use navigateToURL function in the constructor

As far as I understand your problem :
You don't want the browsers to be already open but on click of some button.
If that is the case, Currently navigateToURL(request); is in the constructor of bAEForm class.
Move it into a click event, Something like this :
myButton.addEventListener(MouseEvent.MOUSE_CLICK,
function(e) { navigateToURL(request); }, false,0,true);
where myButton is the button instance on click of which you want the browser to open.

Related

Actionscript Firebase POSTing, Error #2032

I am trying to POST to my firebase account, but I can't seem to figure out why it's not letting me. I can switch the POST to a GET and trace out the data I'm trying to get, but when I POST I get en error.
Code:
package
{
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.net.navigateToURL;
import flash.net.URLLoaderDataFormat;
//import flash.system.Security;
/**
* ...
* #author M
*/
public class FireBaseConnector
{
public function FireBaseConnector()
{
//Security.loadPolicyFile("https://demo.firebaseio-demo.com/crossdomain.xml");
trace("trying to post");
var url:String = 'https://[myURL].firebaseio.com/userData.json';
var req:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
variables.name = "alan"
req.data = variables;
req.method = URLRequestMethod.POST;
var l:URLLoader = new URLLoader()
//l.dataFormat = URLLoaderDataFormat.TEXT;
l.addEventListener(IOErrorEvent.IO_ERROR, onError);
l.addEventListener(Event.COMPLETE, handleResults);
l.load(req);
}
public function onError(e:IOErrorEvent):void {
trace("Error! " + e.text);
}
public function handleResults(e:Event):void {
trace("response" + e.target.data as String);
}
}
}
My output is:
[Starting debug session with FDB]
running
trying to post
Error! Error #2032: Stream Error. URL: https://resplendent-fire-2464.firebaseio.com/userData/.json
closing time!
closing time!
If i switch to GET my output is:
[Starting debug session with FDB]
running
trying to post
response{"dave":{"id":"678","name":"dave"},"mike":{"name":"mike"},"miles":{"id":"456","name":"miles"}}
closing time!
closing time!
That tells me I have the url right, but I have some permissions problem or something when trying to post. Maybe I have the variables sending improperly? I've made sure my Flash debugger is on the accepted app list in my Firewall.
I'm running Windows 10 and FlashDevelop JRE 1.6 Flex 4.6 Air 18
To send a POST request to the Firebase REST API you need to send the data JSON encoded:
var urlVars:Object = new Object();
urlVars.name = nameTxt.text;
urlVars.lastname = lastNameTxt.text;
var request:URLRequest = new URLRequest(FIREBASEURL);
request.data = JSON.stringify(urlVars);
request.method = URLRequestMethod.POST;
var firebaseLoader:URLLoader = new URLLoader();
firebaseLoader.addEventListener(flash.events.Event.COMPLETE, function():void
{
trace(firebaseLoader.data);
});
firebaseLoader.load(request);
I try this code can work
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
var urlVars:Object = new Object();
urlVars.name = "111111";
var url:URLLoader=new URLLoader();
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var req:URLRequest = new URLRequest( "https://[myURL].firebaseio.com/userData.json" );
req.method = URLRequestMethod.POST;
req.data = JSON.stringify(urlVars);
url.load(req);
url.addEventListener(Event.COMPLETE,urlCompelte)
function urlCompelte(e:Event){
trace(e.target.data);//{"name":"-Ka6PGZc_hY-sfJJqeVS"}
}

Video not showing using netstream(bytes)

im working on video streaming i have a php api that return the video and then play it using byte array,but video is not showing, but when i look at the trace is hows the downloaded bytes and bytesloaded.Can you give me idea what i'm doing wrong i'm new in actionscript.
import flash.display.Sprite;
import flash.events.NetStatusEvent;
import flash.events.ProgressEvent;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.NetStreamAppendBytesAction;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.utils.ByteArray;
var video:Video;
var video_nc:NetConnection;
var video_ns:NetStream;
var video_stream:URLStream;
video_nc = new NetConnection();
video_nc.connect(null);
video_ns = new NetStream(video_nc);
video_ns.client = this;
video_ns.addEventListener(NetStatusEvent.NET_STATUS, ns_statusHandler);
video = new Video(1280, 720);
video.attachNetStream(video_ns);
video.smoothing = true;
video_ns.play(null);
video_ns.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
video_stream = new URLStream();
video_stream.addEventListener(ProgressEvent.PROGRESS, videoStream_progressHandler);
video_stream.load(new URLRequest("https://www.xxxx.com/test.php"));
addChild(video);
function ns_statusHandler(event:NetStatusEvent):void
{
trace(event.info.code);
trace("zzz");
}
function videoStream_progressHandler(event:ProgressEvent):void
{
trace(event.bytesLoaded);
var bytes:ByteArray = new ByteArray();
video_stream.readBytes(bytes);
video_ns.appendBytes(bytes);
//trace(bytes);
}

Audio upload not working on server

I have an app which records and upload mic input encoding in mp3.
When I test locally, in Flash IDE, it works fine, my audio file is uploaded.
What I have tried:
All my files are on swf_dir (see in the code below)
My embed tag already have allowScriptAcess set to always;
Already put a generic crossdomain.xml in my host root and in swf_dir;
My main class already load a policy file and allow all domains (even this being unnecessary, because it's in the same server): system.security.loadPolicyFile("http://www.host.com/swf_dir/crossdomain.xml") and system.Security.allowDomain("*")
Here is the upload/encode class.
package
{
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
import org.bytearray.micrecorder.encoder.WaveEncoder;
import fr.kikko.lab.ShineMP3Encoder;
/**
* ...
* #author Marcelo de Assis
*/
public class Mp3Helper extends EventDispatcher
{
var loader:URLLoader = new URLLoader();
var LOCAL_PATH:String = "http://www.host.com/swf_dir/upload.php"; // URL used to test on Flash IDE
var PRODUCTION_PATH:String = "upload.php"; // URL used to test on server
var mp3Encoder:ShineMP3Encoder;
var urlRequest:URLRequest = new URLRequest();
var urlLoader:URLLoader = new URLLoader();
public function Mp3Helper()
{
urlRequest.url = PRODUCTION_PATH;
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
}
function upload_s(soundByteArray: ByteArray)
{
var waveEncoder:WaveEncoder = new WaveEncoder();
var wavData:ByteArray = waveEncoder.encode(soundByteArray, 1);
mp3Encoder = new ShineMP3Encoder(wavData);
mp3Encoder.addEventListener(Event.COMPLETE, mp3EncodeComplete);
mp3Encoder.start();
}
function mp3EncodeComplete(event: Event) : void
{
urlRequest.data = UploadPostHelper.getPostData("audio.mp3", mp3Encoder.mp3Data);
urlLoader.load(urlRequest);
urlLoader.addEventListener(Event.COMPLETE, loaderCompleted);
}
private function loaderCompleted(event: Event):void
{
dispatchEvent(event);
var fileLoader: URLLoader = URLLoader(event.target);
trace("loaderCompleted: ", fileLoader.data);
}
}
}
In case of URLLoader security error try to turn on policy logging (PolicyFileLog = 1) in mm.cfg file (check out this article where to locate mm.cfg file in your OS http://jpauclair.net/2010/02/10/mmcfg-treasure/, for win7 the default log location is C:\Users\user\AppData\Roaming\Macromedia\Flash Player\Logs\policyfiles.txt), it will helps in case of Socket as well.

Showing main menu over objects / movieclips?

I am creating a game in Flash and I am creating a main menu for the game (With buttons like 'Play', 'How to Play', 'Hiscores' etc.) and was wondering what is the best way to go about it?
All of my Actionscript code is in external .as files and I've used classes throughout but I was having trouble figuring out how to get it so that the menu will be shown as soon as the game is ran. The main problem is that there are timers in my game that have event handlers attached to them and I was trying to think of the best way to essentially stop these timers until the user actually clicks 'Play', otherwise the objects spawn over the top of the menu and the timer ticks down.
Would stopping the timers but then adding an event handler to the play button to start the timers be a good idea? I am trying to figure out the best way to do this for future reference.
Thank you for any assistance.
Edit: Tried Cherniv's advice, getting some errors.
Main.as:
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.ui.Mouse;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.LoaderContext;
import flash.display.Sprite;
import flash.net.Socket;
public class Main extends MovieClip {
public static var gameLayer:Sprite = new Sprite;
public static var endGameLayer:Sprite = new Sprite;
public static var menuLayer:Sprite = new Sprite;
public var gameTime:int;
public var levelDuration:int;
public var crosshair:crosshair_mc;
static var score:Number;
var enemyShipTimer:Timer;
var enemyShipTimerMed:Timer;
var enemyShipTimerSmall:Timer;
static var scoreHeader:TextField = new TextField();
static var scoreText:TextField = new TextField();
static var timeHeader:TextField = new TextField();
static var timeText:TextField = new TextField();
public function Main()
{
var mainMenu:myMenu = new myMenu;
addChild(gameLayer);
addChild(endGameLayer);
addChild(menuLayer);
playBtn.addEventListener(MouseEvent.CLICK, startButtonPressed);
}
function startButtonPressed(e:Event)
{
levelDuration = 30;
gameTime = levelDuration;
var gameTimer:Timer = new Timer(1000,levelDuration);
gameTimer.addEventListener(TimerEvent.TIMER, updateTime);
gameTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timeExpired)
gameTimer.start();
scoreHeader = new TextField();
scoreHeader.x = 5;
scoreHeader.text = String("Score: ");
gameLayer.addChild(scoreHeader);
scoreText = new TextField();
scoreText.x = 75;
scoreText.y = 0;
scoreText.text = String(0);
gameLayer.addChild(scoreText);
timeHeader = new TextField();
timeHeader.x = 490;
timeHeader.y = 0;
timeHeader.text = String("Time: ");
gameLayer.addChild(timeHeader);
timeText = new TextField();
timeText.x = 550;
timeText.y = 0;
timeText.text = gameTime.toString();
gameLayer.addChild(timeText);
var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
scoreHeader.setTextFormat(scoreFormat);
scoreText.setTextFormat(scoreFormat);
timeHeader.setTextFormat(scoreFormat);
timeText.setTextFormat(scoreFormat);
enemyShipTimer = new Timer(2000);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();
enemyShipTimerMed = new Timer(2500);
enemyShipTimerMed.addEventListener("timer", sendEnemyMed);
enemyShipTimerMed.start();
enemyShipTimerSmall = new Timer(2750);
enemyShipTimerSmall.addEventListener("timer", sendEnemySmall);
enemyShipTimerSmall.start();
crosshair = new crosshair_mc();
gameLayer.addChild(crosshair);
crosshair.mouseEnabled = crosshair.mouseChildren = false;
Mouse.hide();
gameLayer.addEventListener(Event.ENTER_FRAME, moveCursor);
resetScore();
}
function sendEnemy(e:Event)
{
var enemy = new EnemyShip();
gameLayer.addChild(enemy);
gameLayer.addChild(crosshair);
}
function sendEnemyMed(e:Event)
{
var enemymed = new EnemyShipMed();
gameLayer.addChild(enemymed);
gameLayer.addChild(crosshair);
}
function sendEnemySmall(e:Event)
{
var enemysmall = new EnemyShipSmall();
gameLayer.addChild(enemysmall);
gameLayer.addChild(crosshair);
}
static function updateScore(points)
{
score += points;
scoreText.text = String(score);
var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
scoreHeader.setTextFormat(scoreFormat);
scoreText.setTextFormat(scoreFormat);
}
static function resetScore()
{
score = 0;
scoreText.text = String(score);
}
function updateTime(e:TimerEvent):void
{
trace(gameTime);
// your class variable tracking each second,
gameTime--;
//update your user interface as needed
var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
timeText.defaultTextFormat = scoreFormat;
timeText.text = String(gameTime);
}
function timeExpired(e:TimerEvent):void
{
var gameTimer:Timer = e.target as Timer;
gameTimer.removeEventListener(TimerEvent.TIMER, updateTime)
gameTimer.removeEventListener(TimerEvent.TIMER, timeExpired)
// do whatever you need to do for game over
}
function moveCursor(event:Event)
{
crosshair.x=mouseX;
crosshair.y=mouseY;
}
}
}
Menu.as:
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.ui.Mouse;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.LoaderContext;
import flash.display.Sprite;
import flash.net.Socket;
public class Menu extends MovieClip
{
var mainMenu:Menu = new Menu();
Main.menuLayer.addChild(myMenu);
playBtn.addEventListener(MouseEvent.CLICK, playBtnPressed);
function playBtnPressed()
{
Main.menuLayer.removeChild(myMenu);
dispatchEvent(new Event("playButtonPressed"))
}
}
My menu is a movieclip named myMenu and the class is set as Menu but I get errors such as:
Main.as, Line 50 1120: Access of undefined property playBtn
I gave the button an instance name of playBtn before I converted the menu to a movieclip so not sure what's going on there. I'm probably missing something really easy but it's a bit confusing for me after typing all day.
If you have all of your initialization stuff (including timers initializations) in Main constructor function , so you need to split it to two functions , Main constructor will show the menu , and "start" button will fire the second function , that will include all the initialization stuff

AIR: how to use FileReference.upload() with POST-based web services (AS3)

I can't seem to get this little AIR app I'm making to work right. There is a single button on the stage, and when the user presses it they are presented with a file browser (FileReference.browse() function). When they select an image file, I want the image to be uploaded to the site imgur.com (http://www.api.imgur.com for those interested).
I'm getting a response from imgur, so I know my app is connecting, but it's returning an error, "No image data was sent to the upload API". Any help is greatly appreciated! (Also I do have an API key, just removed it from this post for obvious reasons :) )
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
public class Document extends MovieClip
{
//file browser var
var myFileReference:FileReference = new FileReference();
//file loader var
private var loader:URLLoader;
//string constants
private const API_KEY:String = "******REMOVED*******";
private const UPLOAD_URL:String = "http://api.imgur.com/2/upload.xml";
public function Document()
{
// constructor code
browse_btn.addEventListener(MouseEvent.CLICK, browse);
}
function browse(e:MouseEvent)
{
var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
myFileReference.browse([imagesFilter]);
myFileReference.addEventListener(Event.SELECT, selectHandler);
myFileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
}
function selectHandler(e:Event):void
{
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var params:URLVariables = new URLVariables();
params.date = new Date();
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
//request.contentType = "application/octet-stream";
request.contentType = "multipart/form-data";
request.method = URLRequestMethod.POST;
request.data = params;
myFileReference.upload(request);
try
{
myFileReference.upload(request);
}
catch (error:Error)
{
trace("Unable to upload file.");
}
}
function responseHandler(e:DataEvent):void
{
trace("responseHandler() initaialized");
var res:XML = XML(e.data);
trace(res);
}
}
}
there's actually an example for AS3 on their site:
package
{
import com.adobe.images.PNGEncoder;
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.SecurityErrorEvent;
import flash.events.IOErrorEvent
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
public class ImgurExample
{
private var loader:URLLoader;
private const API_KEY:String = "<api key>";
private const UPLOAD_URL:String = "http://api.imgur.com/2/upload.xml";
public function ImgurExample() {
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, onCookieSent);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
// Create a bitmapdata instance of a movieclip on the stage.
var mc:MovieClip;
var b:BitmapData = new BitmapData(mc.width, mc.height, true);
b.draw(mc);
var png:ByteArray = PNGEncoder.encode(b);
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
request.data = png; // set the data object of the request to your image.
loader.load(request);
}
// privates
private function onSend(e:Event):void {
var res:XML = new XML(unescape(loader.data));
trace(res);
}
private function onIOError(e:IOErrorEvent):void {
trace("ioErrorHandler: " + e);
// Handle error
}
private function onSecurityError(e:SecurityErrorEvent):void {
trace("securityErrorHandler: " + e);
// handle error
}
}
}
http://api.imgur.com/examples