Application Domain and Flash Error #1034: Type Coercion Failed
This is turning into a pretty good week. The other day I got Chrome to use the debug Flash Player and today I've solved a problem to an issue that doesn't creep up too often, but when it does, it can be nearly impossible for a beginner to work through.
Normally, type coercion errors are simple to fix; either you forgot a cast or weren't thinking and made a dumb one. However, sometimes you'll see something like this:
Error #1034: Type Coercion Failed: Cannot Convert myClass@XXX to myClass
Where "myClass" is the same class in both instances! You wouldn't think a coercion would be necessary. This kind of situation can occur when you're loading an swf from a different domain. It may seem a bit silly, but two swf files on different domains will have their own definition for a given class.
When I came across this error, I suspected it was an application domain problem; however, I was trying to solve it the wrong way. I was using the loading swf's domain to make the cast on the loaded content when in fact what you need to do is get the application domain of the loaded swf. I discovered this after a bit of googling lead me to this blog.
Below is a quick example of how to properly implement this.
var loader:Loader;
function loadSwf():void {
var request:URLRequest = new URLRequest('www.difdomain.com/ex.swf');
var con:LoaderContext = new LoaderContext(true, ApplicationDomain.currentDomain);
loader = new Loader();
loader.load(request, con);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
}
function onLoaded(e:Event):void {
var domain:ApplicationDomain = loader.contentLoaderInfo.applicationDomain;
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoaded);
var my_mc:MovieClip = loader.content as MovieClip;
// the cast
var c:Class = domain.getDefinition("myClass") as Class;
c(my_mc).myClassMethod(); // this line would have caused the type error before
}


Please, can you PM me and tell me few more things about this, I am really a fan of your blog…gets solved properly asap.
Thanks so much for your post.
I nearly lost my mind, thinking I was going crazy. How could flash not convert from myClass to myClass.
The ApplicationDomain makes sense, but my mind did not jump to that conclusion.
Thanks for the help.