Giter Club home page Giter Club logo

callbacksample's Introduction

CallbackSample

Callback sample of Swift

ProtocolClosureNSNotificationを使ったコールバックの実装のサンプルです。

Protocol

protocol TaskDelegate {
    func complete(result: AnyObject)
    func failed(error: NSError)
}

final class Task {

    var delegate: TaskDelegate?

	...
	func someTask() {
		...
		someTaskResult(someResult, error: error)
	}

	...
	func someTaskResult(result: AnyObject, error: NSerror) {
		if error == nil {
			self.delegate?.complete(result)
		} else {
			self.delegate?.failed(error)
		}
	}
}
final class SomeViewController: UIViewController {
	...
	func viewDidLoad() {
		super.viewDidload()
		let task = Task()
		task.delegate = self
		task.someTask()
	}
	...
}

// MARK: - TaskDelegate
extension SomeViewController.swift: TaskDelegate {
	func complete(result: AnyObject) {
		// 処理
	}

	func failed(error: NSError) {
		// 処理
	}
}

Closure

final class ClosureAlert {

    class func showAlert(parentViewController: UIViewController, title: String, message: String, completion: ((Bool) -> Void)?) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

        let yesAction = UIAlertAction(title: "見る", style: UIAlertActionStyle.Default, handler: {
            (action:UIAlertAction!) -> Void in
            // 引数にメソッドが使われてれば実行する
            if let completion = completion {
                // yesなのでtrue
                completion(true)
            }
        })

        let noAction = UIAlertAction(title: "見ない", style: UIAlertActionStyle.Default, handler: {
            (action:UIAlertAction!) -> Void in
            // 引数にメソッドが使われてれば実行する
            if let completion = completion {
                // noなのでfalse
                completion(false)
            }
        })

        alert.addAction(yesAction)
        alert.addAction(noAction)
        parentViewController.presentViewController(alert, animated: true, completion: nil)
    }
}
final class SomeViewController: UIViewController {
	...
	func someMethod(){

        // クリック時に呼ばれるメソッドを定義
        let completeAction: (Bool) -> Void = {
            (isPositive) -> Void in
            if isPositive {
				// okの処理
            } else {
				// ngの処理
            }
        }

        // 実行するのはアラート選択時なのでcompleteActionに`()`はつけない。
        ClosureAlert.showAlert(self, title: "最新の記事", message: "注目です!",
            completion: completeAction
        )
	}

NSNotification

final class SomeViewController.swift: UIViewController {

	...
    override func viewDidLoad() {
        super.viewDidLoad()
        // バックグラウンドから復帰した際のObserver
		NSNotificationCenter.defaultCenter().addObserver(self, selector: "comeback:", name: UIApplicationWillEnterForegroundNotification, object: nil)
    }

	...
	internal func comeback(notification: NSNotification) {
    }
	...
}

詳しい説明はブログに。

callbacksample's People

Contributors

sakebook avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.