repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jmwind/FoodTracker
|
FoodTracker/FoodTracker/MealTableViewController.swift
|
1
|
5330
|
//
// MealTableViewController.swift
// FoodTracker
//
// Created by Jean-Michel Lemieux on 2016-04-25.
// Copyright © 2016 Jean-Michel Lemieux. All rights reserved.
//
import UIKit
class MealTableViewController: UITableViewController {
var meals = [Meal]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = editButtonItem()
self.refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
loadSampleMeals()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return meals.count
}
func loadSampleMeals() {
let photo1 = UIImage(named: "meal1")!
let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4)!
let photo2 = UIImage(named: "meal2")!
let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5)!
let photo3 = UIImage(named: "meal3")!
let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3)!
meals += [meal1, meal2, meal3]
}
func handleRefresh(refreshControl: UIRefreshControl) {
let photo = UIImage(named: "meal4")!
let meal = Meal(name: "Pasta with Meatballs", photo: photo, rating: 3)!
meals.append(meal)
self.tableView.reloadData()
refreshControl.endRefreshing()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "MealTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MealTableViewCell
let meal = meals[indexPath.row]
cell.nameLabel.text = meal.name
cell.photoImageView.image = meal.photo
cell.photoImageView.layer.cornerRadius = 10.0
cell.photoImageView.clipsToBounds = true
cell.ratingControl.rating = meal.rating
return cell
}
@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.sourceViewController as? MealViewController, meal = sourceViewController.meal {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing meal.
meals[selectedIndexPath.row] = meal
tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
}
else {
// Add a new meal.
let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0)
meals.append(meal)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
meals.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail" {
let mealDetailViewController = segue.destinationViewController as! MealViewController
// Get the cell that generated this segue.
if let selectedMealCell = sender as? MealTableViewCell {
let indexPath = tableView.indexPathForCell(selectedMealCell)!
let selectedMeal = meals[indexPath.row]
mealDetailViewController.meal = selectedMeal
}
}
else if segue.identifier == "AddItem" {
print("Adding new meal.")
}
}
}
|
mit
|
5385547193469760f01c0e19a15c608e
| 35.251701 | 157 | 0.64984 | 5.291956 | false | false | false | false |
lawrencelomax/XMLParsable
|
XMLParsableTests/Fixtures/Zoo.swift
|
1
|
4629
|
//
// Zoo.swift
// XMLParsable
//
// Created by Lawrence Lomax on 04/09/2014.
// Copyright (c) 2014 Lawrence Lomax. All rights reserved.
//
import Foundation
import swiftz_core
import XMLParsable
public struct Animal: XMLDecoderType {
public let kind: String
public let name: String
public let url: NSURL
public static func build(kind: String)(name: String)(url: NSURL) -> Animal {
return self(kind: kind, name: name, url: url)
}
public static func decodeImperative<X: XMLParsableType>(xml: X) -> Result<Animal> {
if let kind = xml.parseChildren("kind").first?.parseText() {
if let name = xml.parseChildren("nested_nonsense").first?.parseChildren("name").first?.parseText() {
if let urlString = xml.parseChildren("url").first?.parseText() {
if let url = NSURL(string: urlString) {
return Result.value(self(kind: kind, name: name, url: url))
}
}
return Result.Error(XMLParser.error("Could not parse 'urlString' as a String"))
}
return Result.Error(XMLParser.error("Could not parse 'name' as a String"))
}
return Result.Error(XMLParser.error("Could not parse 'kind' as a String"))
}
public static func decodeImperativeReturnEarly<X: XMLParsableType>(xml: X) -> Result<Animal> {
let maybeType = xml.parseChildren("kind").first?.parseText()
if maybeType == .None {
return Result.Error(XMLParser.error("Could not parse 'type' as a String"))
}
let maybeName = xml.parseChildren("name").first?.parseText()
if maybeName == .None {
return Result.Error(XMLParser.error("Could not parse 'name' as a String"))
}
let maybeUrlString = xml.parseChildren("url").first?.parseText()
if maybeUrlString == .None {
return Result.Error(XMLParser.error("Could not parse 'urlString' as a String"))
}
let maybeUrl = NSURL(string: maybeUrlString!)
if maybeUrl == .None {
return Result.Error(XMLParser.error("Could not parse 'urlString' from a String to a URL"))
}
return Result.value(self(kind: maybeType!, name: maybeName!, url: maybeUrl!))
}
public static func decode<X : XMLParsableType>(xml: X) -> Result<Animal> {
let kind = XMLParser.parseChildText("kind")(xml: xml)
let name = XMLParser.parseChildRecusiveText(["nested_nonsense", "name"])(xml: xml)
let url = XMLParser.parseChildText("url")(xml: xml) >>- ({NSURL(string: $0)} <!> XMLParser.promoteError("Could not parse 'url' as an URL"))
return self.build <^> kind <*> name <*> url
}
}
public struct Zoo: XMLDecoderType {
public let toiletCount: Int
public let disabledParking: Bool
public let drainage: String
public let animals: [Animal]
public static func build(toiletCount: Int)(disabledParking: Bool)(drainage: String)(animals: [Animal]) -> Zoo {
return self(toiletCount: toiletCount, disabledParking: disabledParking, drainage: drainage, animals: animals)
}
public static func decode<X : XMLParsableType>(xml: X) -> Result<Zoo> {
let toiletCount = XMLParser.parseChildRecusiveText(["facilities", "toilet"])(xml: xml) >>- (Int.parseString <!> XMLParser.promoteError("Could not intepret 'toilet' as int'"))
let disabledParking = XMLParser.parseChildRecusiveText(["facilities", "disabled_parking"])(xml: xml) >>- (Bool.parseString <!> XMLParser.promoteError("Could interpret 'disabled_parking' as a Bool"))
let drainage = XMLParser.parseChildRecusiveText(["facilities", "seriously", "crazy_nested", "drainage"])(xml: xml)
let animals = XMLParser.parseChild("animals")(xml: xml) >>- XMLParser.parseChildren("animal") >>- resultMapC(Animal.decode)
return self.build <^> toiletCount <*> disabledParking <*> drainage <*> animals
}
public static func decodeKleisli<X : XMLParsableType>(xml: X) -> Result<Zoo> {
let toiletCount = (XMLParser.parseChildRecusiveText(["facilities", "toilet"]) as X -> Result<String>) >=> (Int.parseString <!> XMLParser.promoteError("Could not intepret 'toilet' as int'"))
let disabledParking = (XMLParser.parseChildRecusiveText(["facilities", "disabled_parking"]) as X -> Result<String>) >=> (Bool.parseString <!> XMLParser.promoteError("Could interpret 'disabled_parking' as a Bool"))
let drainage = XMLParser.parseChildRecusiveText(["facilities", "seriously", "crazy_nested", "drainage"]) as X -> Result<String>
let animals = (XMLParser.parseChild("animals") as X -> Result<X>) >=> XMLParser.parseChildren("animal") >=> resultMapC(Animal.decode)
return self.build <^> toiletCount(xml) <*> disabledParking(xml) <*> drainage(xml) <*> animals(xml)
}
}
|
mit
|
26b1cbdcc8f4c0be95cd671dda114035
| 46.234694 | 217 | 0.685677 | 3.84788 | false | false | false | false |
devinroth/SwiftOSC
|
Framework/SwiftOSC/Addresses/OSCAddress.swift
|
1
|
1276
|
//
// OSCAddress.swift
// SwiftOSC
//
// Created by Devin Roth on 6/26/16.
// Copyright © 2016 Devin Roth Music. All rights reserved.
//
import Foundation
public struct OSCAddress {
//MARK: Properties
public var string: String {
didSet {
if !valid(self.string) {
NSLog("\"\(self.string)\" is an invalid address")
self.string = oldValue
}
}
}
//MARK: initializers
public init() {
self.string = "/"
}
public init(_ address: String) {
self.string = "/"
if valid(address) {
self.string = address
} else {
NSLog("\"\(address)\" is an invalid address")
}
}
//MARK: methods
func valid(_ address: String) ->Bool {
var isValid = true
autoreleasepool {
//invalid characters: space * , ? [ ] { } OR two or more / in a row AND must start with / AND no empty strings
if address.range(of: "[\\s\\*,?\\[\\]\\{\\}]|/{2,}|^[^/]|^$", options: .regularExpression) != nil {
//returns false if there are any matches
isValid = false
}
}
return isValid
}
}
|
mit
|
0f40429bf868d1777ebe9eae727c8314
| 23.519231 | 122 | 0.480784 | 4.366438 | false | false | false | false |
pengzishang/AMJBluetooth
|
AMJBluetoothDemo/blueToothTest/Remote/ChooseRemoteController.swift
|
1
|
5125
|
//
// ChooseRemoteController.swift
// blueToothTest
//
// Created by pzs on 2017/9/14.
// Copyright © 2017年 彭子上. All rights reserved.
//
import UIKit
class ChooseRemoteController: UITableViewController {
var devicesArray = Array<Dictionary<String, Any>>.init()
override func viewDidLoad() {
super.viewDidLoad()
BluetoothManager.getInstance()?.peripheralsInfo?.forEach({ (infoDic) in
let deviceInfo = infoDic as! NSDictionary
let deviceID = (deviceInfo.object(forKey: AdvertisementData) as! NSDictionary).object(forKey: "kCBAdvDataLocalName") as! String
if deviceID.contains("WIFI"){
self.devicesArray .append(infoDic as! [String : Any])
}
})
self.tableView.reloadData()
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: BlueToothMangerDidDiscoverNewItem), object: nil, queue: nil) { (notice) in
let infoDic = notice.userInfo;
let deviceInfo = infoDic! as NSDictionary
let deviceID = (deviceInfo.object(forKey: AdvertisementData) as! NSDictionary).object(forKey: "kCBAdvDataLocalName") as! String
if deviceID.contains("WIFI"){
self.devicesArray .append(infoDic as! [String : Any])
self.tableView.reloadData()
}
// print(notice.userInfo!)//userinfo内有信息
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.devicesArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "remotecell", for: indexPath)
let infoDic = self.devicesArray[indexPath.row]
let deviceInfo = infoDic as NSDictionary
let deviceID = (deviceInfo.object(forKey: AdvertisementData) as! NSDictionary).object(forKey: "kCBAdvDataLocalName") as! String
let deviceLab = cell.viewWithTag(1000) as! UILabel
deviceLab.text = deviceID
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let infoDic = self.devicesArray[indexPath.row]
let deviceInfo = infoDic as NSDictionary
var deviceID = (deviceInfo.object(forKey: AdvertisementData) as! NSDictionary).object(forKey: "kCBAdvDataLocalName") as! NSString
deviceID = deviceID.replacingOccurrences(of: " ", with: "") as NSString
deviceID = deviceID.substring(from: 6) as NSString
UserDefaults.standard.set(deviceID, forKey: "Remote")
tableView .deselectRow(at: indexPath, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.nanoseconds(300), execute: {
self.navigationController?.popViewController(animated: true)
})
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
2ffe5f70138204cde2f2978ad03575f0
| 38.596899 | 160 | 0.659554 | 4.983415 | false | false | false | false |
spacedrabbit/100-days
|
One00Days/One00Days/Day10ViewController.swift
|
1
|
3613
|
//
// Day10ViewController.swift
// One00Days
//
// Created by Louis Tur on 3/1/16.
// Copyright © 2016 SRLabs. All rights reserved.
//
import UIKit
import Foundation
class CubeGenerator {
static let standardSize: CGRect = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
internal class func createCubeWithColor(_ color: UIColor) -> UIView {
let view: UIView = UIView(frame: CubeGenerator.standardSize)
view.layer.addSublayer(CubeGenerator().drawCube(color))
return view
}
internal func drawCube(_ color: UIColor) -> CALayer{
let path: UIBezierPath = UIBezierPath(roundedRect: CubeGenerator.standardSize, byRoundingCorners: [.topLeft, .bottomRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
path.lineWidth = 4.0
let layer: CAShapeLayer = CAShapeLayer()
layer.frame = CubeGenerator.standardSize
layer.fillColor = color.cgColor
layer.strokeColor = UIColor.black.cgColor
layer.path = path.cgPath
// path.fill()
return layer
}
}
class Animator {
internal class func animateWithUpwardsSpring(_ cube: UIView) {
let currentFrame: CGRect = cube.frame
let minimumDistanceToCover: CGFloat = 500.0
let xCoordRandomize: CGFloat = CGFloat(NSNumber(value: arc4random_uniform(99) + 1 as UInt32).doubleValue / 100.0) * 356.0
let yCoordRandomize: CGFloat = CGFloat(NSNumber(value: arc4random_uniform(99) + 1 as UInt32).doubleValue) + minimumDistanceToCover
print("\(xCoordRandomize), \(yCoordRandomize)")
UIView.animate(withDuration: 1.5, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.4, options: .beginFromCurrentState, animations: { () -> Void in
let shiftedX: CGFloat = xCoordRandomize
let shiftedY: CGFloat = yCoordRandomize + currentFrame.origin.y
let newFrame: CGRect = CGRect(x: shiftedX, y: 568.0 - shiftedY, width: currentFrame.size.width, height: currentFrame.size.height)
cube.frame = newFrame
}) { (complete: Bool) -> Void in
print("Done animating")
}
}
}
class Day10ViewController: UIViewController {
lazy var button: UIButton = {
let button: UIButton = UIButton(frame: CGRect(x: 10.0, y: 30.0, width: 200.0, height: 100.0))
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
// self.view.addSubview(self.button)
self.button.backgroundColor = UIColor.red
self.button.setTitle("PRESS", for: UIControlState())
self.button.addTarget(self, action: #selector(Day10ViewController.fireCube), for: UIControlEvents.touchUpInside)
let timer: Timer = Timer(timeInterval: 1.35, target: self, selector: #selector(Day10ViewController.fireCube), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
internal func fireCube() {
let cube: UIView = CubeGenerator.createCubeWithColor(self.randomColor())
self.view.addSubview(cube)
cube.frame = CGRect(x: cube.frame.midX, y: self.view.frame.maxY + 100.0, width: 100.0, height: 100.0)
Animator.animateWithUpwardsSpring(cube)
}
internal func randomColor() -> UIColor {
let r: CGFloat = CGFloat(arc4random_uniform(99) + 1)/100.0
let g: CGFloat = CGFloat(arc4random_uniform(99) + 1)/100.0
let b: CGFloat = CGFloat(arc4random_uniform(99) + 1)/100.0
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
}
|
mit
|
42d020851ef5eb27300a3481e93af186
| 34.067961 | 175 | 0.694075 | 3.883871 | false | false | false | false |
kgn/KGNUserInterface
|
Source/TitleBarView.swift
|
1
|
5129
|
//
// TitleBarView.swift
// KGNUserInterface
//
// Created by David Keegan on 10/30/15.
// Copyright © 2015 David Keegan. All rights reserved.
//
import UIKit
private class ContentView: UIView {
override var intrinsicContentSize: CGSize {
let minWidth = Style.Size.Control
var intrinsicContentSize = super.intrinsicContentSize
if let subview = self.subviews.first {
let subviewIntrinsicContentSize = subview.intrinsicContentSize
intrinsicContentSize.width = subviewIntrinsicContentSize.width
if intrinsicContentSize.width < minWidth {
intrinsicContentSize.width = minWidth
}
} else {
intrinsicContentSize.width = 0
}
return intrinsicContentSize
}
}
/// Custom title bar view, similar to UINavigationBar
/// but intended for custom interfaces.
open class TitleBarView: UIView {
/// The title to display in the center of the bar
open var title: String? {
didSet {
self.titleLabel.text = self.title
}
}
/// The left view item
open var leftView: UIView? {
didSet {
for subview in self.leftContainerView.subviews {
subview.removeFromSuperview()
}
if let leftView = self.leftView {
self.leftContainerView.addSubview(leftView)
leftView.pinToEdgesOfSuperview()
}
self.leftContainerView.invalidateIntrinsicContentSize()
}
}
/// The right view item
open var rightView: UIView? {
didSet {
for subview in self.rightContainerView.subviews {
subview.removeFromSuperview()
}
if let rightView = self.rightView {
self.rightContainerView.addSubview(rightView)
rightView.pinToEdgesOfSuperview()
}
self.rightContainerView.invalidateIntrinsicContentSize()
}
}
private lazy var titleLabel: Label = {
let label = Label(textStyle: .subheadline)
label.accessibilityTraits = UIAccessibilityTraits.header
return label
}()
private lazy var leftContainerView: ContentView = ContentView()
private lazy var rightContainerView: ContentView = ContentView()
/// Set the title, if `animated` is `true` then a cross dissolve animation is used.
open func set(title: String?, animated: Bool) {
defer {
self.title = title
}
if !animated{
return
}
guard let snapshot = self.titleLabel.snapshot() else {
return
}
let titleLabelImageView = UIImageView(image: snapshot)
self.addSubview(titleLabelImageView)
titleLabelImageView.centerInSuperview()
self.titleLabel.alpha = 0
UIView.animate(withDuration: Style.Animation.Duration, animations: {
self.titleLabel.alpha = 1
titleLabelImageView.alpha = 0
}) { _ in
titleLabelImageView.removeFromSuperview()
}
}
open override var intrinsicContentSize: CGSize {
if self.traitCollection.userInterfaceIdiom == .phone {
if self.traitCollection.verticalSizeClass == .compact {
return CGSize(width: UIView.noIntrinsicMetric, height: Style.Size.NavigationBarHeightCompact)
}
}
return CGSize(width: UIView.noIntrinsicMetric, height: Style.Size.NavigationBarHeight)
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.invalidateIntrinsicContentSize()
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
private func setup() {
self.addSubview(self.leftContainerView)
self.leftContainerView.size(toMaxWidth: Style.Size.TitleBarItemMaxWidth)
self.leftContainerView.pinToTopAndBottomEdgesOfSuperview()
self.leftContainerView.pinToLeftEdgeOfSuperview(withOffset: Style.Size.SmallPadding)
self.addSubview(self.rightContainerView)
self.rightContainerView.size(toMaxWidth: Style.Size.TitleBarItemMaxWidth)
self.rightContainerView.pinToTopAndBottomEdgesOfSuperview()
self.rightContainerView.pinToRightEdgeOfSuperview(withOffset: Style.Size.SmallPadding)
self.addSubview(self.titleLabel)
self.titleLabel.centerInSuperview()
self.constrain(
item: self.titleLabel, attribute: .left,
toItem: self.leftContainerView,
attribute: .right, relatedBy: .greaterThanOrEqual,
offset: Style.Size.Padding
)
self.constrain(
item: self.titleLabel, attribute: .right,
toItem: self.rightContainerView,
attribute: .left, relatedBy: .lessThanOrEqual,
offset: -Style.Size.Padding
)
}
}
|
mit
|
5cb0472d8a12287a8a304d089eff17d3
| 31.871795 | 109 | 0.641186 | 5.449522 | false | false | false | false |
dasdom/Storyboard2CodeApp
|
Storyboard2Code/Elements/Color.swift
|
2
|
2395
|
import Foundation
public enum Color: AttributeCreatable {
case redGreenBlueRepresentation(key:String, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
case whiteAlphaRepresentation(key: String, white: CGFloat, alpha: CGFloat)
case stringRepresentation(key: String, string: String)
case notSupported
public var key: String {
switch self {
case .redGreenBlueRepresentation(let key, _, _, _, _): return key
case .whiteAlphaRepresentation(let key, _, _): return key
case .stringRepresentation(let key, _): return key
default: return "Not Supported"
}
}
public init(dict: [String : String]) {
if let redString = dict[Key.red.rawValue],
let greenString = dict[Key.green.rawValue],
let blueString = dict[Key.blue.rawValue],
let alphaString = dict[Key.alpha.rawValue],
let red = Float(redString),
let green = Float(greenString),
let blue = Float(blueString),
let alpha = Float(alphaString) {
self = .redGreenBlueRepresentation(key: dict[Key.key.rawValue]!, red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))
} else if let whiteString = dict[Key.white.rawValue],
let alphaString = dict[Key.alpha.rawValue],
let white = Float(whiteString),
let alpha = Float(alphaString) {
self = .whiteAlphaRepresentation(key: dict[Key.key.rawValue]!, white: CGFloat(white), alpha: CGFloat(alpha))
} else if let string = dict[Key.cocoaTouchSystemColor.rawValue] {
self = .stringRepresentation(key: dict[Key.key.rawValue]!, string: string)
} else {
self = .notSupported
}
}
}
extension Color {
fileprivate enum Key: String {
case red, green, blue, alpha, key, white, cocoaTouchSystemColor
}
}
extension Color: AttributeCodeGeneratable {
func codeString(objC: Bool = false) -> String {
switch self {
case .redGreenBlueRepresentation(_, let red, let green, let blue, let alpha):
return String(format: "UIColor(red: %.3lf, green: %.3lf, blue: %.3lf, alpha: %.3lf)", red, green, blue, alpha)
case .whiteAlphaRepresentation(_, let white, let alpha):
return String(format: "UIColor(white: %.3lf, alpha: %.3lf)", white, alpha)
case .stringRepresentation(_, let string):
return "UIColor.\(string)"
default:
return "Not implemented yet"
}
}
}
|
mit
|
c7a7c515b28a6828b238fc66fed87c7c
| 36.421875 | 156 | 0.670146 | 3.945634 | false | false | false | false |
Corotata/CRWeiBo
|
CRWeiBo/CRWeiBo/Classes/Modules/Profile/CRProfileViewController.swift
|
1
|
3237
|
//
// CRProfileViewController.swift
// CRWeiBo
//
// Created by Corotata on 16/2/17.
// Copyright © 2016年 Corotata. All rights reserved.
//
import UIKit
class CRProfileViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
627730640097cf5499adfcb2740ff32c
| 33.042105 | 157 | 0.687384 | 5.54717 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceKit/Sources/EurofurenceKit/EurofurenceModel.swift
|
1
|
12181
|
import Combine
import CoreData
import EurofurenceWebAPI
import Foundation
import Logging
/// Root entry point for entity access, authentication, and more within the Eurofurence targets.
@MainActor
public class EurofurenceModel: ObservableObject {
let configuration: EurofurenceModel.Configuration
private let logger = Logger(label: "EurofurenceModel")
private var pushNotificationDeviceTokenData: Data?
private var subscriptions = Set<AnyCancellable>()
/// The current synchronisation phase between the model and the backing store.
@Published public internal(set) var cloudStatus: CloudStatus = .idle
/// The currently authenticated user within the model, or `nil` if the model is unauthenticated.
@Published public private(set) var currentUser: User?
/// Designates the start time of the next convention, or `nil` if the start time is not known.
@Published public private(set) var conventionStartTime: Date?
/// A read-only managed object context for use in presenting the state of the model to the user.
public var viewContext: NSManagedObjectContext {
configuration.persistentContainer.viewContext
}
public convenience init() {
self.init(configuration: Configuration())
}
public init(configuration: EurofurenceModel.Configuration) {
self.configuration = configuration
}
/// Prepares the model for display within an application. Must be called at least once after the application has
/// launched.
public func prepareForPresentation() async {
await withTaskGroup(of: Void.self) { group in
group.addTask { [self] in
await updateAuthenticatedStateFromPersistentCredential()
}
group.addTask { [self] in
await acquireRemoteConfiguration()
}
await group.waitForAll()
}
}
/// Attempts to synchronise the model with the backing store.
public func updateLocalStore() async throws {
do {
try await performLocalStoreUpdates()
cloudStatus = .updated
} catch {
cloudStatus = .failed
throw error
}
}
private func performLocalStoreUpdates() async throws {
let context = prepareUpdateOperationContext()
let progress = EurofurenceModel.Progress()
let operation = UpdateLocalStoreOperation(progress: progress)
cloudStatus = .updating(progress: progress)
// Simultaneously update the local store and perform any local book-keeping.
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask {
try await operation.execute(context: context)
}
group.addTask { [self] in
await updateAuthenticatedStateFromPersistentCredential()
}
try await group.waitForAll()
}
}
private func prepareUpdateOperationContext() -> UpdateOperationContext {
let writingContext = configuration.persistentContainer.newBackgroundContext()
return UpdateOperationContext(
managedObjectContext: writingContext,
keychain: configuration.keychain,
api: configuration.api,
properties: configuration.properties,
conventionIdentifier: configuration.conventionIdentifier
)
}
}
// MARK: - Remote Configuration
extension EurofurenceModel {
private func acquireRemoteConfiguration() async {
do {
let remoteConfiguration = try await configuration.api.execute(request: APIRequests.FetchConfiguration())
prepareForReading(from: remoteConfiguration)
} catch {
logger.error(
"Failed to fetch remote configuration",
metadata: ["Error": .string(String(describing: error))]
)
}
}
private func prepareForReading(from remoteConfiguration: RemoteConfiguration) {
remoteConfiguration
.onChange
.sink { [self] remoteConfiguration in
read(remoteConfiguration: remoteConfiguration)
}
.store(in: &subscriptions)
read(remoteConfiguration: remoteConfiguration)
}
private func read(remoteConfiguration: RemoteConfiguration) {
let conventionStartTime = remoteConfiguration[RemoteConfigurationKeys.ConventionStartTime.self]
if conventionStartTime != self.conventionStartTime {
self.conventionStartTime = conventionStartTime
}
}
}
// MARK: - Cloud Status
extension EurofurenceModel {
/// Represents a phase of synchronisation status as the model fetches updates from the backing store.
public enum CloudStatus: Equatable {
/// The model is not processing any changes.
case idle
/// The model is currently synchronising with the backing store.
case updating(progress: EurofurenceModel.Progress)
/// The model has completed synchronising with the backing store.
case updated
/// The model attempted to synchronise with the backing store, but encountered an error.
case failed
}
/// Represents the relative progress made by the model during a synchronisation pass with the remote store.
@MainActor
public class Progress: ObservableObject, Equatable {
public nonisolated static func == (lhs: EurofurenceModel.Progress, rhs: EurofurenceModel.Progress) -> Bool {
lhs === rhs
}
private let progress = Foundation.Progress()
/// A number between 0.0 and 1.0 that represents the overall completeness of the current synchronisation pass,
/// where 0 represents not started and 1 represents completed. The absence of a value indicates the overall
/// progress cannot yet be determined.
@Published public private(set) var fractionComplete: Double?
/// A short, localized description that may be presented to the user as the synchronisation pass continues.
public var localizedDescription: String {
progress.localizedDescription
}
init() {
progress.totalUnitCount = 0
progress.completedUnitCount = 0
}
func update(totalUnitCount: Int) {
progress.totalUnitCount = Int64(totalUnitCount)
}
func updateCompletedUnitCount() {
progress.completedUnitCount += 1
fractionComplete = progress.fractionCompleted
}
}
}
// MARK: - Authentication
extension EurofurenceModel {
/// Registers the Apple Push Notification Service (APNS) token of the current device with the model.
///
/// Depending on the user's authentication status, they may begin to receive personalised pushes following the
/// registration of the device push token. Any user who grants push access will still receive non-personalised
/// pushes.
///
/// - Parameter data: The token data generated by the device for use in publishing remote notifications to this
/// device via APNS.
public func registerRemoteNotificationDeviceTokenData(_ data: Data) async {
pushNotificationDeviceTokenData = data
let credential = configuration.keychain.credential
await associateDevicePushNotificationToken(
data: data,
withUserAuthenticationToken: credential?.authenticationToken
)
}
/// Attempts to sign into the application using the provided `Login`.
///
/// - Parameter login: The credentials to use when logging in. An improperly configured set of credentials performs
/// a no-op.
public func signIn(with login: Login) async throws {
guard let loginRequest = login.request else { return }
do {
let authenticatedUser = try await configuration.api.execute(request: loginRequest)
storeAuthenticatedUserIntoKeychain(authenticatedUser)
currentUser = User(authenticatedUser: authenticatedUser)
await withTaskGroup(of: Void.self) { group in
group.addTask { [self] in
await registerPushNotificationToken(against: authenticatedUser)
}
group.addTask { [self] in
await updateLocalMessagesCache()
}
await group.waitForAll()
}
} catch {
logger.error("Failed to authenticate user.", metadata: ["Error": .string(String(describing: error))])
throw EurofurenceError.loginFailed
}
}
/// Attempts to sign out of the application.
///
/// Attempting to sign out when not already signed in is a no-op.
public func signOut() async throws {
guard configuration.keychain.credential != nil else { return }
let logout = APIRequests.Logout(
pushNotificationDeviceToken: pushNotificationDeviceTokenData
)
try await configuration.api.execute(request: logout)
configuration.keychain.credential = nil
currentUser = nil
await updateLocalMessagesCache()
}
private func registerPushNotificationToken(against authenticatedUser: AuthenticatedUser) async {
if let pushNotificationDeviceTokenData = pushNotificationDeviceTokenData {
await associateDevicePushNotificationToken(
data: pushNotificationDeviceTokenData,
withUserAuthenticationToken: authenticatedUser.token
)
}
}
private func updateLocalMessagesCache() async {
do {
let context = prepareUpdateOperationContext()
let updateMessages = UpdateLocalMessagesOperation()
try await updateMessages.execute(context: context)
} catch {
logger.info(
"Failed to update local messages. App may appear in an inconsistent state until next refresh."
)
}
}
private func associateDevicePushNotificationToken(
data: Data,
withUserAuthenticationToken token: AuthenticationToken?
) async {
let pushNotificationDeviceRegistration = APIRequests.RegisterPushNotificationDeviceToken(
authenticationToken: token,
pushNotificationDeviceToken: data
)
do {
try await configuration.api.execute(request: pushNotificationDeviceRegistration)
} catch {
logger.error(
"Failed to register remote notification token.",
metadata: ["Error": .string(String(describing: error))]
)
}
}
private func storeAuthenticatedUserIntoKeychain(_ authenticatedUser: AuthenticatedUser) {
let credential = Credential(
username: authenticatedUser.username,
registrationNumber: authenticatedUser.userIdentifier,
authenticationToken: authenticatedUser.token,
tokenExpiryDate: authenticatedUser.tokenExpires
)
configuration.keychain.credential = credential
}
private func updateAuthenticatedStateFromPersistentCredential() async {
if let credential = configuration.keychain.credential {
if credential.isValid {
currentUser = User(credential: credential)
} else {
await automaticallySignOutUser()
}
}
}
private func automaticallySignOutUser() async {
do {
try await signOut()
} catch {
logger.error(
"Failed to automatically sign out user.",
metadata: ["Error": .string(String(describing: error))]
)
}
}
}
|
mit
|
25773e6051c8c88796cd079283295c87
| 35.361194 | 119 | 0.632542 | 5.947754 | false | true | false | false |
themasterapp/master-app-ios
|
MasterApp/Extensions/UIViewController/UIViewController+IsModal.swift
|
1
|
772
|
//
// UIViewController+IsModal.swift
// Sos
//
// Created by MasterApp on 9/7/16.
// Copyright © 2016 MasterApp. All rights reserved.
//
import UIKit
extension UIViewController {
func isModal() -> Bool {
if self.presentingViewController != nil {
return true
}
if self.presentingViewController?.presentedViewController == self {
return true
}
if self.navigationController != nil && self.navigationController?.presentingViewController?.presentedViewController == self.navigationController {
return true
}
if self.tabBarController?.presentingViewController is UITabBarController {
return true
}
return false
}
}
|
mit
|
910581e73949ae57cd8bf0403cdfc44e
| 23.870968 | 154 | 0.61738 | 5.586957 | false | false | false | false |
DavadDi/flatbuffers
|
swift/Sources/FlatBuffers/Constants.swift
|
1
|
2823
|
/*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if os(Linux)
import CoreFoundation
#else
import Foundation
#endif
/// A boolean to see if the system is littleEndian
let isLitteEndian = CFByteOrderGetCurrent() == Int(CFByteOrderLittleEndian.rawValue)
/// Constant for the file id length
let FileIdLength = 4
/// Type aliases
public typealias Byte = UInt8
public typealias UOffset = UInt32
public typealias SOffset = Int32
public typealias VOffset = UInt16
/// Maximum size for a buffer
public let FlatBufferMaxSize = UInt32.max << ((MemoryLayout<SOffset>.size * 8 - 1) - 1)
/// Protocol that confirms all the numbers
///
/// Scalar is used to confirm all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer.
public protocol Scalar: Equatable {
associatedtype NumericValue
var convertedEndian: NumericValue { get }
}
extension Scalar where Self: FixedWidthInteger {
/// Converts the value from BigEndian to LittleEndian
///
/// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet.
public var convertedEndian: NumericValue {
self as! Self.NumericValue
}
}
extension Double: Scalar {
public typealias NumericValue = UInt64
public var convertedEndian: UInt64 {
bitPattern.littleEndian
}
}
extension Float32: Scalar {
public typealias NumericValue = UInt32
public var convertedEndian: UInt32 {
bitPattern.littleEndian
}
}
extension Bool: Scalar {
public var convertedEndian: UInt8 {
self == true ? 1 : 0
}
public typealias NumericValue = UInt8
}
extension Int: Scalar {
public typealias NumericValue = Int
}
extension Int8: Scalar {
public typealias NumericValue = Int8
}
extension Int16: Scalar {
public typealias NumericValue = Int16
}
extension Int32: Scalar {
public typealias NumericValue = Int32
}
extension Int64: Scalar {
public typealias NumericValue = Int64
}
extension UInt8: Scalar {
public typealias NumericValue = UInt8
}
extension UInt16: Scalar {
public typealias NumericValue = UInt16
}
extension UInt32: Scalar {
public typealias NumericValue = UInt32
}
extension UInt64: Scalar {
public typealias NumericValue = UInt64
}
public func FlatBuffersVersion_1_12_0() {}
|
apache-2.0
|
7bab1b21bbe7de7710d411ab748b2cc5
| 24.205357 | 127 | 0.746723 | 4.277273 | false | false | false | false |
yaobanglin/viossvc
|
viossvc/Scenes/Share/Tour/CustomView/TourLeaderShareCell.swift
|
1
|
2886
|
//
// TourLeaderShareCell.swift
// viossvc
//
// Created by abx’s mac on 2016/11/30.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
class TourLeaderShareCell: OEZTableViewHScrollCell,OEZCalculateProtocol {
var shareModelArray : [TourShareTypeModel] = []
override func awakeFromNib() {
super.awakeFromNib()
hScrollView.registerNib(UINib.init(nibName: "TourLeaderShareScrollView", bundle: nil), forCellReuseIdentifier: "TourLeaderShareScrollView")
}
override func update(data: AnyObject!) {
shareModelArray = data as! [TourShareTypeModel]
hScrollView.reloadData()
}
static func calculateHeightWithData(data: AnyObject!) -> CGFloat {
return 105
}
override func numberColumnCountHScrollView(hScrollView: OEZHScrollView!) -> Int {
return shareModelArray.count
}
override func hScrollView(hScrollView: OEZHScrollView!, widthForColumnAtIndex columnIndex: Int) -> CGFloat {
return UIScreen.width() / 4.0
}
override func hScrollView(hScrollView: OEZHScrollView!, cellForColumnAtIndex columnIndex: Int) -> OEZHScrollViewCell! {
let cell = hScrollView.dequeueReusableCellWithIdentifier("TourLeaderShareScrollView") as? TourLeaderShareScrollView
cell?.update(shareModelArray[columnIndex])
return cell
}
override func hScrollView(hScrollView: OEZHScrollView!, didSelectColumnAtIndex columnIndex: Int) {
didSelectRowColumn(UInt(columnIndex))
}
}
class TourLeaderShareScrollView : OEZHScrollViewCell {
let imageView : UIImageView = UIImageView.init()
let titleName : UILabel = UILabel.init()
override func awakeFromNib() {
super.awakeFromNib()
let edge : CGFloat = (UIScreen.width() / 4.0 - 55 ) / 2.0
imageView.frame = CGRectMake(edge , 10, 55, 55)
imageView.layer.cornerRadius = 55 / 2.0
imageView.layer.masksToBounds = true
// imageView.backgroundColor = UIColor.blueColor()
titleName.frame = CGRectMake(0, 65,UIScreen.width() / 4.0, 105 - 65)
titleName.font = UIFont.systemFontOfSize(13)
titleName.textColor = UIColor(RGBHex: 0x131F32)
titleName.textAlignment = NSTextAlignment.Center
//
self.addSubview(imageView)
self.addSubview(titleName)
}
override func update(data: AnyObject!) {
let model = data as! TourShareTypeModel
imageView.kf_setImageWithURL(NSURL.init(string: model.type_pic), placeholderImage: UIImage(named: "square_placeholder"))
titleName.text = model.type_title
}
}
|
apache-2.0
|
b64e8879624491e62dbb79056c9357a2
| 29.648936 | 147 | 0.632072 | 4.891341 | false | false | false | false |
brentdax/swift
|
stdlib/public/SDK/Foundation/URLComponents.swift
|
5
|
28771
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/// A structure designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts.
///
/// Its behavior differs subtly from the `URL` struct, which conforms to older RFCs. However, you can easily obtain a `URL` based on the contents of a `URLComponents` or vice versa.
public struct URLComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing {
public typealias ReferenceType = NSURLComponents
internal var _handle: _MutableHandle<NSURLComponents>
/// Initialize with all components undefined.
public init() {
_handle = _MutableHandle(adoptingReference: NSURLComponents())
}
/// Initialize with the components of a URL.
///
/// If resolvingAgainstBaseURL is `true` and url is a relative URL, the components of url.absoluteURL are used. If the url string from the URL is malformed, nil is returned.
public init?(url: __shared URL, resolvingAgainstBaseURL resolve: Bool) {
guard let result = NSURLComponents(url: url, resolvingAgainstBaseURL: resolve) else { return nil }
_handle = _MutableHandle(adoptingReference: result)
}
/// Initialize with a URL string.
///
/// If the URLString is malformed, nil is returned.
public init?(string: __shared String) {
guard let result = NSURLComponents(string: string) else { return nil }
_handle = _MutableHandle(adoptingReference: result)
}
/// Returns a URL created from the NSURLComponents.
///
/// If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
public var url: URL? {
return _handle.map { $0.url }
}
// Returns a URL created from the NSURLComponents relative to a base URL.
///
/// If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
public func url(relativeTo base: URL?) -> URL? {
return _handle.map { $0.url(relativeTo: base) }
}
// Returns a URL string created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
@available(macOS 10.10, iOS 8.0, *)
public var string: String? {
return _handle.map { $0.string }
}
/// The scheme subcomponent of the URL.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
/// Attempting to set the scheme with an invalid scheme string will cause an exception.
public var scheme: String? {
get { return _handle.map { $0.scheme } }
set { _applyMutation { $0.scheme = newValue } }
}
/// The user subcomponent of the URL.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
///
/// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
public var user: String? {
get { return _handle.map { $0.user } }
set { _applyMutation { $0.user = newValue } }
}
/// The password subcomponent of the URL.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
///
/// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
public var password: String? {
get { return _handle.map { $0.password } }
set { _applyMutation { $0.password = newValue } }
}
/// The host subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var host: String? {
get { return _handle.map { $0.host } }
set { _applyMutation { $0.host = newValue } }
}
/// The port subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
/// Attempting to set a negative port number will cause a fatal error.
public var port: Int? {
get { return _handle.map { $0.port?.intValue } }
set { _applyMutation { $0.port = newValue != nil ? newValue as NSNumber? : nil as NSNumber?} }
}
/// The path subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var path: String {
get {
guard let result = _handle.map({ $0.path }) else { return "" }
return result
}
set {
_applyMutation { $0.path = newValue }
}
}
/// The query subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var query: String? {
get { return _handle.map { $0.query } }
set { _applyMutation { $0.query = newValue } }
}
/// The fragment subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
public var fragment: String? {
get { return _handle.map { $0.fragment } }
set { _applyMutation { $0.fragment = newValue } }
}
/// The user subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlUserAllowed`).
public var percentEncodedUser: String? {
get { return _handle.map { $0.percentEncodedUser } }
set { _applyMutation { $0.percentEncodedUser = newValue } }
}
/// The password subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPasswordAllowed`).
public var percentEncodedPassword: String? {
get { return _handle.map { $0.percentEncodedPassword } }
set { _applyMutation { $0.percentEncodedPassword = newValue } }
}
/// The host subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlHostAllowed`).
public var percentEncodedHost: String? {
get { return _handle.map { $0.percentEncodedHost } }
set { _applyMutation { $0.percentEncodedHost = newValue } }
}
/// The path subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPathAllowed`).
public var percentEncodedPath: String {
get {
guard let result = _handle.map({ $0.percentEncodedPath }) else { return "" }
return result
}
set {
_applyMutation { $0.percentEncodedPath = newValue }
}
}
/// The query subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlQueryAllowed`).
public var percentEncodedQuery: String? {
get { return _handle.map { $0.percentEncodedQuery } }
set { _applyMutation { $0.percentEncodedQuery = newValue } }
}
/// The fragment subcomponent, percent-encoded.
///
/// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlFragmentAllowed`).
public var percentEncodedFragment: String? {
get { return _handle.map { $0.percentEncodedFragment } }
set { _applyMutation { $0.percentEncodedFragment = newValue } }
}
@available(macOS 10.11, iOS 9.0, *)
private func _toStringRange(_ r : NSRange) -> Range<String.Index>? {
guard r.location != NSNotFound else { return nil }
let utf16Start = String.UTF16View.Index(encodedOffset: r.location)
let utf16End = String.UTF16View.Index(encodedOffset: r.location + r.length)
guard let s = self.string else { return nil }
guard let start = String.Index(utf16Start, within: s) else { return nil }
guard let end = String.Index(utf16End, within: s) else { return nil }
return start..<end
}
/// Returns the character range of the scheme in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfScheme: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfScheme })
}
/// Returns the character range of the user in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfUser: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfUser })
}
/// Returns the character range of the password in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfPassword: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfPassword })
}
/// Returns the character range of the host in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfHost: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfHost })
}
/// Returns the character range of the port in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfPort: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfPort })
}
/// Returns the character range of the path in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfPath: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfPath })
}
/// Returns the character range of the query in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfQuery: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfQuery })
}
/// Returns the character range of the fragment in the string returned by `var string`.
///
/// If the component does not exist, nil is returned.
/// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
@available(macOS 10.11, iOS 9.0, *)
public var rangeOfFragment: Range<String.Index>? {
return _toStringRange(_handle.map { $0.rangeOfFragment })
}
/// Returns an array of query items for this `URLComponents`, in the order in which they appear in the original query string.
///
/// Each `URLQueryItem` represents a single key-value pair,
///
/// Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the `URLComponents` has an empty query component, returns an empty array. If the `URLComponents` has no query component, returns nil.
///
/// The setter combines an array containing any number of `URLQueryItem`s, each of which represents a single key-value pair, into a query string and sets the `URLComponents` query property. Passing an empty array sets the query component of the `URLComponents` to an empty string. Passing nil removes the query component of the `URLComponents`.
///
/// - note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a `URLQueryItem` with a zero-length name and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value.
@available(macOS 10.10, iOS 8.0, *)
public var queryItems: [URLQueryItem]? {
get { return _handle.map { $0.queryItems } }
set { _applyMutation { $0.queryItems = newValue } }
}
/// Returns an array of query items for this `URLComponents`, in the order in which they appear in the original query string. Any percent-encoding in a query item name or value is retained
///
/// The setter combines an array containing any number of `URLQueryItem`s, each of which represents a single key-value pair, into a query string and sets the `URLComponents` query property. This property assumes the query item names and values are already correctly percent-encoded, and that the query item names do not contain the query item delimiter characters '&' and '='. Attempting to set an incorrectly percent-encoded query item or a query item name with the query item delimiter characters '&' and '=' will cause a `fatalError`.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public var percentEncodedQueryItems: [URLQueryItem]? {
get { return _handle.map { $0.percentEncodedQueryItems } }
set { _applyMutation { $0.percentEncodedQueryItems = newValue } }
}
public var hashValue: Int {
return _handle.map { $0.hash }
}
// MARK: - Bridging
fileprivate init(reference: __shared NSURLComponents) {
_handle = _MutableHandle(reference: reference)
}
public static func ==(lhs: URLComponents, rhs: URLComponents) -> Bool {
// Don't copy references here; no one should be storing anything
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
}
extension URLComponents : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
if let u = url {
return u.description
} else {
return self.customMirror.children.reduce("") {
$0.appending("\($1.label ?? ""): \($1.value) ")
}
}
}
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
if let s = self.scheme { c.append((label: "scheme", value: s)) }
if let u = self.user { c.append((label: "user", value: u)) }
if let pw = self.password { c.append((label: "password", value: pw)) }
if let h = self.host { c.append((label: "host", value: h)) }
if let p = self.port { c.append((label: "port", value: p)) }
c.append((label: "path", value: self.path))
if #available(macOS 10.10, iOS 8.0, *) {
if let qi = self.queryItems { c.append((label: "queryItems", value: qi)) }
}
if let f = self.fragment { c.append((label: "fragment", value: f)) }
let m = Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
return m
}
}
extension URLComponents : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSURLComponents.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLComponents {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) -> Bool {
result = URLComponents(reference: x)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLComponents?) -> URLComponents {
guard let src = source else { return URLComponents() }
return URLComponents(reference: src)
}
}
extension NSURLComponents : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URLComponents)
}
}
/// A single name-value pair, for use with `URLComponents`.
@available(macOS 10.10, iOS 8.0, *)
public struct URLQueryItem : ReferenceConvertible, Hashable, Equatable {
public typealias ReferenceType = NSURLQueryItem
fileprivate var _queryItem : NSURLQueryItem
public init(name: __shared String, value: __shared String?) {
_queryItem = NSURLQueryItem(name: name, value: value)
}
fileprivate init(reference: __shared NSURLQueryItem) { _queryItem = reference.copy() as! NSURLQueryItem }
fileprivate var reference : NSURLQueryItem { return _queryItem }
public var name : String {
get { return _queryItem.name }
set { _queryItem = NSURLQueryItem(name: newValue, value: value) }
}
public var value : String? {
get { return _queryItem.value }
set { _queryItem = NSURLQueryItem(name: name, value: newValue) }
}
public var hashValue: Int { return _queryItem.hash }
@available(macOS 10.10, iOS 8.0, *)
public static func ==(lhs: URLQueryItem, rhs: URLQueryItem) -> Bool {
return lhs._queryItem.isEqual(rhs as NSURLQueryItem)
}
}
@available(macOS 10.10, iOS 8.0, *)
extension URLQueryItem : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
if let v = value {
return "\(name)=\(v)"
} else {
return name
}
}
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
let c: [(label: String?, value: Any)] = [
("name", name),
("value", value as Any),
]
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
@available(macOS 10.10, iOS 8.0, *)
extension URLQueryItem : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSURLQueryItem.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLQueryItem {
return _queryItem
}
public static func _forceBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) -> Bool {
result = URLQueryItem(reference: x)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLQueryItem?) -> URLQueryItem {
var result: URLQueryItem?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
@available(macOS 10.10, iOS 8.0, *)
extension NSURLQueryItem : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URLQueryItem)
}
}
extension URLComponents : Codable {
private enum CodingKeys : Int, CodingKey {
case scheme
case user
case password
case host
case port
case path
case query
case fragment
}
public init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.scheme = try container.decodeIfPresent(String.self, forKey: .scheme)
self.user = try container.decodeIfPresent(String.self, forKey: .user)
self.password = try container.decodeIfPresent(String.self, forKey: .password)
self.host = try container.decodeIfPresent(String.self, forKey: .host)
self.port = try container.decodeIfPresent(Int.self, forKey: .port)
self.path = try container.decode(String.self, forKey: .path)
self.query = try container.decodeIfPresent(String.self, forKey: .query)
self.fragment = try container.decodeIfPresent(String.self, forKey: .fragment)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(self.scheme, forKey: .scheme)
try container.encodeIfPresent(self.user, forKey: .user)
try container.encodeIfPresent(self.password, forKey: .password)
try container.encodeIfPresent(self.host, forKey: .host)
try container.encodeIfPresent(self.port, forKey: .port)
try container.encode(self.path, forKey: .path)
try container.encodeIfPresent(self.query, forKey: .query)
try container.encodeIfPresent(self.fragment, forKey: .fragment)
}
}
|
apache-2.0
|
648cc99042c8d02d18dd9336b9347f2f
| 54.011472 | 541 | 0.68079 | 4.783209 | false | false | false | false |
zisko/swift
|
test/SILGen/pointer_conversion.swift
|
1
|
28062
|
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
func sideEffect1() -> Int { return 1 }
func sideEffect2() -> Int { return 2 }
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>) {}
func takesConstPointer(_ x: UnsafePointer<Int>) {}
func takesOptConstPointer(_ x: UnsafePointer<Int>?, and: Int) {}
func takesOptOptConstPointer(_ x: UnsafePointer<Int>??, and: Int) {}
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>, and: Int) {}
func takesConstPointer(_ x: UnsafePointer<Int>, and: Int) {}
func takesMutableVoidPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstVoidPointer(_ x: UnsafeRawPointer) {}
func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstRawPointer(_ x: UnsafeRawPointer) {}
func takesOptConstRawPointer(_ x: UnsafeRawPointer?, and: Int) {}
func takesOptOptConstRawPointer(_ x: UnsafeRawPointer??, and: Int) {}
// CHECK-LABEL: sil hidden @$S18pointer_conversion0A9ToPointeryySpySiG_SPySiGSvtF
// CHECK: bb0([[MP:%.*]] : $UnsafeMutablePointer<Int>, [[CP:%.*]] : $UnsafePointer<Int>, [[MRP:%.*]] : $UnsafeMutableRawPointer):
func pointerToPointer(_ mp: UnsafeMutablePointer<Int>,
_ cp: UnsafePointer<Int>, _ mrp: UnsafeMutableRawPointer) {
// There should be no conversion here
takesMutablePointer(mp)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @$S18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[MP]])
takesMutableVoidPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE_VOID_POINTER:%.*]] = function_ref @$S18pointer_conversion23takesMutableVoidPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_VOID_POINTER]]
takesMutableRawPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @$S18pointer_conversion22takesMutableRawPointeryySvF :
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]
takesConstPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>>
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$S18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]
takesConstVoidPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$S18pointer_conversion21takesConstVoidPointeryySVF
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(mp)
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$S18pointer_conversion20takesConstRawPointeryySVF :
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstPointer(cp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$S18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[CP]])
takesConstVoidPointer(cp)
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$S18pointer_conversion21takesConstVoidPointeryySVF
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(cp)
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$S18pointer_conversion20takesConstRawPointeryySVF
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstRawPointer(mrp)
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer, UnsafeRawPointer>
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$S18pointer_conversion20takesConstRawPointeryySVF
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
}
// CHECK-LABEL: sil hidden @$S18pointer_conversion14arrayToPointeryyF
func arrayToPointer() {
var ints = [1,2,3]
takesMutablePointer(&ints)
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @$Ss37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutablePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutablePointer<Int> on [[OWNER]]
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @$S18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstPointer(ints)
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$Ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @$S18pointer_conversion17takesConstPointeryySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesMutableRawPointer(&ints)
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @$Ss37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutableRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutableRawPointer on [[OWNER]]
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @$S18pointer_conversion22takesMutableRawPointeryySvF :
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(ints)
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$Ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$S18pointer_conversion20takesConstRawPointeryySVF :
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstPointer(ints, and: sideEffect1())
// CHECK: [[SIDE1:%.*]] = function_ref @$S18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @$Ss35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEPENDENT]]
// CHECK: [[TAKES_OPT_CONST_POINTER:%.*]] = function_ref @$S18pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF :
// CHECK: apply [[TAKES_OPT_CONST_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @$S18pointer_conversion15stringToPointeryySSF
func stringToPointer(_ s: String) {
takesConstVoidPointer(s)
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$Ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @$S18pointer_conversion21takesConstVoidPointeryySV{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(s)
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$Ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @$S18pointer_conversion20takesConstRawPointeryySV{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstRawPointer(s, and: sideEffect1())
// CHECK: [[SIDE1:%.*]] = function_ref @$S18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @$Ss40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEPENDENT]]
// CHECK: [[TAKES_OPT_CONST_RAW_POINTER:%.*]] = function_ref @$S18pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF :
// CHECK: apply [[TAKES_OPT_CONST_RAW_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @$S18pointer_conversion14inoutToPointeryyF
func inoutToPointer() {
var int = 0
// CHECK: [[INT:%.*]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[INT]]
takesMutablePointer(&int)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$S18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
var logicalInt: Int {
get { return 0 }
set { }
}
takesMutablePointer(&logicalInt)
// CHECK: [[GETTER:%.*]] = function_ref @$S18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$S18pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @$S18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
takesMutableRawPointer(&int)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$S18pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
takesMutableRawPointer(&logicalInt)
// CHECK: [[GETTER:%.*]] = function_ref @$S18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$S18pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @$S18pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
}
class C {}
func takesPlusOnePointer(_ x: UnsafeMutablePointer<C>) {}
func takesPlusZeroPointer(_ x: AutoreleasingUnsafeMutablePointer<C>) {}
func takesPlusZeroOptionalPointer(_ x: AutoreleasingUnsafeMutablePointer<C?>) {}
// CHECK-LABEL: sil hidden @$S18pointer_conversion19classInoutToPointeryyF
func classInoutToPointer() {
var c = C()
// CHECK: [[VAR:%.*]] = alloc_box ${ var C }
// CHECK: [[PB:%.*]] = project_box [[VAR]]
takesPlusOnePointer(&c)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_PLUS_ONE:%.*]] = function_ref @$S18pointer_conversion19takesPlusOnePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_PLUS_ONE]]
takesPlusZeroPointer(&c)
// CHECK: [[WRITEBACK:%.*]] = alloc_stack $@sil_unmanaged C
// CHECK: [[OWNED:%.*]] = load_borrow [[PB]]
// CHECK: [[UNOWNED:%.*]] = ref_to_unmanaged [[OWNED]]
// CHECK: store [[UNOWNED]] to [trivial] [[WRITEBACK]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITEBACK]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @$S18pointer_conversion20takesPlusZeroPointeryys026AutoreleasingUnsafeMutableF0VyAA1CCGF
// CHECK: apply [[TAKES_PLUS_ZERO]]
// CHECK: [[UNOWNED_OUT:%.*]] = load [trivial] [[WRITEBACK]]
// CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]]
// CHECK: [[OWNED_OUT_COPY:%.*]] = copy_value [[OWNED_OUT]]
// CHECK: assign [[OWNED_OUT_COPY]] to [[PB]]
var cq: C? = C()
takesPlusZeroOptionalPointer(&cq)
}
// Check that pointer types don't bridge anymore.
@objc class ObjCMethodBridging : NSObject {
// CHECK-LABEL: sil hidden [thunk] @$S18pointer_conversion18ObjCMethodBridgingC0A4Args{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (UnsafeMutablePointer<Int>, UnsafePointer<Int>, AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>, ObjCMethodBridging)
@objc func pointerArgs(_ x: UnsafeMutablePointer<Int>,
y: UnsafePointer<Int>,
z: AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>) {}
}
// rdar://problem/21505805
// CHECK-LABEL: sil hidden @$S18pointer_conversion22functionInoutToPointeryyF
func functionInoutToPointer() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_guaranteed () -> () }
var f: () -> () = {}
// CHECK: [[REABSTRACT_BUF:%.*]] = alloc_stack $@callee_guaranteed (@in ()) -> @out ()
// CHECK: address_to_pointer [[REABSTRACT_BUF]]
takesMutableVoidPointer(&f)
}
// rdar://problem/31781386
// CHECK-LABEL: sil hidden @$S18pointer_conversion20inoutPointerOrderingyyF
func inoutPointerOrdering() {
// CHECK: [[ARRAY_BOX:%.*]] = alloc_box ${ var Array<Int> }
// CHECK: [[ARRAY:%.*]] = project_box [[ARRAY_BOX]] :
// CHECK: store {{.*}} to [init] [[ARRAY]]
var array = [Int]()
// CHECK: [[SIDE1:%.*]] = function_ref @$S18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @$S18pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @$S18pointer_conversion19takesMutablePointer_3andySpySiG_SitF
// CHECK: apply [[TAKES_MUTABLE]]({{.*}}, [[RESULT2]])
// CHECK: strong_unpin
// CHECK: end_access [[ACCESS]]
takesMutablePointer(&array[sideEffect1()], and: sideEffect2())
// CHECK: [[SIDE1:%.*]] = function_ref @$S18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @$S18pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: [[TAKES_CONST:%.*]] = function_ref @$S18pointer_conversion17takesConstPointer_3andySPySiG_SitF
// CHECK: apply [[TAKES_CONST]]({{.*}}, [[RESULT2]])
// CHECK: end_access [[ACCESS]]
takesConstPointer(&array[sideEffect1()], and: sideEffect2())
}
// rdar://problem/31542269
// CHECK-LABEL: sil hidden @$S18pointer_conversion20optArrayToOptPointer5arrayySaySiGSg_tF
func optArrayToOptPointer(array: [Int]?) {
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @$S18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$S18pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @$S18pointer_conversion013optOptArrayTodD7Pointer5arrayySaySiGSgSg_tF
func optOptArrayToOptOptPointer(array: [Int]??) {
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @$S18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[T0:%.*]] = select_enum [[SOME_VALUE]]
// CHECK: cond_br [[T0]], [[SOME_SOME_BB:bb[0-9]+]], [[SOME_NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_NONE_BB]]:
// CHECK: destroy_value [[SOME_VALUE]]
// CHECK: br [[SOME_NONE_BB2:bb[0-9]+]]
// CHECK: [[SOME_SOME_BB]]:
// CHECK: [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.some!enumelt.1, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$S18pointer_conversion08takesOptD12ConstPointer_3andySPySiGSgSg_SitF
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[SOME_NONE_BB2]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafePointer<Int>>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @$S18pointer_conversion21optStringToOptPointer6stringySSSg_tF
func optStringToOptPointer(string: String?) {
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @$S18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$S18pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstRawPointer(string, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @$S18pointer_conversion014optOptStringTodD7Pointer6stringySSSgSg_tF
func optOptStringToOptOptPointer(string: String??) {
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @$S18pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// FIXME: this should really go somewhere that will make nil, not some(nil)
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[T0:%.*]] = select_enum [[SOME_VALUE]]
// CHECK: cond_br [[T0]], [[SOME_SOME_BB:bb[0-9]+]], [[SOME_NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_NONE_BB]]:
// CHECK: destroy_value [[SOME_VALUE]]
// CHECK: br [[SOME_NONE_BB2:bb[0-9]+]]
// CHECK: [[SOME_SOME_BB]]:
// CHECK: [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]]
// CHECK: [[CONVERT:%.*]] = function_ref @$Ss40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.some!enumelt.1, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>> on [[OWNER]]
// CHECK: [[TAKES:%.*]] = function_ref @$S18pointer_conversion08takesOptD15ConstRawPointer_3andySVSgSg_SitF
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[SOME_NONE_BB2]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafeRawPointer>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstRawPointer(string, and: sideEffect1())
}
|
apache-2.0
|
7ec497cd5f2bf6c74432050abf48cc8b
| 59.609071 | 259 | 0.643575 | 3.668715 | false | false | false | false |
DingSoung/CCExtension
|
Sources/WebKit/WKWebView+registerScheme.swift
|
2
|
1908
|
// Created by Songwen on 2018/8/29.
// Copyright © 2018 DingSoung. All rights reserved.
#if os(iOS)
import WebKit
import Foundation
extension WKWebView {
private class func browsing_contextController() -> (NSObject.Type)? {
guard let str = "YnJvd3NpbmdDb250ZXh0Q29udHJvbGxlcg==".base64Decode else { assertionFailure(); return nil }
// str: "browsingContextController"
guard let obj = WKWebView().value(forKey: str) else { return nil }
return type(of: obj) as? NSObject.Type
}
private class func perform_browsing_contextController(aSelector: Selector, schemes: Set<String>) -> Bool {
guard let obj = browsing_contextController(), obj.responds(to: aSelector), schemes.count > 0 else {
assertionFailure(); return false
}
var result = schemes.count > 0
schemes.forEach({ (scheme) in
let ret = obj.perform(aSelector, with: scheme)
result = result && (ret != nil)
})
return result
}
}
extension WKWebView {
@discardableResult public class func register(schemes: Set<String>) -> Bool {
guard let str = "cmVnaXN0ZXJTY2hlbWVGb3JDdXN0b21Qcm90b2NvbDo=".base64Decode else {
assertionFailure(); return false
}
// str: "registerSchemeForCustomProtocol:"
let register = NSSelectorFromString(str)
return perform_browsing_contextController(aSelector: register, schemes: schemes)
}
@discardableResult public class func unregister(schemes: Set<String>) -> Bool {
guard let str = "dW5yZWdpc3RlclNjaGVtZUZvckN1c3RvbVByb3RvY29sOg==".base64Decode else {
assertionFailure(); return false
}
//str: "unregisterSchemeForCustomProtocol:"
let unregister = NSSelectorFromString(str)
return perform_browsing_contextController(aSelector: unregister, schemes: schemes)
}
}
#endif
|
mit
|
1f1ef919e2e5d8a974e981b897b9c56f
| 38.729167 | 115 | 0.670163 | 4.074786 | false | false | false | false |
stephentyrone/swift
|
stdlib/public/core/DebuggerSupport.swift
|
5
|
8231
|
//===--- DebuggerSupport.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
@frozen // namespace
public enum _DebuggerSupport {
private enum CollectionStatus {
case notACollection
case collectionOfElements
case collectionOfPairs
case element
case pair
case elementOfPair
internal var isCollection: Bool {
return self != .notACollection
}
internal func getChildStatus(child: Mirror) -> CollectionStatus {
let disposition = child.displayStyle
if disposition == .collection { return .collectionOfElements }
if disposition == .dictionary { return .collectionOfPairs }
if disposition == .set { return .collectionOfElements }
if self == .collectionOfElements { return .element }
if self == .collectionOfPairs { return .pair }
if self == .pair { return .elementOfPair }
return .notACollection
}
}
private static func isClass(_ value: Any) -> Bool {
return type(of: value) is AnyClass
}
private static func checkValue<T>(
_ value: Any,
ifClass: (AnyObject) -> T,
otherwise: () -> T
) -> T {
if isClass(value) {
return ifClass(_unsafeDowncastToAnyObject(fromAny: value))
}
return otherwise()
}
private static func asObjectIdentifier(_ value: Any) -> ObjectIdentifier? {
return checkValue(value,
ifClass: { return ObjectIdentifier($0) },
otherwise: { return nil })
}
private static func asObjectAddress(_ value: Any) -> String {
let address = checkValue(value,
ifClass: { return unsafeBitCast($0, to: Int.self) },
otherwise: { return 0 })
return String(address, radix: 16, uppercase: false)
}
private static func asStringRepresentation(
value: Any?,
mirror: Mirror,
count: Int
) -> String? {
switch mirror.displayStyle {
case .optional? where count > 0:
return "\(mirror.subjectType)"
case .optional?:
return value.map(String.init(reflecting:))
case .collection?, .dictionary?, .set?, .tuple?:
return count == 1 ? "1 element" : "\(count) elements"
case .`struct`?, .`enum`?, nil:
switch value {
case let x as CustomDebugStringConvertible:
return x.debugDescription
case let x as CustomStringConvertible:
return x.description
case _ where count > 0:
return "\(mirror.subjectType)"
default:
return value.map(String.init(reflecting:))
}
case .`class`?:
switch value {
case let x as CustomDebugStringConvertible:
return x.debugDescription
case let x as CustomStringConvertible:
return x.description
case let x?:
// for a Class with no custom summary, mimic the Foundation default
return "<\(type(of: x)): 0x\(asObjectAddress(x))>"
default:
// but if I can't provide a value, just use the type anyway
return "\(mirror.subjectType)"
}
}
}
private static func ivarCount(mirror: Mirror) -> Int {
let ivars = mirror.superclassMirror.map(ivarCount) ?? 0
return ivars + mirror._children.count
}
private static func shouldExpand(
mirror: Mirror,
collectionStatus: CollectionStatus,
isRoot: Bool
) -> Bool {
if isRoot || collectionStatus.isCollection { return true }
if !mirror._children.isEmpty { return true }
if mirror.displayStyle == .`class` { return true }
if let sc = mirror.superclassMirror { return ivarCount(mirror: sc) > 0 }
return true
}
private static func printForDebuggerImpl<StreamType: TextOutputStream>(
value: Any?,
mirror: Mirror,
name: String?,
indent: Int,
maxDepth: Int,
isRoot: Bool,
parentCollectionStatus: CollectionStatus,
refsAlreadySeen: inout Set<ObjectIdentifier>,
maxItemCounter: inout Int,
target: inout StreamType
) {
guard maxItemCounter > 0 else { return }
guard shouldExpand(mirror: mirror,
collectionStatus: parentCollectionStatus,
isRoot: isRoot)
else { return }
maxItemCounter -= 1
print(String(repeating: " ", count: indent), terminator: "", to: &target)
// do not expand classes with no custom Mirror
// yes, a type can lie and say it's a class when it's not since we only
// check the displayStyle - but then the type would have a custom Mirror
// anyway, so there's that...
let willExpand = mirror.displayStyle != .`class` || value is CustomReflectable?
let count = mirror._children.count
let bullet = isRoot && (count == 0 || !willExpand) ? ""
: count == 0 ? "- "
: maxDepth <= 0 ? "▹ " : "▿ "
print(bullet, terminator: "", to: &target)
let collectionStatus = parentCollectionStatus.getChildStatus(child: mirror)
if let name = name {
print("\(name) : ", terminator: "", to: &target)
}
if let str = asStringRepresentation(value: value, mirror: mirror, count: count) {
print(str, terminator: "", to: &target)
}
if (maxDepth <= 0) || !willExpand {
print("", to: &target)
return
}
if let valueIdentifier = value.flatMap(asObjectIdentifier) {
if refsAlreadySeen.contains(valueIdentifier) {
print(" { ... }", to: &target)
return
} else {
refsAlreadySeen.insert(valueIdentifier)
}
}
print("", to: &target)
var printedElements = 0
if let sc = mirror.superclassMirror {
printForDebuggerImpl(
value: nil,
mirror: sc,
name: "super",
indent: indent + 2,
maxDepth: maxDepth - 1,
isRoot: false,
parentCollectionStatus: .notACollection,
refsAlreadySeen: &refsAlreadySeen,
maxItemCounter: &maxItemCounter,
target: &target)
}
for (optionalName,child) in mirror._children {
let childName = optionalName ?? "\(printedElements)"
if maxItemCounter <= 0 {
print(String(repeating: " ", count: indent+4), terminator: "", to: &target)
let remainder = count - printedElements
print("(\(remainder)", terminator: "", to: &target)
if printedElements > 0 {
print(" more", terminator: "", to: &target)
}
print(remainder == 1 ? " child)" : " children)", to: &target)
return
}
printForDebuggerImpl(
value: child,
mirror: Mirror(reflecting: child),
name: childName,
indent: indent + 2,
maxDepth: maxDepth - 1,
isRoot: false,
parentCollectionStatus: collectionStatus,
refsAlreadySeen: &refsAlreadySeen,
maxItemCounter: &maxItemCounter,
target: &target)
printedElements += 1
}
}
public static func stringForPrintObject(_ value: Any) -> String {
var maxItemCounter = Int.max
var refs = Set<ObjectIdentifier>()
var target = ""
printForDebuggerImpl(
value: value,
mirror: Mirror(reflecting: value),
name: nil,
indent: 0,
maxDepth: maxItemCounter,
isRoot: true,
parentCollectionStatus: .notACollection,
refsAlreadySeen: &refs,
maxItemCounter: &maxItemCounter,
target: &target)
return target
}
}
public func _stringForPrintObject(_ value: Any) -> String {
return _DebuggerSupport.stringForPrintObject(value)
}
public func _debuggerTestingCheckExpect(_: String, _: String) { }
// Utilities to get refcount(s) of class objects.
@_silgen_name("swift_retainCount")
public func _getRetainCount(_ Value: AnyObject) -> UInt
@_silgen_name("swift_unownedRetainCount")
public func _getUnownedRetainCount(_ Value: AnyObject) -> UInt
@_silgen_name("swift_weakRetainCount")
public func _getWeakRetainCount(_ Value: AnyObject) -> UInt
|
apache-2.0
|
2a671e7081df57679234e7a119befe44
| 29.928571 | 85 | 0.624407 | 4.495628 | false | false | false | false |
firebase/codelab-friendlychat-ios
|
ios/swift/FriendlyChatSwift/AppDelegate.swift
|
1
|
6062
|
//
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
// UserNotifications are only required for the optional FCM step
import UserNotifications
import Firebase
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any])
-> Bool {
return self.application(application,
open: url,
sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
annotation: "")
}
func application(_ application: UIApplication,
open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return GIDSignIn.sharedInstance().handle(url)
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
if let error = error {
print("Error \(error)")
return
}
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
accessToken: authentication.accessToken)
Auth.auth().signIn(with: credential) { (result, error) in
if let error = error {
print("Error \(error)")
return
}
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance().delegate = self
////////////////////////////////////////////////////////////////////////
// //
// CODE BELOW THIS POINT IS ONLY REQUIRED FOR THE OPTIONAL FCM STEP //
// //
////////////////////////////////////////////////////////////////////////
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions) {_,_ in }
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
showAlert(withUserInfo: userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
showAlert(withUserInfo: userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func showAlert(withUserInfo userInfo: [AnyHashable : Any]) {
let apsKey = "aps"
let gcmMessage = "alert"
let gcmLabel = "google.c.a.c_l"
if let aps = userInfo[apsKey] as? NSDictionary {
if let message = aps[gcmMessage] as? String {
DispatchQueue.main.async {
let alert = UIAlertController(title: userInfo[gcmLabel] as? String ?? "",
message: message, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .destructive, handler: nil)
alert.addAction(dismissAction)
self.window?.rootViewController?.presentedViewController?.present(alert, animated: true, completion: nil)
}
}
}
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
showAlert(withUserInfo: userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
showAlert(withUserInfo: userInfo)
completionHandler()
}
}
|
apache-2.0
|
992c92d71952c7deb455181c7bfb1922
| 39.413333 | 127 | 0.656054 | 5.515924 | false | false | false | false |
rherndon47/TIYAssignments
|
21 -- Mission Briefing Two Swift/20 -- Mission Briefing Two/ViewController.swift
|
1
|
2807
|
//
// ViewController.swift
// 20 -- Mission Briefing Two
//
// Created by Richard Herndon on 4/1/15.
// Copyright (c) 2015 Richard Herndon. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITextFieldDelegate
{
@IBOutlet var agentNameTextField : UITextField! // ! point means that these are optional
@IBOutlet var agenPasswordTextField : UITextField!
@IBOutlet var greetingLabel : UILabel!
@IBOutlet var missionBriefingTextView : UITextView!
override func viewDidLoad()
{
super.viewDidLoad()
agentNameTextField.delegate = self //set delegate to textfile
agenPasswordTextField.delegate = self
agentNameTextField.text = ""
agenPasswordTextField.text = ""
greetingLabel.text = ""
missionBriefingTextView.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func authenticateAgentButton(sender : AnyObject)
{
authenticateAgent()
}
func authenticateAgent()
{
if (!(agentNameTextField.text.isEmpty) && !(agenPasswordTextField.text.isEmpty))
{
self.view.backgroundColor = UIColor.greenColor()
var fullName = agentNameTextField.text
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String = fullNameArr[1]
// var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
greetingLabel.text = "Good evening Agent, \(lastName)"
missionBriefingTextView.text = "This mission will be an arduous one, fraught with peril. You will cover much strange and unfamiliar territory. Should you choose to accept this mission, Agent \(lastName), you will certainly be disavowed, but you will be doing your country a great service. This message will self destruct in 5 seconds. "
}
else
{
self.view.backgroundColor = UIColor.redColor()
}
}
func textFieldShouldReturn(textField: UITextField!) -> Bool //delegate method
{
textField.resignFirstResponder()
println("entered textFieldShouldReturn")
if !agentNameTextField.text.isEmpty && agenPasswordTextField.text.isEmpty
{
agentNameTextField.resignFirstResponder()
agenPasswordTextField.becomeFirstResponder()
}
if !agenPasswordTextField.text.isEmpty
{
agentNameTextField.resignFirstResponder()
authenticateAgent()
}
return true
}
}
|
cc0-1.0
|
18cbbeadc774954118ab5f6e74743e8e
| 32.023529 | 348 | 0.627716 | 5.276316 | false | false | false | false |
editfmah/AeonAPI
|
Sources/Settings.swift
|
1
|
2518
|
//
// Settings.swift
// scale
//
// Created by Adrian Herridge on 30/12/2016.
//
//
import Foundation
import SwiftyJSON
let defaultSettings = ["salt": "<NEEDS TO BE SET>", "port": 10000, "secret" : "<NEEDS TO BE SET>", "primary_node" : "127.0.0.1:11181", "backup_node" : "127.0.0.1:11181", "allow_wallet_downloads" : true, "export_location" : "/root/Dropbox/aeon/exports/", "backup_location" : "/root/Dropbox/aeon/backups/", "backup_hour" : 4, "use_dropbox" : true, "environment_name" : "production", "download_max_days" : "90", "max_downloads" : 3] as [String : Any]
class Settings {
private var settingsFilePath: String
private var values: JSON
init(path: String) {
settingsFilePath = path
values = JSON(defaultSettings)
reloadSettings()
}
private func reloadSettings() {
do {
let fileData = try Data(contentsOf: URL(fileURLWithPath: settingsFilePath))
values = JSON(data: fileData)
} catch {
writeSettings()
}
}
private func writeSettings() {
let str = values.description
do {
try str.write(toFile: settingsFilePath, atomically: true, encoding: .utf8)
} catch {
}
}
func salt() -> String {
return values["salt"].stringValue
}
func secret() -> String {
return values["secret"].stringValue
}
func primaryNode() -> String {
return values["primary_node"].stringValue
}
func backupLocation() -> String {
return values["backup_location"].stringValue
}
func exportLocation() -> String {
return values["export_location"].stringValue
}
func backupNode() -> String {
return values["backup_node"].stringValue
}
func environmentName() -> String {
return values["environment_name"].stringValue
}
func maxDownloadDays() -> Int {
return values["download_max_days"].intValue
}
func maxDownloads() -> Int {
return values["max_downloads"].intValue
}
func backupHour() -> Int {
return values["backup_hour"].intValue
}
func useDropbox() -> Bool {
return values["use_dropbox"].boolValue
}
func allowWalletDownloads() -> Bool {
return values["allow_wallet_downloads"].boolValue
}
func port() -> Int {
return values["port"].intValue
}
}
|
mit
|
3603e64597bb5d66755b3a66ac097d77
| 24.693878 | 447 | 0.57228 | 4.282313 | false | false | false | false |
hstdt/GodEye
|
GodEye/Classes/Controller/TabController/ConsoleController/EyesManager.swift
|
1
|
3320
|
//
// EyesManager.swift
// Pods
//
// Created by zixun on 17/1/18.
//
//
import Foundation
import ASLEye
import NetworkEye
import Log4G
import CrashEye
import ANREye
import LeakEye
class EyesManager: NSObject {
static let shared = EyesManager()
weak var delegate:ConsoleController?
fileprivate lazy var aslEye: ASLEye = { [unowned self] in
let new = ASLEye()
new.delegate = self.delegate
return new
}()
fileprivate lazy var anrEye: ANREye = { [unowned self] in
let new = ANREye()
new.delegate = self.delegate
return new
}()
fileprivate lazy var leakEye: LeakEye = { [unowned self] in
let new = LeakEye()
new.delegate = self.delegate
return new
}()
}
//--------------------------------------------------------------------------
// MARK: - ASL EYE
//--------------------------------------------------------------------------
extension EyesManager {
func isASLEyeOpening() -> Bool {
return self.aslEye.isOpening
}
/// open asl eye
func openASLEye() {
self.aslEye.delegate = self.delegate!
self.aslEye.open(with: 1)
}
/// close asl eys
func closeASLEye() {
self.aslEye.close()
}
}
//--------------------------------------------------------------------------
// MARK: - LOG4G
//--------------------------------------------------------------------------
extension EyesManager {
func isLog4GEyeOpening() -> Bool {
return Log4G.delegateCount > 0
}
func openLog4GEye() {
Log4G.add(delegate: self.delegate!)
}
func closeLog4GEye() {
Log4G.remove(delegate: self.delegate!)
}
}
//--------------------------------------------------------------------------
// MARK: - CRASH
//--------------------------------------------------------------------------
extension EyesManager {
func isCrashEyeOpening() -> Bool {
return CrashEye.isOpen
}
func openCrashEye() {
CrashEye.add(delegate: self.delegate!)
}
func closeCrashEye() {
CrashEye.remove(delegate: self.delegate!)
}
}
//--------------------------------------------------------------------------
// MARK: - NETWORK
//--------------------------------------------------------------------------
extension EyesManager {
func isNetworkEyeOpening() -> Bool {
return NetworkEye.isWatching
}
func openNetworkEye() {
NetworkEye.add(observer: self.delegate!)
}
func closeNetworkEye() {
NetworkEye.remove(observer: self.delegate!)
}
}
//--------------------------------------------------------------------------
// MARK: - ANREye
//--------------------------------------------------------------------------
extension EyesManager {
func isANREyeOpening() -> Bool {
return self.anrEye.isOpening
}
func openANREye() {
self.anrEye.open(with: 2)
}
func closeANREye() {
self.anrEye.close()
}
}
extension EyesManager {
func isLeakEyeOpening() -> Bool {
return self.leakEye.isOpening
}
func openLeakEye() {
self.leakEye.open()
}
func closeLeakEye() {
self.leakEye.close()
}
}
|
mit
|
11a6799165835dd589baa05f3a4788d6
| 21.585034 | 76 | 0.445482 | 4.825581 | false | false | false | false |
sharath-cliqz/browser-ios
|
Client/Cliqz/Frontend/Browser/History/HistoryModule.swift
|
2
|
4698
|
//
// HistoryModule.swift
// Client
//
// Created by Mahmoud Adam on 10/19/17.
// Copyright © 2017 Mozilla. All rights reserved.
//
import UIKit
import Storage
import Shared
class HistoryEntry {
let id: Int
let title: String
let date: Date?
init(id: Int, title: String, date: Date? = nil) {
self.id = id
self.title = title
self.date = date
}
func useRightCell() -> Bool {
return false
}
}
class HistoryUrlEntry : HistoryEntry {
let url: URL
init(id: Int, title: String, url: URL, date: Date? = nil) {
self.url = url
super.init(id: id, title: title, date: date)
}
}
class HistoryQueryEntry : HistoryEntry {
override func useRightCell() -> Bool {
return true
}
}
class HistoryModule: NSObject {
class func getHistory(profile: Profile, completion: @escaping (_ result:[HistoryEntry], _ error:NSError?) -> Void) {
//limit is static for now.
//later there will be a mechanism in place to handle a variable limit and offset.
//It will keep a window of results that updates as the user scrolls.
let backgroundQueue = DispatchQueue.global(qos: .background)
profile.history.getHistoryVisits(0, limit: 500).uponQueue(backgroundQueue) { (result) in
let historyEntries = processHistoryResults(result: result)
completion(historyEntries, nil) //TODO: there should be a better error handling mechanism here
}
}
private class func processHistoryResults(result: Maybe<Cursor<Site>>) -> [HistoryEntry] {
var historyResults: [HistoryEntry] = []
if let sites = result.successValue {
for site in sites {
if let domain = site,
let id = domain.id, let url = URL(string: domain.url) {
let title = domain.title
var date:Date? = nil
if let latestDate = domain.latestVisit?.date {
date = Date(timeIntervalSince1970: Double(latestDate) / 1000000.0) // second = microsecond * 10^-6
}
if url.scheme == QueryScheme {
let result = HistoryQueryEntry(id: id, title: title.unescape(), date: date)
historyResults.append(result)
} else {
let result = HistoryUrlEntry(id: id, title: title, url: url, date: date)
historyResults.append(result)
}
}
}
}
return historyResults
}
class func getFavorites(profile: Profile, completion: @escaping (_ result:[HistoryEntry], _ error:NSError?) -> Void) {
//limit is static for now.
//later there will be a mechanism in place to handle a variable limit and offset.
//It will keep a window of results that updates as the user scrolls.
let backgroundQueue = DispatchQueue.global(qos: .background)
profile.bookmarks.getBookmarks().uponQueue(backgroundQueue) { (result) in
let HistoryEntries = processFavoritesResults(result: result)
completion(HistoryEntries, nil) //TODO: there should be a better error handling mechanism here
}
}
private class func processFavoritesResults(result: Maybe<Cursor<BookmarkNode>>) -> [HistoryEntry] {
var favoritesResults: [HistoryEntry] = []
if let bookmarks = result.successValue {
for bookmark in bookmarks {
switch (bookmark) {
case let item as CliqzBookmarkItem:
if let id = item.id, let url = URL(string: item.url) {
let date = Date(timeIntervalSince1970: Double(item.bookmarkedDate) / 1000.0) // second = millisecond * 10^-3
let result = HistoryUrlEntry(id: id, title: item.title, url: url, date: date)
favoritesResults.append(result)
}
default:
debugPrint("Not a bookmark item")
}
}
}
return favoritesResults
}
class func removeHistoryEntries(profile: Profile, ids: [Int]) {
profile.history.removeHistory(ids)
}
class func removeFavoritesEntry(profile: Profile, url: URL, callback: @escaping () -> ()) {
profile.bookmarks.modelFactory >>== {
$0.removeByURL(url.absoluteString)
.uponQueue(DispatchQueue.main) { res in
callback()
}
}
}
}
|
mpl-2.0
|
1ae3035450312bd3dd8709a1d8f23b1a
| 35.130769 | 132 | 0.567171 | 4.720603 | false | false | false | false |
sharath-cliqz/browser-ios
|
Client/Cliqz/Foundation/BloomFilter/SipHash/SipHashable.swift
|
4
|
2004
|
//
// SipHashable.swift
// SipHash
//
// Created by Károly Lőrentey on 2016-11-14.
// Copyright © 2016 Károly Lőrentey.
//
/// A variant of `Hashable` that makes it simpler to generate good hash values.
///
/// Instead of `hashValue`, you need to implement `addHashes`, adding
/// data that should contribute to the hash to the supplied hasher.
/// The hasher takes care of blending the supplied data together.
///
/// Example implementation:
///
/// ```
/// struct Book: SipHashable {
/// var title: String
/// var pageCount: Int
///
/// func appendHashes(to hasher: inout SipHasher) {
/// hasher.append(title)
/// hasher.append(pageCount)
/// }
///
/// static func ==(left: Book, right: Book) -> Bool {
/// return left.title == right.title && left.pageCount == right.pageCount
/// }
/// }
/// ```
public protocol SipHashable: Hashable {
/// Add components of `self` that should contribute to hashing to `hash`.
func appendHashes(to hasher: inout SipHasher)
}
extension SipHashable {
/// The hash value, calculated using `addHashes`.
///
/// Hash values are not guaranteed to be equal across different executions of your program.
/// Do not save hash values to use during a future execution.
public var hashValue: Int {
var hasher = SipHasher()
appendHashes(to: &hasher)
return hasher.finalize()
}
}
extension SipHasher {
//MARK: Appending Hashable Values
/// Add hashing components in `value` to this hash. This method simply calls `value.addHashes`.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append<H: SipHashable>(_ value: H) {
value.appendHashes(to: &self)
}
/// Add the hash value of `value` to this hash.
///
/// - Requires: `finalize()` hasn't been called on this instance yet.
public mutating func append<H: Hashable>(_ value: H) {
append(value.hashValue)
}
}
|
mpl-2.0
|
a1da82478ada45a57d3b535071c37b72
| 29.753846 | 99 | 0.637819 | 4.071283 | false | false | false | false |
akaralar/SafariHistorySearch
|
SafariHistorySearchFramework/SafariSearch.swift
|
1
|
3292
|
import Foundation
public class Search: NSObject {
static let HISTORY_PATH = "/Caches/Metadata/Safari/History"
static let MAX_RESULTS = 20
static var outputPipe = NSPipe()
static var totalString = ""
static var args = ""
public static func start(arguments: Array<String>) {
outputPipe = NSPipe()
let fileManager = NSFileManager()
let libraryURL = try! fileManager.URLForDirectory(.LibraryDirectory,
inDomain: .UserDomainMask,
appropriateForURL: nil,
create: false)
let fullPath = libraryURL.path!.stringByAppendingString(HISTORY_PATH)
var mdfindArgs = ["mdfind", "-onlyin", fullPath]
let concattedArgs = arguments.dropFirst()
mdfindArgs.appendContentsOf(concattedArgs)
args = concattedArgs.reduce("") { total, next in
return total + next + " "
}.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))
shell(mdfindArgs)
}
static func shell(args: [String]) -> Int32 {
let task = NSTask()
task.launchPath = "/usr/bin/env"
task.arguments = args
captureStandardOutput(task)
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
static func captureStandardOutput(task: NSTask) {
task.standardOutput = outputPipe
outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotify()
NSNotificationCenter.defaultCenter().addObserverForName(
NSFileHandleDataAvailableNotification,
object: outputPipe.fileHandleForReading ,
queue: nil) { notification in
let output = outputPipe.fileHandleForReading.availableData
let outputString = String(data: output, encoding: NSUTF8StringEncoding) ?? ""
dispatch_async(
dispatch_get_main_queue(), {
let previousOutput = totalString ?? ""
let nextOutput = previousOutput + "\n" + outputString
totalString = nextOutput
let paths = totalString.componentsSeparatedByString("\n").filter {
component in
return component != ""
}
showItemsAtPaths(paths)
task.terminate()
})
}
}
static func showItemsAtPaths(paths: [String]) {
var results = [AlfredResult]()
for path in paths {
let item = HistoryItem(fromPlistAtURL: NSURL.fileURLWithPath(path))
guard let alfredResult = item.alfredResult() else {
continue
}
results.append(alfredResult)
if results.count >= MAX_RESULTS {
break
}
}
let root = ["items": results.map { $0.toDictionary() }]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(root, options: .PrettyPrinted)
let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
print(json)
}
}
|
gpl-3.0
|
22121ced8ebaf907600446ea78ef9a41
| 35.988764 | 97 | 0.560146 | 5.695502 | false | false | false | false |
CosmicMind/Motion
|
Sources/MotionModifier.swift
|
3
|
19127
|
/*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* 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 final class MotionModifier {
/// A reference to the callback that applies the MotionModifier.
internal let apply: (inout MotionTargetState) -> Void
/**
An initializer that accepts a given callback.
- Parameter applyFunction: A given callback.
*/
public init(applyFunction: @escaping (inout MotionTargetState) -> Void) {
apply = applyFunction
}
}
public extension MotionModifier {
/**
Animates the view with a matching motion identifier.
- Parameter _ motionIdentifier: A String.
- Returns: A MotionModifier.
*/
static func source(_ motionIdentifier: String) -> MotionModifier {
return MotionModifier {
$0.motionIdentifier = motionIdentifier
}
}
/**
Animates the view's current masksToBounds to the
given masksToBounds.
- Parameter masksToBounds: A boolean value indicating the
masksToBounds state.
- Returns: A MotionModifier.
*/
static func masksToBounds(_ masksToBounds: Bool) -> MotionModifier {
return MotionModifier {
$0.masksToBounds = masksToBounds
}
}
/**
Animates the view's current background color to the
given color.
- Parameter color: A UIColor.
- Returns: A MotionModifier.
*/
static func background(color: UIColor) -> MotionModifier {
return MotionModifier {
$0.backgroundColor = color.cgColor
}
}
/**
Animates the view's current border color to the
given color.
- Parameter color: A UIColor.
- Returns: A MotionModifier.
*/
static func border(color: UIColor) -> MotionModifier {
return MotionModifier {
$0.borderColor = color.cgColor
}
}
/**
Animates the view's current border width to the
given width.
- Parameter width: A CGFloat.
- Returns: A MotionModifier.
*/
static func border(width: CGFloat) -> MotionModifier {
return MotionModifier {
$0.borderWidth = width
}
}
/**
Animates the view's current corner radius to the
given radius.
- Parameter radius: A CGFloat.
- Returns: A MotionModifier.
*/
static func corner(radius: CGFloat) -> MotionModifier {
return MotionModifier {
$0.cornerRadius = radius
}
}
/**
Animates the view's current transform (perspective, scale, rotate)
to the given one.
- Parameter _ transform: A CATransform3D.
- Returns: A MotionModifier.
*/
static func transform(_ transform: CATransform3D) -> MotionModifier {
return MotionModifier {
$0.transform = transform
}
}
/**
Animates the view's current perspective to the given one through
a CATransform3D object.
- Parameter _ perspective: A CGFloat.
- Returns: A MotionModifier.
*/
static func perspective(_ perspective: CGFloat) -> MotionModifier {
return MotionModifier {
var t = $0.transform ?? CATransform3DIdentity
t.m34 = 1 / -perspective
$0.transform = t
}
}
/**
Animates the view's current rotate to the given x, y,
and z values.
- Parameter x: A CGFloat.
- Parameter y: A CGFloat.
- Parameter z: A CGFloat.
- Returns: A MotionModifier.
*/
static func rotate(x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> MotionModifier {
return MotionModifier {
$0.transform = CATransform3DRotate($0.transform ?? CATransform3DIdentity, x, 1, 0, 0)
$0.transform = CATransform3DRotate($0.transform!, y, 0, 1, 0)
$0.transform = CATransform3DRotate($0.transform!, z, 0, 0, 1)
}
}
/**
Animates the view's current rotate to the given point.
- Parameter _ point: A CGPoint.
- Parameter z: A CGFloat, default is 0.
- Returns: A MotionModifier.
*/
static func rotate(_ point: CGPoint, z: CGFloat = 0) -> MotionModifier {
return .rotate(x: point.x, y: point.y, z: z)
}
/**
Rotate 2d.
- Parameter _ z: A CGFloat.
- Returns: A MotionModifier.
*/
static func rotate(_ z: CGFloat) -> MotionModifier {
return .rotate(z: z)
}
/**
Animates the view's current scale to the given x, y, z scale values.
- Parameter x: A CGFloat.
- Parameter y: A CGFloat.
- Parameter z: A CGFloat.
- Returns: A MotionModifier.
*/
static func scale(x: CGFloat = 1, y: CGFloat = 1, z: CGFloat = 1) -> MotionModifier {
return MotionModifier {
$0.transform = CATransform3DScale($0.transform ?? CATransform3DIdentity, x, y, z)
}
}
/**
Animates the view's current x & y scale to the given scale value.
- Parameter _ xy: A CGFloat.
- Returns: A MotionModifier.
*/
static func scale(_ xy: CGFloat) -> MotionModifier {
return .scale(x: xy, y: xy)
}
/**
Animates the view's current translation to the given
x, y, and z values.
- Parameter x: A CGFloat.
- Parameter y: A CGFloat.
- Parameter z: A CGFloat.
- Returns: A MotionModifier.
*/
static func translate(x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> MotionModifier {
return MotionModifier {
$0.transform = CATransform3DTranslate($0.transform ?? CATransform3DIdentity, x, y, z)
}
}
/**
Animates the view's current translation to the given
point value (x & y), and a z value.
- Parameter _ point: A CGPoint.
- Parameter z: A CGFloat, default is 0.
- Returns: A MotionModifier.
*/
static func translate(_ point: CGPoint, z: CGFloat = 0) -> MotionModifier {
return .translate(x: point.x, y: point.y, z: z)
}
/**
Animates the view's current position to the given point.
- Parameter _ point: A CGPoint.
- Returns: A MotionModifier.
*/
static func position(_ point: CGPoint) -> MotionModifier {
return MotionModifier {
$0.position = point
}
}
/**
Animates a view's current position to the given x and y values.
- Parameter x: A CGloat.
- Parameter y: A CGloat.
- Returns: A MotionModifier.
*/
static func position(x: CGFloat, y: CGFloat) -> MotionModifier {
return .position(CGPoint(x: x, y: y))
}
/// Forces the view to not fade during a transition.
static var forceNonFade = MotionModifier {
$0.nonFade = true
}
/// Fades the view in during a transition.
static var fadeIn = MotionModifier.fade(1)
/// Fades the view out during a transition.
static var fadeOut = MotionModifier.fade(0)
/**
Animates the view's current opacity to the given one.
- Parameter to opacity: A Double.
- Returns: A MotionModifier.
*/
static func fade(_ opacity: Double) -> MotionModifier {
return MotionModifier {
$0.opacity = opacity
}
}
/**
Animates the view's current opacity to the given one.
- Parameter _ opacity: A Double.
- Returns: A MotionModifier.
*/
static func opacity(_ opacity: Double) -> MotionModifier {
return MotionModifier {
$0.opacity = opacity
}
}
/**
Animates the view's current zPosition to the given position.
- Parameter _ position: An Int.
- Returns: A MotionModifier.
*/
static func zPosition(_ position: CGFloat) -> MotionModifier {
return MotionModifier {
$0.zPosition = position
}
}
/**
Animates the view's current size to the given one.
- Parameter _ size: A CGSize.
- Returns: A MotionModifier.
*/
static func size(_ size: CGSize) -> MotionModifier {
return MotionModifier {
$0.size = size
}
}
/**
Animates the view's current size to the given width and height.
- Parameter width: A CGFloat.
- Parameter height: A CGFloat.
- Returns: A MotionModifier.
*/
static func size(width: CGFloat, height: CGFloat) -> MotionModifier {
return .size(CGSize(width: width, height: height))
}
/**
Animates the view's current shadow path to the given one.
- Parameter path: A CGPath.
- Returns: A MotionModifier.
*/
static func shadow(path: CGPath) -> MotionModifier {
return MotionModifier {
$0.shadowPath = path
}
}
/**
Animates the view's current shadow color to the given one.
- Parameter color: A UIColor.
- Returns: A MotionModifier.
*/
static func shadow(color: UIColor) -> MotionModifier {
return MotionModifier {
$0.shadowColor = color.cgColor
}
}
/**
Animates the view's current shadow offset to the given one.
- Parameter offset: A CGSize.
- Returns: A MotionModifier.
*/
static func shadow(offset: CGSize) -> MotionModifier {
return MotionModifier {
$0.shadowOffset = offset
}
}
/**
Animates the view's current shadow opacity to the given one.
- Parameter opacity: A Float.
- Returns: A MotionModifier.
*/
static func shadow(opacity: Float) -> MotionModifier {
return MotionModifier {
$0.shadowOpacity = opacity
}
}
/**
Animates the view's current shadow radius to the given one.
- Parameter radius: A CGFloat.
- Returns: A MotionModifier.
*/
static func shadow(radius: CGFloat) -> MotionModifier {
return MotionModifier {
$0.shadowRadius = radius
}
}
/**
Animates the view's contents rect to the given one.
- Parameter rect: A CGRect.
- Returns: A MotionModifier.
*/
static func contents(rect: CGRect) -> MotionModifier {
return MotionModifier {
$0.contentsRect = rect
}
}
/**
Animates the view's contents scale to the given one.
- Parameter scale: A CGFloat.
- Returns: A MotionModifier.
*/
static func contents(scale: CGFloat) -> MotionModifier {
return MotionModifier {
$0.contentsScale = scale
}
}
/**
The duration of the view's animation.
- Parameter _ duration: A TimeInterval.
- Returns: A MotionModifier.
*/
static func duration(_ duration: TimeInterval) -> MotionModifier {
return MotionModifier {
$0.duration = duration
}
}
/**
Sets the view's animation duration to the longest
running animation within a transition.
*/
static var durationMatchLongest = MotionModifier {
$0.duration = .infinity
}
/**
Delays the animation of a given view.
- Parameter _ time: TimeInterval.
- Returns: A MotionModifier.
*/
static func delay(_ time: TimeInterval) -> MotionModifier {
return MotionModifier {
$0.delay = time
}
}
/**
Sets the view's timing function for the transition.
- Parameter _ timingFunction: A CAMediaTimingFunction.
- Returns: A MotionModifier.
*/
static func timingFunction(_ timingFunction: CAMediaTimingFunction) -> MotionModifier {
return MotionModifier {
$0.timingFunction = timingFunction
}
}
/**
Available in iOS 9+, animates a view using the spring API,
given a stiffness and damping.
- Parameter stiffness: A CGFlloat.
- Parameter damping: A CGFloat.
- Returns: A MotionModifier.
*/
@available(iOS 9, *)
static func spring(stiffness: CGFloat, damping: CGFloat) -> MotionModifier {
return MotionModifier {
$0.spring = (stiffness, damping)
}
}
/**
Animates the natural curve of a view. A value of 1 represents
a curve in a downward direction, and a value of -1
represents a curve in an upward direction.
- Parameter intensity: A CGFloat.
- Returns: A MotionModifier.
*/
static func arc(intensity: CGFloat = 1) -> MotionModifier {
return MotionModifier {
$0.arc = intensity
}
}
/**
Animates subviews with an increasing delay between each animation.
- Parameter delta: A TimeInterval.
- Parameter direction: A CascadeDirection.
- Parameter animationDelayedUntilMatchedViews: A boolean indicating whether
or not to delay the subview animation until all have started.
- Returns: A MotionModifier.
*/
static func cascade(delta: TimeInterval = 0.02, direction: CascadeDirection = .topToBottom, animationDelayedUntilMatchedViews: Bool = false) -> MotionModifier {
return MotionModifier {
$0.cascade = (delta, direction, animationDelayedUntilMatchedViews)
}
}
/**
Creates an overlay on the animating view with a given color and opacity.
- Parameter color: A UIColor.
- Parameter opacity: A CGFloat.
- Returns: A MotionModifier.
*/
static func overlay(color: UIColor, opacity: CGFloat) -> MotionModifier {
return MotionModifier {
$0.overlay = (color.cgColor, opacity)
}
}
}
// conditional modifiers
public extension MotionModifier {
/**
Apply modifiers when the condition is true.
- Parameter _ condition: A MotionConditionalContext.
- Returns: A Boolean.
*/
static func when(_ condition: @escaping (MotionConditionalContext) -> Bool, _ modifiers: [MotionModifier]) -> MotionModifier {
return MotionModifier {
if nil == $0.conditionalModifiers {
$0.conditionalModifiers = []
}
$0.conditionalModifiers!.append((condition, modifiers))
}
}
static func when(_ condition: @escaping (MotionConditionalContext) -> Bool, _ modifiers: MotionModifier...) -> MotionModifier {
return .when(condition, modifiers)
}
/**
Apply modifiers when matched.
- Parameter _ modifiers: A list of modifiers.
- Returns: A MotionModifier.
*/
static func whenMatched(_ modifiers: MotionModifier...) -> MotionModifier {
return .when({ $0.isMatched }, modifiers)
}
/**
Apply modifiers when presenting.
- Parameter _ modifiers: A list of modifiers.
- Returns: A MotionModifier.
*/
static func whenPresenting(_ modifiers: MotionModifier...) -> MotionModifier {
return .when({ $0.isPresenting }, modifiers)
}
/**
Apply modifiers when dismissing.
- Parameter _ modifiers: A list of modifiers.
- Returns: A MotionModifier.
*/
static func whenDismissing(_ modifiers: MotionModifier...) -> MotionModifier {
return .when({ !$0.isPresenting }, modifiers)
}
/**
Apply modifiers when appearingg.
- Parameter _ modifiers: A list of modifiers.
- Returns: A MotionModifier.
*/
static func whenAppearing(_ modifiers: MotionModifier...) -> MotionModifier {
return .when({ $0.isAppearing }, modifiers)
}
/**
Apply modifiers when disappearing.
- Parameter _ modifiers: A list of modifiers.
- Returns: A MotionModifier.
*/
static func whenDisappearing(_ modifiers: MotionModifier...) -> MotionModifier {
return .when({ !$0.isAppearing }, modifiers)
}
}
public extension MotionModifier {
/**
Apply transitions directly to the view at the start of the transition.
The transitions supplied here won't be animated.
For source views, transitions are set directly at the begining of the animation.
For destination views, they replace the target state (final appearance).
*/
static func beginWith(_ modifiers: [MotionModifier]) -> MotionModifier {
return MotionModifier {
if nil == $0.beginState {
$0.beginState = []
}
$0.beginState?.append(contentsOf: modifiers)
}
}
static func beginWith(modifiers: [MotionModifier]) -> MotionModifier {
return .beginWith(modifiers)
}
static func beginWith(_ modifiers: MotionModifier...) -> MotionModifier {
return .beginWith(modifiers)
}
/**
Use global coordinate space.
When using global coordinate space. The view becomes an independent view that is not
a subview of any view. It won't move when its parent view moves, and won't be affected
by parent view attributes.
When a view is matched, this is automatically enabled.
The `source` transition will also enable this.
*/
static var useGlobalCoordinateSpace = MotionModifier {
$0.coordinateSpace = .global
}
/// Ignore all motion transition attributes for a view's direct subviews.
static var ignoreSubviewTransitions: MotionModifier = .ignoreSubviewTransitions()
/**
Ignore all motion transition attributes for a view's subviews.
- Parameter recursive: If false, will only ignore direct subviews' transitions.
default false.
*/
static func ignoreSubviewTransitions(recursive: Bool = false) -> MotionModifier {
return MotionModifier {
$0.ignoreSubviewTransitions = recursive
}
}
/**
This will create a snapshot optimized for different view types.
For custom views or views with masking, useOptimizedSnapshot might create snapshots
that appear differently than the actual view.
In that case, use .useNormalSnapshot or .useSlowRenderSnapshot to disable the optimization.
This transition actually does nothing by itself since .useOptimizedSnapshot is the default.
*/
static var useOptimizedSnapshot = MotionModifier {
$0.snapshotType = .optimized
}
/// Create a snapshot using snapshotView(afterScreenUpdates:).
static var useNormalSnapshot = MotionModifier {
$0.snapshotType = .normal
}
/**
Create a snapshot using layer.render(in: currentContext).
This is slower than .useNormalSnapshot but gives more accurate snapshots for some views
(eg. UIStackView).
*/
static var useLayerRenderSnapshot = MotionModifier {
$0.snapshotType = .layerRender
}
/**
Force Motion to not create any snapshots when animating this view.
This will mess up the view hierarchy, therefore, view controllers have to rebuild
their view structure after the transition finishes.
*/
static var useNoSnapshot = MotionModifier {
$0.snapshotType = .noSnapshot
}
/**
Force the view to animate (Motion will create animation contexts & snapshots for them, so
that they can be interactive).
*/
static var forceAnimate = MotionModifier {
$0.forceAnimate = true
}
/**
Force Motion to use scale based size animation. This will convert all .size transitions into
a .scale transition. This is to help Motion animate layers that doesn't support bounds animations.
This also gives better performance.
*/
static var useScaleBasedSizeChange = MotionModifier {
$0.useScaleBasedSizeChange = true
}
}
|
mit
|
0a0ed2e3812f5cd58985fa8df0fafac8
| 28.33589 | 162 | 0.673394 | 4.355955 | false | false | false | false |
victoraliss0n/FireRecord
|
FireRecord/Source/Extensions/Database/RealTime/ReadableInRealTime+FirebaseModel.swift
|
2
|
1099
|
//
// ReadableInRealTime+FirebaseModel.swift
// FireRecord
//
// Created by Victor Alisson on 28/09/17.
//
import Foundation
import FirebaseCommunity
public extension ReadableInRealTime where Self: FirebaseModel {
@discardableResult static func observeAll(when propertyEventType: PropertyEventType, completion: @escaping (_ object: [Self]
) -> Void) -> DatabaseHandle {
var handle: DatabaseHandle = 0
handle = Self.classPath.observe(propertyEventType.rawValue) { snapshot in
let firebaseModels = Self.getFirebaseModels(snapshot)
completion(firebaseModels)
}
return handle
}
@discardableResult static func observeFind(when propertyEventType: PropertyEventType, completion: @escaping (_ objects: [Self]) -> Void) -> DatabaseHandle {
var handle: DatabaseHandle? = 0
handle = Self.fireRecordQuery?.observe(propertyEventType.rawValue) { snapshot in
let firebaseModels = Self.getFirebaseModels(snapshot)
completion(firebaseModels)
}
return handle ?? 0
}
}
|
mit
|
8ba3bff3b94f5aecc0bff8be05333265
| 34.451613 | 159 | 0.686988 | 4.862832 | false | false | false | false |
remirobert/Kinder
|
KinderExample/KinderExample/ViewController.swift
|
1
|
1998
|
//
// ViewController.swift
// tindView
//
// Created by Remi Robert on 04/03/15.
// Copyright (c) 2015 Remi Robert. All rights reserved.
//
import UIKit
class ViewController: UIViewController, KinderDelegate {
var data: Array<KinderModelCard>! = Array()
let controller = KinderViewController()
func acceptCard(card: KinderModelCard?) {
}
func cancelCard(card: KinderModelCard?) {
}
func fetchData(int: Int, completion: (()->())?) {
let newCard = Model()
if let url = NSURL(string: "http://thecatapi.com/api/images/get?format=src&type=gif") {
if let data = NSData(contentsOfURL: url) {
newCard.image = UIImage(data: data)
newCard.content = "cat"
newCard.desc = "Image from the thecatapi.com\nUpdated daily with hundreds of new Kittys"
self.data.append(newCard)
NSLog("fetch new data")
}
else {
completion!()
return
}
}
else {
completion!()
return
}
if self.data.count == 10 {
completion!()
return
}
else {
self.fetchData(0, completion)
}
}
func signalReload() {
println("call signal")
data.removeAll(keepCapacity: false)
self.fetchData(0, completion: { () -> () in
self.controller.reloadData()
})
println("end signl")
}
func reloadCard() -> [KinderModelCard]? {
NSLog("reload data")
return data
}
override func viewDidAppear(animated: Bool) {
fetchData(0, completion: { () -> () in
self.controller.delegate = self
self.presentViewController(self.controller, animated: true, completion: nil)
})
}
}
|
mit
|
d0902e483de6b54cbdf3284bdb114df4
| 23.365854 | 104 | 0.505005 | 4.657343 | false | false | false | false |
melvitax/AFImageHelper
|
Sources/ImageHelper.swift
|
1
|
30675
|
//
// ImageHelper.swift
//
// ImageHelper
// Version 3.2.2
//
// Created by Melvin Rivera on 7/5/14.
// Copyright (c) 2014 All Forces. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
import CoreGraphics
import Accelerate
public enum UIImageContentMode {
case scaleToFill, scaleAspectFit, scaleAspectFill
}
public extension UIImage {
/**
A singleton shared NSURL cache used for images from URL
*/
static var shared: NSCache<AnyObject, AnyObject>! {
struct StaticSharedCache {
static var shared: NSCache<AnyObject, AnyObject>? = NSCache()
}
return StaticSharedCache.shared!
}
// MARK: Image from solid color
/**
Creates a new solid color image.
- Parameter color: The color to fill the image with.
- Parameter size: Image size (defaults: 10x10)
- Returns A new image
*/
convenience init?(color: UIColor, size: CGSize = CGSize(width: 10, height: 10)) {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
self.init(cgImage:(UIGraphicsGetImageFromCurrentImageContext()?.cgImage!)!)
UIGraphicsEndImageContext()
}
// MARK: Image from gradient colors
/**
Creates a gradient color image.
- Parameter gradientColors: An array of colors to use for the gradient.
- Parameter size: Image size (defaults: 10x10)
- Returns A new image
*/
convenience init?(gradientColors:[UIColor], size:CGSize = CGSize(width: 10, height: 10), locations: [Float] = [] )
{
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let context = UIGraphicsGetCurrentContext()
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors = gradientColors.map {(color: UIColor) -> AnyObject! in return color.cgColor as AnyObject! } as NSArray
let gradient: CGGradient
if locations.count > 0 {
let cgLocations = locations.map { CGFloat($0) }
gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: cgLocations)!
} else {
gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: nil)!
}
context!.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: size.height), options: CGGradientDrawingOptions(rawValue: 0))
self.init(cgImage:(UIGraphicsGetImageFromCurrentImageContext()?.cgImage!)!)
UIGraphicsEndImageContext()
}
/**
Applies gradient color overlay to an image.
- Parameter gradientColors: An array of colors to use for the gradient.
- Parameter locations: An array of locations to use for the gradient.
- Parameter blendMode: The blending type to use.
- Returns A new image
*/
func apply(gradientColors: [UIColor], locations: [Float] = [], blendMode: CGBlendMode = CGBlendMode.normal) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(blendMode)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context?.draw(self.cgImage!, in: rect)
// Create gradient
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors = gradientColors.map {(color: UIColor) -> AnyObject! in return color.cgColor as AnyObject! } as NSArray
let gradient: CGGradient
if locations.count > 0 {
let cgLocations = locations.map { CGFloat($0) }
gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: cgLocations)!
} else {
gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: nil)!
}
// Apply gradient
context?.clip(to: rect, mask: self.cgImage!)
context?.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: size.height), options: CGGradientDrawingOptions(rawValue: 0))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image!;
}
// MARK: Image with Text
/**
Creates a text label image.
- Parameter text: The text to use in the label.
- Parameter font: The font (default: System font of size 18)
- Parameter color: The text color (default: White)
- Parameter backgroundColor: The background color (default:Gray).
- Parameter size: Image size (default: 10x10)
- Parameter offset: Center offset (default: 0x0)
- Returns A new image
*/
convenience init?(text: String, font: UIFont = UIFont.systemFont(ofSize: 18), color: UIColor = UIColor.white, backgroundColor: UIColor = UIColor.gray, size: CGSize = CGSize(width: 100, height: 100), offset: CGPoint = CGPoint(x: 0, y: 0)) {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
label.font = font
label.text = text
label.textColor = color
label.textAlignment = .center
label.backgroundColor = backgroundColor
let image = UIImage(fromView: label)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
image?.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
self.init(cgImage:(UIGraphicsGetImageFromCurrentImageContext()?.cgImage!)!)
UIGraphicsEndImageContext()
}
// MARK: Image from UIView
/**
Creates an image from a UIView.
- Parameter fromView: The source view.
- Returns A new image
*/
convenience init?(fromView view: UIView) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
//view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
self.init(cgImage:(UIGraphicsGetImageFromCurrentImageContext()?.cgImage!)!)
UIGraphicsEndImageContext()
}
// MARK: Image with Radial Gradient
// Radial background originally from: http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_shadings/dq_shadings.html
/**
Creates a radial gradient.
- Parameter startColor: The start color
- Parameter endColor: The end color
- Parameter radialGradientCenter: The gradient center (default:0.5,0.5).
- Parameter radius: Radius size (default: 0.5)
- Parameter size: Image size (default: 100x100)
- Returns A new image
*/
convenience init?(startColor: UIColor, endColor: UIColor, radialGradientCenter: CGPoint = CGPoint(x: 0.5, y: 0.5), radius: Float = 0.5, size: CGSize = CGSize(width: 100, height: 100)) {
UIGraphicsBeginImageContextWithOptions(size, true, 0)
let num_locations: Int = 2
let locations: [CGFloat] = [0.0, 1.0] as [CGFloat]
let startComponents = startColor.cgColor.components!
let endComponents = endColor.cgColor.components!
let components: [CGFloat] = [startComponents[0], startComponents[1], startComponents[2], startComponents[3], endComponents[0], endComponents[1], endComponents[2], endComponents[3]]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorSpace: colorSpace, colorComponents: components, locations: locations, count: num_locations)
// Normalize the 0-1 ranged inputs to the width of the image
let aCenter = CGPoint(x: radialGradientCenter.x * size.width, y: radialGradientCenter.y * size.height)
let aRadius = CGFloat(min(size.width, size.height)) * CGFloat(radius)
// Draw it
UIGraphicsGetCurrentContext()?.drawRadialGradient(gradient!, startCenter: aCenter, startRadius: 0, endCenter: aCenter, endRadius: aRadius, options: CGGradientDrawingOptions.drawsAfterEndLocation)
self.init(cgImage:(UIGraphicsGetImageFromCurrentImageContext()?.cgImage!)!)
// Clean up
UIGraphicsEndImageContext()
}
// MARK: Alpha
/**
Returns true if the image has an alpha layer.
*/
var hasAlpha: Bool {
let alpha: CGImageAlphaInfo = self.cgImage!.alphaInfo
switch alpha {
case .first, .last, .premultipliedFirst, .premultipliedLast:
return true
default:
return false
}
}
/**
Returns a copy of the given image, adding an alpha channel if it doesn't already have one.
*/
func applyAlpha() -> UIImage? {
if hasAlpha {
return self
}
let imageRef = self.cgImage;
let width = imageRef?.width;
let height = imageRef?.height;
let colorSpace = imageRef?.colorSpace
// The bitsPerComponent and bitmapInfo values are hard-coded to prevent an "unsupported parameter combination" error
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo().rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
let offscreenContext = CGContext(data: nil, width: width!, height: height!, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace!, bitmapInfo: bitmapInfo.rawValue)
// Draw the image into the context and retrieve the new image, which will now have an alpha layer
let rect: CGRect = CGRect(x: 0, y: 0, width: CGFloat(width!), height: CGFloat(height!))
offscreenContext?.draw(imageRef!, in: rect)
let imageWithAlpha = UIImage(cgImage: (offscreenContext?.makeImage()!)!)
return imageWithAlpha
}
/**
Returns a copy of the image with a transparent border of the given size added around its edges. i.e. For rotating an image without getting jagged edges.
- Parameter padding: The padding amount.
- Returns A new image.
*/
func apply(padding: CGFloat) -> UIImage? {
// If the image does not have an alpha layer, add one
let image = self.applyAlpha()
if image == nil {
return nil
}
let rect = CGRect(x: 0, y: 0, width: size.width + padding * 2, height: size.height + padding * 2)
// Build a context that's the same dimensions as the new size
let colorSpace = self.cgImage?.colorSpace
let bitmapInfo = self.cgImage?.bitmapInfo
let bitsPerComponent = self.cgImage?.bitsPerComponent
let context = CGContext(data: nil, width: Int(rect.size.width), height: Int(rect.size.height), bitsPerComponent: bitsPerComponent!, bytesPerRow: 0, space: colorSpace!, bitmapInfo: (bitmapInfo?.rawValue)!)
// Draw the image in the center of the context, leaving a gap around the edges
let imageLocation = CGRect(x: padding, y: padding, width: image!.size.width, height: image!.size.height)
context?.draw(self.cgImage!, in: imageLocation)
// Create a mask to make the border transparent, and combine it with the image
let transparentImage = UIImage(cgImage: (context?.makeImage()?.masking(imageRef(withPadding: padding, size: rect.size))!)!)
return transparentImage
}
/**
Creates a mask that makes the outer edges transparent and everything else opaque. The size must include the entire mask (opaque part + transparent border).
- Parameter padding: The padding amount.
- Parameter size: The size of the image.
- Returns A Core Graphics Image Ref
*/
fileprivate func imageRef(withPadding padding: CGFloat, size: CGSize) -> CGImage {
// Build a context that's the same dimensions as the new size
let colorSpace = CGColorSpaceCreateDeviceGray()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo().rawValue | CGImageAlphaInfo.none.rawValue)
let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
// Start with a mask that's entirely transparent
context?.setFillColor(UIColor.black.cgColor)
context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
// Make the inner part (within the border) opaque
context?.setFillColor(UIColor.white.cgColor)
context?.fill(CGRect(x: padding, y: padding, width: size.width - padding * 2, height: size.height - padding * 2))
// Get an image of the context
let maskImageRef = context?.makeImage()
return maskImageRef!
}
// MARK: Crop
/**
Creates a cropped copy of an image.
- Parameter bounds: The bounds of the rectangle inside the image.
- Returns A new image
*/
func crop(bounds: CGRect) -> UIImage? {
return UIImage(cgImage: (self.cgImage?.cropping(to: bounds)!)!,
scale: 0.0, orientation: self.imageOrientation)
}
func cropToSquare() -> UIImage? {
let size = CGSize(width: self.size.width * self.scale, height: self.size.height * self.scale)
let shortest = min(size.width, size.height)
let left: CGFloat = (size.width > shortest) ? (size.width - shortest) / 2 : 0
let top: CGFloat = (size.height > shortest) ? (size.height - shortest) / 2 : 0
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
let insetRect = rect.insetBy(dx: left, dy: top)
return crop(bounds: insetRect)
}
// MARK: Resize
/**
Creates a resized copy of an image.
- Parameter size: The new size of the image.
- Parameter contentMode: The way to handle the content in the new size.
- Returns A new image
*/
func resize(toSize: CGSize, contentMode: UIImageContentMode = .scaleToFill) -> UIImage? {
let horizontalRatio = size.width / self.size.width;
let verticalRatio = size.height / self.size.height;
var ratio: CGFloat!
switch contentMode {
case .scaleToFill:
ratio = 1
case .scaleAspectFill:
ratio = max(horizontalRatio, verticalRatio)
case .scaleAspectFit:
ratio = min(horizontalRatio, verticalRatio)
}
let rect = CGRect(x: 0, y: 0, width: size.width * ratio, height: size.height * ratio)
// Fix for a colorspace / transparency issue that affects some types of
// images. See here: http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/comment-page-2/#comment-39951
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: nil, width: Int(rect.size.width), height: Int(rect.size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
let transform = CGAffineTransform.identity
// Rotate and/or flip the image if required by its orientation
context?.concatenate(transform);
// Set the quality level to use when rescaling
context!.interpolationQuality = CGInterpolationQuality(rawValue: 3)!
//CGContextSetInterpolationQuality(context, CGInterpolationQuality(kCGInterpolationHigh.value))
// Draw into the context; this scales the image
context?.draw(self.cgImage!, in: rect)
// Get the resized image from the context and a UIImage
let newImage = UIImage(cgImage: (context?.makeImage()!)!, scale: self.scale, orientation: self.imageOrientation)
return newImage;
}
// MARK: Corner Radius
/**
Creates a new image with rounded corners.
- Parameter cornerRadius: The corner radius.
- Returns A new image
*/
func roundCorners(cornerRadius: CGFloat) -> UIImage? {
// If the image does not have an alpha layer, add one
let imageWithAlpha = applyAlpha()
if imageWithAlpha == nil {
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let width = imageWithAlpha?.cgImage?.width
let height = imageWithAlpha?.cgImage?.height
let bits = imageWithAlpha?.cgImage?.bitsPerComponent
let colorSpace = imageWithAlpha?.cgImage?.colorSpace
let bitmapInfo = imageWithAlpha?.cgImage?.bitmapInfo
let context = CGContext(data: nil, width: width!, height: height!, bitsPerComponent: bits!, bytesPerRow: 0, space: colorSpace!, bitmapInfo: (bitmapInfo?.rawValue)!)
let rect = CGRect(x: 0, y: 0, width: CGFloat(width!)*scale, height: CGFloat(height!)*scale)
context?.beginPath()
if (cornerRadius == 0) {
context?.addRect(rect)
} else {
context?.saveGState()
context?.translateBy(x: rect.minX, y: rect.minY)
context?.scaleBy(x: cornerRadius, y: cornerRadius)
let fw = rect.size.width / cornerRadius
let fh = rect.size.height / cornerRadius
context?.move(to: CGPoint(x: fw, y: fh/2))
context?.addArc(tangent1End: CGPoint(x: fw, y: fh), tangent2End: CGPoint(x: fw/2, y: fh), radius: 1)
context?.addArc(tangent1End: CGPoint(x: 0, y: fh), tangent2End: CGPoint(x: 0, y: fh/2), radius: 1)
context?.addArc(tangent1End: CGPoint(x: 0, y: 0), tangent2End: CGPoint(x: fw/2, y: 0), radius: 1)
context?.addArc(tangent1End: CGPoint(x: fw, y: 0), tangent2End: CGPoint(x: fw, y: fh/2), radius: 1)
context?.restoreGState()
}
context?.closePath()
context?.clip()
context?.draw(imageWithAlpha!.cgImage!, in: rect)
let image = UIImage(cgImage: (context?.makeImage()!)!, scale:scale, orientation: .up)
UIGraphicsEndImageContext()
return image
}
/**
Creates a new image with rounded corners and border.
- Parameter cornerRadius: The corner radius.
- Parameter border: The size of the border.
- Parameter color: The color of the border.
- Returns A new image
*/
func roundCorners(cornerRadius: CGFloat, border: CGFloat, color: UIColor) -> UIImage? {
return roundCorners(cornerRadius: cornerRadius)?.apply(border: border, color: color)
}
/**
Creates a new circle image.
- Returns A new image
*/
func roundCornersToCircle() -> UIImage? {
let shortest = min(size.width, size.height)
return cropToSquare()?.roundCorners(cornerRadius: shortest/2)
}
/**
Creates a new circle image with a border.
- Parameter border :CGFloat The size of the border.
- Parameter color :UIColor The color of the border.
- Returns UIImage?
*/
func roundCornersToCircle(withBorder border: CGFloat, color: UIColor) -> UIImage? {
let shortest = min(size.width, size.height)
return cropToSquare()?.roundCorners(cornerRadius: shortest/2, border: border, color: color)
}
// MARK: Border
/**
Creates a new image with a border.
- Parameter border: The size of the border.
- Parameter color: The color of the border.
- Returns A new image
*/
func apply(border: CGFloat, color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let width = self.cgImage?.width
let height = self.cgImage?.height
let bits = self.cgImage?.bitsPerComponent
let colorSpace = self.cgImage?.colorSpace
let bitmapInfo = self.cgImage?.bitmapInfo
let context = CGContext(data: nil, width: width!, height: height!, bitsPerComponent: bits!, bytesPerRow: 0, space: colorSpace!, bitmapInfo: (bitmapInfo?.rawValue)!)
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
context?.setStrokeColor(red: red, green: green, blue: blue, alpha: alpha)
context?.setLineWidth(border)
let rect = CGRect(x: 0, y: 0, width: size.width*scale, height: size.height*scale)
let inset = rect.insetBy(dx: border*scale, dy: border*scale)
context?.strokeEllipse(in: inset)
context?.draw(self.cgImage!, in: inset)
let image = UIImage(cgImage: (context?.makeImage()!)!)
UIGraphicsEndImageContext()
return image
}
// MARK: Image Effects
/**
Applies a light blur effect to the image
- Returns New image or nil
*/
func applyLightEffect() -> UIImage? {
return applyBlur(withRadius: 30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8)
}
/**
Applies a extra light blur effect to the image
- Returns New image or nil
*/
func applyExtraLightEffect() -> UIImage? {
return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8)
}
/**
Applies a dark blur effect to the image
- Returns New image or nil
*/
func applyDarkEffect() -> UIImage? {
return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8)
}
/**
Applies a color tint to an image
- Parameter color: The tint color
- Returns New image or nil
*/
func applyTintEffect(tintColor: UIColor) -> UIImage? {
let effectColorAlpha: CGFloat = 0.6
var effectColor = tintColor
let componentCount = tintColor.cgColor.numberOfComponents
if componentCount == 2 {
var b: CGFloat = 0
if tintColor.getWhite(&b, alpha: nil) {
effectColor = UIColor(white: b, alpha: effectColorAlpha)
}
} else {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) {
effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha)
}
}
return applyBlur(withRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1.0)
}
/**
Applies a blur to an image based on the specified radius, tint color saturation and mask image
- Parameter blurRadius: The radius of the blur.
- Parameter tintColor: The optional tint color.
- Parameter saturationDeltaFactor: The detla for saturation.
- Parameter maskImage: The optional image for masking.
- Returns New image or nil
*/
func applyBlur(withRadius blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
guard size.width > 0 && size.height > 0 && cgImage != nil else {
return nil
}
if maskImage != nil {
guard maskImage?.cgImage != nil else {
return nil
}
}
let imageRect = CGRect(origin: CGPoint.zero, size: size)
var effectImage = self
let hasBlur = blurRadius > CGFloat(FLT_EPSILON)
let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > CGFloat(FLT_EPSILON)
if (hasBlur || hasSaturationChange) {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let effectInContext = UIGraphicsGetCurrentContext()
effectInContext?.scaleBy(x: 1.0, y: -1.0)
effectInContext?.translateBy(x: 0, y: -size.height)
effectInContext?.draw(cgImage!, in: imageRect)
var effectInBuffer = vImage_Buffer(
data: effectInContext?.data,
height: UInt((effectInContext?.height)!),
width: UInt((effectInContext?.width)!),
rowBytes: (effectInContext?.bytesPerRow)!)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
let effectOutContext = UIGraphicsGetCurrentContext()
var effectOutBuffer = vImage_Buffer(
data: effectOutContext?.data,
height: UInt((effectOutContext?.height)!),
width: UInt((effectOutContext?.width)!),
rowBytes: (effectOutContext?.bytesPerRow)!)
if hasBlur {
let inputRadius = blurRadius * UIScreen.main.scale
let sqrtPi: CGFloat = CGFloat(sqrt(M_PI * 2.0))
var radius = UInt32(floor(inputRadius * 3.0 * sqrtPi / 4.0 + 0.5))
if radius % 2 != 1 {
radius += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s: CGFloat = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let matrixSize = floatingPointSaturationMatrix.count
var saturationMatrix = [Int16](repeating: 0, count: matrixSize)
for i: Int in 0 ..< matrixSize {
saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
}
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let outputContext = UIGraphicsGetCurrentContext()
outputContext?.scaleBy(x: 1.0, y: -1.0)
outputContext?.translateBy(x: 0, y: -size.height)
// Draw base image.
outputContext?.draw(self.cgImage!, in: imageRect)
// Draw effect image.
if hasBlur {
outputContext?.saveGState()
if let image = maskImage {
outputContext?.clip(to: imageRect, mask: image.cgImage!);
}
outputContext?.draw(effectImage.cgImage!, in: imageRect)
outputContext?.restoreGState()
}
// Add in color tint.
if let color = tintColor {
outputContext?.saveGState()
outputContext?.setFillColor(color.cgColor)
outputContext?.fill(imageRect)
outputContext?.restoreGState()
}
// Output image is ready.
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
// MARK: Image From URL
/**
Creates a new image from a URL with optional caching. If cached, the cached image is returned. Otherwise, a place holder is used until the image from web is returned by the closure.
- Parameter url: The image URL.
- Parameter placeholder: The placeholder image.
- Parameter shouldCacheImage: Weather or not we should cache the NSURL response (default: true)
- Parameter closure: Returns the image from the web the first time is fetched.
- Returns A new image
*/
class func image(fromURL url: String, placeholder: UIImage, shouldCacheImage: Bool = true, closure: @escaping (_ image: UIImage?) -> ()) -> UIImage? {
// From Cache
if shouldCacheImage {
if let image = UIImage.shared.object(forKey: url as AnyObject) as? UIImage {
closure(nil)
return image
}
}
// Fetch Image
let session = URLSession(configuration: URLSessionConfiguration.default)
if let nsURL = URL(string: url) {
session.dataTask(with: nsURL, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
DispatchQueue.main.async {
closure(nil)
}
}
if let data = data, let image = UIImage(data: data) {
if shouldCacheImage {
UIImage.shared.setObject(image, forKey: url as AnyObject)
}
DispatchQueue.main.async {
closure(image)
}
}
session.finishTasksAndInvalidate()
}).resume()
}
return placeholder
}
}
|
mit
|
ad1a256ce3e508ebd929d73505c3be96
| 40.677989 | 243 | 0.615583 | 4.851336 | false | false | false | false |
themonki/onebusaway-iphone
|
OneBusAway/ui/MapTable/ChevronCardCell.swift
|
1
|
3164
|
//
// ChevronCardCell.swift
// OneBusAway
//
// Created by Aaron Brethorst on 9/12/18.
// Copyright © 2018 OneBusAway. All rights reserved.
//
import UIKit
import OBAKit
import SnapKit
class ChevronCardCell: SelfSizingCollectionCell {
override open func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
contentStack.removeArrangedSubview(imageView)
imageView.removeFromSuperview()
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = OBATheme.mapTableBackgroundColor
let imageViewWrapper = imageView.oba_embedInWrapperView(withConstraints: false)
imageViewWrapper.backgroundColor = .white
imageView.snp.remakeConstraints { make in
make.width.equalTo(16.0)
make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: OBATheme.defaultPadding, bottom: 0, right: 0))
}
let cardWrapper = contentStack.oba_embedInCardWrapper()
contentView.addSubview(cardWrapper)
cardWrapper.snp.makeConstraints { make in
make.edges.equalToSuperview().inset(SelfSizingCollectionCell.leftRightInsets)
}
contentView.layer.addSublayer(separator)
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func layoutSubviews() {
super.layoutSubviews()
let bounds = contentView.bounds
let height: CGFloat = 0.5
let sideInset = OBATheme.defaultEdgeInsets.left
separator.frame = CGRect(x: sideInset, y: bounds.height - height, width: bounds.width - (2 * sideInset), height: height)
}
// MARK: - Properties
private lazy var contentStack: UIStackView = {
return UIStackView.oba_horizontalStack(withArrangedSubviews: [imageView, contentWrapper, chevronWrapper])
}()
public let contentWrapper: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
return view
}()
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = .white
imageView.contentMode = .scaleAspectFit
return imageView
}()
private let separator: CALayer = {
let layer = CALayer()
layer.backgroundColor = UIColor(red: 200 / 255.0, green: 199 / 255.0, blue: 204 / 255.0, alpha: 1).cgColor
return layer
}()
private let chevronWrapper: UIView = {
let chevronImage = UIImageView(image: #imageLiteral(resourceName: "chevron"))
chevronImage.tintColor = .darkGray
let chevronWrapper = chevronImage.oba_embedInWrapperView(withConstraints: false)
chevronWrapper.backgroundColor = .white
chevronImage.snp.makeConstraints { make in
make.height.equalTo(14)
make.width.equalTo(8)
make.leading.trailing.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: OBATheme.defaultPadding))
make.centerY.equalToSuperview()
}
return chevronWrapper
}()
}
|
apache-2.0
|
da8082f70a56f04c82330ea603bf1282
| 33.380435 | 132 | 0.670882 | 4.903876 | false | false | false | false |
jeremyabannister/JABSwiftCore
|
JABSwiftCore/CGRectExtension.swift
|
1
|
2435
|
//
// CGRectExtension.swift
// JABSwiftCore
//
// Created by Jeremy Bannister on 4/19/15.
// Copyright (c) 2015 Jeremy Bannister. All rights reserved.
//
import Foundation
import UIKit
public extension CGRect {
// MARK:
// MARK: Properties
// MARK:
public var x: CGFloat {
get { return self.origin.x }
set { self.origin.x = newValue } }
public var y: CGFloat {
get { return self.origin.y }
set { self.origin.y = newValue } }
public var left: CGFloat {
get { return self.x } }
public var right: CGFloat {
get { return self.x + size.width } }
public var top: CGFloat {
get { return self.y } }
public var bottom: CGFloat {
get { return self.y + size.height } }
public var zeroedOrigin: CGRect {
get { return CGRect(origin: .zero, size: size) } }
// MARK:
// MARK: Methods
// MARK:
public func containsPoint(_ point: CGPoint) -> Bool {
if ( point.x < self.x ) { return false }
if ( point.y < self.y ) { return false }
if ( point.x > self.right ) { return false }
if ( point.y > self.bottom ) { return false }
return true
}
public func translated (by point: CGPoint) -> CGRect {
return CGRect(x: self.x + point.x, y: self.y + point.y, width: self.size.width, height: self.size.height)
}
public static func rect (encompassing rect1: CGRect, and rect2: CGRect) -> CGRect {
let x = min(of: rect1.x, rect2.x)
let y = min(of: rect1.y, rect2.y)
let width = max(of: rect1.right, rect2.right) - x
let height = max(of: rect1.bottom, rect2.bottom) - y
return CGRect(x: x, y: y, width: width, height: height)
}
public func rect (encompassing rect: CGRect) -> CGRect {
return CGRect.rect(encompassing: self, and: rect)
}
public static func ~= (_ lhs: CGRect, _ rhs: CGRect) -> Bool {
let epsilon: CGFloat = 0.001
if abs(lhs.origin.x - rhs.origin.x) > epsilon { return false }
if abs(lhs.origin.y - rhs.origin.y) > epsilon { return false }
if abs(lhs.size.width - rhs.size.width) > epsilon { return false }
if abs(lhs.size.height - rhs.size.height) > epsilon { return false }
return true
}
// ---------------
// MARK: Print
// ---------------
public func print () { Swift.print(self.description) }
}
extension CGRect: CustomStringConvertible {
public var description: String { return "(\(x), \(y), \(width), \(height))" }
}
|
mit
|
4c8bf0016933035ab0137153e0292b6f
| 26.359551 | 109 | 0.607392 | 3.449008 | false | false | false | false |
programersun/HiChongSwift
|
HiChongSwift/ZXYImageBrowser/ZXY_SheetView.swift
|
1
|
8545
|
//
// ZXY_SheetView.swift
// ZXYPrettysHealth
//
// Created by 宇周 on 15/1/16.
// Copyright (c) 2015年 宇周. All rights reserved.
//
import UIKit
protocol ZXY_SheetViewDelegate : class
{
/**
sheet点击代理时间
:param: sheetView 所创建的sheetView 实例
:param: index 非负表示用户点击按钮 ,-1表示点击取消
:returns: 返回空
*/
func clickItemAtIndex(sheetView: ZXY_SheetView,index: Int) -> Void
}
class ZXY_SheetView: UIView {
private var titleString : String?
private var cancelString: String?
private var listString : [String]?
private var currentTable : UITableView!
private var imgBack : UIImageView?
private var tableHeight = 30.0
private var _parentView : UIView?
private var backCo = UIColor(red: 218/255.0, green: 214/255.0, blue: 218/255.0, alpha: 1)
weak var delegate : ZXY_SheetViewDelegate?
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
/**
实例化方法
:param: zxyTitle 标题 设置为nil
:param: cancelBtn 取消按钮的标题
:param: messages 需要显示的按钮的文字聊表
:returns: 实例
*/
init(zxyTitle : String?,cancelBtn: String?,andMessage messages : [String]) {
super.init(frame: UIScreen.mainScreen().bounds)
self.backgroundColor = UIColor.lightGrayColor()
self.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 0.0)
self.opaque = true
self.clipsToBounds = true
self.titleString = zxyTitle
self.cancelString = cancelBtn
self.listString = messages
if let isNil = currentTable
{
}
else
{
currentTable = UITableView()
currentTable.backgroundColor = self.backCo
currentTable.separatorStyle = UITableViewCellSeparatorStyle.None
currentTable.delegate = self
currentTable.dataSource = self
currentTable.bounces = false
currentTable.registerClass(ZXY_SheetViewCell.self, forCellReuseIdentifier: ZXY_SheetViewCellID)
currentTable.tableFooterView = UIView(frame: CGRectZero)
self.addSubview(currentTable)
}
}
func setBackCo(backCO : UIColor)
{
self.backCo = backCO
}
func getTableHeight() -> CGFloat
{
var currentHeight : CGFloat = 20
if(titleString != nil)
{
currentHeight += 50
}
if(cancelString != nil)
{
currentHeight += 50
}
for var i = 0; i < listString?.count ;i++
{
currentHeight += 50
}
if(currentHeight > self.frame.size.height)
{
return 600
}
else
{
return currentHeight
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
显示sheet
:param: parentV 父类视图
*/
func showSheet(parentV : UIView) -> Void
{
self._parentView = parentV
self.frame = CGRectMake(0, UIScreen.mainScreen().bounds.size.height, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)
if(imgBack == nil)
{
imgBack = UIImageView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
imgBack?.userInteractionEnabled = true
}
imgBack?.backgroundColor = UIColor.blackColor()
imgBack?.alpha = 0
parentV.addSubview(imgBack!)
var tapImg = UITapGestureRecognizer(target: self, action: Selector("tapImageMethod"))
self.addGestureRecognizer(tapImg)
currentTable.frame = CGRectMake(0, UIScreen.mainScreen().bounds.size.height-self.getTableHeight(), UIScreen.mainScreen().bounds.size.width, self.getTableHeight())
parentV.addSubview(self)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {[weak self] () -> Void in
self?.imgBack?.alpha = 0.4
self?.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)
}) { (Bool) -> Void in
}
}
func tapImageMethod() -> Void
{
if let isNil = _parentView
{
self.hideSheet(self._parentView!)
}
else
{
assert({
self._parentView == nil
}(), {
"Parent view is nil"
}())
}
}
func hideSheet(parentV : UIView?)
{
if(parentV == nil)
{
return
}
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {[weak self] () -> Void in
self?.imgBack?.alpha = 0
if var isNil = self?._parentView
{
self?.frame = CGRectMake(0, UIScreen.mainScreen().bounds.size.height, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)
}
}) { [weak self](Bool) -> Void in
self?.removeFromSuperview()
self?.imgBack?.removeFromSuperview()
} }
}
extension ZXY_SheetView :UITableViewDataSource,UITableViewDelegate
{
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var currentSection = indexPath.section
var currentRow = indexPath.row
var cell = tableView.dequeueReusableCellWithIdentifier(ZXY_SheetViewCellID) as! ZXY_SheetViewCell
cell.backgroundColor = backCo
if(currentSection == 0)
{
cell.setBtnString(titleString)
cell.setCurrentIndex(-2)
}
else if(currentSection == 1)
{
cell.setBtnString(listString![currentRow])
cell.setCurrentIndex(currentRow)
}
else
{
cell.setBtnString(cancelString)
cell.setCurrentIndex(-1)
cell.setBackColor(UIColor.lightGrayColor())
cell.setTxTColor(UIColor.whiteColor())
}
cell.delegate = self
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 50
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
if(section == 1)
{
return 10
}
else if(section == 2)
{
return 10
}
else
{
return 0
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if(section == 0)
{
if(titleString == nil)
{
return 0
}
return 1
}
else if (section == 1)
{
if let isNil = listString
{
return listString!.count
}
else
{
return 0
}
}
else
{
if(cancelString == nil)
{
return 0
}
return 1
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var curr: UIView = UIView(frame: CGRectMake(0, 0, self.frame.size.width, 15))
curr.backgroundColor = backCo
return curr
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 3
}
}
extension ZXY_SheetView : SheetViewCellDelegate
{
func clickButtonWithIndex(index: Int) {
if(self.delegate != nil)
{
self.delegate?.clickItemAtIndex(self, index: index)
}
self.tapImageMethod()
}
}
|
apache-2.0
|
10e69b1b3b805b852f9a775669833e74
| 28.463158 | 193 | 0.568536 | 4.760204 | false | false | false | false |
calebd/ReactiveCocoa
|
ReactiveCocoa/NSObject+Intercepting.swift
|
2
|
1121
|
import Foundation
import ReactiveSwift
import enum Result.NoError
extension Reactive where Base: NSObject {
/// Create a signal which sends a `next` event at the end of every invocation
/// of `selector` on the object.
///
/// - parameters:
/// - selector: The selector to observe.
///
/// - returns:
/// A trigger signal.
public func trigger(for selector: Selector) -> Signal<(), NoError> {
return base.synchronized {
let map = associatedValue { _ in NSMutableDictionary() }
let selectorName = String(describing: selector) as NSString
if let signal = map.object(forKey: selectorName) as! Signal<(), NoError>? {
return signal
}
let (signal, observer) = Signal<(), NoError>.pipe()
let isSuccessful = base._rac_setupInvocationObservation(for: selector,
protocol: nil,
receiver: observer.send(value:))
precondition(isSuccessful)
lifetime.ended.observeCompleted(observer.sendCompleted)
map.setObject(signal, forKey: selectorName)
return signal
}
}
}
|
mit
|
6072cec1c219dd25aa07ead2bbfc6e47
| 31.028571 | 91 | 0.631579 | 4.361868 | false | false | false | false |
harenbrs/swix
|
swix/swix/swix/ndarray/initing.swift
|
2
|
3016
|
//
// initing.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
import Swift
// SLOW PARTS: array(doubles), read_csv, write_csv. not a huge deal -- hopefully not used in final code
func zeros(N: Int) -> ndarray{
// N zeros
return ndarray(n: N)
}
func zeros_like(x: ndarray) -> ndarray{
// make an array like the other array
return zeros(x.n)
}
func ones_like(x: ndarray) -> ndarray{
// make an array like the other array
return zeros_like(x) + 1
}
func ones(N: Int) -> ndarray{
// N ones
return ndarray(n: N)+1
}
func arange(max: Double, x exclusive:Bool = true) -> ndarray{
// 0..<max
return arange(0, max: max, x:exclusive)
}
func arange(max: Int, x exclusive:Bool = true) -> ndarray{
// 0..<max
return arange(0, max: max.double, x:exclusive)
}
func range(min:Double, max:Double, step:Double) -> ndarray{
// min, min+step, min+2*step..., max-step, max
return linspace(min, max: max, num:1+((max-min)/step).int)
}
func arange(min: Double, max: Double, x exclusive: Bool = true) -> ndarray{
// min...max
var pad = 0
if !exclusive {pad = 1}
let N = max.int - min.int + pad
let x = zeros(N)
var o = CDouble(min)
var l = CDouble(1)
vDSP_vrampD(&o, &l, !x, 1.stride, N.length)
return x
}
func linspace(min: Double, max: Double, num: Int=50) -> ndarray{
// 0...1
let x = zeros(num+0)
var min = CDouble(min)
var step = CDouble((max-min).double/(num-1).double)
vDSP_vrampD(&min, &step, !x, 1.stride, x.n.length)
return x
}
func array(numbers: Double...) -> ndarray{
// array(1, 2, 3, 4) -> arange(4)+1
// okay to leave unoptimized, only used for testing
var x = zeros(numbers.count)
var i = 0
for number in numbers{
x[i] = number
i++
}
return x
}
func asarray(x: [Double]) -> ndarray{
// convert a grid of double's to an array
var y = zeros(x.count)
y.grid = x
return y
}
func asarray(seq: Range<Int>) -> ndarray {
// make a range a grid of arrays
// improve with [1]
// [1]:https://gist.github.com/nubbel/d5a3639bea96ad568cf2
let start:Double = seq.startIndex.double * 1.0
let end:Double = seq.endIndex.double * 1.0
return arange(start, max: end, x:true)
}
func copy(x: ndarray) -> ndarray{
// copy the value
return x.copy()
}
func rand(N: Int, seed:Int=42, distro:String="uniform") -> ndarray{
let x = zeros(N)
var i:__CLPK_integer = 1
if distro=="normal" {i = __CLPK_integer(3)}
var seed:Array<__CLPK_integer> = [__CLPK_integer(seed), 42, 2, 29]
var nn:__CLPK_integer = __CLPK_integer(N)
dlarnv_(&i, &seed, &nn, !x)
return x
}
func randn(N: Int, mean: Double=0, sigma: Double=1, seed:Int=42) -> ndarray{
return (rand(N, distro:"normal") * sigma) + mean;
}
func randperm(N:Int)->ndarray{
let x = arange(N)
let y = shuffle(x)
return y
}
|
mit
|
75f89830eab8efef998c52a5b7bce036
| 22.2 | 103 | 0.603448 | 2.995035 | false | false | false | false |
harenbrs/swix
|
swixUseCases/swix-iOSb6/swix/matrix/operators.swift
|
2
|
5754
|
//
// twoD-operators.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
func make_operator(lhs: matrix, operation: String, rhs: matrix)->matrix{
assert(lhs.shape.0 == rhs.shape.0, "Sizes must match!")
assert(lhs.shape.1 == rhs.shape.1, "Sizes must match!")
var result = zeros_like(lhs) // real result
var lhsM = lhs.flat
var rhsM = rhs.flat
var resM:ndarray = zeros_like(lhsM) // flat ndarray
if operation=="+" {resM = lhsM + rhsM}
else if operation=="-" {resM = lhsM - rhsM}
else if operation=="*" {resM = lhsM * rhsM}
else if operation=="/" {resM = lhsM / rhsM}
else if operation=="<" {resM = lhsM < rhsM}
else if operation==">" {resM = lhsM > rhsM}
else if operation==">=" {resM = lhsM >= rhsM}
else if operation=="<=" {resM = lhsM <= rhsM}
result.flat.grid = resM.grid
return result
}
func make_operator(lhs: matrix, operation: String, rhs: Double)->matrix{
var result = zeros_like(lhs) // real result
// var lhsM = asmatrix(lhs.grid) // flat
var lhsM = lhs.flat
var resM:ndarray = zeros_like(lhsM) // flat matrix
if operation=="+" {resM = lhsM + rhs}
else if operation=="-" {resM = lhsM - rhs}
else if operation=="*" {resM = lhsM * rhs}
else if operation=="/" {resM = lhsM / rhs}
else if operation=="<" {resM = lhsM < rhs}
else if operation==">" {resM = lhsM > rhs}
else if operation==">=" {resM = lhsM >= rhs}
else if operation=="<=" {resM = lhsM <= rhs}
result.flat.grid = resM.grid
return result
}
func make_operator(lhs: Double, operation: String, rhs: matrix)->matrix{
var result = zeros_like(rhs) // real result
// var rhsM = asmatrix(rhs.grid) // flat
var rhsM = rhs.flat
var resM:ndarray = zeros_like(rhsM) // flat matrix
if operation=="+" {resM = lhs + rhsM}
else if operation=="-" {resM = lhs - rhsM}
else if operation=="*" {resM = lhs * rhsM}
else if operation=="/" {resM = lhs / rhsM}
else if operation=="<" {resM = lhs < rhsM}
else if operation==">" {resM = lhs > rhsM}
else if operation==">=" {resM = lhs >= rhsM}
else if operation=="<=" {resM = lhs <= rhsM}
result.flat.grid = resM.grid
return result
}
// DOUBLE ASSIGNMENT
func <- (inout lhs:matrix, rhs:Double){
var assign = ones((lhs.shape)) * rhs
lhs = assign
}
// DOT PRODUCT
infix operator *! {associativity none precedence 140}
func *! (lhs: matrix, rhs: matrix) -> matrix{
return dot(lhs, rhs)}
// SOLVE
infix operator !/ {associativity none precedence 140}
func !/ (lhs: matrix, rhs: ndarray) -> ndarray{
return solve(lhs, rhs)}
// EQUALITY
func ~== (lhs: matrix, rhs: matrix) -> Bool{
return (rhs.flat ~== lhs.flat)}
infix operator == {associativity none precedence 140}
func == (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat == rhs.flat).reshape(lhs.shape)
}
infix operator !== {associativity none precedence 140}
func !== (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat !== rhs.flat).reshape(lhs.shape)
}
/// ELEMENT WISE OPERATORS
// PLUS
infix operator + {associativity none precedence 140}
func + (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "+", rhs)}
func + (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "+", rhs)}
func + (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "+", rhs)}
// MINUS
infix operator - {associativity none precedence 140}
func - (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "-", rhs)}
func - (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "-", rhs)}
func - (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "-", rhs)}
// TIMES
infix operator * {associativity none precedence 140}
func * (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "*", rhs)}
func * (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "*", rhs)}
func * (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "*", rhs)}
// DIVIDE
infix operator / {associativity none precedence 140}
func / (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "/", rhs)
}
func / (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "/", rhs)}
func / (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "/", rhs)}
// LESS THAN
infix operator < {associativity none precedence 140}
func < (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "<", rhs)}
func < (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "<", rhs)}
func < (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "<", rhs)}
// GREATER THAN
infix operator > {associativity none precedence 140}
func > (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, ">", rhs)}
func > (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, ">", rhs)}
func > (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, ">", rhs)}
// GREATER THAN OR EQUAL
infix operator >= {associativity none precedence 140}
func >= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "=>", rhs)}
func >= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "=>", rhs)}
func >= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "=>", rhs)}
// LESS THAN OR EQUAL
infix operator <= {associativity none precedence 140}
func <= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "=>", rhs)}
func <= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "=>", rhs)}
func <= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "=>", rhs)}
|
mit
|
689ffc5c64fd945cda6f7196871835dc
| 35.891026 | 72 | 0.627911 | 3.316427 | false | false | false | false |
minaatefmaf/Meme-Me
|
Meme Me/MemeEditorViewController.swift
|
1
|
17885
|
//
// MemeEditorViewController.swift
// Meme Me
//
// Created by Mina Atef on 5/20/15.
// Copyright (c) 2015 minaatefmaf. All rights reserved.
//
import UIKit
import Photos
protocol MemeEditorViewControllerDelegate {
func editTheMeme(MemeEditor: MemeEditorViewController, didEditMeme memeIsEdited: Bool, newMeme: Meme?)
}
class MemeEditorViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet private weak var imagePickerView: UIImageView!
@IBOutlet private weak var cameraButton: UIBarButtonItem!
@IBOutlet private weak var topTextField: UITextField!
@IBOutlet private weak var bottomTextField: UITextField!
@IBOutlet private weak var saveButton: UIBarButtonItem!
@IBOutlet private weak var navigationBar: UINavigationBar!
@IBOutlet private weak var toolBar: UIToolbar!
private var tapRecognizer: UITapGestureRecognizer? = nil
// Add references to the delegates
private let memeTopTextFieldDelegate = MemeTextFieldDelegate()
private let memeBottomTextFieldDelegate = MemeTextFieldDelegate()
// Set the default text attributes dictionary.
private let memeTextAttributes = DefaultTextAttributes().memeTextAttributes
// Set the core data stack variable
private let appDelegate = UIApplication.shared.delegate as! AppDelegate
private var coreDataStack: CoreDataStack!
// To hold the mode of the view (whether the statusbar and the toolbars are visible or not)
private enum ViewMode {
case visibleViews
case hiddenViews
}
// Initialize the viewState to all views visible
private var viewState = ViewMode.visibleViews
// For holding the new meme
private var newMeme: Meme!
// For holding the old meme if the scene is initiated to edit an old meme
var oldMeme: Meme?
// A placeholder for the delegate
var memeEditorDelegate: MemeEditorViewControllerDelegate?
// To hold the state of the scene (either creating a new meme, or modifying an old one)
enum EditorMode {
case createNewMeme
case modifyOldMeme
}
// Initialize the sceneMode to meme creation mode
var sceneMode: EditorMode = .createNewMeme
override var prefersStatusBarHidden: Bool {
// Hide the status bar
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// Get the core data stack
coreDataStack = appDelegate.coreDataStack
// Configure the UI
configureUIForViewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Configure the UI
configureUIForViewWillAppear()
// Subscribe to keyboard notifications to allow the view to raise when necessary
subscribeToKeyboardNotifications()
// Add the tap recognizer
addKeyboardDismissRecognizer()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Unsubscribe to keyboard notifications
unsubscribeFromKeyboardNotifications()
// Remove the tap recognizer
removeKeyboardDismissRecognizer()
}
@IBAction private func saveMemedImage(_ sender: UIBarButtonItem) {
// If the editor is in the the "modifying an old meme" mode, check if the user want to keep the old meme or delete it
if sceneMode == .modifyOldMeme {
// Prepare an alert to confirm the meme deletion
let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
// The Save meme action
let saveNewAction = UIAlertAction(title: Alerts.SaveMeme, style: .default) { [weak weakSelf = self] _ in
// Create and sava a new meme
weakSelf?.createAndSaveNewMeme()
// Let the other controller know that the meme has been edited, and pass the new meme
weakSelf?.memeEditorDelegate!.editTheMeme(MemeEditor: self, didEditMeme: true, newMeme: weakSelf?.newMeme)
// Navigate back to the meme viewer
weakSelf?.dismiss(animated: true, completion: nil)
}
// The Save meme & Delete old meme action
let saveNewAndDeleteOldAction = UIAlertAction(title: Alerts.SaveAndDeleteOldMeme, style: .destructive) { [weak weakSelf = self] _ in
// Create and sava a new meme
weakSelf?.createAndSaveNewMeme()
// Delete the old meme
weakSelf?.coreDataStack.context.delete((weakSelf?.oldMeme)!)
// Persist the context to the disk
weakSelf?.coreDataStack.save()
// Let the other controller know that the meme has been edited, and pass the new meme
weakSelf?.memeEditorDelegate!.editTheMeme(MemeEditor: self, didEditMeme: true, newMeme: weakSelf?.newMeme)
// Navigate back to the meme viewer
weakSelf?.dismiss(animated: true, completion: nil)
}
alert.addAction(saveNewAction)
alert.addAction(saveNewAndDeleteOldAction)
alert.addAction(UIAlertAction(title: Alerts.Cancel, style: .cancel, handler: nil))
// Present the alert
self.present(alert, animated: true, completion: nil)
} else { // The meme creation mode
// Save the new meme
createAndSaveNewMeme()
// Navigate back to the table/collection view
self.dismiss(animated: true, completion: nil)
}
}
@IBAction private func cancelMemeEditor(_ sender: UIBarButtonItem) {
// Navigate back to the table/collection view
self.dismiss(animated: true, completion: nil)
}
@IBAction private func pickAnImageFromCamera(_ sender: UIBarButtonItem) {
// Make sure the app has the permission to open the camera
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
guard status == .authorized else {
showAlertAndRedirectToSettings(alertTitle: Alerts.CameraDisabledTitle, alertMessage: Alerts.CameraDisabledMessage)
return
}
pickAnImage(UIImagePickerControllerSourceType.camera)
}
@IBAction private func pickAnImageFromAlbum(_ sender: UIBarButtonItem) {
// Make sure the app has the permission to access the photo library
let status = PHPhotoLibrary.authorizationStatus()
guard status == .authorized else {
showAlertAndRedirectToSettings(alertTitle: Alerts.PhotosDisabledTitle, alertMessage: Alerts.PhotosDisabledMessage)
return
}
pickAnImage(UIImagePickerControllerSourceType.photoLibrary)
}
// A general function to pick an image from a given source.
// Its soul purpose is to serve the (IBAction pickAnImageFromCamera) & (IBAction pickAnImageFromAlbum) functions.
private func pickAnImage(_ sourceType: UIImagePickerControllerSourceType) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = sourceType
self.present(pickerController, animated: true, completion: nil)
}
// Set the chosen image to our imagePickerView
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.imagePickerView.image = image
// Enable the save button when an image has been chosen.
saveButton.isEnabled = true
}
self.dismiss(animated: true, completion: nil)
}
// MARK: - Keyboard Fixes
@objc private func keyboardWillShow(_ notification: Notification) {
// Accommodate for the keyboard when the user try to enter text in the bottom textfield.
if bottomTextField.isFirstResponder {
self.view.frame.origin.y = 0
self.view.frame.origin.y -= getKeyboardHeight(notification)
}
}
@objc private func keyboardWillHide(_ notification: Notification) {
// Accommodate for the keyboard when the user finish editing the text in the bottom textfield.
if bottomTextField.isFirstResponder {
self.view.frame.origin.y += getKeyboardHeight(notification)
}
}
private func getKeyboardHeight(_ notification: Notification) -> CGFloat {
// Get the keyboard height.
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // Of CGRect
return keyboardSize.cgRectValue.height
}
private func subscribeToKeyboardNotifications() {
// Get a notification when the keyboard show or hide.
NotificationCenter.default.addObserver(self, selector: #selector(MemeEditorViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(MemeEditorViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
private func unsubscribeFromKeyboardNotifications() {
// Unsubscribe from the notifications we subscribed earlier.
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
private func addKeyboardDismissRecognizer() {
view.addGestureRecognizer(tapRecognizer!)
}
private func removeKeyboardDismissRecognizer() {
view.removeGestureRecognizer(tapRecognizer!)
}
@objc private func handleSingleTap(_ recognizer: UITapGestureRecognizer) {
if topTextField.isFirstResponder || bottomTextField.isFirstResponder {
view.endEditing(true) // this will cause the view (or any of its embedded text fields to resign the first responder status
} else {
// Toggle the navigation bar and the buttom toolbar
if viewState == .visibleViews {
viewState = .hiddenViews
navigationBar.isHidden = true
toolBar.isHidden = true
} else {
viewState = .visibleViews
navigationBar.isHidden = false
toolBar.isHidden = false
}
// Toggle the view's background color
if view.backgroundColor == .white {
view.backgroundColor = .black
} else {
view.backgroundColor = .white
}
}
}
// MARK: - Creating The Thumbnail Image Helper functions
private func prepareTheThumbnailImage(image: UIImage) -> UIImage {
// Crop the image:
let croppedImage = cropToSquareImage(image: image)
// Resize the image:
let resizedImage = resizeImage(image: croppedImage, scaleX: 0.2, scaleY: 0.2)
return resizedImage
}
private func cropToSquareImage(image: UIImage) -> UIImage {
let contextImage: UIImage = UIImage(cgImage: image.cgImage!)
let contextSize: CGSize = contextImage.size
var squareStartingPointX: CGFloat = 0.0
var squareStartingPointY: CGFloat = 0.0
// Set the square side length to the smaller side of the given rectangle "image"
let sideLength = (contextSize.width < contextSize.height) ? contextSize.width : contextSize.height
// See what size is longer and create the center off of that
if contextSize.width < contextSize.height {
squareStartingPointY = (contextSize.height - contextSize.width) / 2
} else {
squareStartingPointX = (contextSize.width - contextSize.height) / 2
}
// Create the square
let rect: CGRect = CGRect(x: squareStartingPointX, y: squareStartingPointY, width: sideLength, height: sideLength)
// Create bitmap image from context using the rect
let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!
// Create a new image based on the imageRef and rotate back to the original orientation
let image: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
return image
}
private func resizeImage(image: UIImage, scaleX: CGFloat, scaleY: CGFloat) -> UIImage {
let size = image.size.applying(CGAffineTransform(scaleX: scaleX, y: scaleY))
let hasAlpha = false
// Automatically use scale factor of main screen
let scale: CGFloat = 0.0
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
image.draw(in: CGRect(origin: CGPoint.zero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
// MARK: - General Helper Methods
private func createAndSaveNewMeme() {
// Create the meme dictionary
let dictionary: [String : String] = [
Meme.Keys.TopText: topTextField.text!,
Meme.Keys.BottomText: bottomTextField.text!
]
// Create the meme
newMeme = Meme(dictionary: dictionary, context: coreDataStack.context)
// Save the images to the disc
let image = ImageData(context: coreDataStack.context)
// Make sure the image is saved with the correct orientaion (when captured by the camera)
image.originalImage = imagePickerView.image?.correctlyOrientedImage()
let memedImage = generateMemedImage()
image.memedImage = memedImage
newMeme.image = image
newMeme.thumbnailImage = prepareTheThumbnailImage(image: memedImage)
// Persisit the meme to the disc
coreDataStack.save()
}
private func generateMemedImage() -> UIImage {
// Hide navigationBar and toolBar
navigationBar.isHidden = true
toolBar.isHidden = true
// Render view to an image
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
// Show navigationBar and toolBar
navigationBar.isHidden = false
toolBar.isHidden = false
return memedImage
}
private func showAlertAndRedirectToSettings(alertTitle title: String, alertMessage message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: Alerts.GoToSettings, style: .default) { action in
// Redirect the user to the app's settings in the general seeting app
UIApplication.shared.openURL(NSURL(string:UIApplicationOpenSettingsURLString)! as URL)
}
let cancelAction = UIAlertAction(title: Alerts.AskLater, style: .default, handler: nil)
alert.addAction(cancelAction)
alert.addAction(confirmAction)
self.present(alert, animated: true, completion: nil)
}
// MARK: - ConfigureUI Helper Methods
private func configureUIForViewDidLoad() {
// Assign our defult text attributes to the textfields
topTextField.defaultTextAttributes = memeTextAttributes
bottomTextField.defaultTextAttributes = memeTextAttributes
// Set the textfields' initial text
topTextField.text = "TOP TEXT"
bottomTextField.text = "BOTTOM TEXT"
// Align the text in the textfields to center.
topTextField.textAlignment = NSTextAlignment.center
bottomTextField.textAlignment = NSTextAlignment.center
// Disable the save button initially.
saveButton.isEnabled = false
// Assign each textfield to its proper delegate
topTextField.delegate = memeTopTextFieldDelegate
bottomTextField.delegate = memeBottomTextFieldDelegate
// Initialize the meme data if the scene is initiated to edit an old meme
if let oldMeme = self.oldMeme {
imagePickerView.image = oldMeme.image!.getOriginalImage()
topTextField.text = oldMeme.topText
bottomTextField.text = oldMeme.bottomText
// Enable the save button
saveButton.isEnabled = true
}
// Initialize and configure the tap recognizer
tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MemeEditorViewController.handleSingleTap(_:)))
tapRecognizer?.numberOfTapsRequired = 1
}
private func configureUIForViewWillAppear() {
// Disable the camera button if the device doesn't have a camera (e.g. the simulator)
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
cameraButton.isEnabled = false
}
}
}
|
mit
|
3ec2df6681fee7de7e660c5ad34b3897
| 39.191011 | 179 | 0.650657 | 5.69949 | false | false | false | false |
s-aska/Justaway-for-iOS
|
Justaway/SearchKeywordAdapter.swift
|
1
|
4093
|
//
// SearchKeywordAdapter.swift
// Justaway
//
// Created by Shinichiro Aska on 3/30/16.
// Copyright © 2016 Shinichiro Aska. All rights reserved.
//
import UIKit
import KeyClip
import Async
import EventBox
class SearchKeywordAdapter: NSObject {
var historyWord = [String]()
var selectCallback: ((String) -> Void)?
var scrollCallback: (() -> Void)?
func configureView(_ tableView: UITableView) {
tableView.register(UINib(nibName: "SearchKeywordCell", bundle: nil), forCellReuseIdentifier: "SearchKeywordCell")
tableView.dataSource = self
tableView.delegate = self
tableView.separatorInset = UIEdgeInsets.zero
loadData(tableView)
EventBox.onMainThread(self, name: eventSearchKeywordDeleted) { [weak self] (n) in
guard let data = n.object as? [String: String] else {
return
}
if let keyword = data["keyword"] {
self?.removeHistory(keyword, tableView: tableView)
}
}
}
func loadData(_ tableView: UITableView) {
if let data = KeyClip.load("searchKeywordHistory") as NSDictionary? {
if let keywords = data["keywords"] as? [String] {
historyWord = keywords
Async.main {
tableView.reloadData()
}
}
}
}
func appendHistory(_ keyword: String, tableView: UITableView) {
historyWord = historyWord.filter { $0 != keyword }
historyWord.insert(keyword, at: 0)
Async.main {
tableView.reloadData()
}
KeyClip.save("searchKeywordHistory", dictionary: ["keywords": historyWord])
}
func removeHistory(_ keyword: String, tableView: UITableView) {
if let index = historyWord.index(of: keyword) {
historyWord.remove(at: index)
let indexPath = IndexPath.init(row: index, section: 0)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
KeyClip.save("searchKeywordHistory", dictionary: ["keywords": historyWord])
}
deinit {
EventBox.off(self)
}
}
// MARK: - UITableViewDataSource
extension SearchKeywordAdapter: UITableViewDataSource {
// func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// return 1
// }
// func tableView(tableView: UITableView, willDisplayHeaderView view:UIView, forSection: Int) {
// if let headerView = view as? UITableViewHeaderFooterView {
// headerView.textLabel?.textColor = ThemeController.currentTheme.bodyTextColor()
// }
// }
// func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// switch section {
// case 0:
// return "History"
// case 1:
// return "Saved"
// default:
// return nil
// }
// }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return historyWord.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// swiftlint:disable:next force_cast
let cell = tableView.dequeueReusableCell(withIdentifier: "SearchKeywordCell", for: indexPath) as! SearchKeywordCell
if historyWord.count > indexPath.row {
cell.keyword = historyWord[indexPath.row]
cell.nameLabel.text = historyWord[indexPath.row]
}
return cell
}
}
// MARK: - UITableViewDelegate
extension SearchKeywordAdapter: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if historyWord.count > indexPath.row {
selectCallback?(historyWord[indexPath.row])
}
}
}
// MARK: - UIScrollViewDelegate
extension SearchKeywordAdapter {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollCallback?()
}
}
|
mit
|
a0ef90fd314d03eb76ad2518d3a8874b
| 30.72093 | 123 | 0.629277 | 4.7471 | false | false | false | false |
benzguo/stripe-ios
|
Example/Stripe iOS Example (Simple)/ViewController.swift
|
4
|
5274
|
//
// ViewController.swift
// Stripe iOS Exampe (Simple)
//
// Created by Jack Flintermann on 1/15/15.
// Copyright (c) 2015 Stripe. All rights reserved.
//
import UIKit
import Stripe
enum STPBackendChargeResult {
case Success, Failure
}
typealias STPTokenSubmissionHandler = (STPBackendChargeResult?, NSError?) -> Void
class ViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate {
// Replace these values with your application's keys
// Find this at https://dashboard.stripe.com/account/apikeys
let stripePublishableKey = ""
// To set this up, see https://github.com/stripe/example-ios-backend
let backendChargeURLString = ""
// To set this up, see https://stripe.com/docs/mobile/apple-pay
let appleMerchantId = ""
let shirtPrice : UInt = 1000 // this is in cents
@IBAction func beginPayment(sender: AnyObject) {
if (stripePublishableKey == "") {
let alert = UIAlertController(
title: "You need to set your Stripe publishable key.",
message: "You can find your publishable key at https://dashboard.stripe.com/account/apikeys .",
preferredStyle: UIAlertControllerStyle.Alert
)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
return
}
if (appleMerchantId != "") {
if let paymentRequest = Stripe.paymentRequestWithMerchantIdentifier(appleMerchantId) {
if Stripe.canSubmitPaymentRequest(paymentRequest) {
paymentRequest.paymentSummaryItems = [PKPaymentSummaryItem(label: "Cool shirt", amount: NSDecimalNumber(string: "10.00")), PKPaymentSummaryItem(label: "Stripe shirt shop", amount: NSDecimalNumber(string: "10.00"))]
let paymentAuthVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
paymentAuthVC.delegate = self
presentViewController(paymentAuthVC, animated: true, completion: nil)
return
}
}
} else {
print("You should set an appleMerchantId.")
}
}
func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: ((PKPaymentAuthorizationStatus) -> Void)) {
let apiClient = STPAPIClient(publishableKey: stripePublishableKey)
apiClient.createTokenWithPayment(payment, completion: { (token, error) -> Void in
if error == nil {
if let token = token {
self.createBackendChargeWithToken(token, completion: { (result, error) -> Void in
if result == STPBackendChargeResult.Success {
completion(PKPaymentAuthorizationStatus.Success)
}
else {
completion(PKPaymentAuthorizationStatus.Failure)
}
})
}
}
else {
completion(PKPaymentAuthorizationStatus.Failure)
}
})
}
func paymentAuthorizationViewControllerDidFinish(controller: PKPaymentAuthorizationViewController) {
dismissViewControllerAnimated(true, completion: nil)
}
func createBackendChargeWithToken(token: STPToken, completion: STPTokenSubmissionHandler) {
if backendChargeURLString != "" {
if let url = NSURL(string: backendChargeURLString + "/charge") {
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let postBody = "stripeToken=\(token.tokenId)&amount=\(shirtPrice)"
let postData = postBody.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
session.uploadTaskWithRequest(request, fromData: postData, completionHandler: { data, response, error in
let successfulResponse = (response as? NSHTTPURLResponse)?.statusCode == 200
if successfulResponse && error == nil {
completion(.Success, nil)
} else {
if error != nil {
completion(.Failure, error)
} else {
completion(.Failure, NSError(domain: StripeDomain, code: 50, userInfo: [NSLocalizedDescriptionKey: "There was an error communicating with your payment backend."]))
}
}
}).resume()
return
}
}
completion(STPBackendChargeResult.Failure, NSError(domain: StripeDomain, code: 50, userInfo: [NSLocalizedDescriptionKey: "You created a token! Its value is \(token.tokenId). Now configure your backend to accept this token and complete a charge."]))
}
}
|
mit
|
7987029fdbaf8870fc1c85859aebe703
| 44.86087 | 256 | 0.607509 | 5.738847 | false | false | false | false |
imex94/KCLTech-iOS-2015
|
Hackalendar/Hackalendar/Hackalendar/HCHackathonProvider.swift
|
1
|
4549
|
//
// HCHackathonProvider.swift
// Hackalendar
//
// Created by Alex Telek on 10/11/2015.
// Copyright © 2015 Alex Telek. All rights reserved.
//
import UIKit
class HCHackathonProvider: NSObject {
static let baseURL = "http://www.hackalist.org/api/1.0/"
/**
Load Hackathons from local storage and not from the network. Therefore
all the hackathon that matches to the specified year and month will be given
back to us straingth after the method call.
If this method call return an empty array -> Need to call provideHackathonsFor(...) method
*/
class func loadHackathons(year: Int, month: Int) -> [HackathonItem] {
// --> What I was doing wrong :), we need to have %@, which means that '%@' will be
// replaced by the elements from the args array in order.
return HackathonItem.fetchHackathons("year == %@ && month == %@", args: [year, month], sortKeywords: ["startDate", "endDate"])
}
/**
Providehackathons method for fetching hackathons for a specified month in the current year
from the API above
*/
class func provideHackathonsFor(month: Int, completionBlock: ([HackathonItem]) -> Void) {
provideHackathonsFor(HCCalendarUtility.getCurrentYear(), month: month, completionBlock: completionBlock)
}
/**
Providehackathons method for fetching hackathons for a specified year and
month from the API above
*/
class func provideHackathonsFor(year: Int, month: Int, completionBlock: ([HackathonItem]) -> Void) {
// hackalist.org/api/1.0/2015/12.json
var urlString = baseURL
if month < 10 {
urlString += "\(year)/0\(month).json"
} else {
urlString += "\(year)/0\(month).json"
}
print(urlString)
HCServer.sharedServer().GET(urlString) { (response) -> Void in
var parsedHackathons = [HackathonItem]()
switch response {
case .Failure(_): print("Failed to fetch data")
case .Success(let data):
if let json = data as? Dictionary<NSObject, AnyObject> {
// Remove data that is metching the year and month we just about to fetch
// so we won't have any duplicate value in the database
HackathonItem.removeHackathons(year, month: month)
let monthString = HCCalendarUtility.getMonths()[month - 1]
let hackathons = json[monthString] as! Array<Dictionary<String, String>>
for hackathon in hackathons {
let hackathonObject = HackathonItem.item()
hackathonObject.title = hackathon["title"]
hackathonObject.url = hackathon["url"]
hackathonObject.startDate = hackathon["startDate"]
hackathonObject.endDate = hackathon["endDate"]
hackathonObject.year = Int(hackathon["year"]!)
hackathonObject.city = hackathon["city"]
hackathonObject.host = hackathon["host"]
hackathonObject.length = Int(hackathon["length"]!)
hackathonObject.size = hackathon["size"]
hackathonObject.travel = hackathon["travel"]
hackathonObject.prize = hackathon["prize"]! == "yes" ? true : false
hackathonObject.highSchoolers = hackathon["highSchoolers"]! == "yes" ? true : false
hackathonObject.facebookURL = hackathon["facebookURL"]
hackathonObject.twitterURL = hackathon["twitterURL"]
hackathonObject.googlePlusURL = hackathon["googlePlusURL"]
hackathonObject.notes = hackathon["notes"]
hackathonObject.month = month
HCDataManager.saveContext()
parsedHackathons.append(hackathonObject)
}
}
}
completionBlock(parsedHackathons)
}
}
}
|
mit
|
88647aa58350fa2dee49c4dea0fb9ec6
| 44.029703 | 134 | 0.530123 | 5.350588 | false | false | false | false |
huangboju/Moots
|
UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/Extensions/Array+Helpers.swift
|
2
|
1482
|
//
// Array+Helpers.swift
// SwiftNetworkImages
//
// Created by Arseniy on 10/5/16.
// Copyright © 2016 Arseniy Kuznetsov. All rights reserved.
//
import Foundation
/// Common array extensions used in this project
extension Array {
/// Returns the element at the given `index` and a new array with that element removed
private func arrayByRemovingElementAtIndex(index: Int) -> (Element, [Element]) {
var newArray = self
let removedElement = newArray.remove(at: index)
return (removedElement, newArray)
}
/// Returns an array of arrays, where each one is a permutation
public var permutations: [[Element]] {
switch self.count {
case 0:
return []
case 1:
return [self]
default:
precondition(self.count > 1)
var permutations: [[Element]] = []
for idx in 0..<self.count {
let (currentElement, remainingElements) = self.arrayByRemovingElementAtIndex(index: idx)
permutations += remainingElements.permutations.map { [currentElement] + $0 }
}
return permutations
}
}
/// Checks if array is sorted
func isSorted(isOrderedBefore: (Element, Element) -> Bool) -> Bool {
for i in 0..<self.count - 1 {
if !isOrderedBefore(self[i], self[i + 1]) {
return false
}
}
return true
}
}
|
mit
|
26e6af68e6a3c649d6483136c4887f6d
| 29.22449 | 104 | 0.577313 | 4.657233 | false | false | false | false |
jphacks/TK_08
|
iOS/AirMeet/AirMeet/OriginalTabBarController.swift
|
1
|
2189
|
//
// OriginalTabBarController.swift
// AirMeet
//
// Created by koooootake on 2015/11/29.
// Copyright © 2015年 koooootake. All rights reserved.
//
import UIKit
//タブバー設定
class OriginalTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
///(kmdr,momoka)
// 選択時のタブバーアイコン・テキストの色
let selectedColor:UIColor = UIColor(red: 65.0/255.0, green: 168.0/255.0, blue: 186.0/255.0, alpha: 1)//水色
///ボタンをいいかんじに
//let fontFamily: UIFont! = UIFont(name: "Hiragino Kaku Gothic ProN",size:10)
let fontFamily: UIFont! = UIFont.systemFontOfSize(10)
// 選択時・非選択時の文字色を変更する
/// なぜか非選択時の文字色を指定すると文字が切れる(特に「g」の下のほう)
let selectedAttributes = [NSFontAttributeName: fontFamily, NSForegroundColorAttributeName: selectedColor]
let nomalAttributes = [NSFontAttributeName: fontFamily, NSForegroundColorAttributeName: UIColor.whiteColor()]
UITabBarItem.appearance().setTitleTextAttributes(selectedAttributes, forState: UIControlState.Selected)
UITabBarItem.appearance().setTitleTextAttributes(nomalAttributes, forState: UIControlState.Normal)
// 選択時のアイコンの色
UITabBar.appearance().tintColor = selectedColor
// 通常のアイコン
var assets :Array<String> = ["TabBarListImage", "TabBarSearchImage", "TabBarAccountImage"]
for (idx, item) in self.tabBar.items!.enumerate() {
// if let image = item.image {
item.image = UIImage(named: assets[idx])?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
// }
}
// 背景色
UITabBar.appearance().barTintColor = UIColor(red: 128/255.0, green: 204/255.0, blue: 223/255.0, alpha: 1.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
d1f654c9e7772a8380f68f1d8969b692
| 35.407407 | 117 | 0.652594 | 4.078838 | false | false | false | false |
stormpath/stormpath-sdk-swift
|
Stormpath/Networking/SocialLoginAPIRequestManager.swift
|
1
|
2634
|
//
// SocialLoginAPIRequestManager.swift
// Stormpath
//
// Created by Edward Jiang on 3/3/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
class SocialLoginAPIRequestManager: APIRequestManager {
var socialProvider: StormpathSocialProvider
var callback: AccessTokenCallback
var postDictionary: [String: Any]
init(withURL url: URL, accessToken: String, socialProvider: StormpathSocialProvider, callback: @escaping AccessTokenCallback) {
self.socialProvider = socialProvider
self.callback = callback
postDictionary = ["providerData": ["providerId": socialProvider.stringValue(), "accessToken": accessToken]]
super.init(withURL: url)
}
init(withURL url: URL, authorizationCode: String, socialProvider: StormpathSocialProvider, callback: @escaping AccessTokenCallback) {
self.socialProvider = socialProvider
self.callback = callback
postDictionary = ["providerData": ["providerId": socialProvider.stringValue(), "code": authorizationCode]]
super.init(withURL: url)
}
override func prepareForRequest() {
request.httpBody = try? JSONSerialization.data(withJSONObject: postDictionary, options: [])
request.httpMethod = "POST"
}
override func requestDidFinish(_ data: Data, response: HTTPURLResponse) {
// Grab access token from cookies
// Callback
let accessTokenRegex = "(?<=access_token=)[^;]*"
let refreshTokenRegex = "(?<=refresh_token=)[^;]*"
guard let setCookieHeaders = response.allHeaderFields["Set-Cookie"] as? String, let accessTokenRange = setCookieHeaders.range(of: accessTokenRegex, options: .regularExpression) else {
performCallback(StormpathError.APIResponseError)
return
}
let accessToken = setCookieHeaders.substring(with: accessTokenRange)
var refreshToken: String?
if let refreshTokenRange = setCookieHeaders.range(of: refreshTokenRegex, options: .regularExpression) {
refreshToken = setCookieHeaders.substring(with: refreshTokenRange)
}
performCallback(accessToken, refreshToken: refreshToken, error: nil)
}
override func performCallback(_ error: NSError?) {
performCallback(nil, refreshToken: nil, error: error)
}
func performCallback(_ accessToken: String?, refreshToken: String?, error: NSError?) {
DispatchQueue.main.async {
self.callback(accessToken, refreshToken, error)
}
}
}
|
apache-2.0
|
b95c89f1f446b44dd71c984975e01b5f
| 37.15942 | 191 | 0.670718 | 5.24502 | false | false | false | false |
crass45/PoGoApiAppleWatchExample
|
PoGoApiAppleWatchExample/PGoApi/LoginViewController.swift
|
1
|
1965
|
//
// ViewController.swift
// PGoApi
//
// Created by Jose Luis on 5/8/16.
// Copyright © 2016 crass45. All rights reserved.
//
import UIKit
import MapKit
import PGoApi
class LoginViewController: UIViewController, PGoAuthDelegate {
@IBOutlet weak var tfPass: UITextField!
@IBOutlet weak var tfUsername: UITextField!
@IBOutlet weak var acountTypeSegment: UISegmentedControl!
var ptcAuth: PtcOAuth!
var gogleAuth: GPSOAuth!
override func viewDidLoad() {
super.viewDidLoad()
if user != nil {
logIn()
}
}
func didReceiveAuth() {
print("Auth received!!")
performSegueWithIdentifier("mainSegue", sender: self)
// Init with auth
if authType == 0 {
request = PGoApiRequest(auth: ptcAuth)
}
else{
request = PGoApiRequest(auth: gogleAuth)
}
print("Starting simulation...")
request.setLocation(userLocation.latitude, longitude: userLocation.longitude, altitude: 1)
request.simulateAppStart()
request.makeRequest(.Login, delegate: pokemonGoApi)
}
func didNotReceiveAuth() {
print("Failed to auth!")
}
@IBAction func logIn(sender: AnyObject) {
user = tfUsername.text
pass = tfPass.text
authType = acountTypeSegment.selectedSegmentIndex
logIn()
}
func logIn(){
if authType == 0 {
self.ptcAuth = PtcOAuth()
self.ptcAuth.delegate = self
self.ptcAuth.login(withUsername: user!, withPassword: pass!)
}
else{
self.gogleAuth = GPSOAuth()
self.gogleAuth.delegate = self
self.gogleAuth.login(withUsername: user!, withPassword: pass!)
}
}
}
|
mit
|
0e4b21a1a3591509236e6f1a7b32ac24
| 21.067416 | 98 | 0.551426 | 4.873449 | false | false | false | false |
voyages-sncf-technologies/Collor
|
Example/Collor/TextFieldSample/cell/TextFieldCell.swift
|
1
|
2220
|
//
// TextFieldCell.swift
// Collor
//
// Created by Guihal Gwenn on 29/01/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
import Collor
@objc
public protocol RealTextFieldCellDelegate {
@objc
func textFieldDidEndEditing(_ textField: UITextField)
}
public protocol TextFieldCellDelegate: CollectionUserEventDelegate {
func supplyDelegate() -> RealTextFieldCellDelegate
}
public final class TextFieldCell: UICollectionViewCell, CollectionCellAdaptable {
@IBOutlet weak var textField: UITextField!
private var delegate: TextFieldCellDelegate?
public override func awakeFromNib() {
super.awakeFromNib()
}
public func update(with adapter: CollectionAdapter) {
// guard let adapter = adapter as? TextFieldAdapterProtocol else {
// fatalError("TextFieldAdapterProtocol required")
// }
}
public func set(delegate: CollectionUserEventDelegate?) {
guard delegate is TextFieldCellDelegate else {
return
}
textField.addTarget(delegate,
action: #selector(RealTextFieldCellDelegate.textFieldDidEndEditing),
for: .editingDidEnd)
}
}
public protocol TextFieldAdapterProtocol: CollectionAdapter {
}
public struct TextFieldAdapter: TextFieldAdapterProtocol {
public init() {
}
}
public final class TextFieldDescriptor: CollectionCellDescribable {
public let identifier: String = "TextFieldCell"
public let className: String = "TextFieldCell"
public var selectable: Bool = false
let adapter: TextFieldAdapterProtocol
public init(adapter: TextFieldAdapterProtocol) {
self.adapter = adapter
}
public func size(_ collectionView: UICollectionView,
sectionDescriptor: CollectionSectionDescribable) -> CGSize {
let sectionInset = sectionDescriptor.sectionInset(collectionView)
let width: CGFloat = collectionView.bounds.width - sectionInset.left - sectionInset.right - 80
return CGSize(width: width, height: 50)
}
public func getAdapter() -> CollectionAdapter {
return adapter
}
}
|
bsd-3-clause
|
c114d73bb43275dc20b1405bde6c21bc
| 23.384615 | 102 | 0.686345 | 5.258294 | false | false | false | false |
DrabWeb/Booru-chan
|
Booru-chan/Booru-chan/BooruPost.swift
|
1
|
472
|
//
// BooruPost.swift
// Booru-chan
//
// Created by Ushio on 2018-01-14.
//
import Foundation
class BooruPost {
var id: Int = -1;
var url: String = "";
var tags: [String] = [];
var rating: Rating = .none;
var thumbnailUrl: String = "";
var thumbnailSize: NSSize = NSSize.zero;
var imageUrl: String = "";
var imageSize: NSSize = NSSize.zero;
var animated: Bool {
return imageUrl.lowercased().hasSuffix(".gif");
}
}
|
gpl-3.0
|
7dd54ce86db66761766d2db5a376a8ca
| 17.153846 | 55 | 0.591102 | 3.548872 | false | false | false | false |
oddevan/macguffin
|
macguffin/Item.swift
|
1
|
1588
|
//
// Item.swift
// macguffin
//
// Created by Evan Hildreth on 2/5/15.
// Copyright (c) 2015 Evan Hildreth. All rights reserved.
//
enum ItemAffectedStat {
case attack
case defense
case magic
case accuracy
case speed
case hp
case mp
case status
}
struct ItemQuantity {
let item: Item
var quantity: Int
init(item: Item) {
self.item = item
self.quantity = 0
}
}
class Item {
let name: String
let affectedStat: ItemAffectedStat
let amountAffected: Int
init(name: String, affectedStat: ItemAffectedStat, amountAffected: Int) {
self.name = name
self.affectedStat = affectedStat
self.amountAffected = amountAffected
}
func use(_ target:Character) -> Bool {
switch self.affectedStat {
case .hp where target.hp != target.maxHP :
target.hp += amountAffected;
return true
case .mp where target.mp != target.maxMP :
target.mp += amountAffected;
return true
case .status where target.status != Status.normal :
if let futureStatus = Status(rawValue: amountAffected) {
target.status = futureStatus
return true
} else {
print("ERROR: Item.amountAffected does not correspond to known Status")
print(self)
print("--------")
}
default :
return false
}
return false
}
}
|
apache-2.0
|
0f0aa0d754b7ed2a103a24aafaa49269
| 22.014493 | 87 | 0.541562 | 4.616279 | false | false | false | false |
LYM-mg/DemoTest
|
其他功能/SwiftyDemo/Pods/SnapKit/Source/ConstraintMakerExtendable.swift
|
7
|
5098
|
//
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintMakerExtendable: ConstraintMakerRelatable {
public var left: ConstraintMakerExtendable {
self.description.attributes += .left
return self
}
public var top: ConstraintMakerExtendable {
self.description.attributes += .top
return self
}
public var bottom: ConstraintMakerExtendable {
self.description.attributes += .bottom
return self
}
public var right: ConstraintMakerExtendable {
self.description.attributes += .right
return self
}
public var leading: ConstraintMakerExtendable {
self.description.attributes += .leading
return self
}
public var trailing: ConstraintMakerExtendable {
self.description.attributes += .trailing
return self
}
public var width: ConstraintMakerExtendable {
self.description.attributes += .width
return self
}
public var height: ConstraintMakerExtendable {
self.description.attributes += .height
return self
}
public var centerX: ConstraintMakerExtendable {
self.description.attributes += .centerX
return self
}
public var centerY: ConstraintMakerExtendable {
self.description.attributes += .centerY
return self
}
@available(*, deprecated, message:"Use lastBaseline instead")
public var baseline: ConstraintMakerExtendable {
self.description.attributes += .lastBaseline
return self
}
public var lastBaseline: ConstraintMakerExtendable {
self.description.attributes += .lastBaseline
return self
}
@available(iOS 8.0, OSX 10.11, *)
public var firstBaseline: ConstraintMakerExtendable {
self.description.attributes += .firstBaseline
return self
}
@available(iOS 8.0, *)
public var leftMargin: ConstraintMakerExtendable {
self.description.attributes += .leftMargin
return self
}
@available(iOS 8.0, *)
public var rightMargin: ConstraintMakerExtendable {
self.description.attributes += .rightMargin
return self
}
@available(iOS 8.0, *)
public var topMargin: ConstraintMakerExtendable {
self.description.attributes += .topMargin
return self
}
@available(iOS 8.0, *)
public var bottomMargin: ConstraintMakerExtendable {
self.description.attributes += .bottomMargin
return self
}
@available(iOS 8.0, *)
public var leadingMargin: ConstraintMakerExtendable {
self.description.attributes += .leadingMargin
return self
}
@available(iOS 8.0, *)
public var trailingMargin: ConstraintMakerExtendable {
self.description.attributes += .trailingMargin
return self
}
@available(iOS 8.0, *)
public var centerXWithinMargins: ConstraintMakerExtendable {
self.description.attributes += .centerXWithinMargins
return self
}
@available(iOS 8.0, *)
public var centerYWithinMargins: ConstraintMakerExtendable {
self.description.attributes += .centerYWithinMargins
return self
}
public var edges: ConstraintMakerExtendable {
self.description.attributes += .edges
return self
}
public var size: ConstraintMakerExtendable {
self.description.attributes += .size
return self
}
@available(iOS 8.0, *)
public var margins: ConstraintMakerExtendable {
self.description.attributes += .margins
return self
}
@available(iOS 8.0, *)
public var centerWithinMargins: ConstraintMakerExtendable {
self.description.attributes += .centerWithinMargins
return self
}
}
|
mit
|
b2f19a75b3e32337bef5070bc3e09d2b
| 29.16568 | 81 | 0.666732 | 5.304891 | false | false | false | false |
GEOSwift/GEOSwift
|
Sources/GEOSwift/GEOS/GEOSHelpers.swift
|
2
|
3908
|
import geos
func makeGeometries<T>(geometry: GEOSObject) throws -> [T] where T: GEOSObjectInitializable {
let numGeometries = GEOSGetNumGeometries_r(geometry.context.handle, geometry.pointer)
guard numGeometries >= 0 else {
throw GEOSError.libraryError(errorMessages: geometry.context.errors)
}
return try Array(0..<numGeometries).map { (index) -> T in
// returns null on exception
guard let pointer = GEOSGetGeometryN_r(geometry.context.handle, geometry.pointer, index) else {
throw GEOSError.libraryError(errorMessages: geometry.context.errors)
}
return try T(geosObject: GEOSObject(parent: geometry, pointer: pointer))
}
}
func makePoints(from geometry: GEOSObject) throws -> [Point] {
guard let sequence = GEOSGeom_getCoordSeq_r(geometry.context.handle, geometry.pointer) else {
throw GEOSError.libraryError(errorMessages: geometry.context.errors)
}
var count: UInt32 = 0
// returns 0 on exception
guard GEOSCoordSeq_getSize_r(geometry.context.handle, sequence, &count) != 0 else {
throw GEOSError.libraryError(errorMessages: geometry.context.errors)
}
return try Array(0..<count).map { (index) -> Point in
var point = Point(x: 0, y: 0)
// returns 0 on exception
guard GEOSCoordSeq_getX_r(geometry.context.handle, sequence, index, &point.x) != 0,
GEOSCoordSeq_getY_r(geometry.context.handle, sequence, index, &point.y) != 0 else {
throw GEOSError.libraryError(errorMessages: geometry.context.errors)
}
return point
}
}
func makeCoordinateSequence(with context: GEOSContext, points: [Point]) throws -> OpaquePointer {
guard let sequence = GEOSCoordSeq_create_r(context.handle, UInt32(points.count), 2) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
try points.enumerated().forEach { (i, point) in
guard GEOSCoordSeq_setX_r(context.handle, sequence, UInt32(i), point.x) != 0,
GEOSCoordSeq_setY_r(context.handle, sequence, UInt32(i), point.y) != 0 else {
GEOSCoordSeq_destroy_r(context.handle, sequence)
throw GEOSError.libraryError(errorMessages: context.errors)
}
}
return sequence
}
func makeGEOSObject(with context: GEOSContext,
points: [Point],
factory: (GEOSContext, OpaquePointer) -> OpaquePointer?) throws -> GEOSObject {
let sequence = try makeCoordinateSequence(with: context, points: points)
guard let geometry = factory(context, sequence) else {
GEOSCoordSeq_destroy_r(context.handle, sequence)
throw GEOSError.libraryError(errorMessages: context.errors)
}
return GEOSObject(context: context, pointer: geometry)
}
func makeGEOSCollection(with context: GEOSContext,
geometries: [GEOSObjectConvertible],
type: GEOSGeomTypes) throws -> GEOSObject {
let geosObjects = try geometries.map { try $0.geosObject(with: context) }
let geosPointersArray = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: geosObjects.count)
defer { geosPointersArray.deallocate() }
geosObjects.enumerated().forEach { (i, geosObject) in
geosPointersArray[i] = geosObject.pointer
}
guard let collectionPointer = GEOSGeom_createCollection_r(
context.handle, Int32(type.rawValue), geosPointersArray, UInt32(geosObjects.count)) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
// upon success, geosObjects' pointees are now owned by the collection
// it's essential to set their parent properties so that they do not
// destory their pointees upon deinit.
let collection = GEOSObject(context: context, pointer: collectionPointer)
geosObjects.forEach { $0.parent = collection }
return collection
}
|
mit
|
ec198c9921785c2c10a46542c58bcb65
| 46.084337 | 103 | 0.688076 | 4.294505 | false | false | false | false |
icapps/swiftGenericWebService
|
Sources/Request/ParameterEnum.swift
|
3
|
3455
|
public enum Parameter: CustomDebugStringConvertible {
// MARK: - Header
case httpHeader([String: String])
// MARK: - To be inserted in Body
case jsonArray([[String: Any]])
case jsonNode([String: Any])
case urlComponentsInBody([String: String])
case encodedData(Data)
// MARK: - To be added to url
case urlComponentsInURL([String: String])
// MARK: - File
case multipart(MultipartFile)
// MARK: - Debug helper
public var debugDescription: String {
switch self {
case .httpHeader(let headerDict):
return "\(headerDict.map {(key:$0.key, value: $0.value)}.reduce("• .httpHeader:", {"\($0)\n• \($1)"}))"
case .jsonArray(let jsonArray):
do {
let array = try JSONSerialization.data(withJSONObject: jsonArray, options: .prettyPrinted)
let arrayString = String(data: array, encoding: .utf8)
return ".jsonArray:\n\(arrayString ?? "No data")"
} catch {
return "\(error)"
}
case .jsonNode(let jsonNode):
do {
let array = try JSONSerialization.data(withJSONObject: jsonNode, options: .prettyPrinted)
let arrayString = String(data: array, encoding: .utf8)
return "• .jsonNode:\n\(arrayString ?? "No data")"
} catch {
return "•\(error)"
}
case .urlComponentsInURL(let components):
return "\(components.map {(key:$0.key, value: $0.value)}.reduce("• .urlComponentsInUrl:", {"\($0)\n• \($1)"}))"
case .urlComponentsInBody(let components):
return "\(components.map {(key:$0.key, value: $0.value)}.reduce("• .urlComponentsInBody:", {"\($0)\n• \($1)"}))"
case .multipart(_):
return ".multipart"
case .encodedData(let data):
do {
let json = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
let string = String(data: json, encoding: .utf8)
return "• .bodyData:\n\(string ?? "no data")"
} catch {
return "• .bodyData:\n\(String(data: data, encoding: .utf8) ?? "no data")"
}
}
}
// MARK: - Logic
public var isHeader: Bool {
switch self {
case .httpHeader(_):
return true
default:
return false
}
}
public var isJSONArray: Bool {
switch self {
case .jsonArray(_):
return true
default:
return false
}
}
public var isJSONNode: Bool {
switch self {
case .jsonNode(_):
return true
default:
return false
}
}
public var isUrlComponentsInURL: Bool {
switch self {
case .urlComponentsInURL(_):
return true
default:
return false
}
}
public var isUrlComponentsInBody: Bool {
switch self {
case .urlComponentsInBody(_):
return true
default:
return false
}
}
// MARK: - Values
public var httpHeaderValue: [String: String]? {
switch self {
case .httpHeader(let header):
return header
default:
return nil
}
}
public var jsonArrayValue: [[String: Any]]? {
switch self {
case .jsonArray(let json):
return json
default:
return nil
}
}
public var jsonNodeValue: [String: Any]? {
switch self {
case .jsonNode(let node):
return node
default:
return nil
}
}
public var urlComponentsInURLValue: [String: String]? {
switch self {
case .urlComponentsInURL(let components):
return components
default:
return nil
}
}
public var urlComponentsInBodyValue: [String: String]? {
switch self {
case .urlComponentsInBody(let components):
return components
default:
return nil
}
}
}
|
mit
|
7c3b67ddd9c13237f4b5a180838dbcdc
| 21.305195 | 115 | 0.636099 | 3.48731 | false | false | false | false |
5lucky2xiaobin0/PandaTV
|
PandaTV/PandaTV/Classes/Main/VIew/CycleCell.swift
|
1
|
781
|
//
// CycleCell.swift
// PandaTV
//
// Created by 钟斌 on 2017/3/25.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
import Kingfisher
class CycleCell: UICollectionViewCell {
@IBOutlet weak var comImage: UIImageView!
var item : CycleItem? {
didSet {
guard let item = item else {return}
var url : URL?
if var img = item.img {
if img.contains("https") {
img = img.replacingOccurrences(of: "https", with: "http")
}
url = URL(string: img)
}else {
url = URL(string: item.bigimg!)
}
comImage.kf.setImage(with: ImageResource(downloadURL: url!))
}
}
}
|
mit
|
fe4490a0fd9dcbc8e8b8330fb7be62eb
| 23.1875 | 77 | 0.510336 | 4.095238 | false | false | false | false |
bengottlieb/stack-watcher
|
StackWatcher Mac/Controllers/Questions List/QuestionsListController.swift
|
1
|
1890
|
//
// QuestionsListController.swift
// StackWatcher
//
// Created by Ben Gottlieb on 6/9/14.
// Copyright (c) 2014 Stand Alone, Inc. All rights reserved.
//
import Cocoa
import WebKit
class QuestionsListController: NSWindowController, NSTableViewDataSource {
@IBOutlet var webView: WebView
@IBOutlet var splitView: NSSplitView
@IBOutlet var questionsTable: NSTableView
var fetchRequest = NSFetchRequest(entityName: "PostedQuestion")
var questions = []
var searchTag = "swift-language"
class func controller() -> (QuestionsListController) {
var controller = QuestionsListController(windowNibName: "QuestionsListController")
controller.fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "last_activity_date", ascending: false) ]
controller.showWindow(nil)
controller.window.makeKeyAndOrderFront(nil)
NSNotificationCenter.defaultCenter().addObserver(controller, selector: "updateQuestions", name: StackInterface.DefaultInterface.didAuthenticateNotificationName, object: nil)
return controller
}
override func windowWillLoad() {
self.updateQuestions()
}
}
extension QuestionsListController {
func updateQuestions() {
if !StackInterface.DefaultInterface.isAuthorized {
(NSApplication.sharedApplication().delegate as AppDelegate).promptForAuthorization()
return
}
StackInterface.DefaultInterface.fetchQuestionsForTag(self.searchTag, completion: {(error: NSError?) -> Void in
dispatch_async(dispatch_get_main_queue()) {
var error: NSError?
self.questions = Store.DefaultStore.mainQueueContext.executeFetchRequest(self.fetchRequest, error: &error)
self.reloadQuestions()
}
})
}
func reloadQuestions() {
}
}
extension QuestionsListController {
func numberOfRowsInTableView(tableView: NSTableView!) -> Int { println("\(self.questions.count) questions found"); return self.questions.count }
}
|
mit
|
2ea9b70260c41183f9e4dbc07a352b5a
| 27.651515 | 175 | 0.763492 | 4.305239 | false | false | false | false |
quran/quran-ios
|
Sources/BatchDownloader/QProgress.swift
|
1
|
2516
|
//
// QProgress.swift
// Quran
//
// Created by Mohamed Afifi on 4/21/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
import WeakSet
public protocol QProgressListener: AnyObject {
func onProgressUpdated(to progress: Double)
}
public final class BlockQProgressListener: QProgressListener {
private let body: (Double) -> Void
public init(_ body: @escaping (Double) -> Void) {
self.body = body
}
public func onProgressUpdated(to progress: Double) {
body(progress)
}
}
public final class QProgress: NSObject, QProgressListener {
private var children: [QProgress: Double] = [:]
public let progressListeners = WeakSet<QProgressListener>()
public var totalUnitCount: Double {
didSet {
if oldValue != totalUnitCount {
notifyProgressChanged()
}
}
}
public var completedUnitCount: Double = 0 {
didSet { notifyProgressChanged() }
}
private func notifyProgressChanged() {
let progress = progress
for listener in progressListeners {
listener.onProgressUpdated(to: progress)
}
}
public var progress: Double {
Double(completedUnitCount) / Double(totalUnitCount)
}
public init(totalUnitCount: Double) {
self.totalUnitCount = totalUnitCount
}
public func add(child: QProgress, withPendingUnitCount inUnitCount: Double) {
children[child] = inUnitCount
child.progressListeners.insert(self)
}
public func remove(child: QProgress) {
children[child] = nil
child.progressListeners.remove(self)
}
public func onProgressUpdated(to progress: Double) {
var completedUnitCount: Double = 0
for (child, pendingUnitCount) in children {
completedUnitCount += child.progress * pendingUnitCount
}
self.completedUnitCount = completedUnitCount
}
}
|
apache-2.0
|
1b3036ca091055a72601a3d68d05c976
| 27.91954 | 81 | 0.670906 | 4.574545 | false | false | false | false |
jbrjake/caturlog
|
Caturlog/Caturlog/AppDelegate.swift
|
1
|
8339
|
//
// AppDelegate.swift
// Caturlog
//
// Created by Jonathon Rubin on 7/3/14.
// Copyright (c) 2014 Jonathon Rubin. All rights reserved.
//
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
let windowController: CaturlogWindowController = CaturlogWindowController(windowNibName: "CaturlogWindow")
let caturlogServices = CaturlogServices()
func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
windowController.showWindow(nil)
}
func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
}
@IBAction func saveAction(sender: AnyObject) {
// Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
var error: NSError? = nil
if let moc = self.managedObjectContext {
if !moc.commitEditing() {
println("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving")
}
if !moc.save(&error) {
NSApplication.sharedApplication().presentError(error)
}
}
}
var applicationFilesDirectory: NSURL {
// Returns the directory the application uses to store the Core Data store file. This code uses a directory named "us.ubiquit.Caturlog" in the user's Application Support directory.
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
let appSupportURL: AnyObject = urls[urls.endIndex - 1]
return appSupportURL.URLByAppendingPathComponent("Caturlog")
}
var managedObjectModel: NSManagedObjectModel {
// Creates if necessary and returns the managed object model for the application.
if let mom = _managedObjectModel {
return mom
}
let modelURL = NSBundle.mainBundle().URLForResource("Caturlog", withExtension: "mom")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
var persistentStoreCoordinator: NSPersistentStoreCoordinator? {
// Returns the persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.)
if let psc = _persistentStoreCoordinator {
return psc
}
let mom = self.managedObjectModel
let fileManager = NSFileManager.defaultManager()
let applicationFilesDirectory = self.applicationFilesDirectory
var error: NSError? = nil
let optProperties: NSDictionary? = applicationFilesDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error)
if let properties = optProperties {
if !properties[NSURLIsDirectoryKey].boolValue {
// Customize and localize this error.
let failureDescription = "Expected a folder to store application data, found a file \(applicationFilesDirectory.path)."
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = failureDescription
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 101, userInfo: dict)
NSApplication.sharedApplication().presentError(error)
return nil
}
} else {
var ok = false
if error!.code == NSFileReadNoSuchFileError {
ok = fileManager.createDirectoryAtPath(applicationFilesDirectory.path, withIntermediateDirectories: true, attributes: nil, error: &error)
}
if !ok {
NSApplication.sharedApplication().presentError(error)
return nil
}
}
let url = applicationFilesDirectory.URLByAppendingPathComponent("Caturlog.storedata")
var coordinator = NSPersistentStoreCoordinator(managedObjectModel: mom)
if coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption: true], error: &error) == nil {
NSApplication.sharedApplication().presentError(error)
return nil
}
_persistentStoreCoordinator = coordinator
return _persistentStoreCoordinator
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
var managedObjectContext: NSManagedObjectContext? {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if let moc = _managedObjectContext {
return moc
}
let coordinator = self.persistentStoreCoordinator
if !coordinator {
var dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the store"
dict[NSLocalizedFailureReasonErrorKey] = "There was an error building up the data file."
let error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSApplication.sharedApplication().presentError(error)
return nil
}
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator!
return _managedObjectContext
}
var _managedObjectContext: NSManagedObjectContext? = nil
func windowWillReturnUndoManager(window: NSWindow?) -> NSUndoManager? {
// Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application.
if let moc = self.managedObjectContext {
return moc.undoManager
} else {
return nil
}
}
func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
// Save changes in the application's managed object context before the application terminates.
if !_managedObjectContext {
// Accesses the underlying stored property because we don't want to cause the lazy initialization
return .TerminateNow
}
let moc = self.managedObjectContext!
if !moc.commitEditing() {
println("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate")
return .TerminateCancel
}
if !moc.hasChanges {
return .TerminateNow
}
var error: NSError? = nil
if !moc.save(&error) {
// Customize this code block to include application-specific recovery steps.
let result = sender.presentError(error)
if (result) {
return .TerminateCancel
}
let question = "Could not save changes while quitting. Quit anyway?" // NSLocalizedString(@"Could not save changes while quitting. Quit anyway?", @"Quit without saves error question message")
let info = "Quitting now will lose any changes you have made since the last successful save" // NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save", @"Quit without saves error question info");
let quitButton = "Quit anyway" // NSLocalizedString(@"Quit anyway", @"Quit anyway button title")
let cancelButton = "Cancel" // NSLocalizedString(@"Cancel", @"Cancel button title")
let alert = NSAlert()
alert.messageText = question
alert.informativeText = info
alert.addButtonWithTitle(quitButton)
alert.addButtonWithTitle(cancelButton)
let answer = alert.runModal()
if answer == NSAlertFirstButtonReturn {
return .TerminateCancel
}
}
return .TerminateNow
}
}
|
mit
|
f2b982695b55dcd4e6ddcd459da45832
| 44.320652 | 253 | 0.660391 | 5.973496 | false | false | false | false |
roambotics/swift
|
validation-test/compiler_crashers_2_fixed/issue-55443.swift
|
2
|
1727
|
// RUN: %target-swift-frontend -typecheck %s -verify
// https://github.com/apple/swift/issues/55443
enum FooString: String { // expected-error {{'FooString' declares raw type 'String', but does not conform to RawRepresentable and conformance could not be synthesized}}
case bar1 = #file // expected-error {{use of '#file' literal as raw value for enum case is not supported}}
case bar2 = #function // expected-error {{use of '#function' literal as raw value for enum case is not supported}}
case bar3 = #filePath // expected-error {{use of '#filePath' literal as raw value for enum case is not supported}}
case bar4 = #line // expected-error {{cannot convert value of type 'Int' to raw type 'String'}}
case bar5 = #column // expected-error {{cannot convert value of type 'Int' to raw type 'String'}}
case bar6 = #dsohandle // expected-error {{cannot convert value of type 'UnsafeRawPointer' to raw type 'String'}}
}
enum FooInt: Int { // expected-error {{'FooInt' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}}
case bar1 = #file // expected-error {{cannot convert value of type 'String' to raw type 'Int'}}
case bar2 = #function // expected-error {{cannot convert value of type 'String' to raw type 'Int'}}
case bar3 = #filePath // expected-error {{cannot convert value of type 'String' to raw type 'Int'}}
case bar4 = #line // expected-error {{use of '#line' literal as raw value for enum case is not supported}}
case bar5 = #column // expected-error {{use of '#column' literal as raw value for enum case is not supported}}
case bar6 = #dsohandle // expected-error {{cannot convert value of type 'UnsafeRawPointer' to raw type 'Int'}}
}
|
apache-2.0
|
14f1c46f8d44c8ea6e1512e376ccc72c
| 81.238095 | 168 | 0.716271 | 4.025641 | false | false | false | false |
EmmaXiYu/SE491
|
DonateParkSpot/DonateParkSpot/BuyDetailController.swift
|
1
|
7069
|
//
// BuyDetailController.swift
// DonateParkSpot
//
// Created by Rafael Guerra on 10/29/15.
// Copyright © 2015 Apple. All rights reserved.
//
import UIKit
import MapKit
import Parse
class BuyDetailController : UIViewController, MKMapViewDelegate {
var spot : Spot?
//var ownerName:String = ""
//var ownerId:String = ""
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var type: UILabel!
@IBOutlet weak var rate: UILabel!
@IBOutlet weak var timeToLeave: UILabel!
@IBOutlet weak var minDonation: UILabel!
@IBOutlet weak var donation: UIStepper!
let locationManager=CLLocationManager()
override func viewDidLoad() {
if spot != nil {
self.title = spot!.owner!.email! + "'s Spot"
if spot!.type == 1 {
type.text = "Paid Spot"
rate.text = "U$ " + spot!.rate.description + "0"
timeToLeave.text = spot!.timeToLeave?.description
minDonation.text = "U$ " + spot!.minDonation.description + ".00"
}else{
type.text = "Free Spot"
rate.text = "Free"
timeToLeave.text = "Zero Minutes"
minDonation.text = "U$ " + spot!.minDonation.description + ".00"
}
donation.minimumValue = Double(spot!.minDonation)
donation.maximumValue = 1.79e307
donation.stepValue = 1
self.map.delegate = self
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
let pinLocation: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: (spot?.location.latitude)!, longitude: (spot?.location.longitude)!)
let region=MKCoordinateRegion(center: pinLocation, span: MKCoordinateSpan(latitudeDelta: 0.004, longitudeDelta: 0.004))
self.map.setRegion(region, animated: true)
let annotation = CustomerAnnotation(coordinate: pinLocation,spotObject: spot!, title :(spot!.owner!.email!),subtitle: (spot!.owner?.objectId)!)
//annotation.subtitle = "Rating bar here"
self.map.addAnnotation(annotation)
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation
) -> MKAnnotationView!{
if let a = annotation as? CustomerAnnotation {
let pinAnnotationView = MKPinAnnotationView(annotation: a, reuseIdentifier: "myPin")
//let ownerID:String = a.subtitle!
let spot = a.spot
let ownerScore = a.spot.owner?.getRatingAsSeller()
let name = a.title!
let ownerID:String = (a.spot.owner?.objectId)!
a.subtitle = String(ownerScore!)
let pic = UIImageView (image: UIImage(named: "test.png"))
pinAnnotationView.canShowCallout = true
pinAnnotationView.draggable = false
pinAnnotationView.canShowCallout = true
pinAnnotationView.animatesDrop = true
pinAnnotationView.pinColor = MKPinAnnotationColor.Purple
let query = PFUser.query()
do{ let user = try query!.getObjectWithId(ownerID) as! PFUser
if let userPicture = user["Image"] as? PFFile {
userPicture.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if error == nil {
pic.image = UIImage(data:imageData!)
}
}
}
}
catch{
//Throw exception here
}
pic.frame = CGRectMake(0, 0, 40, 40);
pinAnnotationView.leftCalloutAccessoryView = pic
pinAnnotationView.frame = CGRectMake(0,0,500,500)
return pinAnnotationView
}
return nil
}
@IBAction func upDown(sender: UIStepper) {
minDonation.text = "U$ " + sender.value.description + "0"
}
@IBAction func buy() {
if(IsValidBuyer() == true){
let user = PFUser.currentUser()
let query = PFQuery.init(className: "Bid")
query.whereKey("user", equalTo: user!)
query.whereKey("spot", equalTo: spot!.toPFObject())
query.whereKey("StatusId", notEqualTo: 4) // 4 is cancel by bid owner
do{
let results = try query.findObjects()
if results.count > 0 {
let alert = UIAlertView.init(title: "Bid already made", message: "You cannot bid twice on a Spot. You can cancel your current Bid and bid again for this Spot", delegate: nil, cancelButtonTitle: "OK")
alert.show()
return
}
}catch{
}
let bid = Bid()
bid.bidder = user
bid.value = donation.value
bid.spot = spot
bid.statusId = 1
bid.toPFObjet().saveInBackgroundWithBlock{
(success: Bool, error: NSError?) -> Void in
if(success){
print(success)
}else{
print(error)
}
}
updateSpot((self.spot?.spotId)!, status : 1)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
func IsValidBuyer()->Bool
{
var IsValid = true
var msg = ""
if(spot?.owner?.email == PFUser.currentUser()?.email)
{
IsValid = false
msg = "You can not Bid your Own Spot" + "\r\n"
}
if(msg.characters.count > 0)
{
let alertController = UIAlertController(title: "Validation Error", message: msg, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:nil)
}
return IsValid
}
func updateSpot(spotid : String, status :Int)-> Void
{
let prefQuery = PFQuery(className: "Spot")
prefQuery.getObjectInBackgroundWithId(spotid){
(prefObj: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let prefObj = prefObj {
prefObj["StatusId"] = status
prefObj.saveInBackground()
}
}
}
}
|
apache-2.0
|
481b9afc0b9b561156d9abe6095e31f1
| 36.2 | 219 | 0.527731 | 5.216236 | false | false | false | false |
pauljeannot/SnapSliderFilters
|
SnapSliderFilters/Classes/SNButton.swift
|
1
|
6008
|
//
// SNButton.swift
// Pods
//
// Created by Paul Jeannot on 15/08/2016.
//
//
import UIKit
open class SNButton: UIButton {
public typealias actionTypeClosure = () -> ()
fileprivate var action:actionTypeClosure = {}
fileprivate var shouldRunAction = false
fileprivate var _buttonState = ButtonAnimationState.smallButton
fileprivate var buttonState:ButtonAnimationState {
get {
return _buttonState
}
set (newValue) {
// The button is pressed : starting the animation to make it big
if buttonState == .smallButton && newValue == .bigButton {
UIView.animate(withDuration: 0.15,
animations: {
self.transform = ButtonAnimations.animationButtonPressed
self._buttonState = .animating
},
completion: { _ in
// Now it is big :
// Button already released : make it small
if self._buttonState == .smallButton {
self.buttonState = .smallButton
}
// Button still pressed : bounce effect
else {
UIView.animate(withDuration: 0.09,
animations: {
self.transform = ButtonAnimations.animationButtonPressedSmallBounce
},
completion: { _ in
// Boune effect completed : if button not released : stay big
if self._buttonState == .animating {
self._buttonState = .bigButton
}
// If released : make it small
else if self._buttonState == .smallButton {
self.buttonState = .smallButton
}
}
)
}
}
)
}
// The button is released when it was big || during the animation : make it small again
else if _buttonState == .bigButton && newValue == .smallButton || _buttonState == .smallButton && newValue == .smallButton {
if shouldRunAction {
shouldRunAction = false
self.action()
}
UIView.animate(withDuration: 0.15,
animations: {
self.transform = ButtonAnimations.animationButtonReleased
self._buttonState = .animating
},
completion: { _ in
self._buttonState = .smallButton
}
)
}
// The button is released during the animation : make it small
else if buttonState == .animating && newValue == .smallButton {
self._buttonState = .smallButton
}
}
}
fileprivate struct ButtonAnimations {
static let animationButtonPressed = CGAffineTransform(scaleX: 1.25, y: 1.25)
static let animationButtonPressedSmallBounce = CGAffineTransform(scaleX: 1.13, y: 1.13)
static let animationButtonReleased = CGAffineTransform(scaleX: 1, y: 1)
}
fileprivate enum ButtonAnimationState {
case animating // If the animation is running
case smallButton // If the button is/is wanted small
case bigButton // If the button is/is wanted big
}
public init(frame: CGRect, withImageNamed name: String) {
super.init(frame: CGRect(x: frame.origin.x - 10, y: frame.origin.y - 20, width: frame.size.width+20, height: frame.size.height+20))
self.layer.zPosition = 1000
self.adjustsImageWhenHighlighted = false
self.setImage(UIImage(named: name), for: UIControlState())
self.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
self.addTarget(self, action: #selector(buttonTouchUpInside), for: .touchUpInside)
self.addTarget(self, action: #selector(buttonPressed), for: .touchDown)
self.addTarget(self, action: #selector(buttonPressed), for: .touchDragEnter)
self.addTarget(self, action: #selector(buttonPressed), for: .touchDragInside)
self.addTarget(self, action: #selector(buttonReleased), for: .touchDragExit)
self.addTarget(self, action: #selector(buttonReleased), for: .touchCancel)
self.addTarget(self, action: #selector(buttonReleased), for: .touchDragOutside)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func setAction(action actionClosure: @escaping actionTypeClosure) {
self.action = actionClosure
}
func buttonTouchUpInside() {
shouldRunAction=true
buttonReleased()
}
func buttonPressed() {
buttonState = .bigButton
}
func buttonReleased() {
buttonState = .smallButton
}
}
|
mit
|
7aab7e82769d54fddb047628b16460f3
| 45.573643 | 139 | 0.466212 | 6.324211 | false | false | false | false |
QuaereVeritatem/TopHackIncStartup
|
TopHackIncStartUp/NSDateComponents+Timepiece.swift
|
3
|
1033
|
//
// NSDateComponents+Timepiece.swift
// Timepiece
//
// Created by Mattijs on 25/04/15.
// Copyright (c) 2015 Naoto Kaneko. All rights reserved.
//
import Foundation
extension NSDateComponents {
convenience init(_ duration: Duration) {
self.init()
switch duration.unit{
case NSCalendar.Unit.day:
day = duration.value
case NSCalendar.Unit.weekday:
weekday = duration.value
case NSCalendar.Unit.weekOfMonth:
weekOfMonth = duration.value
case NSCalendar.Unit.weekOfYear:
weekOfYear = duration.value
case NSCalendar.Unit.hour:
hour = duration.value
case NSCalendar.Unit.minute:
minute = duration.value
case NSCalendar.Unit.month:
month = duration.value
case NSCalendar.Unit.second:
second = duration.value
case NSCalendar.Unit.year:
year = duration.value
default:
() // unsupported / ignore
}
}
}
|
mit
|
582b39732be4f1e744e9b1a46e7cc06f
| 26.918919 | 57 | 0.598258 | 4.716895 | false | false | false | false |
lukaszwas/mcommerce-api
|
Sources/App/Models/Stripe/Helpers/TokenizedMethod.swift
|
1
|
486
|
//
// TokenizedMethod.swift
// Stripe
//
// Created by Anthony Castelli on 4/15/17.
//
//
import Foundation
public enum TokenizedMethod: String {
case applePay = "apple_pay"
case androidPay = "android_pay"
}
extension TokenizedMethod {
public init?(optionalRawValue: String?) {
if let rawValue = optionalRawValue {
if let value = TokenizedMethod(rawValue: rawValue) {
self = value
}
}
return nil
}
}
|
mit
|
66b4b1700efeeecdb2bf64fa4acb109f
| 18.44 | 64 | 0.600823 | 4.05 | false | false | false | false |
Himnshu/LoginLib
|
Example/LoginLib/LoginCoordinator.swift
|
1
|
2815
|
//
// LoginCoordinator.swift
// LoginFramework
//
// Created by OSX on 28/07/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import LoginLib
class LoginCoordinator: LoginLib.LoginCoordinator
{
override func start() {
super.start()
configureAppearance()
}
override func finish() {
super.finish()
}
func configureAppearance() {
// Customize LoginKit. All properties have defaults, only set the ones you want.
// Customize the look with background & logo images
backgroundImage = #imageLiteral(resourceName: "background")
mainLogoImage = #imageLiteral(resourceName: "parseImage")
secondaryLogoImage = #imageLiteral(resourceName: "parseImage")
// Change colors
tintColor = UIColor(red: 52.0/255.0, green: 152.0/255.0, blue: 219.0/255.0, alpha: 1)
errorTintColor = UIColor(red: 253.0/255.0, green: 227.0/255.0, blue: 167.0/255.0, alpha: 1)
// Change placeholder & button texts, useful for different marketing style or language.
loginButtonText = "Sign In"
signupButtonText = "Create Account"
forgotPasswordButtonText = "Forgot password?"
recoverPasswordButtonText = "Recover"
namePlaceholder = "Full Name"
emailPlaceholder = "E-Mail"
passwordPlaceholder = "Password!"
repeatPasswordPlaceholder = "Confirm password!"
}
// MARK: - Completion Callbacks
override func login(profile: LoginProfile) {
// Handle login via your API
print("Login with: email =\(profile.email) username = \(profile.userName)")
}
override func signup(profile: SignUpProfile) {
// Handle signup via your API
print("Signup with: name = \(profile.userName) email =\(profile.email)")
}
override func loginError(error: NSError) {
// Handle login error via your API
let errorString = error.userInfo["error"] as? String
print("Error: \(errorString)")
}
override func signUpError(error: NSError) {
// Handle login error via your API
print(error)
}
override func enterWithFacebook(profile: FacebookProfile) {
// Handle Facebook login/signup via your API
print("Login/Signup via Facebook with: FB profile =\(profile)")
}
override func enterWithTwitter(profile: TwitterProfile) {
// Handle Facebook login/signup via your API
print("Login/Signup via Facebook with: FB profile =\(profile)")
}
override func recoverPassword(success: Bool) {
// Handle password recovery via your API
print(success)
}
override func recoverPasswordError(error: NSError) {
print(error)
}
}
|
mit
|
3a80d2193fafd7d92129591aabf73328
| 31.344828 | 99 | 0.633618 | 4.62069 | false | false | false | false |
uias/Pageboy
|
Sources/iOS/Extras/ToolbarDelegate.swift
|
1
|
2239
|
//
// ToolbarDelegate.swift
// Example iOS
//
// Created by Merrick Sapsford on 11/10/2020.
// Copyright © 2020 UI At Six. All rights reserved.
//
import UIKit
class ToolbarDelegate: NSObject {
}
#if targetEnvironment(macCatalyst)
extension NSToolbarItem.Identifier {
static let nextPage = NSToolbarItem.Identifier("com.uias.Pageboy.nextPage")
static let previousPage = NSToolbarItem.Identifier("com.uias.Pageboy.previousPage")
}
extension ToolbarDelegate {
@objc func nextPage(_ sender: Any?) {
NotificationCenter.default.post(Notification(name: .nextPage))
}
@objc func previousPage(_ sender: Any?) {
NotificationCenter.default.post(Notification(name: .previousPage))
}
}
extension ToolbarDelegate: NSToolbarDelegate {
func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
let identifiers: [NSToolbarItem.Identifier] = [
.previousPage,
.nextPage
]
return identifiers
}
func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
return toolbarDefaultItemIdentifiers(toolbar)
}
func toolbar(_ toolbar: NSToolbar,
itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier,
willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
var toolbarItem: NSToolbarItem?
switch itemIdentifier {
case .nextPage:
let item = NSToolbarItem(itemIdentifier: itemIdentifier)
item.image = UIImage(systemName: "chevron.right")
item.label = "Next Page"
item.action = #selector(nextPage(_:))
item.target = self
toolbarItem = item
case .previousPage:
let item = NSToolbarItem(itemIdentifier: itemIdentifier)
item.image = UIImage(systemName: "chevron.left")
item.label = "Previous Page"
item.action = #selector(previousPage(_:))
item.target = self
toolbarItem = item
default:
toolbarItem = nil
}
return toolbarItem
}
}
#endif
|
mit
|
801c4abf8e73b93ccbe1ab8b9d598d79
| 27.692308 | 92 | 0.623324 | 4.995536 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet
|
SwiftGL-Demo/Source/iOS/PaintViewStrokeSelect.swift
|
1
|
1039
|
//
// PaintViewStrokeSelect.swift
// SwiftGL
//
// Created by jerry on 2016/5/15.
// Copyright © 2016年 Jerry Chan. All rights reserved.
//
extension PaintViewController
{
func enterSelectStrokeMode(){
appState = AppState.selectStroke
selectStrokeModeToolBarSetUp()
}
func playSeletingStrokes()
{
strokeSelecter.isSelectingClip = true
//strokeSelecter.originalClip = paintManager.artwork.useMasterClip()
paintManager.artwork.loadClip(strokeSelecter.selectingClip)
//.drawClip(strokeSelecter.selectingClip)
//paintView.glDraw()
_ = removeToolBarButton(reviseDoneButton)
appState = AppState.viewArtwork
enterViewMode()
}
func selectStrokeModeToolBarSetUp()
{
addToolBarButton(reviseDoneButton, atIndex: 0)
mainToolBar.setItems(toolBarItems, animated: true)
}
func backToOriginalClip()
{
paintManager.artwork.useMasterClip()
}
}
|
mit
|
286d01affd74f9b75be357c76edc796c
| 24.268293 | 76 | 0.643822 | 4.524017 | false | false | false | false |
movabletype/smartphone-app
|
MT_iOS/MT_iOS/Classes/Model/Asset.swift
|
1
|
3753
|
//
// Asset.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/05/26.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
import SwiftyJSON
class Asset: BaseObject {
var label: String = ""
var url: String = ""
var filename: String = ""
var fileSize: Int = 0
var width: Int = 0
var height: Int = 0
var createdByName: String = ""
var createdDate: NSDate?
var blogID: String = ""
override init(json: JSON) {
super.init(json: json)
label = json["label"].stringValue
url = json["url"].stringValue
filename = json["filename"].stringValue
if !json["meta"]["fileSize"].stringValue.isEmpty {
if let int = Int(json["meta"]["fileSize"].stringValue) {
fileSize = int
}
}
if !json["meta"]["width"].stringValue.isEmpty {
if let int = Int(json["meta"]["width"].stringValue) {
width = int
}
}
if !json["meta"]["height"].stringValue.isEmpty {
if let int = Int(json["meta"]["height"].stringValue) {
height = int
}
}
createdByName = json["createdBy"]["displayName"].stringValue
let dateString = json["createdDate"].stringValue
if !dateString.isEmpty {
createdDate = Utils.dateTimeFromISO8601String(dateString)
}
blogID = json["blog"]["id"].stringValue
}
override func encodeWithCoder(aCoder: NSCoder) {
super.encodeWithCoder(aCoder)
aCoder.encodeObject(self.label, forKey: "label")
aCoder.encodeObject(self.url, forKey: "url")
aCoder.encodeObject(self.filename, forKey: "filename")
aCoder.encodeInteger(self.fileSize, forKey: "fileSize")
aCoder.encodeInteger(self.width, forKey: "width")
aCoder.encodeInteger(self.height, forKey: "height")
aCoder.encodeObject(self.createdByName, forKey: "createdByName")
aCoder.encodeObject(self.createdDate, forKey: "createdDate")
aCoder.encodeObject(self.blogID, forKey: "blogID")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.label = aDecoder.decodeObjectForKey("label") as! String
self.url = aDecoder.decodeObjectForKey("url") as! String
self.filename = aDecoder.decodeObjectForKey("filename") as! String
self.fileSize = aDecoder.decodeIntegerForKey("fileSize")
self.width = aDecoder.decodeIntegerForKey("width")
self.height = aDecoder.decodeIntegerForKey("height")
self.createdByName = aDecoder.decodeObjectForKey("createdByName") as! String
self.createdDate = aDecoder.decodeObjectForKey("createdDate") as? NSDate
self.blogID = aDecoder.decodeObjectForKey("blogID") as! String
}
func dispName()-> String {
if !self.label.isEmpty {
return self.label
}
return self.filename
}
func imageHTML(align: Blog.ImageAlign)-> String {
let dimmensions = "width=\(self.width) height=\(self.height)"
var wrapStyle = "class=\"mt-image-\(align.value().lowercaseString)\" "
switch align {
case .Left:
wrapStyle += "style=\"float: left; margin: 0 20px 20px 0;\""
case .Right:
wrapStyle += "style=\"float: right; margin: 0 0 20px 20px;\""
case .Center:
wrapStyle += "style=\"text-align: center; display: block; margin: 0 auto 20px;\""
default:
wrapStyle += "style=\"\""
}
let html = "<img alt=\"\(label)\" src=\"\(url)\" \(dimmensions) \(wrapStyle) />"
return html
}
}
|
mit
|
105d88871056353d84533407630fdb0e
| 34.733333 | 93 | 0.589976 | 4.508413 | false | false | false | false |
roddi/FURRDataSource
|
DataSource/DataSourceEngine.swift
|
1
|
17168
|
// swiftlint:disable line_length
// swiftlint:disable file_length
// swiftlint:disable function_body_length
// swiftlint:disable type_body_length
// swiftlint:disable cyclomatic_complexity
//
// DataSourceEngine.swift
// FURRDataSource
//
// Created by Ruotger Deecke on 26.12.15.
// Copyright © 2015-2016 Ruotger Deecke. All rights reserved.
//
// TL/DR; BSD 2-clause license
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
import FURRDiff
public enum DataSourceReportingLevel {
case preCondition /// always crashes
case assert /// crashes debug versions otherwise silent, this is the default
case print /// prints in debug versions otherwise silent.
case verbose /// prints a lot of stuff.
case silent /// always silently ignores everything
}
internal class DataSourceEngine <T> where T: DataItem {
private var sectionIDsInternal: [String] = []
private var rowsBySectionID: [String: [T]] = Dictionary()
// MARK: - delegate blocks
var beginUpdates: (() -> Void)?
var endUpdates: (() -> Void)?
var deleteSections: ((IndexSet) -> Void)?
var insertSections: ((IndexSet) -> Void)?
var didChangeSectionIDs: (([String: [T]]) -> Void)?
var deleteRowsAtIndexPaths: (([IndexPath]) -> Void)?
var insertRowsAtIndexPaths: (([IndexPath]) -> Void)?
var reloadRowsAtIndexPaths: (([IndexPath]) -> Void)?
internal var fail: ((String) -> Void )?
internal var warn: ((String) -> Void )?
internal var reportingLevel: DataSourceReportingLevel = .assert
// MARK: - querying
// MARK: by id
func sectionIDs() -> [String] {
let sectionIDs = self.sectionIDsInternal
return sectionIDs
}
func rows(forSectionID sectionID: String) -> [T] {
if let rows = self.rowsBySectionID[sectionID] {
return rows
} else {
return []
}
}
// MARK: by location
func indexPath(forLocation location: Location<T>) -> IndexPath? {
return indexPath(forSectionID: location.sectionID, rowItem: location.item)
}
// MARK: by index
func numberOfRows(forSectionIndex index: Int) -> Int {
guard let sectionID = self.sectionIDs().optionalElement(index: index) else {
self.fail(message: "no section at index '\(index)'")
return 0
}
let rows = self.rows(forSectionID: sectionID)
return rows.count
}
func sectionIDAndItem(forIndexPath indexPath: IndexPath) -> (String, T)? {
let sectionIndex: Int = indexPath.section
guard let (sectionID, rowArray) = self.sectionIDAndRows(forSectionIndex: sectionIndex) else {
return nil
}
guard let item = rowArray.optionalElement(index: indexPath.row) else {
print("item not found at index \(indexPath.row) for sectionID \(sectionID)")
return nil
}
return (sectionID, item)
}
func sectionIDAndRows(forSectionIndex sectionIndex: Int) -> (String, [T])? {
guard let sectionID = self.sectionIDsInternal.optionalElement(index: sectionIndex) else {
print("section not found at index \(sectionIndex)")
return nil
}
guard let rowArray: [T] = self.rowsBySectionID[sectionID] else {
print("row array not found for sectionID \(sectionID)")
return nil
}
return (sectionID, rowArray)
}
// MARK: by index path
func location(forIndexPath indexPath: IndexPath) -> Location<T>? {
guard let (sectionID, item) = self.sectionIDAndItem(forIndexPath: indexPath) else {
return nil
}
let location = Location(sectionID: sectionID, item: item)
return location
}
// MARK: - updating
func update(sectionIDs sectionIDsToUpdate: [String], animated inAnimated: Bool) {
if sectionIDsToUpdate.containsDuplicatesFast() {
self.fail(message: "duplicate section ids - FURRDataSource will be confused by this later on so it is not permitted. Severity: lethal, sorry, nevertheless have a good evening!")
return
}
guard
let beginUpdatesFunc = self.beginUpdates,
let endUpdatesFunc = self.endUpdates,
let deleteSectionsFunc = self.deleteSections,
let insertSectionsFunc = self.insertSections else {
self.fail(message: "At least one of the required callback funcs of DataSourceEngine is nil. Severity: lethal, sorry, nevertheless have a good evening!")
return
}
let diffs = diffBetweenArrays(arrayA: self.sectionIDsInternal, arrayB: sectionIDsToUpdate)
var index = 0
beginUpdatesFunc()
for diff in diffs {
switch diff.operation {
case .delete:
for _ in diff.array {
self.sectionIDsInternal.remove(at: index)
deleteSectionsFunc(IndexSet(integer: index))
}
case .insert:
for string in diff.array {
self.sectionIDsInternal.insert(string, at: index)
insertSectionsFunc(IndexSet(integer: index))
index += 1
}
case .equal:
index += diff.array.count
}
}
endUpdatesFunc()
assert(self.sectionIDsInternal == sectionIDsToUpdate, "should be equal now")
}
func update(rows rowsToUpdate: [T], sectionID: String, animated: Bool, doNotCopy: Bool) -> (() -> Void) {
guard let sectionIndex = self.sectionIndex(forSectionID: sectionID) else {
self.warn(message: "sectionID does not exists. Severity: non lethal but the update just failed and the data source remains unaltered.")
return {}
}
if rowsToUpdate.containsDuplicates() {
self.fail(message: "Supplied rows contain duplicates. This will confuse FURRDataSource later on and we can't have that. Severity: lethal, sorry.")
return {}
}
guard
let beginUpdatesFunc = self.beginUpdates,
let endUpdatesFunc = self.endUpdates,
let deleteRowsAtIndexPathsFunc = self.deleteRowsAtIndexPaths,
let insertRowsAtIndexPathsFunc = self.insertRowsAtIndexPaths,
let reloadRowsAtIndexPathsFunc = self.reloadRowsAtIndexPaths else {
self.fail(message: "At least one of the required callback funcs of DataSourceEngine is nil. Severity: lethal, sorry, nevertheless have a good evening!")
return {}
}
let callbacks = Callbacks(beginUpdatesFunc: beginUpdatesFunc,
endUpdatesFunc: endUpdatesFunc,
deleteRowsAtIndexPathsFunc: deleteRowsAtIndexPathsFunc,
insertRowsAtIndexPathsFunc: insertRowsAtIndexPathsFunc,
reloadRowsAtIndexPathsFunc: reloadRowsAtIndexPathsFunc)
let existingRows: [T] = self.rowsBySectionID[sectionID] ?? []
let secondUpdate = private_update(existingRows: existingRows,
rowsToUpdate: rowsToUpdate,
callbacks: callbacks,
sectionIndex: sectionIndex,
sectionID: sectionID,
doNotCopy: doNotCopy)
return secondUpdate
}
// MARK: updating, convenience
public func deleteItems(_ items: [T], animated: Bool = true) -> (() -> Void) {
let identifiers = items.map { $0.identifier }
let allSections = sectionIDs()
var secondUpdates: [() -> Void] = []
for section in allSections {
let sectionItems = rows(forSectionID: section)
let filteredItems = sectionItems.filter({ (item: T) -> Bool in
return !identifiers.contains(item.identifier)
})
secondUpdates.append(update(rows: filteredItems, sectionID: section, animated: animated, doNotCopy: false))
}
return { secondUpdates.forEach { $0() } }
}
// MARK: - initiated by user
func moveRow(at sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard let (fromSectionID, fromItem) = self.sectionIDAndItem(forIndexPath: sourceIndexPath) else {
print("source not found!")
return
}
guard let didChangeSectionIDsFunc = self.didChangeSectionIDs else {
self.fail(message: "At least one of the required callback funcs of DataSourceEngine is nil. Severity: lethal, sorry, nevertheless have a good evening!")
return
}
var rows = self.rows(forSectionID: fromSectionID)
rows.remove(at: sourceIndexPath.row)
self.rowsBySectionID[fromSectionID] = rows
guard let (toSectionID, toRows) = self.sectionIDAndRows(forSectionIndex: destinationIndexPath.section) else {
print("destination section not found!")
return
}
print("from \(fromSectionID)-\(fromItem.identifier) --- to \(toSectionID)-@\(destinationIndexPath.row)")
rows = toRows
if destinationIndexPath.row >= toRows.count {
rows.append(fromItem)
} else {
rows.insert(fromItem, at: destinationIndexPath.row)
}
self.rowsBySectionID[toSectionID] = rows
let sectionIDs = (fromSectionID == toSectionID) ? [fromSectionID] : [fromSectionID, toSectionID]
var changed: [String: [T]] = Dictionary()
for sectionID in sectionIDs {
changed[sectionID] = self.rowsBySectionID[sectionID]
}
didChangeSectionIDsFunc(changed)
}
func indexPath(forSectionID inSectionID: String, rowItem inRowItem: T) -> IndexPath? {
guard let sectionIndex = sectionIndex(forSectionID: inSectionID) else {
return nil
}
guard let rows: [T] = self.rowsBySectionID[inSectionID] else {
return nil
}
guard let rowIndex = rows.firstIndex(of: inRowItem) else {
return nil
}
return IndexPath(row: rowIndex, section: sectionIndex)
}
func sectionIndex(forSectionID sectionID: String) -> Int? {
guard self.sectionIDsInternal.contains(sectionID) else {
return nil
}
return self.sectionIDsInternal.firstIndex(of: sectionID)
}
func locationWithOptionalItem(forIndexPath indexPath: IndexPath) -> LocationWithOptionalItem<T>? {
guard let (sectionID, rows) = self.sectionIDAndRows(forSectionIndex: indexPath.section) else {
print("sectionID/row not found!")
return nil
}
let item = rows.optionalElement(index: indexPath.row)
let location = LocationWithOptionalItem(sectionID: sectionID, item: item)
return location
}
// MARK: - private
fileprivate struct Callbacks {
let beginUpdatesFunc: (() -> Void)
let endUpdatesFunc: (() -> Void)
let deleteRowsAtIndexPathsFunc: (([IndexPath]) -> Void)
let insertRowsAtIndexPathsFunc: (([IndexPath]) -> Void)
let reloadRowsAtIndexPathsFunc: (([IndexPath]) -> Void)
}
// swiftlint:disable function_parameter_count
fileprivate func private_update(existingRows: [T], rowsToUpdate: [T], callbacks: Callbacks, sectionIndex: Int, sectionID: String, doNotCopy: Bool) -> (() -> Void) {
var newRows: [T] = existingRows
let newIdentifiers = rowsToUpdate.map { $0.identifier }
let existingIdentifiers = existingRows.map { $0.identifier }
let diffs = diffBetweenArrays(arrayA: existingIdentifiers, arrayB: newIdentifiers)
callbacks.beginUpdatesFunc()
var rowIndex = 0
var deleteRowIndex = 0
var indexPathsToUpdate: [IndexPath] = []
for diff in diffs {
switch diff.operation {
case .delete:
for _ in diff.array {
newRows.remove(at: rowIndex)
let indexPath = IndexPath(row: deleteRowIndex, section: sectionIndex)
callbacks.deleteRowsAtIndexPathsFunc([indexPath])
deleteRowIndex += 1
}
case .insert:
for rowID in diff.array {
// find index of new row
let rowIDIndex = rowsToUpdate.firstIndex(where: { rowID == $0.identifier })
if let actualIndex = rowIDIndex {
let newRow = rowsToUpdate[actualIndex]
newRows.insert(newRow, at: rowIndex)
let indexPath = [IndexPath(row: rowIndex, section: sectionIndex)]
callbacks.insertRowsAtIndexPathsFunc(indexPath)
rowIndex += 1
} else {
print("index not found for rowID '\(rowID)'")
}
}
case .equal:
if !doNotCopy {
for rowID in diff.array {
let sourceRowIDIndex = rowsToUpdate.firstIndex(where: { rowID == $0.identifier })
let destinationRowIDIndex = newRows.firstIndex(where: { rowID == $0.identifier })
if let sourceItem = rowsToUpdate.optionalElement(index: sourceRowIDIndex), let destinationIndex = destinationRowIDIndex {
if let destinationItem = newRows.optionalElement(index: destinationIndex), sourceItem != destinationItem {
indexPathsToUpdate.append(contentsOf: [IndexPath(row: destinationIndex, section: sectionIndex)])
}
newRows.insert(sourceItem, at: destinationIndex)
newRows.remove(at: destinationIndex+1)
} else {
print("at least one of the indeces not found for rowID '\(rowID)'")
}
}
}
rowIndex += diff.array.count
deleteRowIndex += diff.array.count
}
}
self.rowsBySectionID[sectionID] = newRows
assert(newRows == rowsToUpdate, "must be equal")
callbacks.endUpdatesFunc()
return {
print("update! \(indexPathsToUpdate)")
callbacks.reloadRowsAtIndexPathsFunc(indexPathsToUpdate)
}
}
// swiftlint:enable function_parameter_count
// MARK: - handling errors
func reportWarningAccordingToLevel(message inMessage: String) {
switch self.reportingLevel {
// a warning will still trigger an assertion.
case .preCondition:
preconditionFailure("ERROR: \(inMessage)")
case .assert:
assertionFailure("WARNING: \(inMessage)")
case .print, .verbose:
print("WARNING: \(inMessage)")
case .silent:
// nothing to do here
break
}
}
func fail(message inMessage: String) {
// when there's a fail block, we fail into that block otherwise
// we fail according to the reporting level
if let failBlock = self.fail {
failBlock(inMessage)
return
}
preconditionFailure("FATAL ERROR: \(inMessage)")
}
func warn(message inMessage: String) {
// when there's a fail block, we fail into that block otherwise
// we fail according to the reporting level
if let warnBlock = self.warn {
warnBlock(inMessage)
return
}
self.reportWarningAccordingToLevel(message: inMessage)
}
func logWhenVerbose( message: @autoclosure() -> String) {
if self.reportingLevel == .verbose {
print(message())
}
}
}
|
bsd-2-clause
|
ea4ed90e76da407754d7e5a4373c0ccb
| 38.283753 | 189 | 0.614901 | 5.046149 | false | false | false | false |
svenbacia/TraktKit
|
TraktKit/Sources/Request/Method.swift
|
1
|
350
|
//
// Method.swift
// TraktKit
//
// Created by Sven Bacia on 06.05.17.
// Copyright © 2017 Sven Bacia. All rights reserved.
//
import Foundation
enum Method: String {
case get = "GET"
case post = "POST"
case delete = "DELETE"
case update = "UPDATE"
public var allowsHttpBody: Bool {
return self == .post
}
}
|
mit
|
bbc793d608a8c7c55f1982bf15fd6168
| 15.619048 | 53 | 0.604585 | 3.455446 | false | false | false | false |
openbuild-sheffield/jolt
|
Sources/RouteAuth/route.RoleDelete.swift
|
1
|
3208
|
import Foundation
import PerfectLib
import PerfectHTTP
import OpenbuildExtensionCore
import OpenbuildExtensionPerfect
import OpenbuildMysql
import OpenbuildRepository
import OpenbuildRouteRegistry
import OpenbuildSingleton
public class RequestRoleDelete: OpenbuildExtensionPerfect.RequestProtocol {
public var method: String
public var uri: String
public var description: String = "Delete a role by id."
public var validation: OpenbuildExtensionPerfect.RequestValidation
public init(method: String, uri: String){
self.method = method
self.uri = uri
self.validation = OpenbuildExtensionPerfect.RequestValidation()
self.validation.addValidators(validators: [
ValidateTokenRoles,
ValidateUriRoleId
])
}
}
public let handlerRouteRoleDelete = { (request: HTTPRequest, response: HTTPResponse) in
guard let handlerResponse = RouteRegistry.getHandlerResponse(
uri: request.path.lowercased(),
method: request.method,
response: response
) else {
return
}
do {
var repository = try RepositoryRole()
guard let model = try repository.getById(
id: request.validatedRequestData?.validated["role_id"] as! Int
) else {
handlerResponse.complete(
status: 404,
model: ResponseModel404(uri: request.uri, method: request.method.description)
)
return
}
let deletedRole = repository.delete(
model: model
)
if deletedRole.errors.isEmpty {
handlerResponse.complete(
status: 200,
model: ModelRole200Delete(deleted: deletedRole)
)
} else {
//422 Unprocessable Entity
handlerResponse.complete(
status: 422,
model: ResponseModel422(
validation: request.validatedRequestData!,
messages: [
"deleted": false,
"errors": deletedRole.errors,
"entity": deletedRole
]
)
)
}
} catch {
print(error)
handlerResponse.complete(
status: 500,
model: ResponseModel500Messages(messages: [
"message": "Failed to generate a successful response."
])
)
}
}
public class RouteRoleDelete: OpenbuildRouteRegistry.FactoryRoute {
override public func route() -> NamedRoute? {
let handlerResponse = ResponseDefined()
handlerResponse.register(status: 200, model: "RouteAuth.ModelRole200Delete")
handlerResponse.register(status: 403)
handlerResponse.register(status: 404)
handlerResponse.register(status: 422)
handlerResponse.register(status: 500)
return NamedRoute(
handlerRequest: RequestRoleDelete(
method: "delete",
uri: "/api/roles/{role_id}"
),
handlerResponse: handlerResponse,
handlerRoute: handlerRouteRoleDelete
)
}
}
|
gpl-2.0
|
6dd6a92d7df3199f83fc733b5c79a2e6
| 24.672 | 93 | 0.59601 | 5.293729 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/PeerMediaTouchBar.swift
|
1
|
7336
|
//
// PeerMediaTouchBar.swift
// Telegram
//
// Created by Mikhail Filimonov on 04/10/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
@available(OSX 10.12.2, *)
private func peerMediaTouchBarItems(presentation: ChatPresentationInterfaceState) -> [NSTouchBarItem.Identifier] {
var items: [NSTouchBarItem.Identifier] = []
items.append(.flexibleSpace)
if presentation.selectionState != nil {
items.append(.forward)
items.append(.delete)
} else {
items.append(.segmentMedias)
}
items.append(.flexibleSpace)
return items
}
@available(OSX 10.12.2, *)
private extension NSTouchBarItem.Identifier {
static let segmentMedias = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.sharedMedia.segment")
static let forward = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.sharedMedia.forward")
static let delete = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.sharedMedia.delete")
}
@available(OSX 10.12.2, *)
class PeerMediaTouchBar: NSTouchBar, NSTouchBarDelegate, Notifable {
private let modeDisposable = MetaDisposable()
private let chatInteraction: ChatInteraction
private let toggleMode: (PeerMediaCollectionMode) -> Void
private var currentMode: PeerMediaCollectionMode = .photoOrVideo
init(chatInteraction: ChatInteraction, currentMode: Signal<PeerMediaCollectionMode?, NoError>, toggleMode: @escaping(PeerMediaCollectionMode) -> Void) {
self.chatInteraction = chatInteraction
self.toggleMode = toggleMode
super.init()
self.delegate = self
chatInteraction.add(observer: self)
self.defaultItemIdentifiers = peerMediaTouchBarItems(presentation: chatInteraction.presentation)
modeDisposable.set(currentMode.start(next: { [weak self] mode in
if let mode = mode {
let view = ((self?.item(forIdentifier: .segmentMedias) as? NSCustomTouchBarItem)?.view as? NSSegmentedControl)
let selected = Int(mode.rawValue + 1)
if selected > 0 {
view?.setSelected(true, forSegment: Int(mode.rawValue + 1))
self?.currentMode = mode
}
}
}))
}
private func updateUserInterface() {
for identifier in itemIdentifiers {
switch identifier {
case .forward:
let button = (item(forIdentifier: identifier) as? NSCustomTouchBarItem)?.view as? NSButton
button?.bezelColor = chatInteraction.presentation.canInvokeBasicActions.forward ? theme.colors.accent : nil
button?.isEnabled = chatInteraction.presentation.canInvokeBasicActions.forward
case .delete:
let button = (item(forIdentifier: identifier) as? NSCustomTouchBarItem)?.view as? NSButton
button?.bezelColor = chatInteraction.presentation.canInvokeBasicActions.delete ? theme.colors.redUI : nil
button?.isEnabled = chatInteraction.presentation.canInvokeBasicActions.delete
case .segmentMedias:
let view = ((item(forIdentifier: identifier) as? NSCustomTouchBarItem)?.view as? NSSegmentedControl)
view?.setSelected(true, forSegment: Int(self.currentMode.rawValue))
default:
break
}
}
}
deinit {
chatInteraction.remove(observer: self)
modeDisposable.dispose()
}
func isEqual(to other: Notifable) -> Bool {
return false
}
func notify(with value: Any, oldValue: Any, animated: Bool) {
if let value = value as? ChatPresentationInterfaceState {
self.defaultItemIdentifiers = peerMediaTouchBarItems(presentation: value)
updateUserInterface()
}
}
@objc private func segmentMediasAction(_ sender: Any?) {
if let sender = sender as? NSSegmentedControl {
switch sender.selectedSegment {
case 0:
toggleMode(.photoOrVideo)
case 1:
toggleMode(.file)
case 2:
toggleMode(.webpage)
case 3:
toggleMode(.music)
case 4:
toggleMode(.voice)
default:
break
}
}
}
@objc private func forwardMessages() {
chatInteraction.forwardSelectedMessages()
}
@objc private func deleteMessages() {
chatInteraction.deleteSelectedMessages()
}
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
switch identifier {
case .segmentMedias:
let item = NSCustomTouchBarItem(identifier: identifier)
let segment = NSSegmentedControl()
segment.segmentStyle = .automatic
segment.segmentCount = 5
segment.setLabel(strings().peerMediaMedia, forSegment: 0)
segment.setLabel(strings().peerMediaFiles, forSegment: 1)
segment.setLabel(strings().peerMediaLinks, forSegment: 2)
segment.setLabel(strings().peerMediaAudio, forSegment: 3)
segment.setLabel(strings().peerMediaVoice, forSegment: 4)
segment.setWidth(93, forSegment: 0)
segment.setWidth(93, forSegment: 1)
segment.setWidth(93, forSegment: 2)
segment.setWidth(93, forSegment: 3)
segment.setWidth(93, forSegment: 4)
segment.trackingMode = .selectOne
segment.target = self
segment.action = #selector(segmentMediasAction(_:))
item.view = segment
return item
case .forward:
let item = NSCustomTouchBarItem(identifier: identifier)
let icon = NSImage(named: NSImage.Name("Icon_TouchBar_MessagesForward"))!
let button = NSButton(title: strings().messageActionsPanelForward, image: icon, target: self, action: #selector(forwardMessages))
button.addWidthConstraint(size: 160)
button.bezelColor = theme.colors.accent
button.imageHugsTitle = true
button.isEnabled = chatInteraction.presentation.canInvokeBasicActions.forward
item.view = button
item.customizationLabel = button.title
return item
case .delete:
let item = NSCustomTouchBarItem(identifier: identifier)
let icon = NSImage(named: NSImage.Name("Icon_TouchBar_MessagesDelete"))!
let button = NSButton(title: strings().messageActionsPanelDelete, image: icon, target: self, action: #selector(deleteMessages))
button.addWidthConstraint(size: 160)
button.bezelColor = theme.colors.redUI
button.imageHugsTitle = true
button.isEnabled = chatInteraction.presentation.canInvokeBasicActions.delete
item.view = button
item.customizationLabel = button.title
return item
default:
return nil
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-2.0
|
1a0b483c146613bc0fe9ea00415511f8
| 39.524862 | 156 | 0.635174 | 5.104384 | false | false | false | false |
mihaicris/digi-cloud
|
Digi Cloud/Managers/Cache.swift
|
1
|
1424
|
//
// CacheStorage.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 19/01/17.
// Copyright © 2017 Mihai Cristescu. All rights reserved.
//
import Foundation
import UIKit.UIImage
final class Cache {
func load(type: CacheType, key: String) -> Data? {
var url = FileManager.documentsDir()
switch type {
case .file:
url = url.appendingPathComponent(CacheFolders.Files)
case .profile:
url = url.appendingPathComponent(CacheFolders.Profiles)
}
url = url.appendingPathComponent(key)
return try? Data(contentsOf: url)
}
func save(type: CacheType, data: Data, for key: String) {
var url = FileManager.documentsDir()
switch type {
case .file:
url = url.appendingPathComponent(CacheFolders.Files)
case .profile:
url = url.appendingPathComponent(CacheFolders.Profiles)
}
url = url.appendingPathComponent(key)
try? data.write(to: url)
}
func clear(type: CacheType, key: String) {
var url = FileManager.documentsDir()
switch type {
case .file:
url = url.appendingPathComponent(CacheFolders.Files)
case .profile:
url = url.appendingPathComponent(CacheFolders.Profiles)
}
url = url.appendingPathComponent(key)
try? FileManager.default.removeItem(at: url)
}
}
|
mit
|
b54f22207306dfbe4cb5353ba18d38ba
| 28.040816 | 67 | 0.619115 | 4.405573 | false | false | false | false |
DungntVccorp/Game
|
P/Sources/P/SynchronizedArray.swift
|
1
|
2243
|
//
// SynchronizedArray.swift
// P
//
// Created by Nguyen Dung on 4/19/17.
//
//
import Foundation
public class SynchronizedArray<T> {
private var array: Array<T> = Array<T>()
private let accessQueue = DispatchQueue(label: "SynchronizedArrayAccess", attributes: .concurrent)
public func append(newElement: T) {
self.accessQueue.async(flags:.barrier) {
self.array.append(newElement)
}
}
public func removeAtIndex(index: Int) {
self.accessQueue.async(flags:.barrier) {
self.array.remove(at: index)
}
}
public func removeObjectsInArray(beginIndex : Int , endIndex: Int) {
self.accessQueue.async(flags:.barrier) {
self.array.removeSubrange(beginIndex...endIndex)
}
}
public func removeAllObject() {
self.accessQueue.async(flags:.barrier) {
self.array.removeAll()
}
}
public var count: Int {
var count = 0
self.accessQueue.sync {
count = self.array.count
}
return count
}
public func first() -> T? {
var element: T?
self.accessQueue.sync {
if !self.array.isEmpty {
element = self.array[0]
}
}
return element
}
public func last() -> T? {
var element: T?
self.accessQueue.sync {
if !self.array.isEmpty {
element = self.array.last!
}
}
return element
}
public func allObject() -> [T]? {
var element: [T]?
self.accessQueue.sync {
if !self.array.isEmpty {
element = self.array
}
}
return element
}
public subscript(index: Int) -> T {
set {
self.accessQueue.async(flags:.barrier) {
self.array[index] = newValue
}
}
get {
var element: T!
self.accessQueue.sync {
element = self.array[index]
}
return element
}
}
}
|
mit
|
361dfa469ef8ee88dd29ad57b874fdc1
| 20.990196 | 102 | 0.483281 | 4.682672 | false | false | false | false |
laant/mqtt_chat_swift
|
App/Utility.swift
|
1
|
3578
|
//
// Utility.swift
// App
//
// Created by Laan on 2016. 1. 19..
// Copyright © 2016년 Laan. All rights reserved.
//
import UIKit
class Utility {
// MARK : Screen Size
static func getScreenSize() -> CGSize {
let windowRect = UIScreen.mainScreen().bounds
return windowRect.size
}
// MARK : check exist image
static func getFilePath() -> String {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.AllDomainsMask, true)
let documentDirectory = paths[0]
return documentDirectory
}
static func isExistImageFile(imageUrl:String) -> (is_exist:Bool, full_path:String) {
let arr = imageUrl.componentsSeparatedByString("/")
var fileName:NSString = ""
if arr.count > 1 {
fileName = arr[arr.count - 2] + arr[arr.count - 1]
}
else {
fileName = arr[arr.count - 1]
}
let filePath = Utility.getFilePath()
let fileManager = NSFileManager.defaultManager()
let fullPath = filePath.stringByAppendingString(fileName as String)
let isExist = fileManager.fileExistsAtPath(fullPath)
return (is_exist:isExist, full_path:fullPath)
}
// MARK: 현재 화면에 존재하는 object들(arr)과 추가하려는 view와 겹치는지 여부(Bool) 리턴
static func checkIntersectsRect(view:UIView, arr:NSArray) -> Bool {
for compareView in arr {
if CGRectIntersectsRect(view.frame, compareView.frame) {
return true
}
}
return false
}
// MARK: block 내부를 delay 후 실행
static func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), block)
}
// MARK: 주어진 max값 내에서 임의의 수를 리턴(Int)
static func random(max: Int) -> Int {
return Int(arc4random_uniform(UInt32(max)))
}
// MARK: Alert
static func alert(text:String, obj:AnyObject) {
let alertController = UIAlertController(title: "", message: text, preferredStyle: UIAlertControllerStyle.Alert)
let cancel = UIAlertAction(title: "확인", style: UIAlertActionStyle.Cancel) { (action: UIAlertAction) -> Void in
obj.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(cancel)
obj.presentViewController(alertController, animated: true, completion: nil)
}
// MARK: NSUserDefault
static func saveStorage(key key:String, object:AnyObject) {
let userDefault = NSUserDefaults.standardUserDefaults()
userDefault.setObject(object, forKey: key)
userDefault.synchronize()
}
static func loadStorage(key:String) -> AnyObject {
let userDefault = NSUserDefaults.standardUserDefaults()
return userDefault.objectForKey(key)!
}
// static func applicationFirstAction() -> Bool {
// let userDefault = NSUserDefaults.standardUserDefaults()
// guard let data = userDefault.objectForKey(Constants.SETTING_INIT) else {
// userDefault.setObject(true, forKey: Constants.SETTING_INIT)
// return true
// }
//
// let rtn = data as! NSNumber
// return !rtn.boolValue
//
// }
}
|
mit
|
6ae40651c1169bab115fdafc64550cfc
| 31.839623 | 139 | 0.61965 | 4.462821 | false | false | false | false |
russbishop/swift
|
stdlib/public/core/Unicode.swift
|
1
|
45254
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value,
/// an indication that no more Unicode scalars are available, or an indication
/// of a decoding error.
///
/// - SeeAlso: `UnicodeCodec.decode(next:)`
public enum UnicodeDecodingResult : Equatable {
/// A decoded Unicode scalar value.
case scalarValue(UnicodeScalar)
/// An indication that no more Unicode scalars are available in the input.
case emptyInput
/// An indication of a decoding error.
case error
}
public func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
/// A Unicode encoding form that translates between Unicode scalar values and
/// form-specific code units.
///
/// The `UnicodeCodec` protocol declares methods that decode code unit
/// sequences into Unicode scalar values and encode Unicode scalar values
/// into code unit sequences. The standard library implements codecs for the
/// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and
/// `UTF32` types, respectively. Use the `UnicodeScalar` type to work with
/// decoded Unicode scalar values.
///
/// - SeeAlso: `UTF8`, `UTF16`, `UTF32`, `UnicodeScalar`
public protocol UnicodeCodec {
/// A type that can hold code unit values for this encoding.
associatedtype CodeUnit
/// Creates an instance of the codec.
init()
/// Starts or continues decoding a code unit sequence into Unicode scalar
/// values.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `UnicodeScalar` instances:
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter next: An iterator of code units to be decoded. `next` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
mutating func decode<I : IteratorProtocol>(
_ next: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code uses the `UTF8` codec to encode a
/// fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", sendingOutputTo: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
static func encode(
_ input: UnicodeScalar,
sendingOutputTo processCodeUnit: @noescape (CodeUnit) -> Void
)
/// Searches for the first occurrence of a `CodeUnit` that is equal to 0.
///
/// Is an equivalent of `strlen` for C-strings.
/// - Complexity: O(n)
static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int
}
/// A codec for translating between Unicode scalar values and UTF-8 code
/// units.
public struct UTF8 : UnicodeCodec {
// See Unicode 8.0.0, Ch 3.9, UTF-8.
// http://www.unicode.org/versions/Unicode8.0.0/ch03.pdf
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt8
/// Creates an instance of the UTF-8 codec.
public init() {}
/// Lookahead buffer used for UTF-8 decoding. New bytes are inserted at MSB,
/// and bytes are read at LSB. Note that we need to use a buffer, because
/// in case of invalid subsequences we sometimes don't know whether we should
/// consume a certain byte before looking at it.
internal var _decodeBuffer: UInt32 = 0
/// The number of bits in `_decodeBuffer` that are current filled.
internal var _bitsInBuffer: UInt8 = 0
/// Whether we have exhausted the iterator. Note that this doesn't mean
/// we are done decoding, as there might still be bytes left in the buffer.
internal var _didExhaustIterator: Bool = false
/// Starts or continues decoding a UTF-8 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `UnicodeScalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter next: An iterator of code units to be decoded. `next` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ next: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
refillBuffer: if !_didExhaustIterator {
// Bufferless ASCII fastpath.
if _fastPath(_bitsInBuffer == 0) {
if let codeUnit = next.next() {
if codeUnit & 0x80 == 0 {
return .scalarValue(UnicodeScalar(_unchecked: UInt32(codeUnit)))
}
// Non-ASCII, proceed to buffering mode.
_decodeBuffer = UInt32(codeUnit)
_bitsInBuffer = 8
} else {
_didExhaustIterator = true
return .emptyInput
}
} else if (_decodeBuffer & 0x80 == 0) {
// ASCII in buffer. We don't refill the buffer so we can return
// to bufferless mode once we've exhausted it.
break refillBuffer
}
// Buffering mode.
// Fill buffer back to 4 bytes (or as many as are left in the iterator).
_sanityCheck(_bitsInBuffer < 32)
repeat {
if let codeUnit = next.next() {
// We use & 0x1f to make the compiler omit a bounds check branch.
_decodeBuffer |= (UInt32(codeUnit) << UInt32(_bitsInBuffer & 0x1f))
_bitsInBuffer = _bitsInBuffer &+ 8
} else {
_didExhaustIterator = true
if _bitsInBuffer == 0 { return .emptyInput }
break // We still have some bytes left in our buffer.
}
} while _bitsInBuffer < 32
} else if _bitsInBuffer == 0 {
return .emptyInput
}
// Decode one unicode scalar.
// Note our empty bytes are always 0x00, which is required for this call.
let (result, length) = UTF8._decodeOne(_decodeBuffer)
// Consume the decoded bytes (or maximal subpart of ill-formed sequence).
let bitsConsumed = 8 &* length
_sanityCheck(1...4 ~= length && bitsConsumed <= _bitsInBuffer)
// Swift doesn't allow shifts greater than or equal to the type width.
// _decodeBuffer >>= UInt32(bitsConsumed) // >>= 32 crashes.
// Mask with 0x3f to let the compiler omit the '>= 64' bounds check.
_decodeBuffer = UInt32(truncatingBitPattern:
UInt64(_decodeBuffer) >> (UInt64(bitsConsumed) & 0x3f))
_bitsInBuffer = _bitsInBuffer &- bitsConsumed
if _fastPath(result != nil) {
return .scalarValue(UnicodeScalar(_unchecked: result!))
} else {
return .error // Ill-formed UTF-8 code unit sequence.
}
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ … … … CU0 ].
let value = buffer & 0xff
return (value, 1)
}
// Determine sequence length using high 5 bits of 1st byte. We use a
// look-up table to branch less. 1-byte sequences are handled above.
//
// case | pattern | description
// ----------------------------
// 00 | 110xx | 2-byte sequence
// 01 | 1110x | 3-byte sequence
// 10 | 11110 | 4-byte sequence
// 11 | other | invalid
//
// 11xxx 10xxx 01xxx 00xxx
let lut0: UInt32 = 0b1011_0000__1111_1111__1111_1111__1111_1111
let lut1: UInt32 = 0b1100_0000__1111_1111__1111_1111__1111_1111
let index = (buffer >> 3) & 0x1f
let bit0 = (lut0 >> index) & 1
let bit1 = (lut1 >> index) & 1
switch (bit1, bit0) {
case (0, 0): // 2-byte sequence, buffer: [ … … CU1 CU0 ].
// Require 10xx xxxx 110x xxxx.
if _slowPath(buffer & 0xc0e0 != 0x80c0) { return (nil, 1) }
// Disallow xxxx xxxx xxx0 000x (<= 7 bits case).
if _slowPath(buffer & 0x001e == 0x0000) { return (nil, 1) }
// Extract data bits.
let value = (buffer & 0x3f00) >> 8
| (buffer & 0x001f) << 6
return (value, 2)
case (0, 1): // 3-byte sequence, buffer: [ … CU2 CU1 CU0 ].
// Disallow xxxx xxxx xx0x xxxx xxxx 0000 (<= 11 bits case).
if _slowPath(buffer & 0x00200f == 0x000000) { return (nil, 1) }
// Disallow xxxx xxxx xx1x xxxx xxxx 1101 (surrogate code points).
if _slowPath(buffer & 0x00200f == 0x00200d) { return (nil, 1) }
// Require 10xx xxxx 10xx xxxx 1110 xxxx.
if _slowPath(buffer & 0xc0c0f0 != 0x8080e0) {
if buffer & 0x00c000 != 0x008000 { return (nil, 1) }
return (nil, 2) // All checks on CU0 & CU1 passed.
}
// Extract data bits.
let value = (buffer & 0x3f0000) >> 16
| (buffer & 0x003f00) >> 2
| (buffer & 0x00000f) << 12
return (value, 3)
case (1, 0): // 4-byte sequence, buffer: [ CU3 CU2 CU1 CU0 ].
// Disallow xxxx xxxx xxxx xxxx xx00 xxxx xxxx x000 (<= 16 bits case).
if _slowPath(buffer & 0x00003007 == 0x00000000) { return (nil, 1) }
// If xxxx xxxx xxxx xxxx xxxx xxxx xxxx x1xx.
if buffer & 0x00000004 == 0x00000004 {
// Require xxxx xxxx xxxx xxxx xx00 xxxx xxxx xx00 (<= 0x10FFFF).
if _slowPath(buffer & 0x00003003 != 0x00000000) { return (nil, 1) }
}
// Require 10xx xxxx 10xx xxxx 10xx xxxx 1111 0xxx.
if _slowPath(buffer & 0xc0c0c0f8 != 0x808080f0) {
if buffer & 0x0000c000 != 0x00008000 { return (nil, 1) }
// All other checks on CU0, CU1 & CU2 passed.
if buffer & 0x00c00000 != 0x00800000 { return (nil, 2) }
return (nil, 3)
}
// Extract data bits.
let value = (buffer & 0x3f000000) >> 24
| (buffer & 0x003f0000) >> 10
| (buffer & 0x00003f00) << 4
| (buffer & 0x00000007) << 18
return (value, 4)
default: // Invalid sequence (CU0 invalid).
return (nil, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code encodes a fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", sendingOutputTo: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
sendingOutputTo processCodeUnit: @noescape (CodeUnit) -> Void
) {
var c = UInt32(input)
var buf3 = UInt8(c & 0xFF)
if c >= UInt32(1<<7) {
c >>= 6
buf3 = (buf3 & 0x3F) | 0x80 // 10xxxxxx
var buf2 = UInt8(c & 0xFF)
if c < UInt32(1<<5) {
buf2 |= 0xC0 // 110xxxxx
}
else {
c >>= 6
buf2 = (buf2 & 0x3F) | 0x80 // 10xxxxxx
var buf1 = UInt8(c & 0xFF)
if c < UInt32(1<<4) {
buf1 |= 0xE0 // 1110xxxx
}
else {
c >>= 6
buf1 = (buf1 & 0x3F) | 0x80 // 10xxxxxx
processCodeUnit(UInt8(c | 0xF0)) // 11110xxx
}
processCodeUnit(buf1)
}
processCodeUnit(buf2)
}
processCodeUnit(buf3)
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// UTF-8 continuation byte.
///
/// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase
/// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8
/// representation: `0b11000011` (195) and `0b10101001` (169). The second
/// byte is a continuation byte.
///
/// let eAcute = "é"
/// for codePoint in eAcute.utf8 {
/// print(codePoint, UTF8.isContinuation(codePoint))
/// }
/// // Prints "195 false"
/// // Prints "169 true"
///
/// - Parameter byte: A UTF-8 code unit.
/// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`.
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
return Int(_swift_stdlib_strlen(UnsafePointer(input)))
}
}
/// A codec for translating between Unicode scalar values and UTF-16 code
/// units.
public struct UTF16 : UnicodeCodec {
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt16
/// Creates an instance of the UTF-16 codec.
public init() {}
/// A lookahead buffer for one UTF-16 code unit.
internal var _decodeLookahead: UInt32 = 0
/// Flags with layout: `0b0000_00xy`.
///
/// `y` is the EOF flag.
///
/// `x` is set when `_decodeLookahead` contains a code unit.
internal var _lookaheadFlags: UInt8 = 0
/// Starts or continues decoding a UTF-16 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string into an
/// array of `UnicodeScalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf16))
/// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]"
///
/// var codeUnitIterator = str.utf16.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf16Decoder = UTF16()
/// Decode: while true {
/// switch utf16Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter next: An iterator of code units to be decoded. `next` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
if _lookaheadFlags & 0b01 != 0 {
return .emptyInput
}
// Note: maximal subpart of ill-formed sequence for UTF-16 can only have
// length 1. Length 0 does not make sense. Neither does length 2 -- in
// that case the sequence is valid.
var unit0: UInt32
if _fastPath(_lookaheadFlags & 0b10 == 0) {
if let first = input.next() {
unit0 = UInt32(first)
} else {
// Set EOF flag.
_lookaheadFlags |= 0b01
return .emptyInput
}
} else {
// Fetch code unit from the lookahead buffer and note this fact in flags.
unit0 = _decodeLookahead
_lookaheadFlags &= 0b01
}
// A well-formed pair of surrogates looks like this:
// [1101 10ww wwxx xxxx] [1101 11xx xxxx xxxx]
if _fastPath((unit0 >> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- sequence of 1 code unit,
// decoding is trivial.
return .scalarValue(UnicodeScalar(unit0))
}
if _slowPath((unit0 >> 10) == 0b1101_11) {
// `unit0` is a low-surrogate. We have an ill-formed sequence.
return .error
}
// At this point we know that `unit0` is a high-surrogate.
var unit1: UInt32
if let second = input.next() {
unit1 = UInt32(second)
} else {
// EOF reached. Set EOF flag.
_lookaheadFlags |= 0b01
// We have seen a high-surrogate and EOF, so we have an ill-formed
// sequence.
return .error
}
if _fastPath((unit1 >> 10) == 0b1101_11) {
// `unit1` is a low-surrogate. We have a well-formed surrogate pair.
let result = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff))
return .scalarValue(UnicodeScalar(result))
}
// Otherwise, we have an ill-formed sequence. These are the possible
// cases:
//
// * `unit1` is a high-surrogate, so we have a pair of two high-surrogates.
//
// * `unit1` is not a surrogate. We have an ill-formed sequence:
// high-surrogate followed by a non-surrogate.
// Save the second code unit in the lookahead buffer.
_decodeLookahead = unit1
_lookaheadFlags |= 0b10
return .error
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@_versioned
internal mutating func _decodeOne<I : IteratorProtocol>(
_ input: inout I
) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires two code units for its UTF-16
/// representation. The following code encodes a fermata in UTF-16:
///
/// var codeUnits: [UTF16.CodeUnit] = []
/// UTF16.encode("𝄐", sendingOutputTo: { codeUnits.append($0) })
/// print(codeUnits)
/// // Prints "[55348, 56592]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
sendingOutputTo processCodeUnit: @noescape (CodeUnit) -> Void
) {
let scalarValue: UInt32 = UInt32(input)
if scalarValue <= UInt32(UInt16.max) {
processCodeUnit(UInt16(scalarValue))
}
else {
let lead_offset = UInt32(0xd800) - UInt32(0x10000 >> 10)
processCodeUnit(UInt16(lead_offset + (scalarValue >> 10)))
processCodeUnit(UInt16(0xdc00 + (scalarValue & 0x3ff)))
}
}
}
/// A codec for translating between Unicode scalar values and UTF-32 code
/// units.
public struct UTF32 : UnicodeCodec {
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt32
/// Creates an instance of the UTF-32 codec.
public init() {}
/// Starts or continues decoding a UTF-32 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string
/// into an array of `UnicodeScalar` instances. This is a demonstration
/// only---if you need the Unicode scalar representation of a string, use
/// its `unicodeScalars` view.
///
/// // UTF-32 representation of "✨Unicode✨"
/// let codeUnits: [UTF32.CodeUnit] =
/// [10024, 85, 110, 105, 99, 111, 100, 101, 10024]
///
/// var codeUnitIterator = codeUnits.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf32Decoder = UTF32()
/// Decode: while true {
/// switch utf32Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter next: An iterator of code units to be decoded. `next` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
return UTF32._decode(&input)
}
internal static func _decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard let x = input.next() else { return .emptyInput }
if _fastPath((x >> 11) != 0b1101_1 && x <= 0x10ffff) {
return .scalarValue(UnicodeScalar(x))
} else {
return .error
}
}
/// Encodes a Unicode scalar as a UTF-32 code unit by calling the given
/// closure.
///
/// For example, like every Unicode scalar, the musical fermata symbol ("𝄐")
/// can be represented in UTF-32 as a single code unit. The following code
/// encodes a fermata in UTF-32:
///
/// var codeUnit: UTF32.CodeUnit = 0
/// UTF32.encode("𝄐", sendingOutputTo: { codeUnit = $0 })
/// print(codeUnit)
/// // Prints "119056"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
sendingOutputTo processCodeUnit: @noescape (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
/// Translates the given input from one Unicode encoding to another by calling
/// the given closure.
///
/// The following example transcodes the UTF-8 representation of the string
/// `"Fermata 𝄐"` into UTF-32.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// var codeUnits: [UTF32.CodeUnit] = []
/// let sink = { codeUnits.append($0) }
/// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self,
/// stoppingOnError: false, sendingOutputTo: sink)
/// print(codeUnits)
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]"
///
/// The `sink` closure is called with each resulting UTF-32 code unit as the
/// function iterates over its input.
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will
/// be exhausted. Otherwise, iteration will stop if an encoding error is
/// detected.
/// - inputEncoding: The Unicode encoding of `input`.
/// - outputEncoding: The destination Unicode encoding.
/// - stopOnError: Pass `true` to stop translation when an encoding error is
/// detected in `input`. Otherwise, a Unicode replacement character
/// (`"\u{FFFD}"`) is inserted for each detected error.
/// - processCodeUnit: A closure that processes one `outputEncoding` code
/// unit at a time.
/// - Returns: `true` if the translation detected encoding errors in `input`;
/// otherwise, `false`.
public func transcode<Input, InputEncoding, OutputEncoding>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
sendingOutputTo processCodeUnit: @noescape (OutputEncoding.CodeUnit) -> Void
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var inputDecoder = inputEncoding.init()
var hadError = false
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
OutputEncoding.encode(us, sendingOutputTo: processCodeUnit)
case .emptyInput:
break loop
case .error:
hadError = true
if stopOnError {
break loop
}
OutputEncoding.encode("\u{fffd}", sendingOutputTo: processCodeUnit)
}
}
return hadError
}
/// Transcode UTF-16 to UTF-8, replacing ill-formed sequences with U+FFFD.
///
/// Returns the index of the first unhandled code unit and the UTF-8 data
/// that was encoded.
internal func _transcodeSomeUTF16AsUTF8<Input>(
_ input: Input, _ startIndex: Input.Index
) -> (Input.Index, _StringCore._UTF8Chunk)
where
Input : Collection,
Input.Iterator.Element == UInt16 {
typealias _UTF8Chunk = _StringCore._UTF8Chunk
let endIndex = input.endIndex
let utf8Max = sizeof(_UTF8Chunk.self)
var result: _UTF8Chunk = 0
var utf8Count = 0
var nextIndex = startIndex
while nextIndex != input.endIndex && utf8Count != utf8Max {
let u = UInt(input[nextIndex])
let shift = _UTF8Chunk(utf8Count * 8)
var utf16Length: Input.IndexDistance = 1
if _fastPath(u <= 0x7f) {
result |= _UTF8Chunk(u) << shift
utf8Count += 1
} else {
var scalarUtf8Length: Int
var r: UInt
if _fastPath((u >> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- well-formed sequence
// of 1 code unit, decoding is trivial.
if u < 0x800 {
r = 0b10__00_0000__110__0_0000
r |= u >> 6
r |= (u & 0b11_1111) << 8
scalarUtf8Length = 2
}
else {
r = 0b10__00_0000__10__00_0000__1110__0000
r |= u >> 12
r |= ((u >> 6) & 0b11_1111) << 8
r |= (u & 0b11_1111) << 16
scalarUtf8Length = 3
}
} else {
let unit0 = u
if _slowPath((unit0 >> 10) == 0b1101_11) {
// `unit0` is a low-surrogate. We have an ill-formed sequence.
// Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else if _slowPath(input.index(nextIndex, offsetBy: 1) == endIndex) {
// We have seen a high-surrogate and EOF, so we have an ill-formed
// sequence. Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else {
let unit1 = UInt(input[input.index(nextIndex, offsetBy: 1)])
if _fastPath((unit1 >> 10) == 0b1101_11) {
// `unit1` is a low-surrogate. We have a well-formed surrogate
// pair.
let v = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff))
r = 0b10__00_0000__10__00_0000__10__00_0000__1111_0__000
r |= v >> 18
r |= ((v >> 12) & 0b11_1111) << 8
r |= ((v >> 6) & 0b11_1111) << 16
r |= (v & 0b11_1111) << 24
scalarUtf8Length = 4
utf16Length = 2
} else {
// Otherwise, we have an ill-formed sequence. Replace it with
// U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
}
}
}
// Don't overrun the buffer
if utf8Count + scalarUtf8Length > utf8Max {
break
}
result |= numericCast(r) << shift
utf8Count += scalarUtf8Length
}
nextIndex = input.index(nextIndex, offsetBy: utf16Length)
}
// FIXME: Annoying check, courtesy of <rdar://problem/16740169>
if utf8Count < sizeofValue(result) {
result |= ~0 << numericCast(utf8Count * 8)
}
return (nextIndex, result)
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_sanityCheck(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(x)
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(utf16)
}
}
extension UTF16 {
/// Returns the number of code units required to encode the given Unicode
/// scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let anA: UnicodeScalar = "A"
/// print(anA.value)
/// // Prints "65"
/// print(UTF16.width(anA))
/// // Prints "1"
///
/// let anApple: UnicodeScalar = "🍎"
/// print(anApple.value)
/// // Prints "127822"
/// print(UTF16.width(anApple))
/// // Prints "2"
///
/// - Parameter x: A Unicode scalar value.
/// - Returns: The width of `x` when encoded in UTF-16, either `1` or `2`.
public static func width(_ x: UnicodeScalar) -> Int {
return x.value <= 0xFFFF ? 1 : 2
}
/// Returns the high-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: UnicodeScalar = "🍎"
/// print(UTF16.leadSurrogate(apple)
/// // Prints "55356"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The leading surrogate code unit of `x` when encoded in UTF-16.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.trailSurrogate(_:)`
public static func leadSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit((x.value - 0x1_0000) >> (10 as UInt32)) + 0xD800
}
/// Returns the low-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: UnicodeScalar = "🍎"
/// print(UTF16.trailSurrogate(apple)
/// // Prints "57166"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The trailing surrogate code unit of `x` when encoded in UTF-16.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func trailSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit(
(x.value - 0x1_0000) & (((1 as UInt32) << 10) - 1)
) + 0xDC00
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// high-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a lead surrogate. The `apple` string contains a single
/// emoji character made up of a surrogate pair when encoded in UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isLeadSurrogate(unit))
/// }
/// // Prints "true"
/// // Prints "false"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// low-surrogate code unit follows `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a high-surrogate code unit; otherwise,
/// `false`.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func isLeadSurrogate(_ x: CodeUnit) -> Bool {
return 0xD800...0xDBFF ~= x
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// low-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a trailing surrogate. The `apple` string contains a
/// single emoji character made up of a surrogate pair when encoded in
/// UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isTrailSurrogate(unit))
/// }
/// // Prints "false"
/// // Prints "true"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// high-surrogate code unit precedes `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a low-surrogate code unit; otherwise,
/// `false`.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func isTrailSurrogate(_ x: CodeUnit) -> Bool {
return 0xDC00...0xDFFF ~= x
}
public // @testable
static func _copy<T : _StringElement, U : _StringElement>(
source: UnsafeMutablePointer<T>,
destination: UnsafeMutablePointer<U>,
count: Int
) {
if strideof(T.self) == strideof(U.self) {
_memcpy(
dest: UnsafeMutablePointer(destination),
src: UnsafeMutablePointer(source),
size: UInt(count) * UInt(strideof(U.self)))
}
else {
for i in 0..<count {
let u16 = T._toUTF16CodeUnit((source + i).pointee)
(destination + i).pointee = U._fromUTF16CodeUnit(u16)
}
}
}
/// Returns the number of UTF-16 code units required for the given code unit
/// sequence when transcoded to UTF-16, and a Boolean value indicating
/// whether the sequence was found to contain only ASCII characters.
///
/// The following example finds the length of the UTF-16 encoding of the
/// string `"Fermata 𝄐"`, starting with its UTF-8 representation.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// let result = transcodedLength(of: bytes.makeIterator(),
/// decodedAs: UTF8.self,
/// repairingIllFormedSequences: false)
/// print(result)
/// // Prints "Optional((10, false))"
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `sourceEncoding`. If `repairingIllFormedSequences` is `true`, the
/// entire iterator will be exhausted. Otherwise, iteration will stop if
/// an ill-formed sequence is detected.
/// - sourceEncoding: The Unicode encoding of `input`.
/// - repairingIllFormedSequences: Pass `true` to measure the length of
/// `input` even when `input` contains ill-formed sequences. Each
/// ill-formed sequence is replaced with a Unicode replacement character
/// (`"\u{FFFD}"`) and is measured as such. Pass `false` to immediately
/// stop measuring `input` when an ill-formed sequence is encountered.
/// - Returns: A tuple containing the number of UTF-16 code units required to
/// encode `input` and a Boolean value that indicates whether the `input`
/// contained only ASCII characters. If `repairingIllFormedSequences` is
/// `false` and an ill-formed sequence is detected, this method returns
/// `nil`.
public static func transcodedLength<Input, Encoding>(
of input: Input,
decodedAs sourceEncoding: Encoding.Type,
repairingIllFormedSequences: Bool
) -> (count: Int, isASCII: Bool)?
where
Input : IteratorProtocol,
Encoding : UnicodeCodec,
Encoding.CodeUnit == Input.Element {
var input = input
var count = 0
var isAscii = true
var inputDecoder = Encoding()
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
if us.value > 0x7f {
isAscii = false
}
count += width(us)
case .emptyInput:
break loop
case .error:
if !repairingIllFormedSequences {
return nil
}
isAscii = false
count += width(UnicodeScalar(0xfffd))
}
}
return (count, isAscii)
}
}
// Unchecked init to avoid precondition branches in hot code paths where we
// already know the value is a valid unicode scalar.
extension UnicodeScalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
internal init(_unchecked value: UInt32) {
_sanityCheck(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_sanityCheck(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
extension UnicodeCodec where CodeUnit : UnsignedInteger {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
var length = 0
while input[length] != 0 {
length += 1
}
return length
}
}
extension UnicodeCodec {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
fatalError("_nullCodeUnitOffset(in:) implementation should be provided")
}
}
@available(*, unavailable, renamed: "UnicodeCodec")
public typealias UnicodeCodecType = UnicodeCodec
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:sendingOutputTo:)'")
public func transcode<Input, InputEncoding, OutputEncoding>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stopOnError: Bool
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
extension UTF16 {
@available(*, unavailable, message: "use 'transcodedLength(of:decodedAs:repairingIllFormedSequences:)'")
public static func measure<Encoding, Input>(
_: Encoding.Type, input: Input, repairIllFormedSequences: Bool
) -> (Int, Bool)?
where
Encoding : UnicodeCodec,
Input : IteratorProtocol,
Encoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
}
|
apache-2.0
|
b02c58b991d90cd450e80f15b9e5cdff
| 36.333058 | 106 | 0.623226 | 3.864574 | false | false | false | false |
JovannyEspinal/Checklists-iOS
|
Checklists/ChecklistTableViewController.swift
|
1
|
4581
|
//
// ChecklistTableViewController.swift
// Checklists
//
// Created by Jovanny Espinal on 12/20/15.
// Copyright © 2015 Jovanny Espinal. All rights reserved.
//
import UIKit
class ChecklistTableViewController: UITableViewController, ItemDetailViewControllerDelegate {
var checklist: Checklist!
override func viewDidLoad() {
super.viewDidLoad()
title = checklist.name
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return checklist.items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ChecklistItem", forIndexPath: indexPath)
let item = checklist.items[indexPath.row]
configureTextForCell(cell, withChecklistItem: item)
configureCheckmarkForCell(cell, withChecklistItem: item)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath){
let item = checklist.items[indexPath.row]
item.toggleChecked()
configureCheckmarkForCell(cell, withChecklistItem: item)
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
checklist.items.removeAtIndex(indexPath.row)
let indexPaths = [indexPath]
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
// MARK: - Cell configuration functions
func configureCheckmarkForCell(cell: UITableViewCell, withChecklistItem item: ChecklistItem) {
let label = cell.viewWithTag(1001) as! UILabel
label.textColor = view.tintColor
if item.checked {
label.text = "√"
} else {
label.text = ""
}
}
func configureTextForCell(cell: UITableViewCell, withChecklistItem item: ChecklistItem) {
let label = cell.viewWithTag(1000) as! UILabel
label.text = item.text
}
// MARK: - ItemDetailViewControllerDelegate functions
func itemDetailViewControllerDidCancel(controller: ItemDetailViewController) {
dismissViewControllerAnimated(true, completion: nil)
}
func itemDetailViewController(controller: ItemDetailViewController, didFinishEditingItem item:ChecklistItem){
if let index = checklist.items.indexOf(item) {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
configureTextForCell(cell, withChecklistItem: item)
}
}
dismissViewControllerAnimated(true, completion: nil)
}
func itemDetailViewController(controller: ItemDetailViewController, didFinishAddingItem item: ChecklistItem) {
let newRowIndex = checklist.items.count
checklist.items.append(item)
let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0)
let indexPaths = [indexPath]
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Navigation functions
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "AddItem" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! ItemDetailViewController
controller.delegate = self
} else if segue.identifier == "EditItem" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! ItemDetailViewController
controller.delegate = self
if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell) {
controller.itemToEdit = checklist.items[indexPath.row]
}
}
}
}
|
mit
|
de1aa8707024292bce46835135b2d3fb
| 34.496124 | 157 | 0.663172 | 6.015769 | false | true | false | false |
yonadev/yona-app-ios
|
Yona/Yona/Others/SMSValidPasscodeLogin/Pin/ConfirmPinViewController.swift
|
1
|
5388
|
//
// ConfirmPinViewController.swift
// Yona
//
// Created by Chandan on 04/04/16.
// Copyright © 2016 Yona. All rights reserved.
//
import UIKit
final class ConfirmPinViewController: LoginSignupValidationMasterView {
var pin: String?
var newUser: Users?
override func viewDidLoad() {
super.viewDidLoad()
setupPincodeScreenDifferentlyWithText(NSLocalizedString("change-pin", comment: ""), headerTitleLabelText: NSLocalizedString("settings_confirm_new_pin", comment: ""), errorLabelText: nil, infoLabelText: NSLocalizedString("settings_confirm_new_pin_message", comment: ""), avtarImageName: R.image.icnAccountCreated())
self.navigationItem.setLeftBarButton(nil, animated: false)
self.navigationItem.setHidesBackButton(true, animated: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let tracker = GAI.sharedInstance().defaultTracker
tracker?.set(kGAIScreenName, value: "ConfirmPinViewController")
let builder = GAIDictionaryBuilder.createScreenView()
tracker?.send(builder?.build() as? [AnyHashable: Any])
self.codeInputView.delegate = self
self.codeInputView.secure = true
codeView.addSubview(self.codeInputView)
//keyboard functions
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)) , name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) }
override func viewDidAppear(_ animated: Bool) {
codeInputView.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override func viewDidLayoutSubviews()
{
var scrollViewInsets = UIEdgeInsets.zero
scrollViewInsets.top = 0
scrollView.contentInset = scrollViewInsets
}
// Go Back To Previous VC
@IBAction func back(_ sender: AnyObject) {
weak var tracker = GAI.sharedInstance().defaultTracker
tracker!.send(GAIDictionaryBuilder.createEvent(withCategory: "ui_action", action: "ConfirmPasscodeBack", label: "Back from confirm passcode pressed", value: nil).build() as? [AnyHashable: Any])
self.navigationController?.popViewController(animated: true)
}
}
extension ConfirmPinViewController: CodeInputViewDelegate {
//post open app event after successfully signup
func postOpenAppEvent() {
if let savedUser = UserDefaults.standard.object(forKey: YonaConstants.nsUserDefaultsKeys.savedUser) {
let user = UserRequestManager.sharedInstance.convertToDictionary(text: savedUser as! String)
self.newUser = Users.init(userData: user! as BodyDataDictionary)
UserRequestManager.sharedInstance.postOpenAppEvent(self.newUser!, onCompletion: { (success, message, code) in
if !success{
self.displayAlertMessage(code!, alertDescription: message!)
}
})
}
}
func codeInputView(_ codeInputView: CodeInputView, didFinishWithCode code: String) {
if (pin == code) {
codeInputView.resignFirstResponder()
KeychainManager.sharedInstance.savePINCode(code)
UserDefaults.standard.set(true, forKey: YonaConstants.nsUserDefaultsKeys.isLoggedIn)
postOpenAppEvent()
//Update flag
setViewControllerToDisplay(ViewControllerTypeString.login, key: YonaConstants.nsUserDefaultsKeys.screenToDisplay)
self.navigationController?.dismiss(animated: true, completion: nil)
} else {
codeInputView.clear()
navigationController?.popViewController(animated: true)
}
}
}
private extension Selector {
static let back = #selector(ConfirmPinViewController.back(_:))
}
extension ConfirmPinViewController: KeyboardProtocol {
@objc func keyboardWasShown (_ notification: Notification) {
if let activeField = self.codeView, let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect = self.view.bounds
aRect.origin.x = 64
aRect.size.height -= 64
aRect.size.height -= keyboardSize.size.height
if (!aRect.contains(activeField.frame.origin)) {
var frameToScrollTo = activeField.frame
frameToScrollTo.size.height += 30
self.scrollView.scrollRectToVisible(frameToScrollTo, animated: true)
}
}
}
@objc func keyboardWillBeHidden(_ notification: Notification) {
let contentInsets = UIEdgeInsets.zero
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
}
}
|
mpl-2.0
|
a3d836a3a48eabc20c40c86e99246634
| 40.122137 | 322 | 0.674958 | 5.40321 | false | false | false | false |
pryomoax/SwiftAbstractLogger
|
SwiftAbstractLogger/Logger.swift
|
1
|
6062
|
//
// Logger.swift
// SwiftAbstractLogger
//
// Created by Paul Bates on 2/4/17.
// Copyright © 2017 Paul Bates. All rights reserved.
//
import Foundation
//
// MARK - Protocols
//
/// To be implemented by a logger to attach to a `Logger`
public protocol LoggerDelegate {
/// Core logger function all logging is routed through
///
/// - Parameter:
/// - level: Log level to log at
/// - category: Optional category to log at for filter
/// - message: Message to log
func log(level: Logger.LogLevel, category: String?, message: String)
}
//
// MARK - Classes
//
/// Logger central coordinator. By default the logger does nothing until a logger implementing `LoggerDelegate` is associated by
/// calling `attach()`.
///
/// Levels for the logger can be adjusted, set `defaultLevel`.
final public class Logger {
public static var defaultLevel: LogLevel = .info
/// Logging levels
public enum LogLevel: Int {
/// Critical, use only in exception cases
case critial = 0
/// Error, use for recoverable errors
case error = 1
/// Warning, use for warning conditions
case warning = 2
/// Information, use for all default logging
case info = 3
/// Verbose, use for verbose logs
case verbose = 4
/// Debug, use for very verbose, debug-only logs
case debug = 5
}
/// Logs to the logger attached to the `Logger` instance
///
/// - Parameter:
/// - level: Log level to log at (below `defaulLevel` will not be logged)
/// - category: Optional category to log at or filter by
/// - message: Message to log
public class func log(level: LogLevel, category: String? = nil, message: String) {
var categoryLevel: LogLevel?
if category != nil {
categoryLevel = categoryLevels[category!]
}
if categoryLevel == nil {
categoryLevel = self.defaultLevel
}
if level.rawValue <= categoryLevel!.rawValue {
if categoryLevel == nil || level.rawValue <= categoryLevel!.rawValue {
// Ensure sync to main queue for logging
DispatchQueue.main.async {
for delegate in loggers {
delegate.log(level: level, category: category, message: message)
}
}
}
}
}
/// Attaches a logger implementation to the logger.
///
/// - Parameters:
/// - logger: Logger implementation to attach to the logger
public static func attach(_ logger: LoggerDelegate) {
self.loggers.append(logger)
}
/// Configures logging level for a given category.
///
/// The level set for the cateogry will override `defaultLevel`.
///
/// - Paramters:
/// - category: Category to configure
/// - level: Threshold level to log against
public static func configureLevel(category: String, level: Logger.LogLevel) {
self.categoryLevels[category] = level
}
//
// MARK: Private implementation
//
private static var loggers: [LoggerDelegate] = []
private static var categoryLevels: [String: Logger.LogLevel] = [:]
}
//
// MARK: -
//
// Default logging level string conversion
extension Logger.LogLevel: CustomStringConvertible {
public var description: String {
switch self {
case .critial:
return "Critical"
case .error:
return "Error"
case .warning:
return "Warning"
case .info:
return "Info"
case .verbose:
return "Verbose"
case .debug:
return "Debug"
}
}
}
//
// MARK: - Convenince functions
//
/// Convenince logging function
public func log(level: Logger.LogLevel = .info, category: String? = nil, _ message: String) {
Logger.log(level: level, category: category, message: message)
}
/// Convenince critical level logging function.
///
/// Use only in exception cases
///
/// - Parameters:
/// - category: Optional category to log at, or filter by
/// - message: Message to log
public func logCritical(category: String? = nil, _ message: String) {
Logger.log(level: .error, category: category, message: message)
}
/// Convenince error level logging function
///
/// Use for recoverable errors
///
/// - Parameters:
/// - category: Optional category to log at, or filter by
/// - message: Message to log
public func logError(category: String? = nil, _ message: String) {
Logger.log(level: .error, category: category, message: message)
}
/// Convenince warning level logging function
///
/// Use for warning conditions
///
/// - Parameters:
/// - category: Optional category to log at, or filter by
/// - message: Message to log
public func logWarning(category: String? = nil, _ message: String) {
Logger.log(level: .warning, category: category, message: message)
}
/// Convenince info level logging function
///
/// Use for all default logging
///
/// - Parameters:
/// - category: Optional category to log at, or filter by
/// - message: Message to log
public func logInfo(category: String? = nil, _ message: String) {
Logger.log(level: .info, category: category, message: message)
}
/// Convenince verbose level logging function
///
/// Use for verbose logs
///
/// - Parameters:
/// - category: Optional category to log at, or filter by
/// - message: Message to log
public func logVerbose(category: String? = nil, _ message: String) {
Logger.log(level: .verbose, category: category, message: message)
}
/// Convenince debug level logging function
///
/// Use for very verbose, debug-only logs
///
/// - Parameters:
/// - category: Optional category to log at, or filter by
/// - message: Message to log
public func logDebug(category: String? = nil, _ message: String) {
Logger.log(level: .debug, category: category, message: message)
}
|
mit
|
4f002780568a931783d5f13ca5a1fe98
| 28.565854 | 128 | 0.61838 | 4.259311 | false | false | false | false |
lioonline/v2ex-lio
|
V2ex/V2ex/NetworkEngine.swift
|
1
|
2113
|
//
// NetworkEngine.swift
// V2ex
//
// Created by Lee on 16/4/13.
// Copyright © 2016年 lio. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class NetworkEngine: NSObject {
class func getDataFromServerWithURLStringAndParameter(
url:String,
parameter:[String: AnyObject]? = nil,
complete:NSArray->(),
errorMsg:ErrorType->()
)->(){
Alamofire.request(.GET, url, parameters: parameter)
.responseJSON { request, response, result in
switch result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
let dic = JSON
print("dic :\(dic.self)")
complete(dic as! NSArray)
case .Failure(let data, let error):
print("Request failed with error: \(error)")
errorMsg(error)
if let data = data {
print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
}
}
}
}
class func getDataFromServerWithURLString(
url:String,
complete:AnyObject->(),
errorMsg:ErrorType->()
)->(){
Alamofire.request(.GET, url, parameters: nil).responseJSON { (request, response, result) in
switch result {
case .Success(let JSON):
let dic = JSON
complete(dic)
case .Failure(let data, let error):
print("Request failed with error: \(error)")
errorMsg(error)
if let data = data {
print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
}
}
}
}
}
|
mit
|
bbc18d6010b36c75ce6ba7fa54241cfa
| 27.513514 | 104 | 0.440758 | 5.687332 | false | false | false | false |
groue/GRDBObjc
|
Sources/GRDBObjcCore/FMResultSet.swift
|
1
|
7153
|
import GRDB
import SQLite3
@objc public class FMResultSet : NSObject {
private enum State {
case initialized(RowCursor)
case row(RowCursor, Row)
case ended
case error(Error)
}
private unowned var db: FMDatabase
private var state: State
private var cursor: RowCursor {
switch state {
case .initialized(let cursor): return cursor
case .row(let cursor, _): return cursor
case .ended: fatalError("FMResultSet has been fully consumed, or closed")
case .error(let error): fatalError("FMResultSet had an error: \(error)")
}
}
private var row: Row {
switch state {
case .initialized: fatalError("-[FMResultSet next] has to be called before accessing fetched results")
case .row(_, let row): return row
case .ended: fatalError("FMResultSet has been fully consumed, or closed")
case .error(let error): fatalError("FMResultSet had an error: \(error)")
}
}
private lazy var columIndexForLowercaseColumnName: [String: Int] = Dictionary(
self.cursor.statement.columnNames.enumerated().map { ($1.lowercased(), $0) },
uniquingKeysWith: { $1 }) // keep rightmost index like FMDB
init(database: FMDatabase, cursor: RowCursor) {
self.db = database
self.state = .initialized(cursor)
super.init()
self.db.autoclosingPool.add(self)
}
@objc
public var columnCount: CInt {
return CInt(cursor.statement.columnCount)
}
@objc
public func next() -> Bool {
return nextWithError(nil)
}
@objc(nextWithError:)
public func nextWithError(_ outErr: NSErrorPointer) -> Bool {
// This FMDB method breaks error handling conventions very badly. The
// GRDBObjc version does the same. The problem is that the return value
// NO does not mean there is an error.
switch state {
case .initialized(let cursor), .row(let cursor, _):
do {
if let row = try cursor.next() {
state = .row(cursor, row)
return true
} else {
state = .ended
return false
}
} catch {
state = .error(error)
outErr?.pointee = db.handleError(error)
return false
}
case .ended:
return false
case .error(let error):
outErr?.pointee = db.handleError(error)
return false
}
}
@objc public func close() {
state = .ended
}
@objc(columnIndexForName:) public func columnIndex(_ columnName: String) -> Int {
return index(forColumn: columnName) ?? -1
}
@objc public func columnIndexIsNull(_ columnIndex: Int) -> Bool {
return sqlite3_column_type(cursor.statement.sqliteStatement, Int32(columnIndex)) == SQLITE_NULL
}
@objc public func columnIsNull(_ columnName: String) -> Bool {
return index(forColumn: columnName).map { columnIndexIsNull($0) } ?? true
}
@objc public subscript(_ columnIndex: Int) -> Any? { return row[columnIndex] }
@objc(objectForColumnIndex:) public func object(columnIndex: Int) -> Any? { return row[columnIndex] }
@objc(intForColumnIndex:) public func int(columnIndex: Int) -> CInt { return row[columnIndex] ?? 0 }
@objc(longForColumnIndex:) public func long(columnIndex: Int) -> CLong { return row[columnIndex] ?? 0 }
@objc(longLongIntForColumnIndex:) public func longlong(columnIndex: Int) -> CLongLong { return row[columnIndex] ?? 0 }
@objc(unsignedLongLongIntForColumnIndex:) public func unsignedLongLong(columnIndex: Int) -> CUnsignedLongLong { return row[columnIndex] ?? 0 }
@objc(boolForColumnIndex:) public func bool(columnIndex: Int) -> Bool { return row[columnIndex] ?? false }
@objc(doubleForColumnIndex:) public func double(columnIndex: Int) -> Double { return row[columnIndex] ?? 0.0 }
@objc(stringForColumnIndex:) public func string(columnIndex: Int) -> String? { return row[columnIndex] }
@objc(dataForColumnIndex:) public func data(columnIndex: Int) -> Data? { return row[columnIndex] }
@objc(dataNoCopyForColumnIndex:) public func dataNoCopy(columnIndex: Int) -> Data? { return row.dataNoCopy(atIndex: columnIndex) }
@objc(dateForColumnIndex:) public func date(columnIndex: Int) -> Date? {
if let dateFormatter = db.dateFormatter {
guard let string = string(columnIndex: columnIndex) else { return nil }
return dateFormatter.date(from: string)
} else {
return Date(timeIntervalSince1970: double(columnIndex: columnIndex))
}
}
@objc public subscript(_ columnName: String) -> Any? { return index(forColumn: columnName).map { self[$0] } ?? nil }
@objc(objectForColumn:) public func object(columnName: String) -> Any? { return index(forColumn: columnName).map { object(columnIndex: $0) } ?? nil }
@objc(intForColumn:) public func int(columnName: String) -> CInt { return index(forColumn: columnName).map { int(columnIndex: $0) } ?? 0 }
@objc(longForColumn:) public func long(columnName: String) -> CLong { return index(forColumn: columnName).map { long(columnIndex: $0) } ?? 0 }
@objc(longLongIntForColumn:) public func longlong(columnName: String) -> CLongLong { return index(forColumn: columnName).map { longlong(columnIndex: $0) } ?? 0 }
@objc(unsignedLongLongIntForColumn:) public func unsignedLongLong(columnName: String) -> CUnsignedLongLong { return index(forColumn: columnName).map { unsignedLongLong(columnIndex: $0) } ?? 0 }
@objc(boolForColumn:) public func bool(columnName: String) -> Bool { return index(forColumn: columnName).map { bool(columnIndex: $0) } ?? false }
@objc(doubleForColumn:) public func double(columnName: String) -> Double { return index(forColumn: columnName).map { double(columnIndex: $0) } ?? 0 }
@objc(stringForColumn:) public func string(columnName: String) -> String? { return index(forColumn: columnName).map { string(columnIndex: $0) } ?? nil }
@objc(dataForColumn:) public func data(columnName: String) -> Data? { return index(forColumn: columnName).map { data(columnIndex: $0) } ?? nil }
@objc(dataNoCopyForColumn:) public func dataNoCopy(columnName: String) -> Data? { return index(forColumn: columnName).map { dataNoCopy(columnIndex: $0) } ?? nil }
@objc(dateForColumn:) public func date(columnName: String) -> Date? { return index(forColumn: columnName).map { date(columnIndex: $0) } ?? nil }
@objc public var resultDictionary: [String: AnyObject]? {
switch state {
case .row(_, let row):
return Dictionary(
row.map { ($0, $1.storage.value as AnyObject) },
uniquingKeysWith: { $1 }) // keep rightmost value like FMDB
default:
return nil
}
}
private func index(forColumn columnName: String) -> Int? {
return columIndexForLowercaseColumnName[columnName.lowercased()]
}
}
|
mit
|
5a6a874deacf08a03a1d4f20e5d043e4
| 48.331034 | 197 | 0.639732 | 4.47622 | false | false | false | false |
codesman/toolbox
|
Sources/VaporToolbox/Version.swift
|
1
|
912
|
import Console
public final class Version: Command {
public let id = "version"
public let help: [String] = [
"Displays Vapor CLI version"
]
public let console: ConsoleProtocol
public let version: String
public init(console: ConsoleProtocol, version: String) {
self.console = console
self.version = version
}
public func run(arguments: [String]) throws {
console.print("Vapor Toolbox v\(version)")
do {
let run = Run(console: console)
try run.run(arguments: ["version"])
} catch ToolboxError.general(_) {
console.warning("Cannot print Vapor Framework version, no project found.")
}
}
public func frameworkVersion(arguments: [String]) throws -> String {
let run = Run(console: console)
return try run.backgroundRun(arguments: ["version"] + arguments)
}
}
|
mit
|
936aae47e85a6a7433b8a17fa049420b
| 26.636364 | 86 | 0.617325 | 4.606061 | false | false | false | false |
filipealva/PickerView
|
Pod/Classes/PickerView.swift
|
1
|
29691
|
//
// PickerView.swift
//
// Created by Filipe Alvarenga on 19/05/15.
// Copyright (c) 2015 Filipe Alvarenga. All rights reserved.
//
// 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
// MARK: - Protocols
@objc public protocol PickerViewDataSource: class {
func pickerViewNumberOfRows(_ pickerView: PickerView) -> Int
func pickerView(_ pickerView: PickerView, titleForRow row: Int) -> String
}
@objc public protocol PickerViewDelegate: class {
func pickerViewHeightForRows(_ pickerView: PickerView) -> CGFloat
@objc optional func pickerView(_ pickerView: PickerView, didSelectRow row: Int)
@objc optional func pickerView(_ pickerView: PickerView, didTapRow row: Int)
@objc optional func pickerView(_ pickerView: PickerView, styleForLabel label: UILabel, highlighted: Bool)
@objc optional func pickerView(_ pickerView: PickerView, viewForRow row: Int, highlighted: Bool, reusingView view: UIView?) -> UIView?
}
open class PickerView: UIView {
// MARK: Nested Types
fileprivate class SimplePickerTableViewCell: UITableViewCell {
lazy var titleLabel: UILabel = {
let titleLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: self.contentView.frame.width, height: self.contentView.frame.height))
titleLabel.textAlignment = .center
return titleLabel
}()
var customView: UIView?
}
/**
ScrollingStyle Enum.
- parameter Default: Show only the number of rows informed in data source.
- parameter Infinite: Loop through the data source offering a infinite scrolling experience to the user.
*/
@objc public enum ScrollingStyle: Int {
case `default`, infinite
}
/**
SelectionStyle Enum.
- parameter None: Don't uses any aditional view to highlight the selection, only the label style customization provided by delegate.
- parameter DefaultIndicator: Provide a simple selection indicator on the bottom of the highlighted row with full width and 2pt of height.
The default color is its superview `tintColor` but you have free access to customize the DefaultIndicator through the `defaultSelectionIndicator` property.
- parameter Overlay: Provide a full width and height (the height you provided on delegate) view that overlay the highlighted row.
The default color is its superview `tintColor` and the alpha is set to 0.25, but you have free access to customize it through the `selectionOverlay` property.
Tip: You can set the alpha to 1.0 and background color to .clearColor() and add your custom selection view to make it looks as you want
(don't forget to properly add the constraints related to `selectionOverlay` to keep your experience with any screen size).
- parameter Image: Provide a full width and height image view selection indicator (the height you provided on delegate) without any image.
You must have a selection indicator as a image and set it to the image view through the `selectionImageView` property.
*/
@objc public enum SelectionStyle: Int {
case none, defaultIndicator, overlay, image
}
// MARK: Properties
var enabled = true {
didSet {
if enabled {
turnPickerViewOn()
} else {
turnPickerViewOff()
}
}
}
fileprivate var selectionOverlayH: NSLayoutConstraint!
fileprivate var selectionImageH: NSLayoutConstraint!
fileprivate var selectionIndicatorB: NSLayoutConstraint!
fileprivate var pickerCellBackgroundColor: UIColor?
var numberOfRowsByDataSource: Int {
get {
return dataSource?.pickerViewNumberOfRows(self) ?? 0
}
}
fileprivate var indexesByDataSource: Int {
get {
return numberOfRowsByDataSource > 0 ? numberOfRowsByDataSource - 1 : numberOfRowsByDataSource
}
}
var rowHeight: CGFloat {
get {
return delegate?.pickerViewHeightForRows(self) ?? 0
}
}
override open var backgroundColor: UIColor? {
didSet {
self.tableView.backgroundColor = self.backgroundColor
self.pickerCellBackgroundColor = self.backgroundColor
}
}
fileprivate let pickerViewCellIdentifier = "pickerViewCell"
open weak var dataSource: PickerViewDataSource?
open weak var delegate: PickerViewDelegate?
open lazy var defaultSelectionIndicator: UIView = {
let selectionIndicator = UIView()
selectionIndicator.backgroundColor = self.tintColor
selectionIndicator.alpha = 0.0
return selectionIndicator
}()
open lazy var selectionOverlay: UIView = {
let selectionOverlay = UIView()
selectionOverlay.backgroundColor = self.tintColor
selectionOverlay.alpha = 0.0
return selectionOverlay
}()
open lazy var selectionImageView: UIImageView = {
let selectionImageView = UIImageView()
selectionImageView.alpha = 0.0
return selectionImageView
}()
public lazy var tableView: UITableView = {
let tableView = UITableView()
return tableView
}()
fileprivate var infinityRowsMultiplier: Int = 1
fileprivate var hasTouchedPickerViewYet = false
open var currentSelectedRow: Int!
open var currentSelectedIndex: Int {
get {
return indexForRow(currentSelectedRow)
}
}
fileprivate var firstTimeOrientationChanged = true
fileprivate var orientationChanged = false
fileprivate var screenSize: CGSize = UIScreen.main.bounds.size
fileprivate var isScrolling = false
fileprivate var setupHasBeenDone = false
fileprivate var shouldSelectNearbyToMiddleRow = true
open var scrollingStyle = ScrollingStyle.default {
didSet {
switch scrollingStyle {
case .default:
infinityRowsMultiplier = 1
case .infinite:
infinityRowsMultiplier = generateInfinityRowsMultiplier()
}
}
}
open var selectionStyle = SelectionStyle.none {
didSet {
setupSelectionViewsVisibility()
}
}
// MARK: Initialization
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public init(frame: CGRect) {
super.init(frame: frame)
}
// MARK: Subviews Setup
fileprivate func setup() {
infinityRowsMultiplier = generateInfinityRowsMultiplier()
// Setup subviews constraints and apperance
translatesAutoresizingMaskIntoConstraints = false
setupTableView()
setupSelectionOverlay()
setupSelectionImageView()
setupDefaultSelectionIndicator()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.reloadData()
// This needs to be done after a delay - I am guessing it basically needs to be called once
// the view is already displaying
DispatchQueue.main.asyncAfter(deadline: .now()) {
// Some UI Adjustments we need to do after setting UITableView data source & delegate.
self.adjustSelectionOverlayHeightConstraint()
}
}
fileprivate func setupTableView() {
tableView.estimatedRowHeight = 0
tableView.estimatedSectionFooterHeight = 0
tableView.estimatedSectionHeaderHeight = 0
tableView.backgroundColor = .clear
tableView.separatorStyle = .none
tableView.separatorColor = .none
tableView.allowsSelection = true
tableView.allowsMultipleSelection = false
tableView.showsVerticalScrollIndicator = false
tableView.showsHorizontalScrollIndicator = false
tableView.scrollsToTop = false
tableView.register(SimplePickerTableViewCell.classForCoder(), forCellReuseIdentifier: self.pickerViewCellIdentifier)
tableView.translatesAutoresizingMaskIntoConstraints = false
addSubview(tableView)
let tableViewH = NSLayoutConstraint(item: tableView, attribute: .height, relatedBy: .equal, toItem: self,
attribute: .height, multiplier: 1, constant: 0)
addConstraint(tableViewH)
let tableViewW = NSLayoutConstraint(item: tableView, attribute: .width, relatedBy: .equal, toItem: self,
attribute: .width, multiplier: 1, constant: 0)
addConstraint(tableViewW)
let tableViewL = NSLayoutConstraint(item: tableView, attribute: .leading, relatedBy: .equal, toItem: self,
attribute: .leading, multiplier: 1, constant: 0)
addConstraint(tableViewL)
let tableViewTop = NSLayoutConstraint(item: tableView, attribute: .top, relatedBy: .equal, toItem: self,
attribute: .top, multiplier: 1, constant: 0)
addConstraint(tableViewTop)
let tableViewBottom = NSLayoutConstraint(item: tableView, attribute: .bottom, relatedBy: .equal, toItem: self,
attribute: .bottom, multiplier: 1, constant: 0)
addConstraint(tableViewBottom)
let tableViewT = NSLayoutConstraint(item: tableView, attribute: .trailing, relatedBy: .equal, toItem: self,
attribute: .trailing, multiplier: 1, constant: 0)
addConstraint(tableViewT)
}
fileprivate func setupSelectionViewsVisibility() {
switch selectionStyle {
case .defaultIndicator:
defaultSelectionIndicator.alpha = 1.0
selectionOverlay.alpha = 0.0
selectionImageView.alpha = 0.0
case .overlay:
selectionOverlay.alpha = 0.25
defaultSelectionIndicator.alpha = 0.0
selectionImageView.alpha = 0.0
case .image:
selectionImageView.alpha = 1.0
selectionOverlay.alpha = 0.0
defaultSelectionIndicator.alpha = 0.0
case .none:
selectionOverlay.alpha = 0.0
defaultSelectionIndicator.alpha = 0.0
selectionImageView.alpha = 0.0
}
}
fileprivate func setupSelectionOverlay() {
selectionOverlay.isUserInteractionEnabled = false
selectionOverlay.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(selectionOverlay)
selectionOverlayH = NSLayoutConstraint(item: selectionOverlay, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1, constant: rowHeight)
self.addConstraint(selectionOverlayH)
let selectionOverlayW = NSLayoutConstraint(item: selectionOverlay, attribute: .width, relatedBy: .equal, toItem: self,
attribute: .width, multiplier: 1, constant: 0)
addConstraint(selectionOverlayW)
let selectionOverlayL = NSLayoutConstraint(item: selectionOverlay, attribute: .leading, relatedBy: .equal, toItem: self,
attribute: .leading, multiplier: 1, constant: 0)
addConstraint(selectionOverlayL)
let selectionOverlayT = NSLayoutConstraint(item: selectionOverlay, attribute: .trailing, relatedBy: .equal, toItem: self,
attribute: .trailing, multiplier: 1, constant: 0)
addConstraint(selectionOverlayT)
let selectionOverlayY = NSLayoutConstraint(item: selectionOverlay, attribute: .centerY, relatedBy: .equal, toItem: self,
attribute: .centerY, multiplier: 1, constant: 0)
addConstraint(selectionOverlayY)
}
fileprivate func setupSelectionImageView() {
selectionImageView.isUserInteractionEnabled = false
selectionImageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(selectionImageView)
selectionImageH = NSLayoutConstraint(item: selectionImageView, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1, constant: rowHeight)
self.addConstraint(selectionImageH)
let selectionImageW = NSLayoutConstraint(item: selectionImageView, attribute: .width, relatedBy: .equal, toItem: self,
attribute: .width, multiplier: 1, constant: 0)
addConstraint(selectionImageW)
let selectionImageL = NSLayoutConstraint(item: selectionImageView, attribute: .leading, relatedBy: .equal, toItem: self,
attribute: .leading, multiplier: 1, constant: 0)
addConstraint(selectionImageL)
let selectionImageT = NSLayoutConstraint(item: selectionImageView, attribute: .trailing, relatedBy: .equal, toItem: self,
attribute: .trailing, multiplier: 1, constant: 0)
addConstraint(selectionImageT)
let selectionImageY = NSLayoutConstraint(item: selectionImageView, attribute: .centerY, relatedBy: .equal, toItem: self,
attribute: .centerY, multiplier: 1, constant: 0)
addConstraint(selectionImageY)
}
fileprivate func setupDefaultSelectionIndicator() {
defaultSelectionIndicator.translatesAutoresizingMaskIntoConstraints = false
addSubview(defaultSelectionIndicator)
let selectionIndicatorH = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1, constant: 2.0)
addConstraint(selectionIndicatorH)
let selectionIndicatorW = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width, multiplier: 1, constant: 0)
addConstraint(selectionIndicatorW)
let selectionIndicatorL = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .leading, relatedBy: .equal,
toItem: self, attribute: .leading, multiplier: 1, constant: 0)
addConstraint(selectionIndicatorL)
selectionIndicatorB = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .bottom, relatedBy: .equal,
toItem: self, attribute: .centerY, multiplier: 1, constant: (rowHeight / 2))
addConstraint(selectionIndicatorB)
let selectionIndicatorT = NSLayoutConstraint(item: defaultSelectionIndicator, attribute: .trailing, relatedBy: .equal,
toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
addConstraint(selectionIndicatorT)
}
// MARK: Infinite Scrolling Helpers
fileprivate func generateInfinityRowsMultiplier() -> Int {
if scrollingStyle == .default {
return 1
}
if numberOfRowsByDataSource > 100 {
return 100
} else if numberOfRowsByDataSource < 100 && numberOfRowsByDataSource > 50 {
return 200
} else if numberOfRowsByDataSource < 50 && numberOfRowsByDataSource > 25 {
return 400
} else {
return 800
}
}
// MARK: Life Cycle
open override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
if let _ = newWindow {
NotificationCenter.default.addObserver(self, selector: #selector(PickerView.adjustCurrentSelectedAfterOrientationChanges),
name: UIDevice.orientationDidChangeNotification, object: nil)
} else {
NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
}
}
override open func layoutSubviews() {
super.layoutSubviews()
if !setupHasBeenDone {
setup()
setupHasBeenDone = true
}
}
fileprivate func adjustSelectionOverlayHeightConstraint() {
if selectionOverlayH.constant != rowHeight || selectionImageH.constant != rowHeight || selectionIndicatorB.constant != (rowHeight / 2) {
selectionOverlayH.constant = rowHeight
selectionImageH.constant = rowHeight
selectionIndicatorB.constant = -(rowHeight / 2)
layoutIfNeeded()
}
}
@objc func adjustCurrentSelectedAfterOrientationChanges() {
guard screenSize != UIScreen.main.bounds.size else {
return
}
screenSize = UIScreen.main.bounds.size
setNeedsLayout()
layoutIfNeeded()
shouldSelectNearbyToMiddleRow = true
if firstTimeOrientationChanged {
firstTimeOrientationChanged = false
return
}
if !isScrolling {
return
}
orientationChanged = true
}
fileprivate func indexForRow(_ row: Int) -> Int {
return row % (numberOfRowsByDataSource > 0 ? numberOfRowsByDataSource : 1)
}
// MARK: - Actions
/**
Selects the nearby to middle row that matches with the provided index.
- parameter row: A valid index provided by Data Source.
*/
fileprivate func selectedNearbyToMiddleRow(_ row: Int) {
currentSelectedRow = row
tableView.reloadData()
// This line adjust the contentInset to UIEdgeInsetZero because when the PickerView are inside of a UIViewController
// presented by a UINavigation controller, the tableView contentInset is affected.
tableView.contentInset = UIEdgeInsets.zero
let indexOfSelectedRow = visibleIndexOfSelectedRow()
tableView.setContentOffset(CGPoint(x: 0.0, y: CGFloat(indexOfSelectedRow) * rowHeight), animated: false)
delegate?.pickerView?(self, didSelectRow: currentSelectedRow)
shouldSelectNearbyToMiddleRow = false
}
/**
Selects literally the row with index that the user tapped.
- parameter row: The row index that the user tapped, i.e. the Data Source index times the `infinityRowsMultiplier`.
*/
fileprivate func selectTappedRow(_ row: Int) {
delegate?.pickerView?(self, didTapRow: indexForRow(row))
selectRow(row, animated: true)
}
fileprivate func turnPickerViewOn() {
tableView.isScrollEnabled = true
setupSelectionViewsVisibility()
}
fileprivate func turnPickerViewOff() {
tableView.isScrollEnabled = false
selectionOverlay.alpha = 0.0
defaultSelectionIndicator.alpha = 0.0
selectionImageView.alpha = 0.0
}
/**
This is an private helper that we use to reach the visible index of the current selected row.
Because of we multiply the rows several times to create an Infinite Scrolling experience, the index of a visible selected row may
not be the same as the index provided on Data Source.
- returns: The visible index of current selected row.
*/
fileprivate func visibleIndexOfSelectedRow() -> Int {
let middleMultiplier = scrollingStyle == .infinite ? (infinityRowsMultiplier / 2) : infinityRowsMultiplier
let middleIndex = numberOfRowsByDataSource * middleMultiplier
let indexForSelectedRow: Int
if let _ = currentSelectedRow , scrollingStyle == .default && currentSelectedRow == 0 {
indexForSelectedRow = 0
} else if let _ = currentSelectedRow {
indexForSelectedRow = middleIndex - (numberOfRowsByDataSource - currentSelectedRow)
} else {
let middleRow = Int(floor(Float(indexesByDataSource) / 2.0))
indexForSelectedRow = middleIndex - (numberOfRowsByDataSource - middleRow)
}
return indexForSelectedRow
}
open func selectRow(_ row : Int, animated: Bool) {
var finalRow = row
if (scrollingStyle == .infinite && row <= numberOfRowsByDataSource) {
let middleMultiplier = scrollingStyle == .infinite ? (infinityRowsMultiplier / 2) : infinityRowsMultiplier
let middleIndex = numberOfRowsByDataSource * middleMultiplier
finalRow = middleIndex - (numberOfRowsByDataSource - finalRow)
}
currentSelectedRow = finalRow
delegate?.pickerView?(self, didSelectRow: indexForRow(currentSelectedRow))
tableView.setContentOffset(CGPoint(x: 0.0, y: CGFloat(currentSelectedRow) * rowHeight), animated: animated)
}
open func reloadPickerView() {
shouldSelectNearbyToMiddleRow = true
tableView.reloadData()
}
}
extension PickerView: UITableViewDataSource {
// MARK: UITableViewDataSource
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRows = numberOfRowsByDataSource * infinityRowsMultiplier
// Select the nearby to middle row when it's needed (first run or orientation change)
if shouldSelectNearbyToMiddleRow && numberOfRows > 0 {
// Configure the PickerView to select the middle row when the orientation changes during scroll
if isScrolling {
let middleRow = Int(floor(Float(indexesByDataSource) / 2.0))
selectedNearbyToMiddleRow(middleRow)
} else {
let rowToSelect = currentSelectedRow != nil ? currentSelectedRow : Int(floor(Float(indexesByDataSource) / 2.0))
selectedNearbyToMiddleRow(rowToSelect!)
}
}
// If PickerView have items to show set it as enabled otherwise set it as disabled
if numberOfRows > 0 {
turnPickerViewOn()
} else {
turnPickerViewOff()
}
return numberOfRows
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let indexOfSelectedRow = visibleIndexOfSelectedRow()
let pickerViewCell = tableView.dequeueReusableCell(withIdentifier: pickerViewCellIdentifier, for: indexPath) as! SimplePickerTableViewCell
let view = delegate?.pickerView?(self, viewForRow: indexForRow((indexPath as NSIndexPath).row), highlighted: (indexPath as NSIndexPath).row == indexOfSelectedRow, reusingView: pickerViewCell.customView)
pickerViewCell.selectionStyle = .none
pickerViewCell.backgroundColor = pickerCellBackgroundColor ?? UIColor.white
if (view != nil) {
var frame = view!.frame
frame.origin.y = (indexPath as NSIndexPath).row == 0 ? (self.frame.height / 2) - (rowHeight / 2) : 0.0
view!.frame = frame
pickerViewCell.customView = view
pickerViewCell.contentView.addSubview(pickerViewCell.customView!)
} else {
// As the first row have a different size to fit in the middle of the PickerView and rows below, the titleLabel position must be adjusted.
let centerY = (indexPath as NSIndexPath).row == 0 ? (self.frame.height / 2) - (rowHeight / 2) : 0.0
pickerViewCell.titleLabel.frame = CGRect(x: 0.0, y: centerY, width: frame.width, height: rowHeight)
pickerViewCell.contentView.addSubview(pickerViewCell.titleLabel)
pickerViewCell.titleLabel.backgroundColor = UIColor.clear
pickerViewCell.titleLabel.text = dataSource?.pickerView(self, titleForRow: indexForRow((indexPath as NSIndexPath).row))
delegate?.pickerView?(self, styleForLabel: pickerViewCell.titleLabel, highlighted: (indexPath as NSIndexPath).row == indexOfSelectedRow)
}
return pickerViewCell
}
}
extension PickerView: UITableViewDelegate {
// MARK: UITableViewDelegate
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectTappedRow((indexPath as NSIndexPath).row)
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let numberOfRowsInPickerView = dataSource!.pickerViewNumberOfRows(self) * infinityRowsMultiplier
// When the scrolling reach the end on top/bottom we need to set the first/last row to appear in the center of PickerView, so that row must be bigger.
if (indexPath as NSIndexPath).row == 0 {
return (frame.height / 2) + (rowHeight / 2)
} else if numberOfRowsInPickerView > 0 && (indexPath as NSIndexPath).row == numberOfRowsInPickerView - 1 {
return (frame.height / 2) + (rowHeight / 2)
}
return rowHeight
}
}
extension PickerView: UIScrollViewDelegate {
// MARK: UIScrollViewDelegate
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isScrolling = true
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let partialRow = Float(targetContentOffset.pointee.y / rowHeight) // Get the estimative of what row will be the selected when the scroll animation ends.
var roundedRow = Int(lroundf(partialRow)) // Round the estimative to a row
if roundedRow < 0 {
roundedRow = 0
} else {
targetContentOffset.pointee.y = CGFloat(roundedRow) * rowHeight // Set the targetContentOffset (where the scrolling position will be when the animation ends) to a rounded value.
}
// Update the currentSelectedRow and notify the delegate that we have a new selected row.
currentSelectedRow = indexForRow(roundedRow)
delegate?.pickerView?(self, didSelectRow: currentSelectedRow)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// When the orientation changes during the scroll, is required to reset the picker to select the nearby to middle row.
if orientationChanged {
selectedNearbyToMiddleRow(currentSelectedRow)
orientationChanged = false
}
isScrolling = false
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let partialRow = Float(scrollView.contentOffset.y / rowHeight)
let roundedRow = Int(lroundf(partialRow))
// Avoid to have two highlighted rows at the same time
if let visibleRows = tableView.indexPathsForVisibleRows {
for indexPath in visibleRows {
if let cellToUnhighlight = tableView.cellForRow(at: indexPath) as? SimplePickerTableViewCell , (indexPath as NSIndexPath).row != roundedRow {
let _ = delegate?.pickerView?(self, viewForRow: indexForRow((indexPath as NSIndexPath).row), highlighted: false, reusingView: cellToUnhighlight.customView)
delegate?.pickerView?(self, styleForLabel: cellToUnhighlight.titleLabel, highlighted: false)
}
}
}
// Highlight the current selected cell during scroll
if let cellToHighlight = tableView.cellForRow(at: IndexPath(row: roundedRow, section: 0)) as? SimplePickerTableViewCell {
let _ = delegate?.pickerView?(self, viewForRow: indexForRow(roundedRow), highlighted: true, reusingView: cellToHighlight.customView)
let _ = delegate?.pickerView?(self, styleForLabel: cellToHighlight.titleLabel, highlighted: true)
}
}
}
|
mit
|
5fadb6920772238bebb4f00a69c6aa21
| 42.535191 | 210 | 0.643865 | 5.857368 | false | false | false | false |
bitjammer/swift
|
stdlib/public/SDK/Intents/INSetSeatSettingsInCarIntent.swift
|
27
|
1576
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Intents
import Foundation
#if os(iOS)
@available(iOS 10.0, *)
extension INSetSeatSettingsInCarIntent {
@nonobjc
public convenience init(
enableHeating: Bool? = nil,
enableCooling: Bool? = nil,
enableMassage: Bool? = nil,
seat: INCarSeat = .unknown,
level: Int? = nil,
relativeLevel: INRelativeSetting = .unknown
) {
self.init(__enableHeating: enableHeating.map { NSNumber(value: $0) },
enableCooling: enableCooling.map { NSNumber(value: $0) },
enableMassage: enableMassage.map { NSNumber(value: $0) },
seat: seat,
level: level.map { NSNumber(value: $0) },
relativeLevel: relativeLevel)
}
@nonobjc
public final var enableHeating: Bool? {
return __enableHeating?.boolValue
}
@nonobjc
public final var enableCooling: Bool? {
return __enableCooling?.boolValue
}
@nonobjc
public final var enableMassage: Bool? {
return __enableMassage?.boolValue
}
@nonobjc
public final var level: Int? {
return __level?.intValue
}
}
#endif
|
apache-2.0
|
70cfd304d23b37a19c66a7fff988947c
| 27.142857 | 80 | 0.613579 | 4.104167 | false | false | false | false |
DSanzh/GuideMe-iOS
|
Pods/Sugar/Sources/Shared/Application.swift
|
2
|
1349
|
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
public struct Application {
fileprivate static func getString(_ key: String) -> String {
guard let infoDictionary = Bundle.main.infoDictionary,
let value = infoDictionary[key] as? String
else { return "" }
return value
}
public static var name: String = {
let displayName = Application.getString("CFBundleDisplayName")
return !displayName.isEmpty ? displayName : Application.getString("CFBundleName")
}()
public static var version: String = {
return Application.getString("CFBundleShortVersionString")
}()
public static var build: String = {
return Application.getString("CFBundleVersion")
}()
public static var executable: String = {
return Application.getString("CFBundleExecutable")
}()
public static var bundle: String = {
return Application.getString("CFBundleIdentifier")
}()
public static var schemes: [String] = {
guard let infoDictionary = Bundle.main.infoDictionary,
let urlTypes = infoDictionary["CFBundleURLTypes"] as? [AnyObject],
let urlType = urlTypes.first as? [String : AnyObject],
let urlSchemes = urlType["CFBundleURLSchemes"] as? [String]
else { return [] }
return urlSchemes
}()
public static var mainScheme: String? = {
return schemes.first
}()
}
|
mit
|
488d2d0e1529340dab7d427514dceb01
| 24.45283 | 85 | 0.690141 | 4.835125 | false | false | false | false |
dinhcong/ALCameraViewController
|
ALCameraViewController/Views/CameraView.swift
|
1
|
6711
|
//
// CameraView.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/17.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
import AVFoundation
public class CameraView: UIView {
var session: AVCaptureSession!
var input: AVCaptureDeviceInput!
var device: AVCaptureDevice!
var imageOutput: AVCaptureStillImageOutput!
var preview: AVCaptureVideoPreviewLayer!
let cameraQueue = dispatch_queue_create("com.zero.ALCameraViewController.Queue", DISPATCH_QUEUE_SERIAL);
let focusView = CropOverlay(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
public var currentPosition = AVCaptureDevicePosition.Back
public func startSession() {
dispatch_async(cameraQueue) {
self.createSession()
self.session?.startRunning()
}
}
public func stopSession() {
dispatch_async(cameraQueue) {
self.session?.stopRunning()
self.preview?.removeFromSuperlayer()
self.session = nil
self.input = nil
self.imageOutput = nil
self.preview = nil
self.device = nil
}
}
public override func layoutSubviews() {
super.layoutSubviews()
if let p = preview {
p.frame = bounds
}
}
public func configureFocus() {
if let gestureRecognizers = gestureRecognizers {
for gesture in gestureRecognizers {
removeGestureRecognizer(gesture)
}
}
let tapGesture = UITapGestureRecognizer(target: self, action: "focus:")
addGestureRecognizer(tapGesture)
userInteractionEnabled = true
addSubview(focusView)
focusView.hidden = true
let lines = focusView.horizontalLines + focusView.verticalLines + focusView.outerLines
lines.forEach { line in
line.alpha = 0
}
}
internal func focus(gesture: UITapGestureRecognizer) {
let point = gesture.locationInView(self)
guard let device = device else { return }
do { try device.lockForConfiguration() } catch {
return
}
if device.isFocusModeSupported(.Locked) {
let focusPoint = CGPoint(x: point.x / frame.width, y: point.y / frame.height)
device.focusPointOfInterest = focusPoint
device.unlockForConfiguration()
focusView.hidden = false
focusView.center = point
focusView.alpha = 0
focusView.transform = CGAffineTransformMakeScale(1.2, 1.2)
bringSubviewToFront(focusView)
UIView.animateKeyframesWithDuration(1.5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.15, animations: { () -> Void in
self.focusView.alpha = 1
self.focusView.transform = CGAffineTransformIdentity
})
UIView.addKeyframeWithRelativeStartTime(0.80, relativeDuration: 0.20, animations: { () -> Void in
self.focusView.alpha = 0
self.focusView.transform = CGAffineTransformMakeScale(0.8, 0.8)
})
}, completion: { finished in
if finished {
self.focusView.hidden = true
}
})
}
}
private func createSession() {
session = AVCaptureSession()
session.sessionPreset = AVCaptureSessionPresetHigh
dispatch_async(dispatch_get_main_queue()) {
self.createPreview()
}
}
private func createPreview() {
device = cameraWithPosition(currentPosition)
if device.hasFlash {
do {
try device.lockForConfiguration()
device.flashMode = .Auto
device.unlockForConfiguration()
} catch _ {}
}
let outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
do {
input = try AVCaptureDeviceInput(device: device)
} catch let error as NSError {
input = nil
print("Error: \(error.localizedDescription)")
return
}
if session.canAddInput(input) {
session.addInput(input)
}
imageOutput = AVCaptureStillImageOutput()
imageOutput.outputSettings = outputSettings
session.addOutput(imageOutput)
preview = AVCaptureVideoPreviewLayer(session: session)
preview.videoGravity = AVLayerVideoGravityResizeAspectFill
preview.frame = bounds
layer.addSublayer(preview)
}
private func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? {
let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
var _device: AVCaptureDevice?
for d in devices {
if d.position == position {
_device = d as? AVCaptureDevice
break
}
}
return _device
}
public func capturePhoto(completion: ALCameraShotCompletion) {
dispatch_async(cameraQueue) {
let orientation = AVCaptureVideoOrientation(rawValue: UIDevice.currentDevice().orientation.rawValue)!
CameraShot().takePhoto(self.imageOutput, videoOrientation: orientation, cropSize: self.frame.size) { image in
completion(image)
}
}
}
public func swapCameraInput() {
if session != nil && input != nil {
session.beginConfiguration()
session.removeInput(input)
if input.device.position == AVCaptureDevicePosition.Back {
currentPosition = AVCaptureDevicePosition.Front
device = cameraWithPosition(currentPosition)
} else {
currentPosition = AVCaptureDevicePosition.Back
device = cameraWithPosition(currentPosition)
}
let error = NSErrorPointer()
do {
input = try AVCaptureDeviceInput(device: device)
} catch let error1 as NSError {
error.memory = error1
input = nil
}
session.addInput(input)
session.commitConfiguration()
}
}
}
|
mit
|
62b01fe43706d7b7b5df7b07c2673ce1
| 30.957143 | 121 | 0.565937 | 5.991964 | false | false | false | false |
jasperscholten/programmeerproject
|
JasperScholten-project/ChooseReviewFormVC.swift
|
1
|
2854
|
//
// ChooseReviewFormVC.swift
// JasperScholten-project
//
// Created by Jasper Scholten on 20-01-17.
// Copyright © 2017 Jasper Scholten. All rights reserved.
//
// In this view, the user can select a form from a tableView, that he wants to use to review the previously selected employee.
import UIKit
import Firebase
class ChooseReviewFormVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Constants and variables
let formsRef = FIRDatabase.database().reference(withPath: "Forms")
var forms = [Form]()
var employee = String()
var employeeID = String()
var observatorName = String()
var organisation = String()
var organisationID = String()
var location = String()
// MARK: - Outlets
@IBOutlet weak var formListTableView: UITableView!
// MARK: - UIViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Retrieve available forms from Firebase.
formsRef.observe(.value, with: { snapshot in
var newForms: [Form] = []
for item in snapshot.children {
let formData = Form(snapshot: item as! FIRDataSnapshot)
if formData.organisationID == self.organisationID {
newForms.append(formData)
}
}
self.forms = newForms
self.formListTableView.reloadData()
})
}
// MARK: - Tableview Population
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return forms.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = formListTableView.dequeueReusableCell(withIdentifier: "reviewForms", for: indexPath) as! ReviewFormsCell
cell.form.text = forms[indexPath.row].formName
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "newReview", sender: self)
formListTableView.deselectRow(at: indexPath, animated: true)
}
// Segue data necessary to fill in a new review.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let newReview = segue.destination as? NewReviewVC {
let indexPath = self.formListTableView.indexPathForSelectedRow
newReview.employee = employee
newReview.employeeID = employeeID
newReview.form = forms[indexPath!.row].formName
newReview.formID = forms[indexPath!.row].formID
newReview.observatorName = observatorName
newReview.organisation = organisation
newReview.organisationID = organisationID
newReview.location = location
}
}
}
|
apache-2.0
|
53e085caf5e399623576090d5a219508
| 35.576923 | 127 | 0.650193 | 4.953125 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk
|
Sources/PagedPublication/PagedPublicationView+ImageLoader.swift
|
1
|
3028
|
//
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2018 ShopGun. All rights reserved.
import UIKit
/// The object that knows how to load/cache the page images from a URL
/// Loosely based on `Kingfisher` interface
public protocol PagedPublicationViewImageLoader: class {
func loadImage(in imageView: UIImageView, url: URL, transition: (fadeDuration: TimeInterval, evenWhenCached: Bool), completion: @escaping ((Result<(image: UIImage, fromCache: Bool), Error>, URL) -> Void))
func cancelImageLoad(for imageView: UIImageView)
}
extension PagedPublicationView {
enum ImageLoaderError: Error {
case unknownImageLoadError(url: URL)
case cancelled
}
}
extension Error where Self == PagedPublicationView.ImageLoaderError {
var isCancellationError: Bool {
switch self {
case .cancelled:
return true
default:
return false
}
}
}
// MARK: -
import Kingfisher
extension PagedPublicationView {
/// This class wraps the Kingfisher library
class KingfisherImageLoader: PagedPublicationViewImageLoader {
init() {
// max 150 Mb of disk cache
KingfisherManager.shared.cache.maxDiskCacheSize = 150*1024*1024
}
func loadImage(in imageView: UIImageView, url: URL, transition: (fadeDuration: TimeInterval, evenWhenCached: Bool), completion: @escaping ((Result<(image: UIImage, fromCache: Bool), Error>, URL) -> Void)) {
var options: KingfisherOptionsInfo = [.transition(.fade(transition.fadeDuration))]
if transition.evenWhenCached == true {
options.append(.forceTransition)
}
imageView.kf.setImage(with: url, options: options) { (image, error, cacheType, _) in
if let img = image {
completion(.success((img, cacheType.cached)), url)
} else {
let err: Error
// if it is a KingFisher cancellation error, convert into our own cancellation error
if let nsErr: NSError = error, nsErr.domain == KingfisherErrorDomain, nsErr.code == KingfisherError.downloadCancelledBeforeStarting.rawValue {
err = PagedPublicationView.ImageLoaderError.cancelled
} else {
err = error ?? PagedPublicationView.ImageLoaderError.unknownImageLoadError(url: url)
}
completion(.failure(err), url)
}
}
}
func cancelImageLoad(for imageView: UIImageView) {
imageView.kf.cancelDownloadTask()
}
}
}
|
mit
|
2c8adab3e9bf8f0856d6ba7a6e03bdd4
| 35.487179 | 214 | 0.576599 | 5.001757 | false | false | false | false |
FandyLiu/FDDemoCollection
|
Swift/Apply/Apply/ApplyBaseTableView.swift
|
1
|
631
|
//
// ApplyBaseTableView.swift
// Apply
//
// Created by 刘欢 on 2017/4/21.
// Copyright © 2017年 fandy. All rights reserved.
//
import UIKit
class ApplyBaseTableView: UITableView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
if ((view as? UITextField) != nil) {
return view
}
endEditing(true)
let isButton = view as? UIButton != nil
let isImageView = view as? UIImageView != nil
if isButton || isImageView {
return view
}
return self
}
}
|
mit
|
e1e528add7dd95d6b5249115278e05ca
| 22.111111 | 78 | 0.583333 | 4.025806 | false | true | false | false |
toggl/superday
|
teferi/Services/Implementations/Persistency/DefaultGoalService.swift
|
1
|
5349
|
import Foundation
import RxSwift
class DefaultGoalService : GoalService
{
// MARK: Public Properties
let goalCreatedObservable : Observable<Goal>
let goalUpdatedObservable : Observable<Goal>
// MARK: Private Properties
private let timeService : TimeService
private let timeSlotService : TimeSlotService
private let loggingService : LoggingService
private let metricsService : MetricsService
private let settingsService : SettingsService
private let persistencyService : BasePersistencyService<Goal>
private let goalCreatedSubject = PublishSubject<Goal>()
private let goalUpdatedSubject = PublishSubject<Goal>()
init(timeService : TimeService,
timeSlotService : TimeSlotService,
loggingService: LoggingService,
metricsService : MetricsService,
settingsService : SettingsService,
persistencyService: BasePersistencyService<Goal>)
{
self.timeService = timeService
self.timeSlotService = timeSlotService
self.loggingService = loggingService
self.metricsService = metricsService
self.settingsService = settingsService
self.persistencyService = persistencyService
goalCreatedObservable = goalCreatedSubject.asObservable()
goalUpdatedObservable = goalUpdatedSubject.asObservable()
}
func addGoal(forDate date: Date, category: Category, targetTime: Seconds) -> Goal?
{
let goal = Goal(date: date, category: category, targetTime: targetTime)
return tryAdd(goal: goal)
}
func getGoals(sinceDaysAgo days: Int) -> [Goal]
{
let today = timeService.now.ignoreTimeComponents()
let startTime = today.add(days: -days).ignoreTimeComponents() as NSDate
let endTime = today.tomorrow.ignoreTimeComponents() as NSDate
let predicate = Predicate(parameter: "date", rangesFromDate: startTime, toDate: endTime)
let goals = persistencyService.get(withPredicate: predicate)
return goals.map(withCompletedTimes)
}
func getGoals(sinceDate date: Date) -> [Goal]
{
let today = timeService.now.ignoreTimeComponents()
return getGoals(sinceDaysAgo: date.differenceInDays(toDate: today))
}
func update(goal: Goal, withCategory category: Category?, withTargetTime targetTime: Seconds?)
{
let predicate = Predicate(parameter: "date", equals: goal.date as AnyObject)
let editFunction = { (goal: Goal) -> (Goal) in
return goal.with(category: category, targetTime: targetTime)
}
if let updatedGoal = persistencyService.singleUpdate(withPredicate: predicate, updateFunction: editFunction)
{
goalUpdatedSubject.on(.next(updatedGoal))
}
else
{
if let category = category, let targetTime = targetTime
{
loggingService.log(withLogLevel: .warning, message: "Error updating category or value of Goal created on \(goal.date). Category from \(goal.category) to \(category) or targetTime from \(goal.targetTime) to \(targetTime)")
}
else if let category = category
{
loggingService.log(withLogLevel: .warning, message: "Error updating category of Goal created on \(goal.date). Category from \(goal.category) to \(category)")
}
else if let targetTime = targetTime
{
loggingService.log(withLogLevel: .warning, message: "Error updating value of Goal created on \(goal.date). Value from from \(goal.targetTime) to \(targetTime)")
}
}
}
// MARK: Private Methods
private func withCompletedTimes(_ goal: Goal) -> Goal
{
let slotsFromSameCateoryAndDay = timeSlotService.getTimeSlots(forDay: goal.date, category: goal.category)
let sumOfDurations = slotsFromSameCateoryAndDay
.map({ timeSlotService.calculateDuration(ofTimeSlot: $0) })
.reduce(0, +)
return goal.with(timeSoFar: sumOfDurations)
}
private func tryAdd(goal: Goal) -> Goal?
{
guard persistencyService.create(goal) else
{
loggingService.log(withLogLevel: .warning, message: "Failed to create new Goal")
return nil
}
loggingService.log(withLogLevel: .info, message: "New Goal with category \"\(goal.category)\" value \"\(goal.targetTime)\" created")
goalCreatedSubject.on(.next(goal))
return goal
}
func logFinishedGoals()
{
var goals = [Goal]()
if let date = settingsService.lastGoalLoggingDate
{
goals = getGoals(sinceDate: date)
}
else if let installDate = settingsService.installDate
{
goals = getGoals(sinceDate: installDate)
}
goals.forEach { (goal) in
if goal.percentageCompleted < 1.0
{
metricsService.log(event: .goalFailed(goal: goal))
}
else
{
metricsService.log(event: .goalAchieved(goal: goal))
}
}
settingsService.setLastGoalLoggingDate(timeService.now)
}
}
|
bsd-3-clause
|
d4f7fd1c6714a9df7c343862f3d2a69c
| 36.145833 | 237 | 0.632829 | 4.939058 | false | false | false | false |
dictav/SwiftLint
|
Source/SwiftLintFramework/Rules/TrailingNewlineRule.swift
|
1
|
1297
|
//
// TrailingNewlineRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
public struct TrailingNewlineRule: Rule {
public init() {}
public static let description = RuleDescription(
identifier: "trailing_newline",
name: "Trailing Newline",
description: "Files should have a single trailing newline.",
nonTriggeringExamples: [
"let a = 0\n"
],
triggeringExamples: [
"let a = 0",
"let a = 0\n\n"
]
)
public func validateFile(file: File) -> [StyleViolation] {
let string = file.contents
let start = string.endIndex.advancedBy(-2, limit: string.startIndex)
let range = Range(start: start, end: string.endIndex)
let substring = string[range].utf16
let newLineSet = NSCharacterSet.newlineCharacterSet()
let slices = substring.split(allowEmptySlices: true) { !newLineSet.characterIsMember($0) }
guard let slice = slices.last where slice.count != 1 else { return [] }
return [StyleViolation(ruleDescription: self.dynamicType.description,
location: Location(file: file.path, line: max(file.lines.count, 1)))]
}
}
|
mit
|
52c9f609b519339633c074abe99aeeca
| 31.425 | 98 | 0.63377 | 4.352349 | false | false | false | false |
Rendel27/RDExtensionsSwift
|
RDExtensionsSwift/RDExtensionsSwift/Source/UITextView/UITextView+General.swift
|
1
|
2147
|
//
// UITextView+General.swift
//
// Created by Giorgi Iashvili on 19.09.16.
// Copyright (c) 2016 Giorgi Iashvili
//
// 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.
//
public extension UITextView {
/// RDExtensionsSwift: Return non nilable text
var string : String { get { return self.text == nil ? "" : self.text! } set { self.text = newValue } }
/// RDExtensionsSwift: Calculate and return width of the text view for given hight with given font
var widthForText : CGFloat { return self.string.widthForHeight(self.frame.size.height, font: self.font!) }
/// RDExtensionsSwift: Calculate and return height of the text view for given width with given font
var heightForText : CGFloat { return self.string.heightForWidth(self.frame.size.width, font: self.font!) }
/// RDExtensionsSwift: Sets attributed text with given components
func setAttributedText(_ components: [(String, [NSAttributedString.Key: Any])])
{
let label = UILabel()
label.setAttributedText(components)
self.attributedText = label.attributedText
}
}
|
mit
|
6d18710717c50f2565d4055b18ccffce
| 46.711111 | 110 | 0.724266 | 4.482255 | false | false | false | false |
SkyGrass/souyun
|
souyun/ShowApiRequest.swift
|
1
|
4358
|
//
// ShowAPI_SDK.swift
// ShowAPI_demo
//
// Created by 兰文栋 on 16/1/8.
// Copyright © 2016年 showapi. All rights reserved.
//
import Foundation
import Alamofire
@objc class ShowApiRequest:NSObject {
//showAPI申请的appId
private let appId:String?
//showAPI申请的secret
private let secret:String?
//超时时间(毫秒)
private let timeout:Int?
//接口地址
private let url:String?
//请求实例,持有以实现取消操作
private var request:Request?
//构造方法
@objc init(url:String,appId:String,secret:String,timeout:Int=5000){
self.appId=appId
self.secret=secret
self.timeout=timeout
self.url=url
}
//发送请求
@objc func post(parameters: [String: AnyObject]? = nil,fileParameters:[String:NSURL]?=nil,callback:(NSDictionary)->Void){
if let fileParameters=fileParameters{
Alamofire.upload(
.POST,
self.url!,
multipartFormData: { multipartFormData in
for(key,value) in fileParameters{
multipartFormData.appendBodyPart(fileURL:value,name: key);
}
let params=self.createSecretParam(parameters)
for(key,value) in params{
multipartFormData.appendBodyPart(data: "\(value)".dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
self.request = upload.responseJSON { response in
self.response(response, callback: callback)
}
case .Failure(let encodingError):
print(encodingError)
self.error("\(encodingError)",callback:callback)
}
}
)
}else{
self.request = Alamofire.request(.POST, self.url!,parameters: self.createSecretParam(parameters)).responseJSON(){response in
self.response(response, callback: callback)
}
}
}
//取消请求,只能取消最后一个发送的请求
@objc func cancel(){
if let request=self.request{
request.cancel()
}
}
private func createSecretParam(parameters: [String: AnyObject]? = nil) -> [String: AnyObject]{
let formatter=NSDateFormatter()
formatter.dateFormat="yyyyMMddHHmmss"
var re:[String: AnyObject]=[
"showapi_appid":self.appId!,
"showapi_timestamp":formatter.stringFromDate(NSDate())
]
if let parameters=parameters{
for (key, value) in parameters {
re[key]=value
}
}
let sortKeys=Array(re.keys).sort(<)
var temp=""
for key in sortKeys{
temp+=key+"\(re[key]!)"
}
temp+=self.secret!
re["showapi_sign"]=ShowApiRequest.md5(temp)
return re
}
private func response(response:Response<AnyObject, NSError>,callback:(NSDictionary)->Void){
if(response.result.isSuccess){
callback(response.result.value as! NSDictionary)
}else{
print(response.result.error)
self.error(response.result.error?.description,callback:callback)
}
}
private func error(error:String?=nil,callback:(NSDictionary)->Void){
let re:NSDictionary=["showapi_res_code":-1,"showapi_res_error":error!]
callback(re)
}
static func md5(str: String) -> String {
var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
if let data = str.dataUsingEncoding(NSUTF8StringEncoding) {
CC_MD5(data.bytes, CC_LONG(data.length), &digest)
}
var digestHex = ""
for index in 0..<Int(CC_MD5_DIGEST_LENGTH) {
digestHex += String(format: "%02x", digest[index])
}
return digestHex
}
}
|
apache-2.0
|
012b2484d004c468485c173852dca1f9
| 28.809859 | 137 | 0.534373 | 4.682522 | false | false | false | false |
chweihan/Weibo
|
Weibo/Weibo/Classes/Home/StatusViewModel.swift
|
1
|
3269
|
//
// StatusViewModel.swift
// Weibo
//
// Created by 陈伟涵 on 2016/10/26.
// Copyright © 2016年 cweihan. All rights reserved.
//
import UIKit
class StatusViewModel: NSObject {
/// 模型对象
var status : Status
init(_ status : Status) {
self.status = status
// 处理头像
icon_URL = NSURL(string: status.user?.profile_image_url ?? "")
// 处理会员图标
if (status.user?.mbrank)! >= 1 && (status.user?.mbrank)! <= 6 {
mbrankImage = UIImage(named: "common_icon_membership_level\(status.user!.mbrank)")
}
// 处理认证图片
switch status.user?.verified_type ?? -1 {
case 0:
verified_image = UIImage(named: "avatar_vip")
break
case 2, 3, 5:
verified_image = UIImage(named: "avatar_enterprise_vip")
break
case 220:
verified_image = UIImage(named: "avatar_grassroot")
break
default:
verified_image = nil
}
// 处理来源
if let sourceStr : String = status.source, sourceStr != "" {
let startIndex = (sourceStr as NSString).range(of: ">").location + 1
let length = (sourceStr as NSString).range(of: "<").location - startIndex
let result = (sourceStr as NSString).substring(with: NSRange(location : startIndex, length:length))
source_Text = "来自" + result
}
// 处理时间
if let timeStr = status.created_at, timeStr != "" {
//将服务器返回的时间格式化成Date
let createDate = Date.createDate(timeStr, "EE MM dd HH:mm:ss Z yyyy")
//生成发布微博时间对应的字符串
created_Time = createDate.descriptionStr()
}
// 处理配图url
// 从模型中取出配图数组
// if let picurls = status.pic_urls
if let picurls = (status.retweeted_status != nil) ? status.retweeted_status?.pic_urls :status.pic_urls {
thumbnail_pic = [NSURL]()
//遍历配图数组下载图片
for dict in picurls {
//取出图片的url字符串
guard let urlStr = dict["thumbnail_pic"] as? String else {
continue
}
let url = NSURL(string: urlStr)!
thumbnail_pic?.append(url)
}
}
//处理转发
if let text = status.retweeted_status?.text {
let name = status.retweeted_status?.user?.screen_name ?? ""
forwardText = "@" + name + ":" + text
}
}
/// 用户认证图片
var verified_image : UIImage?
/// 会员图片
var mbrankImage : UIImage?
/// 用户头像URL地址
var icon_URL : NSURL?
/// 微博格式化之后的创建时间
var created_Time : String = ""
/// 微博格式化之后的来源
var source_Text : String = ""
/// 保存所有配图URL
var thumbnail_pic : [NSURL]?
/// 转发微博格式化之后正文
var forwardText : String?
}
|
mit
|
c00c8c72358f840b51aa747cb59284e4
| 28.058824 | 112 | 0.506073 | 4.264748 | false | false | false | false |
gkye/TheMovieDatabaseSwiftWrapper
|
Sources/TMDBSwift/OldModels/Authentication/AuthenticationMDBModel.swift
|
1
|
1043
|
//
// GuestSession.swift
// TMDBSwift
//
// Created by user on 28/01/2019.
// Copyright © 2019 George. All rights reserved.
//
import Foundation
public struct GuestSessionMDB: Decodable {
public var success: Bool!
public var guestSessionId: String!
public var expiresAt: String!
enum CodingKeys: String, CodingKey {
case success
case guestSessionId = "guest_session_id"
case expiresAt = "expires_at"
}
}
public struct RequestTokenMDB: Decodable {
public var success: Bool!
public var requestToken: String!
public var expiresAt: String!
enum CodingKeys: String, CodingKey {
case success
case requestToken = "request_token"
case expiresAt = "expires_at"
}
}
public struct SessionMDB: Decodable {
public var success: Bool!
public var sessionId: String!
enum CodingKeys: String, CodingKey {
case success
case sessionId = "session_id"
}
}
public struct DeleteSessionMDB: Decodable {
public var success: Bool!
}
|
mit
|
ee05a52464f0a4f8ca58160e0388b9a0
| 21.170213 | 49 | 0.666987 | 4.253061 | false | false | false | false |
tokyovigilante/CesiumKit
|
CesiumKit/Core/TerrainMesh.swift
|
1
|
4892
|
//
// BoundingRectangle.swift
// CesiumKit
//
// Created by Ryan Walklin on 13/06/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Metal
/**
* A mesh plus related metadata for a single tile of terrain. Instances of this type are
* usually created from raw {@link TerrainData}.
*
* @alias TerrainMesh
* @constructor
*
* @param {Cartesian3} center The center of the tile. Vertex positions are specified relative to this center.
* @param {Float32Array} vertices The vertex data, including positions, texture coordinates, and heights.
* The vertex data is in the order [X, Y, Z, H, U, V], where X, Y, and Z represent
* the Cartesian position of the vertex, H is the height above the ellipsoid, and
* U and V are the texture coordinates.
* @param {Uint16Array} indices The indices describing how the vertices are connected to form triangles.
* @param {Number} minimumHeight The lowest height in the tile, in meters above the ellipsoid.
* @param {Number} maximumHeight The highest height in the tile, in meters above the ellipsoid.
* @param {BoundingSphere} boundingSphere3D A bounding sphere that completely contains the tile.
* @param {Cartesian3} occludeePointInScaledSpace The occludee point of the tile, represented in ellipsoid-
* scaled space, and used for horizon culling. If this point is below the horizon,
* the tile is considered to be entirely below the horizon.
*/
struct TerrainMesh {
//var TerrainMesh = function TerrainMesh(center, vertices, indices, minimumHeight, maximumHeight, boundingSphere3D, occludeePointInScaledSpace) {
/**
* The center of the tile. Vertex positions are specified relative to this center.
* @type {Cartesian3}
*/
let center: Cartesian3
/**
* The vertex data, including positions, texture coordinates, and heights.
* The vertex data is in the order [X, Y, Z, H, U, V], where X, Y, and Z represent
* the Cartesian position of the vertex, H is the height above the ellipsoid, and
* U and V are the texture coordinates. The vertex data may have additional attributes after those
* mentioned above when the {@link TerrainMesh#stride} is greater than 6.
* @type {Float32Array}
*/
let vertices: [Float]
/**
* @param {Uint16Array|Uint32Array} indices The indices describing how the vertices are connected to form triangles.
* @type {Uint16Array}
*/
let indices: [Int]
/**
* Index buffers (if any) generated from indices.
* @type {Dictionary<String, IndexBuffer>}
*/
var indexBuffer: Buffer? = nil
/**
* The lowest height in the tile, in meters above the ellipsoid.
* @type {Number}
*/
let minimumHeight: Double
/**
* The highest height in the tile, in meters above the ellipsoid.
* @type {Number}
*/
let maximumHeight: Double
/**
* A bounding sphere that completely contains the tile.
* @type {BoundingSphere}
*/
let boundingSphere3D: BoundingSphere
/**
* The occludee point of the tile, represented in ellipsoid-
* scaled space, and used for horizon culling. If this point is below the horizon,
* the tile is considered to be entirely below the horizon.
* @type {Cartesian3}
*/
let occludeePointInScaledSpace: Cartesian3
/**
* The number of components in each vertex. Typically this is 6 for the 6 components
* [X, Y, Z, H, U, V], but if each vertex has additional data (such as a vertex normal), this value
* may be higher.
* @type {Number}
*/
let stride: Int
/**
* A bounding box that completely contains the tile.
* @type {OrientedBoundingBox}
*/
let orientedBoundingBox: OrientedBoundingBox?
/**
* Information for decoding the mesh vertices.
* @type {TerrainEncoding}
*/
let encoding: TerrainEncoding
/**
* The amount that this mesh was exaggerated.
* @type {Number}
*/
let exaggeration: Double
init (center: Cartesian3, vertices: [Float], indices: [Int], minimumHeight: Double, maximumHeight: Double, boundingSphere3D: BoundingSphere, occludeePointInScaledSpace: Cartesian3, vertexStride: Int = 6, orientedBoundingBox: OrientedBoundingBox?, encoding: TerrainEncoding, exaggeration: Double) {
self.center = center
self.vertices = vertices
self.indices = indices
self.minimumHeight = minimumHeight
self.maximumHeight = maximumHeight
self.boundingSphere3D = boundingSphere3D
self.occludeePointInScaledSpace = occludeePointInScaledSpace
self.stride = vertexStride
self.orientedBoundingBox = orientedBoundingBox
self.encoding = encoding
self.exaggeration = exaggeration
}
}
|
apache-2.0
|
40ea6c2239cd3f770030da0837854e86
| 37.21875 | 301 | 0.674162 | 4.375671 | false | false | false | false |
AaronMT/firefox-ios
|
Extensions/Today/ButtonWithSublabel.swift
|
4
|
1772
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class ButtonWithSublabel: UIButton {
lazy var subtitleLabel = UILabel()
lazy var label = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init() {
self.init(frame: .zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
performLayout()
}
fileprivate func performLayout() {
let buttonImage = self.imageView!
self.titleLabel?.removeFromSuperview()
addSubview(self.label)
addSubview(self.subtitleLabel)
buttonImage.snp.makeConstraints { make in
make.centerY.left.equalTo(10)
make.width.equalTo(TodayUX.copyLinkImageWidth)
}
self.label.snp.makeConstraints { make in
make.left.equalTo(buttonImage.snp.right).offset(10)
make.trailing.top.equalTo(self)
make.height.greaterThanOrEqualTo(15)
}
self.label.numberOfLines = 1
self.label.lineBreakMode = .byWordWrapping
self.subtitleLabel.lineBreakMode = .byTruncatingTail
self.subtitleLabel.snp.makeConstraints { make in
make.bottom.equalTo(self).inset(10)
make.top.equalTo(self.label.snp.bottom).offset(3)
make.leading.trailing.equalTo(self.label)
make.height.greaterThanOrEqualTo(10)
}
}
override func setTitle(_ text: String?, for state: UIControl.State) {
self.label.text = text
super.setTitle(text, for: state)
}
}
|
mpl-2.0
|
8d2c4c2ef39c9f939edc2615b7a6b5a7
| 30.642857 | 73 | 0.639391 | 4.386139 | false | false | false | false |
nutiteq/hellomap3d-ios
|
hellomap3swift/hellomap3swift/MyMapViewController.swift
|
1
|
4158
|
import UIKit
import GLKit
// NOTE: NTMapView is imported through 'bridging header' (hellomap3swift-Bridging-Header.h)
class MyMapViewController: GLKViewController {
override func loadView() {
// The initial step: register your license.
// You can get your free/commercial license from: http://developer.nutiteq.com
// The license string used here is intended only for Nutiteq demos and WILL NOT WORK with other apps!
NTMapView.registerLicense("XTUN3Q0ZBd2NtcmFxbUJtT1h4QnlIZ2F2ZXR0Mi9TY2JBaFJoZDNtTjUvSjJLay9aNUdSVjdnMnJwVXduQnc9PQoKcHJvZHVjdHM9c2RrLWlvcy0zLiosc2RrLWFuZHJvaWQtMy4qCnBhY2thZ2VOYW1lPWNvbS5udXRpdGVxLioKYnVuZGxlSWRlbnRpZmllcj1jb20ubnV0aXRlcS4qCndhdGVybWFyaz1ldmFsdWF0aW9uCnVzZXJLZXk9MTVjZDkxMzEwNzJkNmRmNjhiOGE1NGZlZGE1YjA0OTYK")
super.loadView();
}
override func viewDidLoad() {
super.viewDidLoad()
// GLKViewController-specific parameters for smoother animations
resumeOnDidBecomeActive = false
preferredFramesPerSecond = 60
let mapView = view as! NTMapView
// Set the base projection, that will be used for most MapView, MapEventListener and Options methods
let proj = NTEPSG3857()
mapView.getOptions().setBaseProjection(proj) // EPSG3857 is actually the default base projection, so this is actually not needed
// General options
mapView.getOptions().setRotatable(true) // make map rotatable (this is actually the default)
mapView.getOptions().setTileThreadPoolSize(2) // use 2 threads to download tiles
// Set initial location and other parameters, don't animate
mapView.setFocusPos(proj.fromWgs84(NTMapPos(x:24.650415, y:59.428773)), durationSeconds:0)
mapView.setZoom(14, durationSeconds:0)
mapView.setRotation(0, durationSeconds:0)
// Create online vector tile layer, use style asset embedded in the project
let vectorTileLayer = NTNutiteqOnlineVectorTileLayer(styleAssetName:"nutibright-v3.zip")
// Add vector tile layer
mapView.getLayers().add(vectorTileLayer)
// Load bitmaps for custom markers
let markerImage = UIImage(named:"marker.png")
let markerBitmap = NTBitmapUtils.createBitmapFromUIImage(markerImage)
// Create a marker style, use it for both markers, because they should look the same
let markerStyleBuilder = NTMarkerStyleBuilder()
markerStyleBuilder.setBitmap(markerBitmap)
markerStyleBuilder.setSize(30)
let sharedMarkerStyle = markerStyleBuilder.buildStyle()
// Initialize a local vector data source
let vectorDataSource = NTLocalVectorDataSource(projection:proj)
// Create marker, add it to the data source
let pos = proj.fromWgs84(NTMapPos(x:24.646469, y:59.426939)) // Tallinn
let marker = NTMarker(pos:pos, style:sharedMarkerStyle)
vectorDataSource.add(marker)
// Create line with positions and style, add to data source
let pos1 = proj.fromWgs84(NTMapPos(x:24.646469, y:59.426939)) // Tallinn
let pos2 = proj.fromWgs84(NTMapPos(x:0, y:51.426939)) // London
let posArray = NTMapPosVector();
posArray.add(pos1);
posArray.add(pos2);
let lineStyleBuilder = NTLineStyleBuilder()
lineStyleBuilder.setColor(NTColor(r: 0xff, g: 0x00, b: 0x00, a: 0xff))
lineStyleBuilder.setWidth(1.0);
let line = NTLine(poses: posArray, style: lineStyleBuilder.buildStyle())
vectorDataSource.add(line)
// Initialize a vector layer with the previous data source
let vectorLayer = NTVectorLayer(dataSource:vectorDataSource)
// Add the previous vector layer to the map
mapView.getLayers().add(vectorLayer)
let listener = MapListener(mapView_:mapView)
mapView.setMapEventListener(listener)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
// GLKViewController-specific, do on-demand rendering instead of constant redrawing
// This is VERY IMPORTANT as it stops battery drain when nothing changes on the screen!
paused = true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
bsd-2-clause
|
0c7978722f1f70b38e1499badadf6384
| 39.764706 | 334 | 0.744829 | 3.634615 | false | false | false | false |
luispadron/GradePoint
|
GradePoint/Models/Main/Assignment.swift
|
1
|
1456
|
//
// Assignment.swift
// GradePoint
//
// Created by Luis Padron on 12/5/16.
// Copyright © 2016 Luis Padron. All rights reserved.
//
import Foundation
import RealmSwift
class Assignment: Object {
// MARK: - Properties
@objc dynamic var id = UUID().uuidString
@objc dynamic var name = ""
@objc dynamic var date = Date()
@objc dynamic var score: Double = 0.0
@objc dynamic var rubric: Rubric?
// Score of points when using point based class system
@objc dynamic var pointsScore: Double = 0.0
@objc dynamic var totalPointsScore: Double = 0.0
@objc dynamic var isDeleted: Bool = false
let parentClass = LinkingObjects(fromType: Class.self, property: "assignments")
// MARK: - Initializers
/// Creates a new Assignment for a weighted class
convenience init(name: String, date: Date, score: Double, associatedRubric: Rubric) {
self.init()
self.name = name
self.date = date
self.score = score
self.rubric = associatedRubric
}
// MARK: - Overrides
override class func primaryKey() -> String? {
return "id"
}
/// Returns the percentage of the assignment, takes into account the type of assignment (weighted/point)
public var percentage: Double {
if totalPointsScore == 0 {
return score
} else {
return (pointsScore / totalPointsScore) * 100
}
}
}
|
apache-2.0
|
b774d9238cab0e24020e5920e23d6a75
| 25.944444 | 108 | 0.628866 | 4.343284 | false | false | false | false |
tgsala/HackingWithSwift
|
project02/project02/ViewController.swift
|
1
|
2235
|
//
// ViewController.swift
// project02
//
// Created by g5 on 3/2/16.
// Copyright © 2016 tgsala. All rights reserved.
//
import UIKit
import GameplayKit
class ViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
var countries = [String]()
var score = 0
var correctAnswer = 0
override func viewDidLoad() {
super.viewDidLoad()
countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria",
"poland", "russia", "spain", "uk", "us"]
button1.layer.borderWidth = 1
button2.layer.borderWidth = 1
button3.layer.borderWidth = 1
button1.layer.borderColor = UIColor.lightGrayColor().CGColor
button2.layer.borderColor = UIColor.lightGrayColor().CGColor
button3.layer.borderColor = UIColor.lightGrayColor().CGColor
askQuestion()
}
func askQuestion(action: UIAlertAction! = nil) {
countries = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(countries) as! [String]
correctAnswer = GKRandomSource.sharedRandom().nextIntWithUpperBound(3)
button1.setImage(UIImage(named: countries[0]), forState: .Normal)
button2.setImage(UIImage(named: countries[1]), forState: .Normal)
button3.setImage(UIImage(named: countries[2]), forState: .Normal)
title = countries[correctAnswer].uppercaseString
}
@IBAction func buttonTapped(sender: UIButton) {
var title: String
if sender.tag == correctAnswer {
title = "Correct"
score += 1
} else {
title = "Wrong"
score -= 1
}
let ac = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "Continue", style: .Default, handler: askQuestion))
presentViewController(ac, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
unlicense
|
9bc8e347e4cd62916e9b381e73bd2df8
| 31.376812 | 108 | 0.63026 | 4.625259 | false | false | false | false |
guumeyer/MarveListHeroes
|
MarvelHeroes/Extensions/UIAlertController+Extension.swift
|
1
|
1147
|
//
// UIAlertController.swift
// MarvelHeroes
//
// Created by gustavo r meyer on 8/13/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import UIKit
extension UIAlertController {
public class func showAlert(title: String? = nil, message: String? = nil, inViewController viewController: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(defaultAction)
viewController.present(alert, animated: true, completion: nil)
}
public class func showWarning(message: String? = nil, inViewController viewController: UIViewController) {
UIAlertController.showAlert(title: NSLocalizedString("Alert", comment: ""),message:message, inViewController: viewController)
}
public class func showError(message: String? = nil, inViewController viewController: UIViewController) {
UIAlertController.showAlert(title: NSLocalizedString("Error", comment: ""),message:message, inViewController: viewController)
}
}
|
apache-2.0
|
dfe94554a36f3aba999bf436dbbff71a
| 39.928571 | 133 | 0.723386 | 4.794979 | false | false | false | false |
prebid/prebid-mobile-ios
|
PrebidMobile/ImageHelper.swift
|
1
|
2172
|
/* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
public class ImageHelper {
public static func downloadImageSync(_ urlString: String) -> Result<UIImage, Error> {
guard let url = URL(string: urlString) else {
return .failure(PBMError.init(message: "Image URL is invalid"))
}
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
return .success(image)
} else {
return .failure(PBMError.init(message: "Error while creating UIImage from received data"))
}
} else {
return .failure(PBMError.init(message: "Error while receiving data by url"))
}
}
public static func downloadImageAsync(_ urlString: String, completion: @escaping(Result<UIImage, Error>) -> Void) {
guard let url = URL(string: urlString) else {
completion(.failure(PBMError.init(message: "Image URL is invalid")))
return
}
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url) {
DispatchQueue.main.async {
if let image = UIImage(data:data) {
completion(.success(image))
} else {
return completion(.failure(PBMError.init(message: "Error while creating UIImage from received data")))
}
}
} else {
return completion(.failure(PBMError.init(message: "Error while receiving data by url")))
}
}
}
}
|
apache-2.0
|
24eb85fdd4bde5b8ec2ba432468a4f7e
| 39.018519 | 126 | 0.602962 | 4.677489 | false | false | false | false |
tectijuana/iOS
|
VargasJuan/Demo-MVC/Demo MVC/DBUtil.swift
|
2
|
2969
|
//
// DBUtil.swift
// Demo MVC
//
// Created by isc on 11/29/16.
// Copyright © 2016 isc. All rights reserved.
//
import SQLite
class DBUtil {
static let instance = DBUtil()
private var db: Connection?
private let dbFileName = "test"
private let users = Table("users")
private let id = Expression<Int64>("id")
private let first_name = Expression<String?>("first_name")
private let last_name = Expression<String>("last_name")
private let email = Expression<String>("email")
private let votes = Expression<Int64>("votes")
private init() {
if !openExistingDatabase() {
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
do {
db = try Connection("\(path)/\(dbFileName).sqlite3")
} catch {
db = nil
print("Unable to open database")
}
}
createTable()
}
func openExistingDatabase() -> Bool {
let dbPath = Bundle.main.path(forResource: dbFileName, ofType: "sqlite3")!
print("Data base directory: \(dbPath)")
do {
db = try Connection(dbPath)
return true
} catch {
db = nil
print("Unable to open preloaded database")
return false
}
}
func createTable() {
do {
try db!.run(users.create(ifNotExists: true) { table in
table.column(id, primaryKey: true)
table.column(first_name)
table.column(last_name)
table.column(email)
table.column(votes)
})
} catch {
print("Unable to create table")
}
}
func addUser(ufirst_name: String, ulast_name: String, uemail: String) -> Int64? {
do {
let insert = users.insert(
first_name <- ufirst_name,
last_name <- ulast_name,
email <- uemail,
votes <- 0
)
let id = try db!.run(insert)
return id
} catch {
print ("Insert failed")
return -1
}
}
func getUsers() -> [User] {
var users = [User]()
do {
for user in try db!.prepare(self.users) {
users.append(User(
id: user[id],
first_name: user[first_name]!,
last_name: user[last_name],
email: user[email],
votes: user[votes]))
}
} catch {
print("Select failed")
}
return users
}
func deleteUser(uid: Int64) -> Bool {
do {
let user = users.filter(id == uid)
try db!.run(user.delete())
return true
} catch {
print("Delete failed")
}
return false
}
func updateUser(uid: Int64, newUser: User) -> Bool {
let user = users.filter(id == uid)
do {
let update = user.update([
first_name <- newUser.first_name,
last_name <- newUser.last_name,
email <- newUser.email,
votes <- newUser.votes
])
if try db!.run(update) > 0 {
return true
}
} catch {
print("Update failed: \(error)")
}
return false
}
}
|
mit
|
a9e11c94114d6732a937ba3f01abe603
| 20.985185 | 83 | 0.564353 | 3.854545 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity
|
EnjoyUniversity/EnjoyUniversity/Classes/View/Activity/EUActivityViewController.swift
|
1
|
14796
|
//
// ActivityViewController.swift
// EnjoyUniversity
//
// Created by lip on 17/3/31.
// Copyright © 2017年 lip. All rights reserved.
//
import Foundation
import UIKit
import Kingfisher
/// 我参加的活动
class EUActivityViewController: EUBaseAvtivityViewController {
// 分享按钮
var shareBtn = UIButton()
// 收藏按钮
var collectBtn = UIButton()
// 发起者昵称
let nicknamelabel = UILabel(frame: CGRect(x: 72, y: 20, width: 200, height: 15))
// 主办者标签背景
let sponsorShadowView = UIView()
// 发起者节操值
let reputationlabel = UILabel(frame: CGRect(x: 72, y: 41, width: 200, height: 10))
// 发起者头像
let headimg = UIImageView(frame: CGRect(x: 10, y: 10, width: 50, height: 50))
// 参加活动按钮
let participateButton = UIButton(frame: CGRect(x: 12, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width - 24, height: 44))
/// 参与者数据源
lazy var participatorslist = UserInfoListViewModel()
/// 活动视图模型列表
var activitylistviewmodel:ActivityListViewModel?
/// 这是第几个,用于删除
var row:Int = 0
/// 是否直接 pop 回根控制器,用于二维码跳转
var shouldPopToRootViewController:Bool = false
/// ViewModel 数据源
var viewmodel:ActivityViewModel?{
didSet{
titleLabel.text = viewmodel?.activitymodel.avTitle ?? "标题加载失败"
placeLabel.text = viewmodel?.activitymodel.avPlace
timeLabel.text = viewmodel?.allTime
priceLabel.text = viewmodel?.price
detailLabel.text = viewmodel?.activitymodel.avDetail ?? "详情加载失败"
detailHeight = viewmodel?.detailHeight ?? 0.0
warnLabel.text = viewmodel?.needRegister
registerCode = viewmodel?.activitymodel.avRegister ?? 0
if EUNetworkManager.shared.userAccount.uid == (viewmodel?.activitymodel.uid ?? 0) && activityStatus == 0{
activityStatus = 2
}
let url = URL(string: viewmodel?.imageURL ?? "")
backgroudImage.kf.setImage(with: url,
placeholder: UIImage(named: "tempbackground"),
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
}
}
/// 活动状态 0默认 1我参加的 2我创建的
var activityStatus:Int = 0{
didSet{
if activityStatus == 2{
participateButton.setTitle("无法参加自己创建的活动", for: .normal)
participateButton.backgroundColor = UIColor.lightGray
participateButton.isEnabled = false
}else if activityStatus == 1 {
participateButton.setTitle("退出活动", for: .normal)
participateButton.backgroundColor = UIColor.red
}
}
}
/// 签到码
var registerCode = 0{
didSet{
if activityStatus == 1 && registerCode > 999{
participateButton.setTitle("我要签到", for: .normal)
participateButton.backgroundColor = UIColor.init(red: 46/255, green: 183/255, blue: 144/255, alpha: 1)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadData()
setupNavUI()
setupLeaderInfoUI()
setupParticipateButton()
}
private func loadData(){
guard let uid = viewmodel?.activitymodel.uid,let avid = viewmodel?.activitymodel.avid else {
return
}
EUNetworkManager.shared.getUserInfomation(uid: uid) { (isSuccess, dict) in
if !isSuccess{
SwiftyProgressHUD.showFaildHUD(text: "网络错误", duration: 1)
}
guard let dict = dict else{
return
}
let name = dict["name"] as? String
let reputation = (dict["reputation"] as? Int) ?? 100
let avaterurl = dict["avatar"] as? String
self.nicknamelabel.text = name
self.nicknamelabel.sizeToFit()
self.sponsorShadowView.frame.origin.x = self.nicknamelabel.frame.maxX + 5
self.reputationlabel.text = "节操值 \(reputation)"
self.headimg.kf.setImage(with: URL(string: PICTURESERVERADDRESS + "/user/user" + (avaterurl ?? "") + ".jpg"),
placeholder: UIImage(named: "av_leader"),
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
}
participatorslist.loadActivityMemberInfoList(avid: avid) { (isSuccess,hasMember) in
if !isSuccess{
self.participatornumLabel.text = "列表加载失败,请检查网络设置"
return
}
if !hasMember{
self.participatornumLabel.text = "还没有小伙伴报名参加~"
return
}
self.participatornumLabel.text = "已报名\(self.participatorslist.activityParticipatorList.count)人/" + (self.viewmodel?.expectPeople ?? "人数不限")
}
}
}
// MARK: - UI 相关方法
extension EUActivityViewController{
fileprivate func setupNavUI(){
// 分享按钮
let shareshadow = UIImageView(frame: CGRect(x: UIScreen.main.bounds.width - 94, y: 30, width: 30, height: 30))
shareshadow.image = UIImage(named: "nav_background")
shareshadow.alpha = 0.7
view.addSubview(shareshadow)
shareBtn.setImage(UIImage(named: "nav_share"), for: .normal)
shareBtn.frame = CGRect(x: 3, y: 3, width: 24, height: 24)
shareshadow.isUserInteractionEnabled = true
shareshadow.addSubview(shareBtn)
shareBtn.addTarget(nil, action: #selector(shareButtonIsClicked), for: .touchUpInside)
// 收藏按钮
let collectshadow = UIImageView(frame: CGRect(x: UIScreen.main.bounds.width - 50, y: 30, width: 30, height: 30))
collectshadow.image = UIImage(named: "nav_background")
collectshadow.alpha = 0.7
collectshadow.isUserInteractionEnabled = true
view.addSubview(collectshadow)
collectBtn.setImage(UIImage(named: "nav_collect"), for: .normal)
collectBtn.frame = CGRect(x: 3, y: 3, width: 24, height: 24)
collectBtn.addTarget(nil, action: #selector(collectButtonIsClicked), for: .touchUpInside)
collectshadow.addSubview(collectBtn)
}
fileprivate func setupLeaderInfoUI(){
/// 发起者视图
let leaderView = UIView(frame: CGRect(x: 5, y: 190, width: UIScreen.main.bounds.width - 10, height: 70))
leaderView.backgroundColor = UIColor.white
scrollView.addSubview(leaderView)
headimg.image = UIImage(named: "av_leader")
headimg.layer.cornerRadius = 25
headimg.layer.masksToBounds = true
leaderView.addSubview(headimg)
nicknamelabel.text = "假诗人"
nicknamelabel.font = UIFont.boldSystemFont(ofSize: 15)
nicknamelabel.sizeToFit()
nicknamelabel.textColor = UIColor.black
leaderView.addSubview(nicknamelabel)
reputationlabel.text = "节操值 100"
reputationlabel.textColor = UIColor.lightGray
reputationlabel.font = UIFont.boldSystemFont(ofSize: 10)
leaderView.addSubview(reputationlabel)
sponsorShadowView.frame = CGRect(x: 72 + nicknamelabel.frame.width + 5, y: 20, width: 37, height: 15)
sponsorShadowView.center.y = nicknamelabel.center.y
sponsorShadowView.backgroundColor = UIColor.init(red: 214/255, green: 241/255, blue: 1, alpha: 1)
leaderView.addSubview(sponsorShadowView)
let leaderlabel = UILabel(frame: CGRect(x: 0, y: 0, width: 37, height: 15))
leaderlabel.text = "主办者"
leaderlabel.textColor = UIColor.init(red: 14/255, green: 36/255, blue: 48/255, alpha: 1)
leaderlabel.font = UIFont.boldSystemFont(ofSize: 10)
leaderlabel.textAlignment = .center
sponsorShadowView.addSubview(leaderlabel)
let phonebtn = UIButton(frame: CGRect(x: leaderView.frame.width - 60, y: 10, width: 50, height: 50))
phonebtn.setImage(UIImage(named: "av_call"), for: .normal)
leaderView.addSubview(phonebtn)
phonebtn.addTarget(nil, action: #selector(callButtonIsClicked), for: .touchUpInside)
}
fileprivate func setupParticipateButton(){
if activityStatus == 0{
participateButton.backgroundColor = UIColor.orange
participateButton.setTitle("我要参加", for: .normal)
}
participateButton.addTarget(nil, action: #selector(participateActivity), for: .touchUpInside)
view.addSubview(participateButton)
}
}
// MARK: - 监听方法集合
extension EUActivityViewController{
/// 打电话按钮
@objc fileprivate func callButtonIsClicked(){
guard let phone = viewmodel?.activitymodel.uid else{
return
}
UIApplication.shared.open(URL(string: "telprompt://\(phone)")!, options: [:], completionHandler: nil)
}
/// 分享活动
@objc fileprivate func shareButtonIsClicked(){
shareImageAndText(sharetitle: "分享活动:" + (viewmodel?.activitymodel.avTitle ?? ""),
sharedetail: viewmodel?.activitymodel.avDetail ?? "",
url: "http://www.euswag.com?avid=\(viewmodel?.activitymodel.avid ?? 0)",
image: backgroudImage.image,
currentViewController: self)
}
/// 收藏
@objc fileprivate func collectButtonIsClicked(){
guard let avid = viewmodel?.activitymodel.avid else{
return
}
SwiftyProgressHUD.showLoadingHUD()
EUNetworkManager.shared.collectActivity(avid: avid) { (requestIsSuccess, collectIsSuccess) in
SwiftyProgressHUD.hide()
if !requestIsSuccess{
SwiftyProgressHUD.showFaildHUD(text: "网络错误", duration: 1)
return
}
if !collectIsSuccess{
SwiftyProgressHUD.showFaildHUD(text: "收藏过啦", duration: 1)
return
}
SwiftyProgressHUD.showSuccessHUD(duration: 1)
}
}
/// 查看已报名列表
@objc fileprivate func showListOfParticipators(){
}
/// 参加活动
@objc fileprivate func participateActivity(){
guard let avid = viewmodel?.activitymodel.avid else {
return
}
// activityStatus 0默认 1我参加的 2我创建的
if activityStatus == 0 {
let nowdate = Date().timeIntervalSince1970 * 1000
let enroll = Double(viewmodel?.activitymodel.avEnrolldeadline ?? "") ?? 0
// 活动已经开始签到或者报名截止
if registerCode > 1000 || nowdate > enroll{
SwiftyProgressHUD.showFaildHUD(text: "报名已截止", duration: 1)
return
}
// 参加活动
SwiftyProgressHUD.showLoadingHUD()
EUNetworkManager.shared.participateActivity(avid: avid,needregist:viewmodel?.needRegisterBool ?? false) { (isSuccess, isParticiateSuccess) in
SwiftyProgressHUD.hide()
if !isSuccess{
SwiftyProgressHUD.showFaildHUD(text: "网络错误", duration: 1)
return
}
if !isParticiateSuccess{
SwiftyProgressHUD.showFaildHUD(text: "您已参加", duration: 1)
return
}
SwiftyProgressHUD.showSuccessHUD(duration: 1)
}
}else if activityStatus == 1 && registerCode < 1000{
let altervc = UIAlertController(title: "退出活动", message: "您确定要退出当前活动吗?", preferredStyle: .alert)
let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let confirm = UIAlertAction(title: "确定", style: .destructive, handler: { (_) in
// 退出活动
SwiftyProgressHUD.showLoadingHUD()
EUNetworkManager.shared.leaveActivity(avid: avid, completion: { (isSuccess, isQuitSuccess) in
SwiftyProgressHUD.hide()
if !isSuccess{
SwiftyProgressHUD.showFaildHUD(text: "网络错误", duration: 1)
return
}
if !isQuitSuccess{
SwiftyProgressHUD.showFaildHUD(text: "已退出", duration: 1)
return
}
SwiftyProgressHUD.showSuccessHUD(duration: 1)
self.activitylistviewmodel?.participatedlist.remove(at: self.row)
_ = self.navigationController?.popViewController(animated: true)
})
})
altervc.addAction(cancel)
altervc.addAction(confirm)
present(altervc, animated: true, completion: nil)
}else if activityStatus == 1 && registerCode > 999{
let vc = EURegisterViewController()
vc.registerCode = registerCode
vc.avid = avid
navigationController?.pushViewController(vc, animated: true)
}
}
/// 返回按钮
override func backButtonIsClicked() {
if shouldPopToRootViewController{
_ = navigationController?.popToRootViewController(animated: true)
}else{
_ = navigationController?.popViewController(animated: true)
}
}
}
|
mit
|
4b5c39b9efd69b1b337831fc09d15783
| 33.769042 | 153 | 0.556074 | 4.849554 | false | false | false | false |
mateuscampos/brejas
|
Brejas/BrejasTests/BillListControllerSpec.swift
|
1
|
2332
|
//
// ErrorResultSpec.swift
// Brejas
//
// Created by Mateus Campos on 02/07/17.
// Copyright © 2017 Mateus Campos. All rights reserved.
//
import Quick
import Nimble
import ObjectMapper
@testable import Brejas
class BillListControllerSpec: QuickSpec {
class MockBeerListController: BeersListController {
var methodCalled = false
override func viewDidLoad() {
super.viewDidLoad()
methodCalled = true
}
override func didSelectedBeer(beer: BeerModel) {
super.didSelectedBeer(beer: beer)
methodCalled = true
}
}
override func spec() {
describe("the BeersListController init") {
let controller = MockBeerListController()
beforeEach {
controller.methodCalled = false
}
it("has life cycle") {
_ = controller.view
expect(controller.methodCalled).to(beTruthy())
}
it("should update layout") {
let controller = BeersListController()
let jsonData = JsonHelper.sharedInstance.jsonDataFromFile(BeersCollectionViewDataSourceDelegateSpec.self, name: "ResponseMock")
let jsonString = String(data: jsonData, encoding: .utf8)
let beers = Mapper<BeerModel>().mapArray(JSONString: jsonString!)!
controller.updateScreen(withBeers: beers)
expect(controller.beersList.count).to(equal(beers.count))
}
it("should call detail") {
let jsonData = JsonHelper.sharedInstance.jsonDataFromFile(BeerModelSpec.self, name: "BeerMock")
let jsonString = String(data: jsonData, encoding: .utf8)
let object: BeerModel = Mapper<BeerModel>().map(JSONString: jsonString!)!
let controller = MockBeerListController()
controller.didSelectedBeer(beer: object)
expect(controller.methodCalled).to(beTruthy())
}
}
}
}
|
mit
|
15462ce773d884f5255a8965175cc6f5
| 28.1375 | 143 | 0.528958 | 5.616867 | false | false | false | false |
jindulys/EbloVaporServer
|
Sources/App/Models/CompanySource/CompanySource.swift
|
1
|
1108
|
//
// CompanySource.swift
// EbloVaporServer
//
// Created by yansong li on 2017-06-05.
//
//
import Foundation
import Vapor
/// Company source object.
public final class CompanySource: Model {
public var id: Node?
public var exists: Bool = false
/// The company data url string.
public var companyDataURLString: String
public init(node: Node, in context: Context) throws {
id = try node.extract("id")
companyDataURLString = try node.extract("companydataurlstring")
}
public init(companyDataURLString: String) {
self.companyDataURLString = companyDataURLString
self.id = nil
}
public func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id" : id,
"companydataurlstring" : companyDataURLString])
}
public static func prepare(_ database: Database) throws {
try database.create("companysources", closure: { companys in
companys.id()
companys.string("companydataurlstring")
})
}
public static func revert(_ database: Database) throws {
try database.delete("companysources")
}
}
|
mit
|
6f4dde13e075aa143b76709a455e7689
| 22.083333 | 67 | 0.680505 | 4.014493 | false | false | false | false |
codercd/xmppChat
|
Chat/Classes/Me/MeTableViewController.swift
|
1
|
3245
|
//
// MeTableViewController.swift
// Chat
//
// Created by LiChendi on 16/3/23.
// Copyright © 2016年 lcd. All rights reserved.
//
import UIKit
let group1 = [""]
class MeTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
9fce0164d1ff66550ac2e63e158eaf0b
| 32.081633 | 157 | 0.684762 | 5.54188 | false | false | false | false |
ChrisMash/Fieldbook-SwiftSDK
|
Example/Fieldbook-SwiftSDK/AddEditViewController.swift
|
1
|
5520
|
//
// AddEditViewController.swift
// Fieldbook-SwiftSDK
//
// Created by Chris Mash on 22/02/2016.
// Copyright © 2016 Chris Mash. All rights reserved.
//
import UIKit
import Fieldbook_SwiftSDK
protocol AddEditViewControllerDelegate
{
func addEditViewControllerAddedItem( item: NSDictionary )
func addEditViewControllerUpdatedItem( item: NSDictionary )
}
class AddEditViewController: UIViewController
{
@IBOutlet weak var savingIndicator : UIActivityIndicatorView?
@IBOutlet weak var col1TextField : UITextField?
@IBOutlet weak var col2TextField : UITextField?
@IBOutlet weak var col3TextField : UITextField?
@IBOutlet weak var addButton : UIButton?
var item : NSDictionary?
var delegate : AddEditViewControllerDelegate?
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
savingIndicator?.hidden = true
if let unwrappedItem = item
{
self.title = "Edit Item"
addButton?.setTitle( self.title, forState: .Normal )
col1TextField?.text = "\(unwrappedItem[ "col_1" ]!)"
col2TextField?.text = "\(unwrappedItem[ "col_2" ]!)"
col3TextField?.text = "\(unwrappedItem[ "col_3" ]!)"
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func preferredStatusBarStyle() -> UIStatusBarStyle
{
return .LightContent
}
private func onError( error: NSError )
{
savingIndicator?.stopAnimating()
savingIndicator?.hidden = true
addButton?.enabled = true
col1TextField?.enabled = true
col2TextField?.enabled = true
col3TextField?.enabled = true
Utility.displayAlert( "Error", message: error.localizedDescription, viewController: self )
}
// MARK: IBAction methods
@IBAction func addButtonPressed( button: UIButton? )
{
let col1 = col1TextField?.text as String?
let col2 = col2TextField?.text as String?
let col3 = col3TextField?.text as String?
// Validate the input first
if let unwrappedCol1 = col1,
let unwrappedCol2 = col2,
let unwrappedCol3 = col3
{
if unwrappedCol1.characters.count == 0
{
Utility.displayAlert( "Error", message: "Please enter a value for Col 1", viewController: self )
return
}
else if unwrappedCol2.characters.count == 0
{
Utility.displayAlert( "Error", message: "Please enter a value for Col 2", viewController: self )
return
}
else if unwrappedCol3.characters.count == 0
{
Utility.displayAlert( "Error", message: "Please enter a value for Col 3", viewController: self )
return
}
savingIndicator?.hidden = false
savingIndicator?.startAnimating()
addButton?.enabled = false
col1TextField?.enabled = false
col2TextField?.enabled = false
col3TextField?.enabled = false
let dict = NSDictionary( dictionary: [ "col_1" : unwrappedCol1, "col_2" : unwrappedCol2, "col_3" : unwrappedCol3 ] )
// If we've got an item referenced then we're intending to update it
if let unwrappedItem = item
{
// Send Fieldbook the updated info
FieldbookSDK.updateItem( Constants.fieldbookPath(), id: unwrappedItem[ "id" ]! as! NSNumber, item: dict ) {
(updatedItem, error) -> Void in
if let unwrappedError = error
{
self.onError( unwrappedError )
}
else
{
// Success! Let the delegate know
if let unwrappedDelegate = self.delegate,
let unwrappedItem = updatedItem
{
unwrappedDelegate.addEditViewControllerUpdatedItem( unwrappedItem )
}
}
}
}
else
{
// Send the new item's info to Fieldbook
FieldbookSDK.addToList( Constants.fieldbookPath(), item: dict ) {
(newItem, error) -> Void in
if let unwrappedError = error
{
self.onError( unwrappedError )
}
else
{
// Success! Let the delegate know
if let unwrappedDelegate = self.delegate,
let unwrappedItem = newItem
{
unwrappedDelegate.addEditViewControllerAddedItem( unwrappedItem )
}
}
}
}
}
else
{
Utility.displayAlert( "Error", message: "Please enter the full set of information for the item", viewController: self )
}
}
}
|
mit
|
144607696d2a3932126a338eea9b4ab5
| 33.49375 | 131 | 0.527994 | 5.563508 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.