VERNSTOKED
VERNSTOKED

Reputation: 117

Xcode 7 Swift 2 - How can I initialize a view with a .SKS file?

I have looked everywhere for examples on how to initialize a view from a .SKS file. Every example I found seems to now be broken with the introduction of Swift 2 and Xcode 7. I am using Xcode 7 GM.

Could someone please provide an example of how to do this in the quickest way possible?

Edit* Please be aware of both the iOS version and Xcode version before you mark this as a duplicate.

Upvotes: 0

Views: 528

Answers (1)

CloakedEddy
CloakedEddy

Reputation: 1995

I copied my code off of the SpriteKit sample project. I'm at work now, I can convert it to Swift this weekend if you need me to. Runs in Xcode 7, on iOS 9.1.

@implementation SKScene (Archiving)

+ (instancetype)unarchiveFromFile:(NSString *)file {
  /* Retrieve scene file path from the application bundle */
  NSString *nodePath = [[NSBundle mainBundle] pathForResource:file ofType:@"sks"];
  /* Unarchive the file to an SKScene object */
  NSData *data = [NSData dataWithContentsOfFile:nodePath
                                        options:NSDataReadingMappedIfSafe
                                          error:nil];
  NSKeyedUnarchiver *arch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
  [arch setClass:self forClassName:@"SKScene"];
  SKScene *scene = [arch decodeObjectForKey:NSKeyedArchiveRootObjectKey];
  [arch finishDecoding];

  return scene;
}

@end

// ...

@implementation VTMillScene

+ (instancetype)loadMill {
  return [self unarchiveFromFile:@"mill"]; // loads "mill.sks"
}

@end

Upvotes: 1

Related Questions