Pirijan
Pirijan

Reputation: 3579

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 ...

Upvotes: 0

Views: 1668

Answers (2)

davecom
davecom

Reputation: 1498

You could use a class I wrote that simplifies asynchronously downloading images from the web and displaying them using NSImageView and Swift (ported from an Objective-C version by someone else): https://github.com/davecom/DKAsyncImageView

Upvotes: 1

David Berry
David Berry

Reputation: 41236

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

let image = NSImage(data:avatarData!)

Upvotes: 3

Related Questions