Skip to content

Instantly share code, notes, and snippets.

@jsramraj
Last active October 22, 2015 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsramraj/b0a33a2fa3a18a47818d to your computer and use it in GitHub Desktop.
Save jsramraj/b0a33a2fa3a18a47818d to your computer and use it in GitHub Desktop.
Protocols/Delegates in Swift - Sample
import Foundation
@objc public protocol MyConnectionDelegate {
optional func didStartService(object: String)
optional func didFinishDownload(jsonData: NSData)
optional func didFailedDownload()
}
public class MyConnection {
weak public var delegate: MyConnectionDelegate?
public func callService() {
let url = NSURL(string: "http://cbld.zanec.com/user/countriesList")
let request = NSURLRequest(URL: url!)
self.delegate?.didStartService?("Started")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (jsonData, response, error) -> Void in
if (error != nil) {
self.delegate?.didFailedDownload?()
} else {
self.delegate?.didFinishDownload?(jsonData!)
}
}
task.resume()
}
}
class ViewController: UIViewController, MyConnectionDelegate {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let connection = MyConnection()
connection.delegate = self
connection.callService()
}
func didFinishDownload(jsonData: NSData) {
do {
let countryDict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
countries = (countryDict["countryList"] as? [NSDictionary])!
} catch {
}
}
func didStartService(object: String) {
print(object)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment