모바일/iOS
Swift2 - CallBack 예제
늘근이
2016. 7. 10. 11:01
비동기식 데이터에서 콜백함수를 넣어야함.
func loadImage(urlString:String, handler:(image:UIImage?)-> Void)
{
var imgURL: NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue(),
completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
handler(image: UIImage(data: data))
}else{
handler(image: nil)
}
})
}
Call func like this:
loadImage("someurl", { (image) -> Void in
if let image = image{
view.image.image = image
}
})