I am trying to load a facebook profile picture with Loader() - actionscript-3

I'm having trouble passing the url for a users facebook profile picture to a Loader() variable. I'm using a PHP file to get around the security and from the debug I made, it shows that I'm getting the URL fine, but the Loader runs the error event listener. Here is what my facebookProxy.php file looks like;
<?php
$path=$_GET['path'];
header("Content-Description: Facebook Proxied File");
header("Content-Type: image");
header("Content-Disposition: attactment; filename =".$path);
#readfile($path);
?>
and here is my code for loading the url then loading the image.
function LoadMyPicture():void
{
debug.text = "Entered loadMyPicture() function";
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, MyPictureLoaded, false, 0, true);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, MyPictureLoadError, false, 0, true);
var request:URLRequest = new URLRequest("facebookProxy.php");
var variables:URLVariables = new URLVariables();
variables.path = Facebook.getImageUrl(Facebook.getSession().uid);
request.data = variables;
loader.load(request);
addChild(loader);
debug.appendText(" \nURLRequest url: " + request.url);
debug.appendText(" \nURLRequest data: " + request.data);
debug.appendText(" \n" + loader.content);
}
function MyPictureLoaded(e:Event):void
{
debug.appendText(" \nEntering MyPictureLoaded");
var loader:Loader = e.target.loader;
var bitmap = Bitmap(loader.content);
bitmap.smoothing = true;
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, MyPictureLoaded);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, MyPictureLoadError);
debug.appendText(" \nLoader Content: " + loader.content);
//Note: picturePlaceholder is just a blank movie clip on the Stage
bitmap.width = picturePlaceHolder.width;
bitmap.height = picturePlaceHolder.height;
picturePlaceHolder.addChild(bitmap);
debug.appendText(" \nBitmap width: " + String(bitmap.width) +
" \nBitmap height: " + String(bitmap.height))
}
function MyPictureLoadError(e:Event):void
{
debug.appendText(" \nMyPictureLoadError: Loader Error!");
}
debug.appendText(" \nURLRequest url: " + request.url);
debug.appendText(" \nURLRequest data: " + request.data);
debug.appendText(" \n" + loader.content);
These lines show as follows;
URLRequest url: facebookProxy.php
URLRequest data: path=https%3A%2F%2Fgraph%2Efacebook%2Ecom%2F100001902730917%2Fpicture
null
So the content in the loader is null, how would I debug this? Does anyone have any solutions that could help me?
EDIT
I forgot to mention that I followed a tutorial to that did not explain any of the basics about the code that they provided, so I'm fairly lost to the concept of the loader. This is the tutorial I followed Loading Facebook profile picture into Flash SWF using open graph api.

The line
debug.appendText(" \n" + loader.content);
occurs outside of the Event.COMPLETE handler.
I would add more listeners for the open, progress, and httpStatus events. The httpStatus event should be very helpful.
Can you add some debugging in your facebookProxy.php?

I was able to figure this out. The variables.path and request.data together with the facebookProxy.php wasn't necessary at all.
After changing the
var request:URLRequest = new URLRequest("facebookProxy.php");
to
var request:URLRequest = new URLRequest(Facebook.getImageUrl(Facebook.getSession().uid, large));
loader.load(request);
picturePlaceHolder.addChild(loader);
Removing
var variables:URLVariables = new URLVariables();
variables.path = Facebook.getImageUrl(Facebook.getSession().uid);
request.data = variables;
Allowed the picture to load properly. It's hard to find an up to date tutorial for all of this, why is that? but I guess I would have to open up a new question to find out lol.

Related

Animate 2021 Action Script 3 URLRequest causes Error 2035

I'm working on an application and we are using Flash to add an interface. During the initialize the app loads in a config file with references to image paths. When I use the Loader and URLRequest classes to load those images the path is not working and it's causing issues. Based on everything I've researched my code should work. I have a trace that outputs "source/icons/default.png" which is the correct relative path for the external image and loading the image works, but I need to use a variable to set the image path. Setting the URLRequest with a variable, new URLRequest("source/icons/" + default.png);, causes it use a full file path that looks wrong and reports a 2035 error. Is there something that I'm doing wrong? I'm not sure what to do at this point. I've verified the file exists and I've verified the path of the file.
Trace Ouput:
source/icons/default.png
Error Output:
[CompanionStatus] Error occurred while loading bitmap
[CompanionStatus] 2035 : Error #2035: URL Not Found. URL: file:///C|/Users/devtrooper/Desktop/project/source/icons/default.png
It looks like flash is replacing the colon (:) near the drive letter with a pipe (|) and I'm not sure if that is the issue.
Here is my method for loading images:
private function getBitmapData(nameString:String, imagePath:String):void{
try{
var bitmapDataFunction:Function = addBitmapDataToDictionary(nameString);
var path:String = ICON_FOLDER_PATH + imagePath;
var loader:Loader = new Loader();
var urlRequest:URLRequest = new URLRequest("source/icons/" + imagePath);
trace("URLRequest.url " + urlRequest.url);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, bitmapDataFunction, false, 0, true);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, handleBitmapDataError, false, 0, true);
loader.load(urlRequest);
} catch (e:Error) {
log("Error occured while trying to load image data");
log(e.name + " : " + e.message);
}
}
you can use File method instead of urlRequest method like this:
var urlPath:String="";
var picFile:File = File.desktopDirectory.resolvePath("source/icons/default.png");//you can use applicationDirectory,applicationStorageDirectory,userDirectory,doumenntDirectory and ...
if (picFile.exists == true) {
urlPath = picFile.url;
}

How to handle error dialog boxes in ActionScripts 3

I write some code to check an XML from a URL, it works when Internet connection exist, but when i manually disable internet for test an Error dialog box show, i coudn't handle it with try() catch().
try {
var myXML: XML = new XML();
var XML_URL: String = "https://drive.google.com/uc?export=download&id=0B5pkl4TJ7V0OTFBPanUyMWQxUnM";
var myXMLURL: URLRequest = new URLRequest(XML_URL);
var myLoader: URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function xmlLoaded(event: Event): void {
myXML = XML(myLoader.data);
trace("LOCK CODE: " + myXML.LOCK);
if (myXML.LOCK == 0) {
gotoAndStop(71);
};
}
} catch (e: Error) {
gotoAndStop(71);
trace("FAILED TO CHECK LOCK.");
} finally {
gotoAndStop(71);
trace("FAILED TO CHECK LOCK.");
}
How can i hide this dialog from user?
Add an URLLoader event listener for IOErrorEvent.IO_ERROR
e.g.
myLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
You should handle all events as good measure anyway (e.g. security error, etc.)
The as3 docs example provides a helpful snippet
Ideally you would not only silently trace message, but hopefully display helpful feedback or placeholder content for the user to understand what to expect.

Flash object cannot connect to remote server

My company design digital signage solutions for companies. The animated widgets are typically produced in Flash.
In a current project I'm experiencing a bit of an odd issue. The screen is split into 3 areas: Video, RSS Ticker, and Weather. The RSS and Weather objects are created using Flash. Each object is it's own Flash file.
Both Flash object utilize the same method to connect to the remote servers:
function loadWeatherFromUrl():void
{
var urlRequest:URLRequest = new URLRequest("MY URL");
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
try{
urlLoader.load(urlRequest);
} catch (error:Error) {
trace("Cannot load : " + error.message);
}
}
function completeHandler(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
//Do stuff with the data...
}
When testing in the IDE, both the Weather object and the RSS object work fine, as seen below:
Once deployed to the signage software it doesn't work anymore. However, the Weather object works as expected. The Flash object doesn't encounter a URL loading error either. Compare pic #2 and pic #3 to see how I view errors.
If I try to preview both the Weather object and the RSS object locally in a web-browser (IE, Firefox), I do get local permission errors, as expected.
So any ideas why one would work and the other wouldn't? If it had something to do with CORS (Cross Origin Resource Sharing) wouldn't both fail? I have tried both options (local only / network only) in the Publish -> Playback settings.
The weather object is powered by Yahoo:
Yahoo Weather
and the RSS object is powered by CTV News (Canadian Television Network):
CTV RSS Feed
EDIT:
For the RSS feed (above I used the Weather object's methods, they're identical except the function name and error output) I have the following:
At run time
error_msg.text = "Loading...";
Then the URL loading:
function loadFeedFromUrl():void
{
var urlRequest:URLRequest = new URLRequest("http://ottawa.ctvnews.ca/rss/ctv-news-ottawa-1.1245493");
error_msg.text = "";
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
try{
urlLoader.load(urlRequest);
} catch (error:Error) {
trace("Cannot load : " + error.message);
error_msg.text = error.message;
}
}
EDIT #2
Here is the UPDATED loading function, as well as the basic error handling functions.
function loadFeedFromUrl():void
{
var urlRequest:URLRequest = new URLRequest("http://ottawa.ctvnews.ca/rss/ctv-news-ottawa-1.1245493");
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
try{
urlLoader.load(urlRequest);
} catch (error:Error) {
trace("Cannot load : " + error.message);
error_msg.text = error.message;
}
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandlerFunction);
urlLoader.addEventListener(IOErrorEvent.NETWORK_ERROR, ioErrorHandlerFunction);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandlerFunction);
}
function ioErrorHandlerFunction() {
error_msg.text = "IO Error!";
}
function securityErrorHandlerFunction() {
error_msg.text = "Security Error!";
}
The error_msg textfield stays "Loading...", so it doesn't appear any of those error types are being received.

how to get a function to activate which is ment to be used with

I have this code were I take from a external XML file a Link of an Image load it with ...
<mx:Label
id="textboxLink" text=""/>
private function loadRemoteImg(url:String):void {
textboxLink.text
.....
loader, completeHandler etc.
Save Image(), with ByteArray, JPEGEcoder and then to the location - filestream etc.
This works all fine yet it is only possible (due to supposedly Flash Player 10 onwards) by MouseEvent so of a Click of a button!
As mentioned it works all fine, but I really would need this to activate on start up like in a creationComplete or else!
Any help or any ideas would be appriciated! regards aktell
Ah, sorry, I thought you were just trying to load the image; I didn't see that you were trying to save it as well.
For both of the following cases, you'll need to load the image as Binary:
var urlLoader:URLLoader = new URLLoader(new URLRequest( myURL ));
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
...
This is because if we load it normally (using a Loader), then what we'll get is a Bitmap object, i.e. Flash's representation of your image, rather than the jpg/png data itself. Loading it using this method will give you a ByteArray when it's loaded.
If you're using AIR, you should be able to use the FileStream class: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/filesystem/FileStream.html
Something like:
// NOTE: you can use any of the other File constants to get your path (e.g.
// documentsDirectory, desktopDirectory...
// myImageFileName is the name of your image, e.g. "myPic.jpg"
var file:File = File.applicationStorageDirectory.resolvePath( myImageFileName );
var fs:FileStream = new FileStream;
try
{
fs.open( file, FileMode.WRITE );
fs.writeBytes( imageBinaryData ); // imageBinaryData is a ByteArray
fs.close();
}
catch ( e:Error )
{
trace( "Can't save image: " + e.errorID + ": " + e.name + ": " + e.message );
}
If you're using Flash, then the only way you can save something without user interaction, is through a SharedObject. This will mean that you data won't be available outside the app (it'll be a .sol file), but depending on how you're doing it, this might not be a problem.
// get our shared object - if you're saving a lot of images, then you might need another shared
// object, whose name you know, that stores the names of the other images
var so:SharedObject = null;
try { so = SharedObject.getLocal( this.m_name ); }
catch ( e:Error )
{
trace( "Couldn't get shared object: " + e.errorID + ": " + e.name + ": " + e.message );
return;
}
// NOTE: it's possible you may need a registerClassAlias on the ByteArray before this
so.data["image"] = imageBinaryData;
// save the lso
try { so.flush( minDiskSpace ); }
catch ( e:Error )
{
trace( "Couldn't save the lso: " + e.errorID + ": " + e.name + ": " + e.message );
}
To actually use your image later, load your file(in binary mode)/get your SharedObject, and convert the saved binary to an image:
var l:Loader = new Loader;
l.contentLoaderInfo.addEventListener( Event.COMPLETE, this._onConvertComplete ); // you could probably also listen for the IO_ERROR event
try
{
// NOTE: you can pass a LoaderContext to the loadBytes methods
l.loadBytes( imageBinaryData );
}
catch( e:Error )
{
trace( "Couldn't convert image: " + e.errorID + ": " + e.name + ": " + e.message );
}
...
// called when our loader has finished converting our image
private function _onConvertComplete( e:Event ):void
{
// remove the event listeners
var loaderInfo:LoaderInfo = ( e.target as LoaderInfo );
loaderInfo.removeEventListener( Event.COMPLETE, this._onConvertComplete );
// get our image
var bitmap:Bitmap = loaderInfo.content;
this.addChild( bitmap );
}
If you can't use any of those methods, then you're going to have to have some sort of user interaction (e.g. mouse click). (Out of curiosity, have you tried just dispatching a MouseEvent.CLICK on the relevant object, to see if it would work?)

Adobe AIR and different OS filesystems

Another Adobe Air question for you but first here some background into the project I have been tasked with. It is an AIR app that will read assets from a USB key and must work on both WIN and MacOS. The problem is, how do I load assets into the app on MacOS! Sounds simple enough and works seamlessly on Windows.
Here is a code snippet of what i am trying to do:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ok);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
var p:String;
if (os == "mac")
{
p = "/Volumes/" + keyVolume.rootDirectory.name + File.separator + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg";
}
else
{
p = keyVolume.rootDirectory.name + File.separator + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg";
}
var temp:File = new File(p);
Debugger.Display.text += "\nAttempting to load: " + p;
Debugger.Display.text += "\nDoes it exist? " + temp.exists;
loader.load(new URLRequest(p));
... the variable OS and keyVolume are being successfully set in earlier code. Also, I have the event listener callbacks defined as well for ok() and ioErro().
When this is run it prints out on windows:
Attempting to load: G:\0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg
Does it exist: true
... and then successfully loads the asset.
On MacOS, it prints out:
Attempting to load: /Volumes/AC/0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg
Does it exist: true
... and then fails with an IOError every time.
Can anyone see something that I am missing here? Do I have some sort of permission error or something (file has "read / write" access). The USB key is formatted in MS-DOS FAT32, could that be a problem?
EDIT
I formatted a new USB key in MacOS to FAT16 and put the files onto it with no success. Problems remain.
EDIT
I am now just trying to load an asset from /users/-USERNAME-/Desktop and still am receiving the same error, so it looks like it isn't a permissions issue on just the USB stick, it is more widespread than that.
EDIT
PROBLEM SOLVED! I finally worded my Google search correctly and it revealed the answer.
These changes will fix the problem:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ok);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
var p:String = keyVolume.rootDirectory.nativePath + ((os == "mac") ? File.separator : "") + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg";
var temp:File = new File(p);
Debugger.Display.text += "\nAttempting to load: " + temp.url;
Debugger.Display.text += "\nDoes it exist? " + temp.exists;
loader.load(new URLRequest(temp.url));
I have also refined the logical statement involving the OS detection a bit as well.
I hope someone finds this useful!
PROBLEM SOLVED! I finally worded my Google search correctly and it revealed the answer.
These changes will fix the problem:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ok);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
var p:String = keyVolume.rootDirectory.nativePath + ((os == "mac") ? File.separator : "") + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg";
var temp:File = new File(p);
Debugger.Display.text += "\nAttempting to load: " + temp.url;
Debugger.Display.text += "\nDoes it exist? " + temp.exists;
loader.load(new URLRequest(temp.url));
I have also refined the logical statement involving the OS detection a bit as well.
I hope someone finds this useful!