Skip to content

Instantly share code, notes, and snippets.

@cockscomb
Created July 21, 2015 03:47
Show Gist options
  • Save cockscomb/b40b5e2906c84b07c3ab to your computer and use it in GitHub Desktop.
Save cockscomb/b40b5e2906c84b07c3ab to your computer and use it in GitHub Desktop.

How to use

var stdAlert = StdAlert(self)
print("Alert Title\nAlert Body", &stdAlert)

Place this code in your view controller.

// The MIT License (MIT)
//
// Copyright (c) 2015 Hiroki KATO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public struct StdAlert: OutputStreamType {
private let viewController: UIViewController
public init(_ viewController: UIViewController) {
self.viewController = viewController
}
public init?() {
if let vc = UIApplication.sharedApplication().keyWindow?.rootViewController {
self.init(vc)
} else {
return nil
}
}
public mutating func write(string: String) {
var lines = string.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let title = lines.first
let body: String?
if lines.count > 1 {
body = "\n".join(lines[1..<lines.endIndex])
} else {
body = nil
}
let alert = UIAlertController(title: title, message: body, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { (action) in
// Dismiss
})
viewController.presentViewController(alert, animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment