Reputation: 417
Based on code from this question (How do I get the color of a pixel in a UIImage with Swift?), I'm trying to run a function when a button gets tapped. Here is my code thus far:
@IBOutlet weak var graphImage: UIImageView!
var image : UIImage?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func getPixelColor(pos: CGPoint) -> UIColor {
var pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.image!.CGImage))
var data : UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
var pixelInfo : Int = ((Int(image!.size.width) * Int(pos.y) + Int(pos.x)*4))
let r = CGFloat(data[pixelInfo])
let g = CGFloat(data[pixelInfo]+1)
let b = CGFloat(data[pixelInfo]+2)
let a = CGFloat(data[pixelInfo]+3)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
@IBAction func playTapped(sender: AnyObject) {
var c : CGFloat = 100.0
var d : CGFloat = 100.0
getPixelColor(CGPoint(x:c,y:d))
}
However, whenever I tap the play button in the iOS Simulator, the app crashes and I get the warning "fatal error: unexpectedly found nil while unwrapping an Optional value" on the first line of the function getPixelColor. What am I doing wrong here/what do I need to add?
Upvotes: 0
Views: 1349
Reputation: 1498
Pretty straight forward. Based on the code here, you are indeed unwrapping a nil
object. Your instance variable, image
, is never initialized to anything... So you're trying to force unwrap it with !
but it is actually nil
.
Upvotes: 1