I load an XML file with this simple Flash CS5 / ActionScript 3 program:
import flash.net.*;
var URL_REQUEST:URLRequest = new URLRequest('http://preferans.de/top-xml.php');
var URL_STREAM:URLStream = new URLStream();
var URL_VARS:URLVariables = new URLVariables();
var UPDATE_TIMER:Timer = new Timer(1000);
stop();
UPDATE_TIMER.addEventListener(TimerEvent.TIMER, handleTimer);
UPDATE_TIMER.start();
URL_REQUEST.method = URLRequestMethod.GET;
URL_REQUEST.data = URL_VARS;
URL_STREAM.addEventListener(IOErrorEvent.IO_ERROR, handleUserError);
URL_STREAM.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleUserError);
URL_STREAM.addEventListener(Event.OPEN, handleUserOpen);
URL_STREAM.addEventListener(ProgressEvent.PROGRESS, handleUserData);
URL_STREAM.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleUserStatus);
URL_STREAM.addEventListener(Event.COMPLETE, handleUserComplete);
URL_STREAM.load(URL_REQUEST);
function handleUserOpen(event:Event):void {
trace('handleUserOpen: ' + event);
}
function handleUserData(event:Event):void {
trace('handleUserData: ' + event);
}
function handleUserStatus(event:HTTPStatusEvent):void {
trace('handleUserStatus: ' + event.status);
}
function handleUserError(event:Event):void {
trace('handleUserError: ' + event);
}
function handleUserComplete(event:Event):void {
trace('handleUserComplete: ' + event);
try {
var str:String = URL_STREAM.readUTFBytes(URL_STREAM.bytesAvailable);
var xml:XML = new XML(str);
trace(xml);
} catch(e:Error){
trace('Invalid data: ' + e);
return;
}
}
function handleTimer(event:TimerEvent):void {
var now:int = getTimer();
trace(UPDATE_TIMER.currentCount + ' ' + now + ' ' + URL_STREAM.connected);
}
it works fine and I can see the XML content:
handleUserOpen: [Event type="open" bubbles=false cancelable=false eventPhase=2]
handleUserData: [ProgressEvent type="progress" bubbles=false cancelable=false eventPhase=2 bytesLoaded=2390 bytesTotal=2390]
handleUserStatus: 200
handleUserComplete: [Event type="complete" bubbles=false cancelable=false eventPhase=2]
<pref>
[ .... XML content .....]
</pref>
1 1054 true
2 2054 true
3 3054 true
4 4054 true
5 5054 true
.....
90 90054 true
91 91054 true
but I don't understand, why is URLStream.connected always true.
I even restart Apache at my web server, but it doesn't change anything.
I'm asking this question, because I plan implementing Comet-like (aka HTTP-push) calls in my program and need to know, if URLStream is still working/busy or if it is completed/interrupted and can be reused for a new load() call (and I don't want to introduce a workaround state variable for that).
Thank you!
Alex
I think with URLStream as long it accesses the file its connection stays established, even when it hasn't started downloading anything or has finished downloading something. So I think you have to .close() it manually in the .COMPLETE function after your done reading the values.
Related
i am attempting (for some time now) to upload a video to Facebook from an air for android app. i have recorded the video on the device, saved it to the device and have the path to the video stored in a string. i was advised to convert the video to byteArray and pass that into the FacebookMobile.uploadVideo method of the as3 Facebook api which i attempted to do but am getting a 353 You must select a video file to upload. error (from Facebook i presume).
file to byteArray
public function UICompleteHandler(event:MediaEvent):void
{
trace("Welcome back from the camera");
var media:MediaPromise = event.data;
trace("file info "+media.file.url + " - " + media.relativePath + " - " + media.mediaType);
filePath = media.file.url;
trace("Object encoding is: " + inBytes.objectEncoding + "\n\n" + "order file: \n\n");
readFileIntoByteArray(filePath, inBytes);
trace("length 1: "+inBytes.length);
trace("position 1: "+inBytes.position);
inBytes.position = 0; // reset position to beginning
inBytes.uncompress(CompressionAlgorithm.DEFLATE);
trace("position 2: "+inBytes.position);
inBytes.position = 0; //reset position to beginning
}
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = new File(fileName);
trace ("file to byte array "+ inFile.url);
trace ("file name var : "+fileName);
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
inStream.close();
}
Upload to Facebook(attempt)
public function handleUpload(ev:TouchEvent)
{
trace ("posting to facebook - FileName: "+ accessCamera.fileName + " - FilePath: " + accessCamera.filePath);
var params:Object ={
title:'test upload on FB api',
description:'test upload on FB api',
fileName: accessCamera.fileName,
video: accessCamera.inBytes
}
//trace ("params.video = "+params.video);
FacebookMobile.uploadVideo('me/videos', onComplete, params);
}
private function onComplete( result:Object, fail:Object ):void
{
trace("facebook post onComplete called" );
if (result)
{
//result.id is id of post that was just posted
trace ("great");
}
else if (fail)
{
trace("post Failed");
trace('code: '+fail.error.code);
trace('message: '+fail.error.message);
trace('type: '+fail.error.type);
}
}
when i uncomment the trace params.video i get a huge amount of random characters which i thought to be the data of the byteArray
any guidance or help from anyone would be appreciated
i am attempting to upload a video to facebook using the as3 api(FacebookMobile.uploadVideo) which accepts a video as either fieleReferance or byteArray. a followed the example # http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7d54.html for creating the byteArray i ma getting a 2058 error when uncompressing the byte array (this may be because i dident compress it but neither did adobe in the example).
if i comment this bit out i am getting an #353 You must select a video file to upload error from Facebook.
Byte Array Code:
public function UICompleteHandler(event:MediaEvent):void
{
trace("Welcome back from the camera");
var media:MediaPromise = event.data;
trace("file info "+media.file.url + " - " + media.relativePath + " - " + media.mediaType);
filePath = media.file.url;
trace("Object encoding is: " + inBytes.objectEncoding + "\n\n" + "order file: \n\n");
readFileIntoByteArray(filePath, inBytes);
trace("length 1: "+inBytes.length);
trace("position 1: "+inBytes.position);
inBytes.position = 0; // reset position to beginning
//inBytes.uncompress(CompressionAlgorithm.DEFLATE);
trace("position 2: "+inBytes.position);
inBytes.position = 0; //reset position to beginning
}
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = new File(fileName);
trace ("file to byte array "+ inFile.url);
trace ("file name var : "+fileName);
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
inStream.close();
}
Handle Upload Code:
public function handleUpload(ev:TouchEvent)
{
trace ("posting to facebook - FileName: "+ accessCamera.fileName + " - FilePath: " + accessCamera.filePath);
var params:Object ={
title:'test upload on FB api',
description:'test upload on FB api',
fileName: accessCamera.fileName,
video: accessCamera.inBytes
}
trace ("params.video = "+params.video);
FacebookMobile.uploadVideo('me/videos', onComplete, params);
}
private function onComplete( result:Object, fail:Object ):void {
trace("facebook post onComplete called" );
if (result)
{
//result.id is id of post that was just posted
trace ("great");
}
else if (fail)
{
trace("post Failed");
trace('code: '+fail.error.code);
trace('message: '+fail.error.message);
trace('type: '+fail.error.type);
}
}
when i trace out the params.video i get a load of random characters. the problem seems to be facebook dosnt appear to see the bytearray(if i even success fully created it) as a video.
Im trying too load new messages every second, but new messages are doubled everytime they are loaded, I suppose because the timer is completed before the php is executed?
so I tried to add
if (checker != "" + idstored + "done") {
checker = "" + idstored + "done";
so that once the timer completes, it changes the checker so that when the timer restarts and finishes again it would not execute again... but it stopped checking for all new messages... any tips??
var count:Timer = new Timer(1000, 1);
count.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
count.start();
var checker;
function onTimerComplete(event:TimerEvent):void{
if (checker != "" + idstored + "done") {
checker = "" + idstored + "done";
var variables_cc:URLVariables = new URLVariables();
var varSend_cc:URLRequest = new URLRequest("chat.php");
varSend_cc.method = URLRequestMethod.POST;
varSend_cc.data = variables_cc;
var varLoader_cc:URLLoader = new URLLoader;
varLoader_cc.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader_cc.addEventListener(Event.COMPLETE, completeHandler_cc);
function completeHandler_cc(event:Event):void{
if (event.target.data.statusline == "is_new") {
stored_id_txt.text = "" + event.target.data.stored_id;
status_txt.text = "" + event.target.data.statusline;
returnline.text = "" + event.target.data.returnBody;
checker.text = checker;
splitByDelimiter(event.target.data.returnBody);
idstored = event.target.data.stored_id;
checker = "refresh";
}
}}
// ready the last_refresh_time variable for sending to PHP
variables_cc.requester = "chat_check";
variables_cc.stored_id = idstored;
varLoader_cc.load(varSend_cc);
count.reset();
count.start();
}
You get errors becouse you sometimes try to start new download when the previous is not finished. It's not wise to do something latency dependent every 1 second real time. You need to start something, wait for it to finish, and then start it again.
removeEventListener of the timer after it launches (inside onTimerComplete function) and stop the timer and reset it. qddEventListener to the timer and start it after the data is downloaded (inside completeHangler_cc function).
i am having one form accepting json post in Asp.net which i need to call from Flash As3...
i am using below code to do that. I have seen some post in which they say its working fine.
But i am encountering below Error
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Here is my code.
var messages:Array = new Array ();
messages.push({"From":fromemailTxt.text,"To": ToemailTxt.text,"Body": BodyText.text,"Subject":SubjectText.text});
var JsonObj:String = JSON.encode(messages);
trace(JsonObj);
var variables:URLVariables=new URLVariables(JsonObj);
RequestURL= srvStringURL;
var JSONLoader:URLLoader = new URLLoader();
JSONLoader.dataFormat=URLLoaderDataFormat.TEXT;
JSONLoader.addEventListener(IOErrorEvent.IO_ERROR, GetBookmarkURLError, false, 0, true);
JSONLoader.addEventListener(Event.COMPLETE, parseBookmarkURLResult, false, 0, true);
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var request:URLRequest = new URLRequest(RequestURL);
request.requestHeaders.push(hdr);
request.data=variables;
request.method = URLRequestMethod.POST;
try
{
JSONLoader.load(request);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred."+error.errorID.toString());
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
catch (error:Error)
{
trace("Unable to load requested document.");
}
Anybody have any idea on this??
Thanks
The error is, because you are passing incorrect string to URLVariables constructor. Do not use URLVariables. Instead pass data as string: request.data=JsonObj;
Below is the code I am using to consume REST Web service and pass json parameter to service it shows. Error #2032: Stream Error.
Andy idea what is going wrong
var ldr:URLLoader = new URLLoader();
ldr.dataFormat = URLLoaderDataFormat.TEXT;
var strData:String = "{\"gparam\": [ {\"productid\": \"" + productId + "\"},{\"message\": \"" + mesage + "\"},{\"googleappid\": \"" + googleappid + "\"},{\"senderid\": \"" + senderid + "\"},{\"appname\": \"" + appName + "\"},{\"userid\": \"" + userId + "\"},{\"receiverid\": \"" + receiverId + "\"} ]}";
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
var req:URLRequest = new URLRequest("http://localhost/AndroidGCM/GCMNotification.svc/SendGCM");
req.requestHeaders.push(hdr);
req.method = URLRequestMethod.POST;
req.data = strData;
trace("data: " + req.data);
ldr.addEventListener(Event.COMPLETE,onComplete);
ldr.addEventListener(IOErrorEvent.IO_ERROR , onError);
ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR ,onSecurityErr);
ldr.load(req);
function onComplete(e:Event):void
{
trace("LOAD COMPLETE: " + ldr.data);
TextField(parMC.getChildByName("txtCheck")).appendText("\n LOAD COMPLETE: " + ldr.data);
}
function onSecurityErr(e:SecurityErrorEvent):void
{
trace("error: " + e.text );
}
function onError(e:IOErrorEvent):void
{
trace("error: " + e.toString());
}
I followed this tutorial Loading Facebook Profile Picture Into Flash SWF Using Graph API to get the users profile picture to show in my flash game, but I'm having some issues.
import com.facebook.graph.Facebook;
import com.facebook.graph.data.FacebookSession;
import com.facebook.graph.net.FacebookRequest;
import flash.events.Event;
import flash.events.IOErrorEvent;
//place your APP ID here
const APP_ID:String = "app_id";
//Initialize facebbok library
Facebook.init(APP_ID, HandleLogin);
function HandleLogin(response:Object, fail:Object):void
{
if(Facebook.getSession().accessToken)
{
LoadMyInfo();
LoadMyPicture();
}
}
function LoadMyInfo():void
{
Facebook.api("/me", MyInfoLoaded);
}
function MyInfoLoaded(response:Object, fail:Object):void
{
nameTextField.text = response.name;
}
function LoadMyPicture():void
{
debug.text = "Entered loadMyPicture() function ";
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, MyPictureLoaded, false, 0, true);
var request:URLRequest = new URLRequest("facebookProxy.php");
var variables:URLVariables = new URLVariables();
variables.path = Facebook.getImageUrl(String(Facebook.getSession().uid), 'large');
debug.appendText(" \nvariables.path: " + String(variables.path));
request.data = variables;
debug.appendText(" \nrequest.data: " + String(request.data))
loader.load(request);
debug.appendText(" \n" + String(loader.load(request)));
}
function MyPictureLoaded(event:Event):void
{
debug.appendText(" \nEntering MyPictureLoaded");
var loader:Loader = event.target.loader;
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, MyPictureLoaded);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, MyPictureLoadError);
var bitmap = Bitmap(loader.content);
bitmap.smoothing = true;
//Note: picturePlaceholder is just a blank movie clip on the Stage
bitmap.x = picturePlaceHolder.x;
bitmap.y = picturePlaceHolder.y;
bitmap.width = picturePlaceHolder.width;
bitmap.height = picturePlaceHolder.height;
picturePlaceHolder.addChild(bitmap);
debug.appendText(" \nBitmap is null: " + String(bitmap == null) +
" \nBitmap X: " + String(bitmap.x) + " Bitmap Y: " + String(bitmap.y) +
" \nBitmap width: " + String(bitmap.width) +
" \nBitmap height: " + String(bitmap.height))
}
function MyPictureLoadError(e:IOErrorEvent):void
{
debug.appendText("Loading Error");
}
This is what my code looks like after following the tutorials on the link above. With the debug I noticed that the function MyPictureLoaded is never called.
They never specified where I would call the function LoadMyPicture. I assumed it would go together with LoadMyInfo so I placed it there. They have a working example but no source code, so I'm hope someone here would shed some light on this.
EDIT 1
Here is what it looks like when I put it up on facebook. The last line debug.appendText(" \n" + String(loader.load(request))); is outputting undefined. I also made a change in the variables.path = Facebook.getImageUrl(String(Facebook.getSession().uid), 'large'); I added (String(), 'large') because in the docs it saying to pass strings into there. Edit: I realized adding String() is pointless.
var request:URLRequest = new URLRequest("facebookProxy.php");
Did you do the part of the tutorial that writes a server-side PHP proxy loader on your server?
If you don't have a file named facebookProxy.php on your server where you run this it won't work (the code is requesting "./facebookProxy.php" which probably doesn't exist). If you want to run this in the debugger on your local machine, you will need to make that file in the same directory as your swf and make sure you have apache/php running on your localhost.
If that's too much work for you, I would suggest following some of the examples from the API' project page: http://code.google.com/p/facebook-actionscript-api/downloads/detail?name=GraphAPI_Examples_1_6.zip&can=2&q=