Search code examples
macosswiftnsdatansimage

creating an NSImage from downloaded NSData in Swift


So I'm using the AlamoFire library to download an image url which returns the NSData object 'avatarData'. But I can't figure out how to save this information into an NSImage object for later use in a view.

Here's my best attempt at converting to NSImage:

private func GetAvatar(avatarHash: String) {
    let avatar = "https://trello-avatars.s3.amazonaws.com/\(avatarHash)/30.png"
    Alamofire.request(.GET, avatar)
        .response {(request, response, avatarData, error) in
            if (error != nil) {
                self.handleConnectionError(error)
            } else {
                println(avatarData)
                let backgroundImage = NSImage(avatarData: NSData)
            }
    }

}

I've tried a couple variations of the syntax, but I usually end up with the errors:

expected member name or constructor call after type name

and/or

missing argument for parameter 'flipped' in call


Here's a sample of the println(avatarData)

Optional(<89504e47 0d0a1a0a 0000000d 49484452 0000001e 0000001e 08020000 01c35509 63000008 72494441 5448c705 ...


Solution

  • avatarData is an NSData, NSImage has a constructor that takes an NSData, just use that:

    let image = NSImage(data:avatarData!)