Last active
October 22, 2015 11:00
-
-
Save jsramraj/b0a33a2fa3a18a47818d to your computer and use it in GitHub Desktop.
Protocols/Delegates in Swift - Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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