repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
noppoMan/SwiftKnex | Sources/SwiftKnex/QueryBuilder/QueryBuilder.swift | 1 | 5042 | //
// QueryBuilder.swift
// SwiftKnex
//
// Created by Yuki Takei on 2017/01/14.
//
//
func insertSpace(_ str: String) -> String {
if str.isEmpty {
return ""
}
return " " + str
}
public enum QueryBuilderError: Error {
case tableIsNotSet
case unimplementedStatement(QueryType)
case emptyValues
}
public enum QueryType {
case select
case delete
case update([String: Any])
case updateRaw(query: String, params: [Any]) // query
case insert([String: Any])
case batchInsert([[String: Any]])
case forUpdate([String: Any])
}
public protocol QueryBuildable {
func build() throws -> (String, [Any])
}
public final class QueryBuilder {
var table: Table?
var condistions = [ConditionConnector]()
var limit: Limit?
var orders = [OrderBy]()
var group: GroupBy?
var having: Having?
var joins = [Join]()
var selectFields = [Field]()
public init(){}
@discardableResult
public func table(_ t: Table) -> Self {
self.table = t
return self
}
@discardableResult
public func table(_ name: String) -> Self {
self.table = Table(name)
return self
}
@discardableResult
public func table(_ qb: QueryBuilder) -> Self {
self.table = Table(qb)
return self
}
@discardableResult
public func select(_ fields: [Field]) -> Self {
self.selectFields = fields
return self
}
@discardableResult
public func select(_ fields: Field...) -> Self {
select(fields)
return self
}
@discardableResult
public func `where`(_ filter: ConditionalFilter) -> Self {
if condistions.count == 0 {
condistions.append(.where(filter))
} else {
condistions.append(.and(filter))
}
return self
}
@discardableResult
public func or(_ filter: ConditionalFilter) -> Self {
condistions.append(.or(filter))
return self
}
@discardableResult
public func join(_ table: String) -> Self {
joins.append(Join(table: table, type: .default))
return self
}
@discardableResult
public func leftJoin(_ table: String) -> Self {
joins.append(Join(table: table, type: .left))
return self
}
@discardableResult
public func rightJoin(_ table: String) -> Self {
joins.append(Join(table: table, type: .right))
return self
}
@discardableResult
public func innerJoin(_ table: String) -> Self {
joins.append(Join(table: table, type: .inner))
return self
}
@discardableResult
public func on(_ filter: ConditionalFilter) -> Self {
joins.last?.conditions.append(filter)
return self
}
@discardableResult
public func limit(_ limit: Int) -> Self {
if let lim = self.limit {
self.limit = Limit(limit: limit, offset: lim.offset)
} else {
self.limit = Limit(limit: limit)
}
return self
}
@discardableResult
public func offset(_ offset: Int) -> Self {
if let lim = self.limit {
self.limit = Limit(limit: lim.limit, offset: offset)
}
return self
}
@discardableResult
public func order(by: String, sort: OrderSort = .asc) -> Self {
let order = OrderBy(field: by, sort: sort)
self.orders.append(order)
return self
}
@discardableResult
public func group(by name: String) -> Self {
group = GroupBy(name: name)
return self
}
@discardableResult
public func having(_ filter: ConditionalFilter) -> Self {
self.having = Having(condition: filter)
return self
}
public func build(_ type: QueryType) throws -> QueryBuildable {
switch type {
case .select:
return BasicQueryBuilder(type: .select, builder: self)
case .delete:
return BasicQueryBuilder(type: .delete, builder: self)
case .insert(let values):
guard let table = self.table else {
throw QueryBuilderError.tableIsNotSet
}
return InsertQueryBuilder(into: table, values: values)
case .batchInsert(let collection):
guard let table = self.table else {
throw QueryBuilderError.tableIsNotSet
}
return BatchInsertQueryBuilder(into: table, collection: collection)
case .update(let sets):
return UpdateQueryBuilder(builder: self, setValue: .dictionary(sets))
case .updateRaw(query: let query, params: let params):
return UpdateQueryBuilder(builder: self, setValue: .raw(query: query, params: params))
default:
throw QueryBuilderError.unimplementedStatement(type)
}
}
}
| mit | cb3e30e6a9e4c7214a80181147158dac | 24.336683 | 98 | 0.573979 | 4.638454 | false | false | false | false |
TOWNTHON/Antonym | iOS/Antonym/InputSpeech/InputSpeechViewController.swift | 1 | 6173 | //
// InputSpeechViewController.swift
// Antonym
//
// Created by 広瀬緑 on 2016/10/29.
// Copyright © 2016年 midori hirose. All rights reserved.
//
import UIKit
import Speech
import AVFoundation
//import SwiftDate
final class InputSpeechViewController: UIViewController {
// "ja-JP"を指定すると日本語になります。
private let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "ja-JP"))!
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private var recognitionTask: SFSpeechRecognitionTask?
private let audioEngine = AVAudioEngine()
private let talker = AVSpeechSynthesizer()
private var inputText = ""
@IBOutlet weak var label: UILabel!
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
speechRecognizer.delegate = self
button.isEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
requestRecognizerAuthorization()
}
@IBAction func tapStartButton(_ sender: UIButton) {
if audioEngine.isRunning {
audioEngine.stop()
recognitionRequest?.endAudio()
button.isEnabled = false
button.setTitle("停止中", for: .disabled)
let network = NetworkEngine()
network.getAsync(text: inputText)
} else {
try! startRecording()
button.setTitle("音声認識を中止", for: [])
}
}
private func requestRecognizerAuthorization() {
// 認証処理
SFSpeechRecognizer.requestAuthorization { authStatus in
// メインスレッドで処理したい内容のため、OperationQueue.main.addOperationを使う
OperationQueue.main.addOperation { [weak self] in
guard let `self` = self else { return }
switch authStatus {
case .authorized:
self.button.isEnabled = true
case .denied:
self.button.isEnabled = false
self.button.setTitle("音声認識へのアクセスが拒否されています。", for: .disabled)
case .restricted:
self.button.isEnabled = false
self.button.setTitle("この端末で音声認識はできません。", for: .disabled)
case .notDetermined:
self.button.isEnabled = false
self.button.setTitle("音声認識はまだ許可されていません。", for: .disabled)
}
}
}
}
private func startRecording() throws {
refreshTask()
let audioSession = AVAudioSession.sharedInstance()
// 録音用のカテゴリをセット
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") }
guard let recognitionRequest = recognitionRequest else { fatalError("Unable to created a SFSpeechAudioBufferRecognitionRequest object") }
// 録音が完了する前のリクエストを作るかどうかのフラグ。
// trueだと現在-1回目のリクエスト結果が返ってくる模様。falseだとボタンをオフにしたときに音声認識の結果が返ってくる設定。
recognitionRequest.shouldReportPartialResults = true
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { [weak self] result, error in
guard let `self` = self else { return }
var isFinal = false
if let result = result {
self.inputText = result.bestTranscription.formattedString
self.label.text = self.inputText
isFinal = result.isFinal
}
// エラーがある、もしくは最後の認識結果だった場合の処理
if error != nil || isFinal {
self.audioEngine.stop()
inputNode.removeTap(onBus: 0)
self.recognitionRequest = nil
self.recognitionTask = nil
self.button.isEnabled = true
self.button.setTitle("音声認識スタート", for: [])
}
}
// マイクから取得した音声バッファをリクエストに渡す
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
self.recognitionRequest?.append(buffer)
}
try startAudioEngine()
}
func changeView(sender:Timer) {
print("5秒後だよ")
}
private func refreshTask() {
if let recognitionTask = recognitionTask {
recognitionTask.cancel()
self.recognitionTask = nil
}
}
private func startAudioEngine() throws {
// startの前にリソースを確保しておく。
audioEngine.prepare()
try audioEngine.start()
label.text = "どうぞ喋ってください。"
}
}
extension InputSpeechViewController: SFSpeechRecognizerDelegate {
// 音声認識の可否が変更したときに呼ばれるdelegate
func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
if available {
button.isEnabled = true
button.setTitle("音声認識スタート", for: [])
} else {
button.isEnabled = false
button.setTitle("音声認識ストップ", for: .disabled)
}
}
}
| mit | 5f13b0331cc2a88295f4bddb09e26b11 | 32.90184 | 145 | 0.595729 | 5.088398 | false | false | false | false |
Jeffchiucp/Swift_PlayGrounds | 8-Functions.playground/Contents.swift | 1 | 5776 | import UIKit
/*:
# Functions
Programming is not powerful without functions. Functions are a block of code that perform a specific task. They are there to make code more organized, more readable, and more reusable. Let's dig in to see how it works!
*/
/*:
Here's how you declare a function with no parameters or return value.
*/
func doNothing() {
}
/*:
If you want to add a parameter, you guessed it - it goes within the parantheses.
Notice the parameter name comes first, followed by colon and type, just like normal variable declarations.
*/
func takesParam(name: String) {
}
/*:
Here's how you return a value back to the caller:
*/
func returnsSomething(name: String) -> String {
return name + "!"
}
/*:
Try commenting out the code within the function. What happens?
The compiler gives an error, becuase the function is telling the caller that it will return a String, but the function never actually used the "return" keyword to send something back. The compiler prevents this code from running because it would eventually crash your program!
*/
/*:
In order to take more than one parameter, you simply separate the inputs with a comma:
*/
func difference(num1: Int, num2: Int) -> Int {
return num1 - num2
}
/*:
Sometimes, you want a function to return more than one value back. However, in many programming languages, this is not possible and workaround strategies have been used. Well, no more! In Swift you can return multiple values back to the caller using tuples. A tuple is a data structure with a specific number of items as well as a specific sequence of those items. Let's look at a function that returns multiple items using a tuple.
In this function, we send in an array of integers as input, and expect 2 values to be returned. Notice the syntax: for the returned value, we have 2 items, first and last. They have their types declared, and they are wrapped inside parentheses. Furthermore, in order to return a tuple, the function simply wraps the items it wants to return inside parantheses.
*/
func firstLast(array: [Int]) -> (first: Int, last: Int) {
let firstItem = array[0]
let lastItem = array[array.count-1]
return (firstItem, lastItem)
}
/*:
Let's see how a caller can use this function to receive 2 values back from the function. We're going to call the `firstLast` function and put the returned value (the tuple) in a variable called `result`.
*/
var numbers = [10, 30, 13, 5, 9]
let result = firstLast(numbers)
/*:
There are a few ways you can retrieve values from the tuple returned from the function:
*/
/*:
The function had defined a name for each item in the tuple, so you could simply use those names to get the values:
*/
let val1 = result.first
/*:
Also, since the items in the tuple are in a specific sequence, they can be accessed by their index. Note that, just like arrays, the first item is at index 0 not 1.
*/
let val2 = result.0
/*:
There is a totally different way to get back the values as well. You can define your own tuple items, and they will be bound to the values returned by the function. In the line below, item1 is bound to the value of the first item returned by the function. Note that they do not need to have their types defined. Why? because Swift is smart enough to realize that you are calling firstLast function which returns 2 integers, so as a programmer, you obviously wanted item1 and item2 to be integers as well. Cool, huh?
*/
let (item1, item2) = firstLast(numbers)
print(item1)
print(item2)
/*:
All right, time to talk about an advanced topic: internal and external parameter names. Coming from another programming language, you probably have not heard about such a thing, but no worries, once you understand why it is needed, you will be using it everywhere in your code.
*/
/*:
Let's first discuss the syntax. As you can see below, first you define the external name, followed by the internal name. The body of the function only sees the internal name and not the external name. Similarly, a caller will only see the external name and not the internal name.
*/
func someFunc(externalName internalName: Int) -> Int {
return internalName + 10
}
/*:
When you define the external name for a parameter, you force the caller to use that name when they call the function:
*/
let res = someFunc(externalName: 40)
/*:
Try uncommenting the line below. What error do you get?
*/
//let res2 = someFunc(40)
/*:
Now, let's talk about why you would use external names. Look at the function below:
*/
func resize(width1: Int, height1: Int, width2: Int, height2: Int) {
}
/*:
Notice how this function is being called. The caller sends in 4 numbers, but it is confusing which number matches which parameter. This is how bugs are made! Imagine accidentally switching two of these numbers, and everything falls apart.
*/
resize(20, height1: 30, width2: 100, height2: 400)
/*:
This is where external names come in handy. You can force the caller to use the external names when calling the function to make it easier for them to see which value matches which parameter. Look at this modified version:
*/
func resize2(fromWidth width1: Int, fromHeight height1: Int, toWidth width2: Int, toHeight height2: Int) {
}
/*:
Look at how much more readable the line below is! If a programmer comes back later on to this code, she knows exactly what is happening. She does not have to go to look at the definition of the function to figure out what is happening on this line. Everything is explained right there in one line. It is obvious that the code is resizing (something) from width 20 to width 100 and from height 30 to height 400. This is all thanks to the power of internal/external parameter names!
*/
resize2(fromWidth: 20, fromHeight: 30, toWidth: 100, toHeight: 400)
| mit | de7bd08d0d41af50907db95092a345ef | 47.537815 | 515 | 0.753636 | 4.125714 | false | false | false | false |
liveminds/AERecord | AERecordExample/MasterViewController.swift | 4 | 4206 | //
// MasterViewController.swift
// AERecordExample
//
// Created by Marko Tadic on 11/3/14.
// Copyright (c) 2014 ae. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: CoreDataTableViewController, UISplitViewControllerDelegate {
private var collapseDetailViewController = true
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
splitViewController?.delegate = self
// setup row height
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
// setup buttons
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
// setup fetchedResultsController property
refreshFetchedResultsController()
}
// MARK: - CoreData
func insertNewObject(sender: AnyObject) {
// create object
Event.createWithAttributes(["timeStamp" : NSDate()])
AERecord.saveContextAndWait()
}
func refreshFetchedResultsController() {
let sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: true)]
let request = Event.createFetchRequest(sortDescriptors: sortDescriptors)
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: AERecord.defaultContext, sectionNameKeyPath: nil, cacheName: nil)
}
// MARK: - Table View
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
if let frc = fetchedResultsController {
if let event = frc.objectAtIndexPath(indexPath) as? Event {
// set data
cell.textLabel?.text = event.timeStamp.description
cell.accessoryType = event.selected ? .Checkmark : .None
// set highlight color
let highlightColorView = UIView()
highlightColorView.backgroundColor = yellow
cell.selectedBackgroundView = highlightColorView
cell.textLabel?.highlightedTextColor = UIColor.darkGrayColor()
}
}
}
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 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// delete object
if let event = fetchedResultsController?.objectAtIndexPath(indexPath) as? NSManagedObject {
event.delete()
AERecord.saveContext()
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// update value
if let frc = fetchedResultsController {
if let event = frc.objectAtIndexPath(indexPath) as? Event {
// deselect previous / select current
if let previous = Event.firstWithAttribute("selected", value: true) as? Event {
previous.selected = false
}
event.selected = true
AERecord.saveContextAndWait()
}
}
}
// MARK: - UISplitViewControllerDelegate
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController!, ontoPrimaryViewController primaryViewController: UIViewController!) -> Bool {
return collapseDetailViewController
}
}
| mit | 21f2c8e33a5eeb0f8e06ccb963d60c9d | 37.236364 | 226 | 0.662625 | 6.431193 | false | false | false | false |
6ag/BaoKanIOS | BaoKanIOS/Classes/Application/AppDelegate.swift | 1 | 15179 | //
// AppDelegate.swift
// BaoKanIOS
//
// Created by jianfeng on 15/12/20.
// Copyright © 2015年 六阿哥. All rights reserved.
//
import UIKit
import CoreData
import IQKeyboardManagerSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, JPUSHRegisterDelegate {
var window: UIWindow?
var hostReach: Reachability?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setupRootViewController() // 配置控制器
setupGlobalStyle() // 配置全局样式
setupGlobalData() // 配置全局数据
setupKeyBoardManager() // 配置键盘管理
setupShareSDK() // 配置shareSDK
setupJPush(launchOptions) // 配置JPUSH
setupReachability() // 配置网络检测
return true
}
/**
配置网络检测
*/
fileprivate func setupReachability() {
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(_:)), name: NSNotification.Name.reachabilityChanged, object: nil)
hostReach = Reachability.forInternetConnection()
hostReach?.startNotifier()
}
/**
监听网络状态改变
*/
@objc func reachabilityChanged(_ notification: Notification) {
guard let curReach = notification.object as? Reachability else {
return
}
var networkState = 0
switch curReach.currentReachabilityStatus() {
case NetworkStatus.init(0):
print("无网络")
networkState = 0
case NetworkStatus.init(1):
networkState = 1
print("WiFi")
case NetworkStatus.init(2):
networkState = 2
print("WAN")
default:
networkState = 3
}
// 发出网络改变通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "networkStatusChanged"), object: nil, userInfo: ["networkState" : networkState])
}
/**
配置全局数据
*/
fileprivate func setupGlobalData() {
// 设置初始正文字体大小
if UserDefaults.standard.string(forKey: CONTENT_FONT_TYPE_KEY) == nil || UserDefaults.standard.integer(forKey: CONTENT_FONT_SIZE_KEY) == 0 {
// 字体 16小 18中 20大 22超大 24巨大 26极大 共6个等级,可以用枚举列举使用
UserDefaults.standard.set(18, forKey: CONTENT_FONT_SIZE_KEY)
UserDefaults.standard.set("", forKey: CONTENT_FONT_TYPE_KEY)
UserDefaults.standard.set(nil, forKey: "selectedArray")
UserDefaults.standard.set(nil, forKey: "optionalArray")
}
// 验证缓存的账号是否有效
JFAccountModel.checkUserInfo({})
// 是否需要更新本地搜索关键词列表
JFNetworkTool.shareNetworkTool.shouldUpdateKeyboardList({ (update) in
if update {
JFNewsDALManager.shareManager.updateSearchKeyListData()
}
})
}
/**
配置shareSDK
*/
fileprivate func setupShareSDK() {
ShareSDK.registerApp(SHARESDK_APP_KEY, activePlatforms:[
SSDKPlatformType.typeSinaWeibo.rawValue,
SSDKPlatformType.typeQQ.rawValue,
SSDKPlatformType.typeWechat.rawValue],
onImport: { (platform : SSDKPlatformType) in
switch platform {
case SSDKPlatformType.typeWechat:
ShareSDKConnector.connectWeChat(WXApi.classForCoder())
case SSDKPlatformType.typeQQ:
ShareSDKConnector.connectQQ(QQApiInterface.classForCoder(), tencentOAuthClass: TencentOAuth.classForCoder())
case SSDKPlatformType.typeSinaWeibo:
ShareSDKConnector.connectWeibo(WeiboSDK.classForCoder())
default:
break
}
}) { (platform : SSDKPlatformType, appInfo : NSMutableDictionary?) in
switch platform {
case SSDKPlatformType.typeWechat:
// 微信
appInfo?.ssdkSetupWeChat(byAppId: WX_APP_ID, appSecret: WX_APP_SECRET)
case SSDKPlatformType.typeQQ:
// QQ
appInfo?.ssdkSetupQQ(byAppId: QQ_APP_ID,
appKey : QQ_APP_KEY,
authType : SSDKAuthTypeBoth)
case SSDKPlatformType.typeSinaWeibo:
appInfo?.ssdkSetupSinaWeibo(byAppKey: WB_APP_KEY,
appSecret: WB_APP_SECRET,
redirectUri: WB_REDIRECT_URL,
authType: SSDKAuthTypeBoth)
default:
break
}
}
}
/**
配置键盘管理者
*/
fileprivate func setupKeyBoardManager() {
IQKeyboardManager.sharedManager().enable = true
}
/**
全局样式
*/
fileprivate func setupGlobalStyle() {
UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
JFProgressHUD.setupHUD() // 配置HUD
}
/**
根控制器
*/
fileprivate func setupRootViewController() {
window = UIWindow(frame: UIScreen.main.bounds)
// 是否是新版本,新版本就进新特性里
if isNewVersion() {
window?.rootViewController = JFNewFeatureViewController()
JFAccountModel.logout()
} else {
window?.rootViewController = JFTabBarController()
}
window?.makeKeyAndVisible()
}
/**
判断是否是新版本
*/
fileprivate func isNewVersion() -> Bool {
// 获取当前的版本号
let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String
// 获取到之前的版本号
let sandboxVersionKey = "sandboxVersionKey"
let sandboxVersion = UserDefaults.standard.string(forKey: sandboxVersionKey)
// 保存当前版本号
UserDefaults.standard.set(currentVersion, forKey: sandboxVersionKey)
UserDefaults.standard.synchronize()
// 当前版本和沙盒版本不一致就是新版本
return currentVersion != sandboxVersion
}
/**
配置极光推送
*/
fileprivate func setupJPush(_ launchOptions: [AnyHashable: Any]?) {
if #available(iOS 10.0, *){
let entiity = JPUSHRegisterEntity()
entiity.types = Int(UNAuthorizationOptions.alert.rawValue |
UNAuthorizationOptions.badge.rawValue |
UNAuthorizationOptions.sound.rawValue)
JPUSHService.register(forRemoteNotificationConfig: entiity, delegate: self)
} else if #available(iOS 8.0, *) {
let types = UIUserNotificationType.badge.rawValue |
UIUserNotificationType.sound.rawValue |
UIUserNotificationType.alert.rawValue
JPUSHService.register(forRemoteNotificationTypes: types, categories: nil)
} else {
let type = UIRemoteNotificationType.badge.rawValue |
UIRemoteNotificationType.sound.rawValue |
UIRemoteNotificationType.alert.rawValue
JPUSHService.register(forRemoteNotificationTypes: type, categories: nil)
}
JPUSHService.setup(withOption: launchOptions, appKey: JPUSH_APP_KEY, channel: JPUSH_CHANNEL, apsForProduction: JPUSH_IS_PRODUCTION)
JPUSHService.crashLogON()
// 延迟发送通知(app被杀死进程后收到通知,然后通过点击通知打开app在这个方法中发送通知)
perform(#selector(sendNotification(_:)), with: launchOptions, afterDelay: 1.5)
}
/**
如果app是未启动状态,点击了通知。在launchOptions会携带通知数据
*/
@objc fileprivate func sendNotification(_ launchOptions: [AnyHashable: Any]?) {
if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {
NotificationCenter.default.post(name: Notification.Name(rawValue: "didReceiveRemoteNotificationOfJPush"), object: nil, userInfo: userInfo)
}
}
/**
注册 DeviceToken
*/
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
JPUSHService.registerDeviceToken(deviceToken)
}
/**
注册远程通知失败
*/
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("did Fail To Register For Remote Notifications With Error: \(error)")
}
/**
将要显示
*/
@available(iOS 10.0, *)
func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
let userInfo = notification.request.content.userInfo
if let trigger = notification.request.trigger {
if trigger.isKind(of: UNPushNotificationTrigger.classForCoder()) {
JPUSHService.handleRemoteNotification(userInfo)
}
}
completionHandler(Int(UNAuthorizationOptions.alert.rawValue))
}
/**
已经收到消息
*/
@available(iOS 10.0, *)
func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
let userInfo = response.notification.request.content.userInfo
if let trigger = response.notification.request.trigger {
if trigger.isKind(of: UNPushNotificationTrigger.classForCoder()) {
JPUSHService.handleRemoteNotification(userInfo)
// 处理远程通知
remoteNotificationHandler(userInfo: userInfo)
}
}
completionHandler()
}
/**
iOS7后接收到远程通知
*/
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
JPUSHService.handleRemoteNotification(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
// 处理远程通知
remoteNotificationHandler(userInfo: userInfo)
}
/// 处理远程通知
///
/// - Parameter userInfo: 通知数据
private func remoteNotificationHandler(userInfo: [AnyHashable : Any]) {
if UIApplication.shared.applicationState == .background || UIApplication.shared.applicationState == .inactive {
NotificationCenter.default.post(name: Notification.Name(rawValue: "didReceiveRemoteNotificationOfJPush"), object: nil, userInfo: userInfo)
} else if UIApplication.shared.applicationState == .active {
let message = (userInfo as [AnyHashable : AnyObject])["aps"]!["alert"] as! String
let alertC = UIAlertController(title: "收到新的消息", message: message, preferredStyle: UIAlertControllerStyle.alert)
let confrimAction = UIAlertAction(title: "查看", style: UIAlertActionStyle.destructive, handler: { (action) in
NotificationCenter.default.post(name: Notification.Name(rawValue: "didReceiveRemoteNotificationOfJPush"), object: nil, userInfo: userInfo)
})
let cancelAction = UIAlertAction(title: "忽略", style: UIAlertActionStyle.default, handler: nil)
alertC.addAction(confrimAction)
alertC.addAction(cancelAction)
UIApplication.shared.keyWindow?.rootViewController?.present(alertC, animated: true, completion: nil)
}
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: "BaoKanIOS", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| apache-2.0 | 041f6df0b559a6e273170a9eec651009 | 37.338624 | 199 | 0.615374 | 5.692066 | false | false | false | false |
podverse/podverse-ios | Podverse/PVTimeHelpers.swift | 1 | 2542 | //
// PVTimeHelpers.swift
// Podverse
//
// Created by Creon on 12/24/16.
// Copyright © 2016 Podverse LLC. All rights reserved.
//
import Foundation
class PVTimeHelper {
static func convertIntToHMSString (time : Int?) -> String {
guard let time = time else {
return ""
}
var hours = String(time / 3600) + ":"
if hours == "0:" {
hours = ""
}
var minutes = String((time / 60) % 60) + ":"
if minutes.count < 3 && hours != "" {
minutes = "0" + minutes
}
var seconds = String(time % 60)
if seconds.count < 2 && (hours != "" || minutes != "") {
seconds = "0" + seconds
}
return "\(hours)\(minutes)\(seconds)"
}
static func convertHMSStringToInt(hms : String) -> Int {
var hmsComponents = hms.components(separatedBy:":").reversed().map() { String($0) }
var seconds = 0
var minutes = 0
var hours = 0
if let secondsVal = hmsComponents.first, let sec = Int(secondsVal) {
seconds = sec
hmsComponents.removeFirst()
}
if let minutesVal = hmsComponents.first, let min = Int(minutesVal) {
minutes = min
hmsComponents.removeFirst()
}
if let hoursVal = hmsComponents.first, let hr = Int(hoursVal) {
hours = hr
hmsComponents.removeFirst()
}
return convertHMSIntsToSeconds(hms:(hours, minutes, seconds))
}
static func convertIntToHMSInts (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
static func convertHMSIntsToSeconds(hms:(Int,Int,Int)) -> Int {
let hoursInSeconds = hms.0 * 3600
let minutesInSeconds = hms.2 * 60
let totalSeconds = hoursInSeconds + minutesInSeconds + hms.2
return totalSeconds
}
static func convertIntToReadableHMSDuration(seconds: Int) -> String {
var string = ""
let hmsInts = convertIntToHMSInts(seconds: seconds)
if hmsInts.0 > 0 {
string += String(hmsInts.0) + "h "
}
if hmsInts.1 > 0 {
string += String(hmsInts.1) + "m "
}
if hmsInts.2 > 0 {
string += String(hmsInts.2) + "s"
}
return string.trimmingCharacters(in: .whitespaces)
}
}
| agpl-3.0 | 787b02bbe1bd28dbc11d9e7632174be0 | 27.233333 | 91 | 0.516332 | 4.411458 | false | false | false | false |
OpsLabJPL/MarsImagesIOS | Pods/SwiftMessages/SwiftMessages/BaseView.swift | 4 | 16567 |
//
// BaseView.swift
// SwiftMessages
//
// Created by Timothy Moose on 8/17/16.
// Copyright © 2016 SwiftKick Mobile LLC. All rights reserved.
//
import UIKit
/**
The `BaseView` class is a reusable message view base class that implements some
of the optional SwiftMessages protocols and provides some convenience functions
and a configurable tap handler. Message views do not need to inherit from `BaseVew`.
*/
open class BaseView: UIView, BackgroundViewable, MarginAdjustable {
/*
MARK: - IB outlets
*/
/**
Fulfills the `BackgroundViewable` protocol and is the target for
the optional `tapHandler` block. Defaults to `self`.
*/
@IBOutlet open weak var backgroundView: UIView! {
didSet {
if let old = oldValue {
old.removeGestureRecognizer(tapRecognizer)
}
installTapRecognizer()
updateBackgroundHeightConstraint()
}
}
// The `contentView` property was removed because it no longer had any functionality
// in the framework. This is a minor backwards incompatible change. If you've copied
// one of the included nib files from a previous release, you may get a key-value
// coding runtime error related to contentView, in which case you can subclass the
// view and add a `contentView` property or you can remove the outlet connection in
// Interface Builder.
// @IBOutlet public var contentView: UIView!
/*
MARK: - Initialization
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundView = self
layoutMargins = UIEdgeInsets.zero
}
public override init(frame: CGRect) {
super.init(frame: frame)
backgroundView = self
layoutMargins = UIEdgeInsets.zero
}
/*
MARK: - Installing background and content
*/
/**
A convenience function for installing a content view as a subview of `backgroundView`
and pinning the edges to `backgroundView` with the specified `insets`.
- Parameter contentView: The view to be installed into the background view
and assigned to the `contentView` property.
- Parameter insets: The amount to inset the content view from the background view.
Default is zero inset.
*/
open func installContentView(_ contentView: UIView, insets: UIEdgeInsets = UIEdgeInsets.zero) {
contentView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.addSubview(contentView)
contentView.topAnchor.constraint(equalTo: backgroundView.topAnchor, constant: insets.top).isActive = true
contentView.bottomAnchor.constraint(equalTo: backgroundView.bottomAnchor, constant: -insets.bottom).isActive = true
contentView.leftAnchor.constraint(equalTo: backgroundView.leftAnchor, constant: insets.left).isActive = true
contentView.rightAnchor.constraint(equalTo: backgroundView.rightAnchor, constant: -insets.right).isActive = true
contentView.heightAnchor.constraint(equalToConstant: 350).with(priority: UILayoutPriority(rawValue: 200)).isActive = true
}
/**
A convenience function for installing a background view and pinning to the layout margins.
This is useful for creating programatic layouts where the background view needs to be
inset from the message view's edges (like a card-style layout).
- Parameter backgroundView: The view to be installed as a subview and
assigned to the `backgroundView` property.
- Parameter insets: The amount to inset the content view from the margins. Default is zero inset.
*/
open func installBackgroundView(_ backgroundView: UIView, insets: UIEdgeInsets = UIEdgeInsets.zero) {
backgroundView.translatesAutoresizingMaskIntoConstraints = false
if backgroundView != self {
backgroundView.removeFromSuperview()
}
addSubview(backgroundView)
self.backgroundView = backgroundView
backgroundView.centerXAnchor.constraint(equalTo: centerXAnchor).with(priority: UILayoutPriority(rawValue: 950)).isActive = true
backgroundView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor, constant: insets.top).with(priority: UILayoutPriority(rawValue: 900)).isActive = true
backgroundView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor, constant: -insets.bottom).with(priority: UILayoutPriority(rawValue: 900)).isActive = true
backgroundView.heightAnchor.constraint(equalToConstant: 350).with(priority: UILayoutPriority(rawValue: 200)).isActive = true
layoutConstraints = [
backgroundView.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: insets.left).with(priority: UILayoutPriority(rawValue: 900)),
backgroundView.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -insets.right).with(priority: UILayoutPriority(rawValue: 900)),
]
regularWidthLayoutConstraints = [
backgroundView.leftAnchor.constraint(greaterThanOrEqualTo: layoutMarginsGuide.leftAnchor, constant: insets.left).with(priority: UILayoutPriority(rawValue: 900)),
backgroundView.rightAnchor.constraint(lessThanOrEqualTo: layoutMarginsGuide.rightAnchor, constant: -insets.right).with(priority: UILayoutPriority(rawValue: 900)),
backgroundView.widthAnchor.constraint(lessThanOrEqualToConstant: 500).with(priority: UILayoutPriority(rawValue: 950)),
backgroundView.widthAnchor.constraint(equalToConstant: 500).with(priority: UILayoutPriority(rawValue: 200)),
]
installTapRecognizer()
}
/**
A convenience function for installing a background view and pinning to the horizontal
layout margins and to the vertical edges. This is useful for creating programatic layouts where
the background view needs to be inset from the message view's horizontal edges (like a tab-style layout).
- Parameter backgroundView: The view to be installed as a subview and
assigned to the `backgroundView` property.
- Parameter insets: The amount to inset the content view from the horizontal margins and vertical edges.
Default is zero inset.
*/
open func installBackgroundVerticalView(_ backgroundView: UIView, insets: UIEdgeInsets = UIEdgeInsets.zero) {
backgroundView.translatesAutoresizingMaskIntoConstraints = false
if backgroundView != self {
backgroundView.removeFromSuperview()
}
addSubview(backgroundView)
self.backgroundView = backgroundView
backgroundView.centerXAnchor.constraint(equalTo: centerXAnchor).with(priority: UILayoutPriority(rawValue: 950)).isActive = true
backgroundView.topAnchor.constraint(equalTo: topAnchor, constant: insets.top).with(priority: UILayoutPriority(rawValue: 1000)).isActive = true
backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -insets.bottom).with(priority: UILayoutPriority(rawValue: 1000)).isActive = true
backgroundView.heightAnchor.constraint(equalToConstant: 350).with(priority: UILayoutPriority(rawValue: 200)).isActive = true
layoutConstraints = [
backgroundView.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: insets.left).with(priority: UILayoutPriority(rawValue: 900)),
backgroundView.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -insets.right).with(priority: UILayoutPriority(rawValue: 900)),
]
regularWidthLayoutConstraints = [
backgroundView.leftAnchor.constraint(greaterThanOrEqualTo: layoutMarginsGuide.leftAnchor, constant: insets.left).with(priority: UILayoutPriority(rawValue: 900)),
backgroundView.rightAnchor.constraint(lessThanOrEqualTo: layoutMarginsGuide.rightAnchor, constant: -insets.right).with(priority: UILayoutPriority(rawValue: 900)),
backgroundView.widthAnchor.constraint(lessThanOrEqualToConstant: 500).with(priority: UILayoutPriority(rawValue: 950)),
backgroundView.widthAnchor.constraint(equalToConstant: 500).with(priority: UILayoutPriority(rawValue: 200)),
]
installTapRecognizer()
}
/*
MARK: - Tap handler
*/
/**
An optional tap handler that will be called when the `backgroundView` is tapped.
*/
open var tapHandler: ((_ view: BaseView) -> Void)? {
didSet {
installTapRecognizer()
}
}
fileprivate lazy var tapRecognizer: UITapGestureRecognizer = {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MessageView.tapped))
return tapRecognizer
}()
@objc func tapped() {
tapHandler?(self)
}
fileprivate func installTapRecognizer() {
guard let backgroundView = backgroundView else { return }
removeGestureRecognizer(tapRecognizer)
backgroundView.removeGestureRecognizer(tapRecognizer)
if tapHandler != nil {
// Only install the tap recognizer if there is a tap handler,
// which makes it slightly nicer if one wants to install
// a custom gesture recognizer.
backgroundView.addGestureRecognizer(tapRecognizer)
}
}
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if backgroundView != self {
let backgroundViewPoint = convert(point, to: backgroundView)
return backgroundView.point(inside: backgroundViewPoint, with: event)
}
return super.point(inside: point, with: event)
}
/*
MARK: - MarginAdjustable
These properties fulfill the `MarginAdjustable` protocol and are exposed
as `@IBInspectables` so that they can be adjusted directly in nib files
(see MessageView.nib).
*/
public var layoutMarginAdditions: UIEdgeInsets {
get {
return UIEdgeInsets(top: topLayoutMarginAddition, left: leftLayoutMarginAddition, bottom: bottomLayoutMarginAddition, right: rightLayoutMarginAddition)
}
set {
topLayoutMarginAddition = newValue.top
leftLayoutMarginAddition = newValue.left
bottomLayoutMarginAddition = newValue.bottom
rightLayoutMarginAddition = newValue.right
}
}
/// IBInspectable access to layoutMarginAdditions.top
@IBInspectable open var topLayoutMarginAddition: CGFloat = 0
/// IBInspectable access to layoutMarginAdditions.left
@IBInspectable open var leftLayoutMarginAddition: CGFloat = 0
/// IBInspectable access to layoutMarginAdditions.bottom
@IBInspectable open var bottomLayoutMarginAddition: CGFloat = 0
/// IBInspectable access to layoutMarginAdditions.right
@IBInspectable open var rightLayoutMarginAddition: CGFloat = 0
@IBInspectable open var collapseLayoutMarginAdditions: Bool = true
@IBInspectable open var bounceAnimationOffset: CGFloat = 5
/*
MARK: - Setting the height
*/
/**
An optional explicit height for the background view, which can be used if
the message view's intrinsic content size does not produce the desired height.
*/
open var backgroundHeight: CGFloat? {
didSet {
updateBackgroundHeightConstraint()
}
}
private func updateBackgroundHeightConstraint() {
if let existing = backgroundHeightConstraint {
let view = existing.firstItem as! UIView
view.removeConstraint(existing)
backgroundHeightConstraint = nil
}
if let height = backgroundHeight, let backgroundView = backgroundView {
let constraint = NSLayoutConstraint(item: backgroundView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)
backgroundView.addConstraint(constraint)
backgroundHeightConstraint = constraint
}
}
private var backgroundHeightConstraint: NSLayoutConstraint?
/*
Mark: - Layout
*/
open override func updateConstraints() {
super.updateConstraints()
let on: [NSLayoutConstraint]
let off: [NSLayoutConstraint]
switch traitCollection.horizontalSizeClass {
case .regular:
on = regularWidthLayoutConstraints
off = layoutConstraints
default:
on = layoutConstraints
off = regularWidthLayoutConstraints
}
on.forEach { $0.isActive = true }
off.forEach { $0.isActive = false }
}
private var layoutConstraints: [NSLayoutConstraint] = []
private var regularWidthLayoutConstraints: [NSLayoutConstraint] = []
}
/*
MARK: - Theming
*/
extension BaseView {
/// A convenience function to configure a default drop shadow effect.
/// The shadow is to this view's layer instead of that of the background view
/// because the background view may be masked. So, when modifying the drop shadow,
/// be sure to set the shadow properties of this view's layer. The shadow path is
/// updated for you automatically.
open func configureDropShadow() {
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
layer.shadowRadius = 6.0
layer.shadowOpacity = 0.4
layer.masksToBounds = false
updateShadowPath()
}
/// A convenience function to turn off drop shadow
open func configureNoDropShadow() {
layer.shadowOpacity = 0
}
private func updateShadowPath() {
backgroundView?.layoutIfNeeded()
let shadowLayer = backgroundView?.layer ?? layer
let shadowRect = layer.convert(shadowLayer.bounds, from: shadowLayer)
let shadowPath: CGPath?
if let backgroundMaskLayer = shadowLayer.mask as? CAShapeLayer,
let backgroundMaskPath = backgroundMaskLayer.path {
var transform = CGAffineTransform(translationX: shadowRect.minX, y: shadowRect.minY)
shadowPath = backgroundMaskPath.copy(using: &transform)
} else {
shadowPath = UIBezierPath(roundedRect: shadowRect, cornerRadius: shadowLayer.cornerRadius).cgPath
}
// This is a workaround needed for smooth rotation animations.
if let foundAnimation = layer.findAnimation(forKeyPath: "bounds.size") {
// Update the layer's `shadowPath` with animation, copying the relevant properties
// from the found animation.
let animation = CABasicAnimation(keyPath: "shadowPath")
animation.duration = foundAnimation.duration
animation.timingFunction = foundAnimation.timingFunction
animation.fromValue = layer.shadowPath
animation.toValue = shadowPath
layer.add(animation, forKey: "shadowPath")
layer.shadowPath = shadowPath
} else {
// Update the layer's `shadowPath` without animation
layer.shadowPath = shadowPath }
}
open override func layoutSubviews() {
super.layoutSubviews()
updateShadowPath()
}
}
/*
MARK: - Configuring the width
This extension provides a few convenience functions for configuring the
background view's width. You are encouraged to write your own such functions
if these don't exactly meet your needs.
*/
extension BaseView {
/**
A shortcut for configuring the left and right layout margins. For views that
have `backgroundView` as a subview of `MessageView`, the background view should
be pinned to the left and right `layoutMargins` in order for this configuration to work.
*/
public func configureBackgroundView(sideMargin: CGFloat) {
layoutMargins.left = sideMargin
layoutMargins.right = sideMargin
}
/**
A shortcut for adding a width constraint to the `backgroundView`. When calling this
method, it is important to ensure that the width constraint doesn't conflict with
other constraints. The CardView.nib and TabView.nib layouts are compatible with
this method.
*/
public func configureBackgroundView(width: CGFloat) {
guard let backgroundView = backgroundView else { return }
let constraint = NSLayoutConstraint(item: backgroundView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width)
backgroundView.addConstraint(constraint)
}
}
| apache-2.0 | 1e4fd72cd5ade4344bd2c974206ba2db | 43.532258 | 182 | 0.702342 | 5.564662 | false | false | false | false |
adamdahan/GraphKit | Source/Graph.swift | 1 | 47667 | //
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import CoreData
private struct GraphPersistentStoreCoordinator {
static var onceToken: dispatch_once_t = 0
static var persistentStoreCoordinator: NSPersistentStoreCoordinator?
}
private struct GraphMainManagedObjectContext {
static var onceToken: dispatch_once_t = 0
static var managedObjectContext: NSManagedObjectContext?
}
private struct GraphPrivateManagedObjectContext {
static var onceToken: dispatch_once_t = 0
static var managedObjectContext: NSManagedObjectContext?
}
private struct GraphManagedObjectModel {
static var onceToken: dispatch_once_t = 0
static var managedObjectModel: NSManagedObjectModel?
}
internal struct GraphUtility {
static let storeName: String = "GraphKit.sqlite"
static let entityIndexName: String = "ManagedEntity"
static let entityDescriptionName: String = "ManagedEntity"
static let entityObjectClassName: String = "ManagedEntity"
static let entityGroupIndexName: String = "EntityGroup"
static let entityGroupObjectClassName: String = "EntityGroup"
static let entityGroupDescriptionName: String = "EntityGroup"
static let entityPropertyIndexName: String = "EntityProperty"
static let entityPropertyObjectClassName: String = "EntityProperty"
static let entityPropertyDescriptionName: String = "EntityProperty"
static let actionIndexName: String = "ManagedAction"
static let actionDescriptionName: String = "ManagedAction"
static let actionObjectClassName: String = "ManagedAction"
static let actionGroupIndexName: String = "ActionGroup"
static let actionGroupObjectClassName: String = "ActionGroup"
static let actionGroupDescriptionName: String = "ActionGroup"
static let actionPropertyIndexName: String = "ActionProperty"
static let actionPropertyObjectClassName: String = "ActionProperty"
static let actionPropertyDescriptionName: String = "ActionProperty"
static let bondIndexName: String = "ManagedBond"
static let bondDescriptionName: String = "ManagedBond"
static let bondObjectClassName: String = "ManagedBond"
static let bondGroupIndexName: String = "BondGroup"
static let bondGroupObjectClassName: String = "BondGroup"
static let bondGroupDescriptionName: String = "BondGroup"
static let bondPropertyIndexName: String = "BondProperty"
static let bondPropertyObjectClassName: String = "BondProperty"
static let bondPropertyDescriptionName: String = "BondProperty"
}
@objc(GraphDelegate)
public protocol GraphDelegate {
optional func graphDidInsertEntity(graph: Graph, entity: Entity)
optional func graphDidDeleteEntity(graph: Graph, entity: Entity)
optional func graphDidInsertEntityGroup(graph: Graph, entity: Entity, group: String)
optional func graphDidInsertEntityProperty(graph: Graph, entity: Entity, property: String, value: AnyObject)
optional func graphDidUpdateEntityProperty(graph: Graph, entity: Entity, property: String, value: AnyObject)
optional func graphDidInsertAction(graph: Graph, action: Action)
optional func graphDidUpdateAction(graph: Graph, action: Action)
optional func graphDidDeleteAction(graph: Graph, action: Action)
optional func graphDidInsertActionGroup(graph: Graph, action: Action, group: String)
optional func graphDidInsertActionProperty(graph: Graph, action: Action, property: String, value: AnyObject)
optional func graphDidUpdateActionProperty(graph: Graph, action: Action, property: String, value: AnyObject)
optional func graphDidInsertBond(graph: Graph, bond: Bond)
optional func graphDidDeleteBond(graph: Graph, bond: Bond)
optional func graphDidInsertBondGroup(graph: Graph, bond: Bond, group: String)
optional func graphDidInsertBondProperty(graph: Graph, bond: Bond, property: String, value: AnyObject)
optional func graphDidUpdateBondProperty(graph: Graph, bond: Bond, property: String, value: AnyObject)
}
@objc(Graph)
public class Graph: NSObject {
public var batchSize: Int = 20
public var batchOffset: Int = 0
internal var watching: OrderedDictionary<String, Array<String>>
internal var masterPredicate: NSPredicate?
public weak var delegate: GraphDelegate?
/**
:name: init
:description: Initializer for the Object.
*/
override public init() {
watching = OrderedDictionary<String, Array<String>>()
super.init()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/**
:name: save
:description: Updates the persistent layer by processing all the changes in the Graph.
*/
public func save() {
save(nil)
}
/**
:name: save
:description: Updates the persistent layer by processing all the changes in the Graph.
*/
public func save(completion: ((success: Bool, error: NSError?) -> ())?) {
var w: NSManagedObjectContext? = worker
var p: NSManagedObjectContext? = privateContext
if nil != w && nil != p {
w!.performBlockAndWait {
var error: NSError?
let result: Bool = w!.save(&error)
dispatch_async(dispatch_get_main_queue()) {
completion?(success: result ? p!.save(&error) : false, error: error)
}
}
}
}
/**
:name: watch(Entity)
:description: Attaches the Graph instance to NotificationCenter in order to observe changes for an Entity with the spcified type.
*/
public func watch(Entity type: String!) {
addWatcher("type", value: type, index: GraphUtility.entityIndexName, entityDescriptionName: GraphUtility.entityDescriptionName, managedObjectClassName: GraphUtility.entityObjectClassName)
}
/**
:name: watch(EntityGroup)
:description: Attaches the Graph instance to NotificationCenter in order to observe changes for an Entity with the specified group name.
*/
public func watch(EntityGroup name: String!) {
addWatcher("name", value: name, index: GraphUtility.entityGroupIndexName, entityDescriptionName: GraphUtility.entityGroupDescriptionName, managedObjectClassName: GraphUtility.entityGroupObjectClassName)
}
/**
:name: watch(EntityProperty)
:description: Attaches the Graph instance to NotificationCenter in order to observe changes for an Entity with the specified property name.
*/
public func watch(EntityProperty name: String!) {
addWatcher("name", value: name, index: GraphUtility.entityPropertyIndexName, entityDescriptionName: GraphUtility.entityPropertyDescriptionName, managedObjectClassName: GraphUtility.entityPropertyObjectClassName)
}
/**
:name: watch(Action)
:description: Attaches the Graph instance to NotificationCenter in order to Observe changes for an Action with the spcified type.
*/
public func watch(Action type: String!) {
addWatcher("type", value: type, index: GraphUtility.actionIndexName, entityDescriptionName: GraphUtility.actionDescriptionName, managedObjectClassName: GraphUtility.actionObjectClassName)
}
/**
:name: watch(ActionGroup)
:description: Attaches the Graph instance to NotificationCenter in order to observe changes for an Action with the specified group name.
*/
public func watch(ActionGroup name: String!) {
addWatcher("name", value: name, index: GraphUtility.actionGroupIndexName, entityDescriptionName: GraphUtility.actionGroupDescriptionName, managedObjectClassName: GraphUtility.actionGroupObjectClassName)
}
/**
:name: watch(ActionProperty)
:description: Attaches the Graph instance to NotificationCenter in order to observe changes for an Action with the specified property name.
*/
public func watch(ActionProperty name: String!) {
addWatcher("name", value: name, index: GraphUtility.actionPropertyIndexName, entityDescriptionName: GraphUtility.actionPropertyDescriptionName, managedObjectClassName: GraphUtility.actionPropertyObjectClassName)
}
/**
:name: watch(Bond)
:description: Attaches the Graph instance to NotificationCenter in order to Observe changes for an Bond with the spcified type.
*/
public func watch(Bond type: String!) {
addWatcher("type", value: type, index: GraphUtility.bondIndexName, entityDescriptionName: GraphUtility.bondDescriptionName, managedObjectClassName: GraphUtility.bondObjectClassName)
}
/**
:name: watch(BondGroup)
:description: Attaches the Graph instance to NotificationCenter in order to observe changes for an Bond with the specified group name.
*/
public func watch(BondGroup name: String!) {
addWatcher("name", value: name, index: GraphUtility.bondGroupIndexName, entityDescriptionName: GraphUtility.bondGroupDescriptionName, managedObjectClassName: GraphUtility.bondGroupObjectClassName)
}
/**
:name: watch(BondProperty)
:description: Attaches the Graph instance to NotificationCenter in order to observe changes for an Bond with the specified property name.
*/
public func watch(BondProperty name: String!) {
addWatcher("name", value: name, index: GraphUtility.bondPropertyIndexName, entityDescriptionName: GraphUtility.bondPropertyDescriptionName, managedObjectClassName: GraphUtility.bondPropertyObjectClassName)
}
/**
:name: search(Entity)
:description: Searches the Graph for Entity Objects with the following type LIKE ?.
*/
public func search(Entity type: String) -> OrderedDictionary<String, Entity> {
let entries: Array<AnyObject> = search(GraphUtility.entityDescriptionName, predicate: NSPredicate(format: "type LIKE %@", type as NSString), sort: [NSSortDescriptor(key: "createdDate", ascending: false)])
let nodes: OrderedDictionary<String, Entity> = OrderedDictionary<String, Entity>()
for entity: ManagedEntity in entries as! Array<ManagedEntity> {
let node: Entity = Entity(entity: entity)
nodes.insert((node.id, node))
}
return nodes
}
/**
:name: search(EntityGroup)
:description: Searches the Graph for Entity Group Objects with the following name LIKE ?.
*/
public func search(EntityGroup name: String) -> OrderedMultiDictionary<String, Entity> {
let entries: Array<AnyObject> = search(GraphUtility.entityGroupDescriptionName, predicate: NSPredicate(format: "name LIKE %@", name as NSString))
let nodes: OrderedMultiDictionary<String, Entity> = OrderedMultiDictionary<String, Entity>()
for group: EntityGroup in entries as! Array<EntityGroup> {
let node: Entity = Entity(entity: group.node)
nodes.insert((group.name, node))
}
return nodes
}
/**
:name: search(EntityGroupMap)
:description: Retrieves all the unique Group Names for Entity Nodes with their Entity Objects.
*/
public func search(EntityGroupMap name: String) -> OrderedDictionary<String, OrderedMultiDictionary<String, Entity>> {
let entries: Array<AnyObject> = search(GraphUtility.entityGroupDescriptionName, predicate: NSPredicate(format: "name LIKE %@", name as NSString))
let nodes: OrderedDictionary<String, OrderedMultiDictionary<String, Entity>> = OrderedDictionary<String, OrderedMultiDictionary<String, Entity>>()
for group: EntityGroup in entries as! Array<EntityGroup> {
let node: Entity = Entity(entity: group.node)
if (nil == nodes[group.name]) {
let set: OrderedMultiDictionary<String, Entity> = OrderedMultiDictionary<String, Entity>()
set.insert((node.type, node))
nodes.insert((group.name, set))
} else {
nodes[group.name]!.insert((node.type, node))
}
}
return nodes
}
/**
:name: search(EntityProperty)
:description: Searches the Graph for Entity Property Objects with the following name LIKE ?.
*/
public func search(EntityProperty name: String) -> OrderedMultiDictionary<String, Entity> {
let entries: Array<AnyObject> = search(GraphUtility.entityPropertyDescriptionName, predicate: NSPredicate(format: "name LIKE %@", name as NSString))
let nodes: OrderedMultiDictionary<String, Entity> = OrderedMultiDictionary<String, Entity>()
for property: EntityProperty in entries as! Array<EntityProperty> {
let node: Entity = Entity(entity: property.node)
nodes.insert((property.name, node))
}
return nodes
}
/**
:name: search(EntityProperty)
:description: Searches the Graph for Entity Property Objects with the following name == ? and value == ?.
*/
public func search(EntityProperty name: String, value: String) -> OrderedMultiDictionary<String, Entity> {
let entries: Array<AnyObject> = search(GraphUtility.entityPropertyDescriptionName, predicate: NSPredicate(format: "(name == %@) AND (object == %@)", name as NSString, value as NSString))
let nodes: OrderedMultiDictionary<String, Entity> = OrderedMultiDictionary<String, Entity>()
for property: EntityProperty in entries as! Array<EntityProperty> {
let node: Entity = Entity(entity: property.node)
nodes.insert((property.name, node))
}
return nodes
}
/**
:name: search(EntityProperty)
:description: Searches the Graph for Entity Property Objects with the following name == ? and value == ?.
*/
public func search(EntityProperty name: String, value: Int) -> OrderedMultiDictionary<String, Entity> {
let entries: Array<AnyObject> = search(GraphUtility.entityPropertyDescriptionName, predicate: NSPredicate(format: "(name == %@) AND (object == %@)", name as NSString, value as NSNumber))
let nodes: OrderedMultiDictionary<String, Entity> = OrderedMultiDictionary<String, Entity>()
for property: EntityProperty in entries as! Array<EntityProperty> {
let node: Entity = Entity(entity: property.node)
nodes.insert((property.name, node))
}
return nodes
}
/**
:name: search(Action)
:description: Searches the Graph for Action Objects with the following type LIKE ?.
*/
public func search(Action type: String) -> OrderedDictionary<String, Action> {
let entries: Array<AnyObject> = search(GraphUtility.actionDescriptionName, predicate: NSPredicate(format: "type LIKE %@", type as NSString), sort: [NSSortDescriptor(key: "createdDate", ascending: false)])
let nodes: OrderedDictionary<String, Action> = OrderedDictionary<String, Action>()
for action: ManagedAction in entries as! Array<ManagedAction> {
let node: Action = Action(action: action)
nodes.insert((node.id, node))
}
return nodes
}
/**
:name: search(ActionGroup)
:description: Searches the Graph for Action Group Objects with the following name LIKE ?.
*/
public func search(ActionGroup name: String) -> OrderedMultiDictionary<String, Action> {
let entries: Array<AnyObject> = search(GraphUtility.actionGroupDescriptionName, predicate: NSPredicate(format: "name LIKE %@", name as NSString))
let nodes: OrderedMultiDictionary<String, Action> = OrderedMultiDictionary<String, Action>()
for group: ActionGroup in entries as! Array<ActionGroup> {
let node: Action = Action(action: group.node)
nodes.insert((group.name, node))
}
return nodes
}
/**
:name: search(ActionGroupMap)
:description: Retrieves all the unique Group Names for Action Nodes with their Action Objects.
*/
public func search(ActionGroupMap name: String) -> OrderedDictionary<String, OrderedMultiDictionary<String, Action>> {
let entries: Array<AnyObject> = search(GraphUtility.actionGroupDescriptionName, predicate: NSPredicate(format: "name LIKE %@", name as NSString))
let nodes: OrderedDictionary<String, OrderedMultiDictionary<String, Action>> = OrderedDictionary<String, OrderedMultiDictionary<String, Action>>()
for group: ActionGroup in entries as! Array<ActionGroup> {
let node: Action = Action(action: group.node)
if (nil == nodes[group.name]) {
let set: OrderedMultiDictionary<String, Action> = OrderedMultiDictionary<String, Action>()
set.insert((node.type, node))
nodes.insert((group.name, set))
} else {
nodes[group.name]!.insert((node.type, node))
}
}
return nodes
}
/**
:name: search(ActionProperty)
:description: Searches the Graph for Action Property Objects with the following name LIKE ?.
*/
public func search(ActionProperty name: String) -> OrderedMultiDictionary<String, Action> {
let entries: Array<AnyObject> = search(GraphUtility.actionPropertyDescriptionName, predicate: NSPredicate(format: "name LIKE %@", name as NSString))
let nodes: OrderedMultiDictionary<String, Action> = OrderedMultiDictionary<String, Action>()
for property: ActionProperty in entries as! Array<ActionProperty> {
let node: Action = Action(action: property.node)
nodes.insert((property.name, node))
}
return nodes
}
/**
:name: search(ActionProperty)
:description: Searches the Graph for Action Property Objects with the following name == ? and value == ?.
*/
public func search(ActionProperty name: String, value: String) -> OrderedMultiDictionary<String, Action> {
let entries: Array<AnyObject> = search(GraphUtility.actionPropertyDescriptionName, predicate: NSPredicate(format: "(name == %@) AND (object == %@)", name as NSString, value as NSString))
let nodes: OrderedMultiDictionary<String, Action> = OrderedMultiDictionary<String, Action>()
for property: ActionProperty in entries as! Array<ActionProperty> {
let node: Action = Action(action: property.node)
nodes.insert((property.name, node))
}
return nodes
}
/**
:name: search(ActionProperty)
:description: Searches the Graph for Action Property Objects with the following name == ? and value == ?.
*/
public func search(ActionProperty name: String, value: Int) -> OrderedMultiDictionary<String, Action> {
let entries: Array<AnyObject> = search(GraphUtility.actionPropertyDescriptionName, predicate: NSPredicate(format: "(name == %@) AND (object == %@)", name as NSString, value as NSNumber))
let nodes: OrderedMultiDictionary<String, Action> = OrderedMultiDictionary<String, Action>()
for property: ActionProperty in entries as! Array<ActionProperty> {
let node: Action = Action(action: property.node)
nodes.insert((property.name, node))
}
return nodes
}
/**
:name: search(Bond)
:description: Searches the Graph for Bond Objects with the following type LIKE ?.
*/
public func search(Bond type: String) -> OrderedDictionary<String, Bond> {
let entries: Array<AnyObject> = search(GraphUtility.bondDescriptionName, predicate: NSPredicate(format: "type LIKE %@", type as NSString), sort: [NSSortDescriptor(key: "createdDate", ascending: false)])
let nodes: OrderedDictionary<String, Bond> = OrderedDictionary<String, Bond>()
for bond: ManagedBond in entries as! Array<ManagedBond> {
let node: Bond = Bond(bond: bond)
nodes.insert((node.id, node))
}
return nodes
}
/**
:name: search(BondGroup)
:description: Searches the Graph for Bond Group Objects with the following name LIKE ?.
*/
public func search(BondGroup name: String) -> OrderedMultiDictionary<String, Bond> {
let entries: Array<AnyObject> = search(GraphUtility.bondGroupDescriptionName, predicate: NSPredicate(format: "name LIKE %@", name as NSString))
let nodes: OrderedMultiDictionary<String, Bond> = OrderedMultiDictionary<String, Bond>()
for group: BondGroup in entries as! Array<BondGroup> {
let node: Bond = Bond(bond: group.node)
nodes.insert((group.name, node))
}
return nodes
}
/**
:name: search(BondGroupMap)
:description: Retrieves all the unique Group Names for Bond Nodes with their Bond Objects.
*/
public func search(BondGroupMap name: String) -> OrderedDictionary<String, OrderedMultiDictionary<String, Bond>> {
let entries: Array<AnyObject> = search(GraphUtility.bondGroupDescriptionName, predicate: NSPredicate(format: "name LIKE %@", name as NSString))
let nodes: OrderedDictionary<String, OrderedMultiDictionary<String, Bond>> = OrderedDictionary<String, OrderedMultiDictionary<String, Bond>>()
for group: BondGroup in entries as! Array<BondGroup> {
let node: Bond = Bond(bond: group.node)
if (nil == nodes[group.name]) {
let set: OrderedMultiDictionary<String, Bond> = OrderedMultiDictionary<String, Bond>()
set.insert((node.type, node))
nodes.insert((group.name, set))
} else {
nodes[group.name]!.insert((node.type, node))
}
}
return nodes
}
/**
:name: search(BondProperty)
:description: Searches the Graph for Bond Property Objects with the following name LIKE ?.
*/
public func search(BondProperty name: String) -> OrderedMultiDictionary<String, Bond> {
let entries: Array<AnyObject> = search(GraphUtility.bondPropertyDescriptionName, predicate: NSPredicate(format: "name LIKE %@", name as NSString))
let nodes: OrderedMultiDictionary<String, Bond> = OrderedMultiDictionary<String, Bond>()
for property: BondProperty in entries as! Array<BondProperty> {
let node: Bond = Bond(bond: property.node)
nodes.insert((property.name, node))
}
return nodes
}
/**
:name: search(BondProperty)
:description: Searches the Graph for Bond Property Objects with the following name == ? and value == ?.
*/
public func search(BondProperty name: String, value: String) -> OrderedMultiDictionary<String, Bond> {
let entries: Array<AnyObject> = search(GraphUtility.bondPropertyDescriptionName, predicate: NSPredicate(format: "(name == %@) AND (object == %@)", name as NSString, value as NSString))
let nodes: OrderedMultiDictionary<String, Bond> = OrderedMultiDictionary<String, Bond>()
for property: BondProperty in entries as! Array<BondProperty> {
let node: Bond = Bond(bond: property.node)
nodes.insert((property.name, node))
}
return nodes
}
/**
:name: search(BondProperty)
:description: Searches the Graph for Bond Property Objects with the following name == ? and value == ?.
*/
public func search(BondProperty name: String, value: Int) -> OrderedMultiDictionary<String, Bond> {
let entries: Array<AnyObject> = search(GraphUtility.bondPropertyDescriptionName, predicate: NSPredicate(format: "(name == %@) AND (object == %@)", name as NSString, value as NSNumber))
let nodes: OrderedMultiDictionary<String, Bond> = OrderedMultiDictionary<String, Bond>()
for property: BondProperty in entries as! Array<BondProperty> {
let node: Bond = Bond(bond: property.node)
nodes.insert((property.name, node))
}
return nodes
}
//
// :name: managedObjectContextDidSave
// :description: The callback that NotificationCenter uses when changes occur in the Graph.
//
public func managedObjectContextDidSave(notification: NSNotification) {
let incomingManagedObjectContext: NSManagedObjectContext = notification.object as! NSManagedObjectContext
let incomingPersistentStoreCoordinator: NSPersistentStoreCoordinator = incomingManagedObjectContext.persistentStoreCoordinator!
let userInfo = notification.userInfo
// inserts
let insertedSet: NSSet = userInfo?[NSInsertedObjectsKey] as! NSSet
let inserted: NSMutableSet = insertedSet.mutableCopy() as! NSMutableSet
inserted.filterUsingPredicate(masterPredicate!)
if 0 < inserted.count {
let nodes: Array<NSManagedObject> = inserted.allObjects as! [NSManagedObject]
for node: NSManagedObject in nodes {
let className = String.fromCString(object_getClassName(node))
switch(className!) {
case "ManagedEntity_ManagedEntity_":
delegate?.graphDidInsertEntity?(self, entity: Entity(entity: node as! ManagedEntity))
break
case "EntityGroup_EntityGroup_":
let group: EntityGroup = node as! EntityGroup
delegate?.graphDidInsertEntityGroup?(self, entity: Entity(entity: group.node), group: group.name)
break
case "EntityProperty_EntityProperty_":
let property: EntityProperty = node as! EntityProperty
delegate?.graphDidInsertEntityProperty?(self, entity: Entity(entity: property.node), property: property.name, value: property.object)
break
case "ManagedAction_ManagedAction_":
delegate?.graphDidInsertAction?(self, action: Action(action: node as! ManagedAction))
break
case "ActionGroup_ActionGroup_":
let group: ActionGroup = node as! ActionGroup
delegate?.graphDidInsertActionGroup?(self, action: Action(action: group.node), group: group.name)
break
case "ActionProperty_ActionProperty_":
let property: ActionProperty = node as! ActionProperty
delegate?.graphDidInsertActionProperty?(self, action: Action(action: property.node), property: property.name, value: property.object)
break
case "ManagedBond_ManagedBond_":
delegate?.graphDidInsertBond?(self, bond: Bond(bond: node as! ManagedBond))
break
case "BondGroup_BondGroup_":
let group: BondGroup = node as! BondGroup
delegate?.graphDidInsertBondGroup?(self, bond: Bond(bond: group.node), group: group.name)
break
case "BondProperty_BondProperty_":
let property: BondProperty = node as! BondProperty
delegate?.graphDidInsertBondProperty?(self, bond: Bond(bond: property.node), property: property.name, value: property.object)
break
default:
assert(false, "[GraphKit Error: Graph observed an object that is invalid.]")
}
}
}
// updates
let updatedSet: NSSet = userInfo?[NSUpdatedObjectsKey] as! NSSet
let updated: NSMutableSet = updatedSet.mutableCopy() as! NSMutableSet
updated.filterUsingPredicate(masterPredicate!)
if 0 < updated.count {
let nodes: Array<NSManagedObject> = updated.allObjects as! [NSManagedObject]
for node: NSManagedObject in nodes {
let className = String.fromCString(object_getClassName(node))
switch(className!) {
case "EntityProperty_EntityProperty_":
let property: EntityProperty = node as! EntityProperty
delegate?.graphDidUpdateEntityProperty?(self, entity: Entity(entity: property.node), property: property.name, value: property.object)
break
case "ActionProperty_ActionProperty_":
let property: ActionProperty = node as! ActionProperty
delegate?.graphDidUpdateActionProperty?(self, action: Action(action: property.node), property: property.name, value: property.object)
break
case "BondProperty_BondProperty_":
let property: BondProperty = node as! BondProperty
delegate?.graphDidUpdateBondProperty?(self, bond: Bond(bond: property.node), property: property.name, value: property.object)
break
case "ManagedAction_ManagedAction_":
delegate?.graphDidUpdateAction?(self, action: Action(action: node as! ManagedAction))
break
default:
assert(false, "[GraphKit Error: Graph observed an object that is invalid.]")
}
}
}
// deletes
var deletedSet: NSSet? = userInfo?[NSDeletedObjectsKey] as? NSSet
if nil == deletedSet {
return
}
var deleted: NSMutableSet = deletedSet!.mutableCopy() as! NSMutableSet
deleted.filterUsingPredicate(masterPredicate!)
if 0 < deleted.count {
let nodes: Array<NSManagedObject> = deleted.allObjects as! [NSManagedObject]
for node: NSManagedObject in nodes {
let className = String.fromCString(object_getClassName(node))
switch(className!) {
case "ManagedEntity_ManagedEntity_":
delegate?.graphDidDeleteEntity?(self, entity: Entity(entity: node as! ManagedEntity))
break
case "ManagedAction_ManagedAction_":
delegate?.graphDidDeleteAction?(self, action: Action(action: node as! ManagedAction))
break
case "ManagedBond_ManagedBond_":
delegate?.graphDidDeleteBond?(self, bond: Bond(bond: node as! ManagedBond))
break
default:break
}
}
}
}
/**
:name: worker
:description: A NSManagedObjectContext that is configured to be thread safe
for the NSManagedObjects calling on it.
*/
internal var worker: NSManagedObjectContext? {
dispatch_once(&GraphMainManagedObjectContext.onceToken) {
GraphMainManagedObjectContext.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
GraphMainManagedObjectContext.managedObjectContext?.parentContext = self.privateContext
}
return GraphPrivateManagedObjectContext.managedObjectContext
}
// make thread safe by creating this asynchronously
private var privateContext: NSManagedObjectContext? {
dispatch_once(&GraphPrivateManagedObjectContext.onceToken) {
GraphPrivateManagedObjectContext.managedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
GraphPrivateManagedObjectContext.managedObjectContext?.persistentStoreCoordinator = self.persistentStoreCoordinator
}
return GraphPrivateManagedObjectContext.managedObjectContext
}
private var managedObjectModel: NSManagedObjectModel? {
dispatch_once(&GraphManagedObjectModel.onceToken) {
GraphManagedObjectModel.managedObjectModel = NSManagedObjectModel()
var entityDescription: NSEntityDescription = NSEntityDescription()
var entityProperties: Array<AnyObject> = Array<AnyObject>()
entityDescription.name = GraphUtility.entityDescriptionName
entityDescription.managedObjectClassName = GraphUtility.entityObjectClassName
var actionDescription: NSEntityDescription = NSEntityDescription()
var actionProperties: Array<AnyObject> = Array<AnyObject>()
actionDescription.name = GraphUtility.actionDescriptionName
actionDescription.managedObjectClassName = GraphUtility.actionObjectClassName
var bondDescription: NSEntityDescription = NSEntityDescription()
var bondProperties: Array<AnyObject> = Array<AnyObject>()
bondDescription.name = GraphUtility.bondDescriptionName
bondDescription.managedObjectClassName = GraphUtility.bondObjectClassName
var entityPropertyDescription: NSEntityDescription = NSEntityDescription()
var entityPropertyProperties: Array<AnyObject> = Array<AnyObject>()
entityPropertyDescription.name = GraphUtility.entityPropertyDescriptionName
entityPropertyDescription.managedObjectClassName = GraphUtility.entityPropertyObjectClassName
var actionPropertyDescription: NSEntityDescription = NSEntityDescription()
var actionPropertyProperties: Array<AnyObject> = Array<AnyObject>()
actionPropertyDescription.name = GraphUtility.actionPropertyDescriptionName
actionPropertyDescription.managedObjectClassName = GraphUtility.actionPropertyObjectClassName
var bondPropertyDescription: NSEntityDescription = NSEntityDescription()
var bondPropertyProperties: Array<AnyObject> = Array<AnyObject>()
bondPropertyDescription.name = GraphUtility.bondPropertyDescriptionName
bondPropertyDescription.managedObjectClassName = GraphUtility.bondPropertyObjectClassName
var entityGroupDescription: NSEntityDescription = NSEntityDescription()
var entityGroupProperties: Array<AnyObject> = Array<AnyObject>()
entityGroupDescription.name = GraphUtility.entityGroupDescriptionName
entityGroupDescription.managedObjectClassName = GraphUtility.entityGroupObjectClassName
var actionGroupDescription: NSEntityDescription = NSEntityDescription()
var actionGroupProperties: Array<AnyObject> = Array<AnyObject>()
actionGroupDescription.name = GraphUtility.actionGroupDescriptionName
actionGroupDescription.managedObjectClassName = GraphUtility.actionGroupObjectClassName
var bondGroupDescription: NSEntityDescription = NSEntityDescription()
var bondGroupProperties: Array<AnyObject> = Array<AnyObject>()
bondGroupDescription.name = GraphUtility.bondGroupDescriptionName
bondGroupDescription.managedObjectClassName = GraphUtility.bondGroupObjectClassName
var nodeClass: NSAttributeDescription = NSAttributeDescription()
nodeClass.name = "nodeClass"
nodeClass.attributeType = .StringAttributeType
nodeClass.optional = false
entityProperties.append(nodeClass.copy() as! NSAttributeDescription)
actionProperties.append(nodeClass.copy() as! NSAttributeDescription)
bondProperties.append(nodeClass.copy() as! NSAttributeDescription)
var type: NSAttributeDescription = NSAttributeDescription()
type.name = "type"
type.attributeType = .StringAttributeType
type.optional = false
entityProperties.append(type.copy() as! NSAttributeDescription)
actionProperties.append(type.copy() as! NSAttributeDescription)
bondProperties.append(type.copy() as! NSAttributeDescription)
var createdDate: NSAttributeDescription = NSAttributeDescription()
createdDate.name = "createdDate"
createdDate.attributeType = .DateAttributeType
createdDate.optional = false
entityProperties.append(createdDate.copy() as! NSAttributeDescription)
actionProperties.append(createdDate.copy() as! NSAttributeDescription)
bondProperties.append(createdDate.copy() as! NSAttributeDescription)
var propertyName: NSAttributeDescription = NSAttributeDescription()
propertyName.name = "name"
propertyName.attributeType = .StringAttributeType
propertyName.optional = false
entityPropertyProperties.append(propertyName.copy() as! NSAttributeDescription)
actionPropertyProperties.append(propertyName.copy() as! NSAttributeDescription)
bondPropertyProperties.append(propertyName.copy() as! NSAttributeDescription)
var propertyValue: NSAttributeDescription = NSAttributeDescription()
propertyValue.name = "object"
propertyValue.attributeType = .TransformableAttributeType
propertyValue.attributeValueClassName = "AnyObject"
propertyValue.optional = false
propertyValue.storedInExternalRecord = true
entityPropertyProperties.append(propertyValue.copy() as! NSAttributeDescription)
actionPropertyProperties.append(propertyValue.copy() as! NSAttributeDescription)
bondPropertyProperties.append(propertyValue.copy() as! NSAttributeDescription)
var propertyRelationship: NSRelationshipDescription = NSRelationshipDescription()
propertyRelationship.name = "node"
propertyRelationship.minCount = 1
propertyRelationship.maxCount = 1
propertyRelationship.optional = false
propertyRelationship.deleteRule = .NullifyDeleteRule
var propertySetRelationship: NSRelationshipDescription = NSRelationshipDescription()
propertySetRelationship.name = "propertySet"
propertySetRelationship.minCount = 0
propertySetRelationship.maxCount = 0
propertySetRelationship.optional = false
propertySetRelationship.deleteRule = .CascadeDeleteRule
propertyRelationship.inverseRelationship = propertySetRelationship
propertySetRelationship.inverseRelationship = propertyRelationship
propertyRelationship.destinationEntity = entityDescription
propertySetRelationship.destinationEntity = entityPropertyDescription
entityPropertyProperties.append(propertyRelationship.copy() as! NSRelationshipDescription)
entityProperties.append(propertySetRelationship.copy() as! NSRelationshipDescription)
propertyRelationship.destinationEntity = actionDescription
propertySetRelationship.destinationEntity = actionPropertyDescription
actionPropertyProperties.append(propertyRelationship.copy() as! NSRelationshipDescription)
actionProperties.append(propertySetRelationship.copy() as! NSRelationshipDescription)
propertyRelationship.destinationEntity = bondDescription
propertySetRelationship.destinationEntity = bondPropertyDescription
bondPropertyProperties.append(propertyRelationship.copy() as! NSRelationshipDescription)
bondProperties.append(propertySetRelationship.copy() as! NSRelationshipDescription)
var group: NSAttributeDescription = NSAttributeDescription()
group.name = "name"
group.attributeType = .StringAttributeType
group.optional = false
entityGroupProperties.append(group.copy() as! NSAttributeDescription)
actionGroupProperties.append(group.copy() as! NSAttributeDescription)
bondGroupProperties.append(group.copy() as! NSAttributeDescription)
var groupRelationship: NSRelationshipDescription = NSRelationshipDescription()
groupRelationship.name = "node"
groupRelationship.minCount = 1
groupRelationship.maxCount = 1
groupRelationship.optional = false
groupRelationship.deleteRule = .NullifyDeleteRule
var groupSetRelationship: NSRelationshipDescription = NSRelationshipDescription()
groupSetRelationship.name = "groupSet"
groupSetRelationship.minCount = 0
groupSetRelationship.maxCount = 0
groupSetRelationship.optional = false
groupSetRelationship.deleteRule = .CascadeDeleteRule
groupRelationship.inverseRelationship = groupSetRelationship
groupSetRelationship.inverseRelationship = groupRelationship
groupRelationship.destinationEntity = entityDescription
groupSetRelationship.destinationEntity = entityGroupDescription
entityGroupProperties.append(groupRelationship.copy() as! NSRelationshipDescription)
entityProperties.append(groupSetRelationship.copy() as! NSRelationshipDescription)
groupRelationship.destinationEntity = actionDescription
groupSetRelationship.destinationEntity = actionGroupDescription
actionGroupProperties.append(groupRelationship.copy() as! NSRelationshipDescription)
actionProperties.append(groupSetRelationship.copy() as! NSRelationshipDescription)
groupRelationship.destinationEntity = bondDescription
groupSetRelationship.destinationEntity = bondGroupDescription
bondGroupProperties.append(groupRelationship.copy() as! NSRelationshipDescription)
bondProperties.append(groupSetRelationship.copy() as! NSRelationshipDescription)
// Inverse relationship for Subjects -- B.
var actionSubjectSetRelationship: NSRelationshipDescription = NSRelationshipDescription()
actionSubjectSetRelationship.name = "subjectSet"
actionSubjectSetRelationship.minCount = 0
actionSubjectSetRelationship.maxCount = 0
actionSubjectSetRelationship.optional = false
actionSubjectSetRelationship.deleteRule = .NullifyDeleteRule
actionSubjectSetRelationship.destinationEntity = entityDescription
var actionSubjectRelationship: NSRelationshipDescription = NSRelationshipDescription()
actionSubjectRelationship.name = "actionSubjectSet"
actionSubjectRelationship.minCount = 0
actionSubjectRelationship.maxCount = 0
actionSubjectRelationship.optional = false
actionSubjectRelationship.deleteRule = .CascadeDeleteRule
actionSubjectRelationship.destinationEntity = actionDescription
actionSubjectRelationship.inverseRelationship = actionSubjectSetRelationship
actionSubjectSetRelationship.inverseRelationship = actionSubjectRelationship
entityProperties.append(actionSubjectRelationship.copy() as! NSRelationshipDescription)
actionProperties.append(actionSubjectSetRelationship.copy() as! NSRelationshipDescription)
// Inverse relationship for Subjects -- E.
// Inverse relationship for Objects -- B.
var actionObjectSetRelationship: NSRelationshipDescription = NSRelationshipDescription()
actionObjectSetRelationship.name = "objectSet"
actionObjectSetRelationship.minCount = 0
actionObjectSetRelationship.maxCount = 0
actionObjectSetRelationship.optional = false
actionObjectSetRelationship.deleteRule = .NullifyDeleteRule
actionObjectSetRelationship.destinationEntity = entityDescription
var actionObjectRelationship: NSRelationshipDescription = NSRelationshipDescription()
actionObjectRelationship.name = "actionObjectSet"
actionObjectRelationship.minCount = 0
actionObjectRelationship.maxCount = 0
actionObjectRelationship.optional = false
actionObjectRelationship.deleteRule = .CascadeDeleteRule
actionObjectRelationship.destinationEntity = actionDescription
actionObjectRelationship.inverseRelationship = actionObjectSetRelationship
actionObjectSetRelationship.inverseRelationship = actionObjectRelationship
entityProperties.append(actionObjectRelationship.copy() as! NSRelationshipDescription)
actionProperties.append(actionObjectSetRelationship.copy() as! NSRelationshipDescription)
// Inverse relationship for Objects -- E.
// Inverse relationship for Subjects -- B.
var bondSubjectSetRelationship = NSRelationshipDescription()
bondSubjectSetRelationship.name = "subject"
bondSubjectSetRelationship.minCount = 1
bondSubjectSetRelationship.maxCount = 1
bondSubjectSetRelationship.optional = true
bondSubjectSetRelationship.deleteRule = .NullifyDeleteRule
bondSubjectSetRelationship.destinationEntity = entityDescription
var bondSubjectRelationship: NSRelationshipDescription = NSRelationshipDescription()
bondSubjectRelationship.name = "bondSubjectSet"
bondSubjectRelationship.minCount = 0
bondSubjectRelationship.maxCount = 0
bondSubjectRelationship.optional = false
bondSubjectRelationship.deleteRule = .CascadeDeleteRule
bondSubjectRelationship.destinationEntity = bondDescription
bondSubjectRelationship.inverseRelationship = bondSubjectSetRelationship
bondSubjectSetRelationship.inverseRelationship = bondSubjectRelationship
entityProperties.append(bondSubjectRelationship.copy() as! NSRelationshipDescription)
bondProperties.append(bondSubjectSetRelationship.copy() as! NSRelationshipDescription)
// Inverse relationship for Subjects -- E.
// Inverse relationship for Objects -- B.
var bondObjectSetRelationship = NSRelationshipDescription()
bondObjectSetRelationship.name = "object"
bondObjectSetRelationship.minCount = 1
bondObjectSetRelationship.maxCount = 1
bondObjectSetRelationship.optional = true
bondObjectSetRelationship.deleteRule = .NullifyDeleteRule
bondObjectSetRelationship.destinationEntity = entityDescription
var bondObjectRelationship: NSRelationshipDescription = NSRelationshipDescription()
bondObjectRelationship.name = "bondObjectSet"
bondObjectRelationship.minCount = 0
bondObjectRelationship.maxCount = 0
bondObjectRelationship.optional = false
bondObjectRelationship.deleteRule = .CascadeDeleteRule
bondObjectRelationship.destinationEntity = bondDescription
bondObjectRelationship.inverseRelationship = bondObjectSetRelationship
bondObjectSetRelationship.inverseRelationship = bondObjectRelationship
entityProperties.append(bondObjectRelationship.copy() as! NSRelationshipDescription)
bondProperties.append(bondObjectSetRelationship.copy() as! NSRelationshipDescription)
// Inverse relationship for Objects -- E.
entityDescription.properties = entityProperties
entityGroupDescription.properties = entityGroupProperties
entityPropertyDescription.properties = entityPropertyProperties
actionDescription.properties = actionProperties
actionGroupDescription.properties = actionGroupProperties
actionPropertyDescription.properties = actionPropertyProperties
bondDescription.properties = bondProperties
bondGroupDescription.properties = bondGroupProperties
bondPropertyDescription.properties = bondPropertyProperties
GraphManagedObjectModel.managedObjectModel?.entities = [
entityDescription,
entityGroupDescription,
entityPropertyDescription,
actionDescription,
actionGroupDescription,
actionPropertyDescription,
bondDescription,
bondGroupDescription,
bondPropertyDescription
]
}
return GraphManagedObjectModel.managedObjectModel
}
private var persistentStoreCoordinator: NSPersistentStoreCoordinator? {
dispatch_once(&GraphPersistentStoreCoordinator.onceToken) {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent(GraphUtility.storeName)
var error: NSError?
GraphPersistentStoreCoordinator.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel!)
var options: Dictionary = [NSReadOnlyPersistentStoreOption: false, NSSQLitePragmasOption: ["journal_mode": "DELETE"]];
if nil == GraphPersistentStoreCoordinator.persistentStoreCoordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options as [NSObject : AnyObject], error: &error) {
assert(nil == error, "[GraphKit Error: Saving to internal context.]")
}
}
return GraphPersistentStoreCoordinator.persistentStoreCoordinator
}
private var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex - 1] as! NSURL
}
/**
:name: prepareForObservation
:description: Ensures NotificationCenter is watching the callback selector for this Graph.
*/
private func prepareForObservation() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "managedObjectContextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: privateContext)
}
/**
:name: addPredicateToContextWatcher
:description: Adds the given predicate to the master predicate, which holds all watchers for the Graph.
*/
private func addPredicateToContextWatcher(entityDescription: NSEntityDescription!, predicate: NSPredicate!) {
var entityPredicate: NSPredicate = NSPredicate(format: "entity.name == %@", entityDescription.name!)
var predicates: Array<NSPredicate> = [entityPredicate, predicate]
let finalPredicate: NSPredicate = NSCompoundPredicate.andPredicateWithSubpredicates(predicates)
masterPredicate = nil != masterPredicate ? NSCompoundPredicate.orPredicateWithSubpredicates([masterPredicate!, finalPredicate]) : finalPredicate
}
/**
:name: ensureWatching
:description: A sanity check if the Graph is already watching the specified index and key.
*/
private func ensureWatching(key: String!, index: String!) -> Bool {
var watch: Array<String> = nil != watching[index] ? watching[index]! as Array<String> : Array<String>()
for entry: String in watch {
if entry == key {
return true
}
}
watch.append(key)
watching[index] = watch
return false
}
/**
:name: addWatcher
:description: Adds a watcher to the Graph.
*/
internal func addWatcher(key: String!, value: String!, index: String!, entityDescriptionName: String!, managedObjectClassName: String!) {
if true == ensureWatching(value, index: index) {
return
}
var entityDescription: NSEntityDescription = NSEntityDescription()
entityDescription.name = entityDescriptionName
entityDescription.managedObjectClassName = managedObjectClassName
var predicate: NSPredicate = NSPredicate(format: "%K LIKE %@", key as NSString, value as NSString)
addPredicateToContextWatcher(entityDescription, predicate: predicate)
prepareForObservation()
}
/**
:name: search
:description: Executes a search through CoreData.
*/
private func search(entityDescriptorName: NSString!, predicate: NSPredicate!) -> Array<AnyObject>! {
return search(entityDescriptorName, predicate: predicate, sort: nil)
}
/**
:name: search
:description: Executes a search through CoreData.
*/
private func search(entityDescriptorName: NSString!, predicate: NSPredicate!, sort: Array<NSSortDescriptor>?) -> Array<AnyObject>! {
let request: NSFetchRequest = NSFetchRequest()
let entity: NSEntityDescription = managedObjectModel?.entitiesByName[entityDescriptorName] as! NSEntityDescription
request.entity = entity
request.predicate = predicate
request.fetchBatchSize = batchSize
request.fetchOffset = batchOffset
request.sortDescriptors = sort
var error: NSError?
var nodes: Array<AnyObject> = Array<AnyObject>()
var moc: NSManagedObjectContext? = worker
if let result: Array<AnyObject> = moc?.executeFetchRequest(request, error: &error) {
assert(nil == error, "[GraphKit Error: Fecthing nodes.]")
for item: AnyObject in result {
nodes.append(item)
}
}
return nodes
}
}
| agpl-3.0 | fb7009869defbf08bd92abadfa7f3b4c | 45.824165 | 214 | 0.781778 | 4.821667 | false | false | false | false |
JigarM/SwiftTweets | SwiftTweets/TweetsTableviewDelegate.swift | 1 | 857 | //
// TweetsTableviewDelegate.swift
// SwiftTweets
//
// Created by Jigar M on 30/07/14.
// Copyright (c) 2014 Jigar M. All rights reserved.
//
import UIKit
class TweetsTableviewDelegate: NSObject, UITableViewDataSource, UITableViewDelegate {
var tweets = Array<AnyObject>()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
let tweet = tweets[indexPath.row] as NSDictionary
cell.textLabel.text = tweet["text"] as String
cell.detailTextLabel.text = tweet["created_at"] as String
return cell
}
}
| mit | df8a06904dcf411ad97139b03513e3c6 | 31.961538 | 114 | 0.70245 | 4.897143 | false | false | false | false |
jayesh15111988/JKWayfairPriceGame | JKWayfairPriceGame/GameHomePageViewController.swift | 1 | 15149 | //
// GameHomePage.swift
// JKWayfairPriceGame
//
// Created by Jayesh Kawli Backup on 8/16/16.
// Copyright © 2016 Jayesh Kawli Backup. All rights reserved.
//
import Foundation
import UIKit
private let GameInstructionsViewDisplayedIndicator: String = "gameInstructionsViewDisplayedIndicator"
class GameHomePageViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let viewModel: GameHomePageViewModel
let categoryInputTextField: UITextField
var selectedCategoryIdentifier: String
let instructionsNavigationViewController: UINavigationController
let beginGameButton: CustomButton
let beginGameWithDefaultsButton: CustomButton
init(viewModel: GameHomePageViewModel) {
self.viewModel = viewModel
self.selectedCategoryIdentifier = ""
self.categoryInputTextField = UITextField()
self.categoryInputTextField.translatesAutoresizingMaskIntoConstraints = false
self.categoryInputTextField.borderStyle = .Line
self.categoryInputTextField.textAlignment = .Center
self.categoryInputTextField.font = Appearance.defaultFont()
self.categoryInputTextField.placeholder = "Please Choose Product Category"
let instructionsViewController = GameInstructionsViewController(viewModel: GameInstructionsViewModel(instructionsFileName: "instructions"))
self.instructionsNavigationViewController = UINavigationController(rootViewController: instructionsViewController)
beginGameButton = CustomButton()
beginGameButton.translatesAutoresizingMaskIntoConstraints = false
beginGameButton.setTitle("Begin Game", forState: .Normal)
beginGameButton.titleLabel?.font = Appearance.buttonsFont()
beginGameButton.setTitleColor(.whiteColor(), forState: .Normal)
beginGameButton.backgroundColor = Appearance.buttonBackgroundColor()
beginGameButton.rac_command = self.viewModel.startGameActionCommand
beginGameWithDefaultsButton = CustomButton()
beginGameWithDefaultsButton.translatesAutoresizingMaskIntoConstraints = false
beginGameWithDefaultsButton.setTitle("Begin Game Default Category", forState: .Normal)
beginGameWithDefaultsButton.titleLabel?.font = Appearance.buttonsFont()
beginGameWithDefaultsButton.setTitleColor(.whiteColor(), forState: .Normal)
beginGameWithDefaultsButton.backgroundColor = Appearance.buttonBackgroundColor()
beginGameWithDefaultsButton.rac_command = self.viewModel.startGameWithDefaultActionCommand
super.init(nibName: nil, bundle: nil)
instructionsViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(dismiss))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Price Guesser"
self.view.backgroundColor = UIColor.whiteColor()
self.setupAppearance()
let instructionsButton = UIButton(frame: CGRectMake(0, 0, 34, 34))
instructionsButton.setImage(UIImage(named: "Instructions"), forState: .Normal)
instructionsButton.rac_command = self.viewModel.gameInstructionsActionCommand
RACObserve(viewModel, keyPath: "showInstructionsView").ignore(false).subscribeNext { (_) in
self.showInstructionsView()
}
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: instructionsButton)
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(scrollView)
let contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(contentView)
let activityIndicatorView = UIActivityIndicatorView()
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
activityIndicatorView.activityIndicatorViewStyle = .WhiteLarge
activityIndicatorView.hidesWhenStopped = true
activityIndicatorView.color = Appearance.defaultAppColor()
let basicInstructionsLabel = UILabel()
basicInstructionsLabel.translatesAutoresizingMaskIntoConstraints = false
basicInstructionsLabel.numberOfLines = 0
basicInstructionsLabel.font = Appearance.titleFont()
basicInstructionsLabel.text = "Please select the category of your choice from the picker below and press Begin Game button to start the quiz"
contentView.addSubview(basicInstructionsLabel)
let pickerView = UIPickerView()
pickerView.translatesAutoresizingMaskIntoConstraints = false
pickerView.delegate = self
pickerView.dataSource = self
let toolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.width, 44))
toolbar.tintColor = .whiteColor()
toolbar.barTintColor = Appearance.defaultAppColor()
toolbar.items = [UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(cancelSelection)), UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(finishSelection))]
categoryInputTextField.inputView = pickerView
categoryInputTextField.inputAccessoryView = toolbar
contentView.addSubview(categoryInputTextField)
contentView.addSubview(beginGameButton)
contentView.addSubview(beginGameWithDefaultsButton)
let resetCategoriesButton = CustomButton()
resetCategoriesButton.translatesAutoresizingMaskIntoConstraints = false
resetCategoriesButton.setTitle("Reset Categories", forState: .Normal)
resetCategoriesButton.setTitleColor(.whiteColor(), forState: .Normal)
resetCategoriesButton.backgroundColor = Appearance.buttonBackgroundColor()
resetCategoriesButton.titleLabel?.font = Appearance.buttonsFont()
resetCategoriesButton.rac_command = self.viewModel.resetCategoriesActionCommand
contentView.addSubview(resetCategoriesButton)
self.view.addSubview(activityIndicatorView)
self.view.addConstraint(NSLayoutConstraint(item: activityIndicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: activityIndicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0))
let topLayoutGuide = self.topLayoutGuide
let spacer1 = UIView()
spacer1.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(spacer1)
let spacer2 = UIView()
spacer2.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(spacer2)
let views: [String: AnyObject] = ["topLayoutGuide": topLayoutGuide, "beginGameButton": beginGameButton, "contentView": contentView, "scrollView": scrollView, "basicInstructionsLabel": basicInstructionsLabel, "categoryInputTextField": categoryInputTextField, "beginGameWithDefaultsButton": beginGameWithDefaultsButton, "resetCategoriesButton": resetCategoriesButton, "spacer1": spacer1, "spacer2": spacer2]
let metrics = ["inputFieldHeight": 34, "bottomViewPadding": 40, "defaultViewPadding": 20]
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1.0, constant: 0))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[spacer1(==20@999)]-[basicInstructionsLabel(<=400)]-[spacer2(==spacer1@999)]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[spacer1(==20@999)]-[categoryInputTextField(<=400)]-[spacer2(==spacer1@999)]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[spacer1(==20@999)]-[beginGameButton]-[spacer2(==spacer1@999)]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[spacer1(==20@999)]-[beginGameWithDefaultsButton]-[spacer2(==spacer1@999)]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[spacer1(==20@999)]-[resetCategoriesButton]-[spacer2(==spacer1@999)]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-defaultViewPadding-[basicInstructionsLabel(>=0)]-defaultViewPadding-[categoryInputTextField(inputFieldHeight)]-defaultViewPadding-[beginGameButton(inputFieldHeight)]-[beginGameWithDefaultsButton(inputFieldHeight)]-[resetCategoriesButton(inputFieldHeight)]-bottomViewPadding-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
RACObserve(viewModel, keyPath: "productsLoading").subscribeNext { (loading) in
if let loading = loading as? Bool {
if (loading == true) {
activityIndicatorView.startAnimating()
} else {
activityIndicatorView.stopAnimating()
}
self.buttonsUserInteractionEnable(!loading)
}
}
RACObserve(viewModel, keyPath: "defaultGameModeStatus").ignore(nil).subscribeNext { (defaultGameModeStatus) in
if let defaultGameModeStatus = defaultGameModeStatus as? Bool {
self.beginGameButton.userInteractionEnabled = !defaultGameModeStatus
self.beginGameButton.alpha = defaultGameModeStatus == true ? 0.5 : 1.0
}
}
RACObserve(viewModel, keyPath: "errorMessage").ignore("").ignore(nil).subscribeNext { (errorMessage) in
if let errorMessage = errorMessage as? String {
let alertController = UIAlertController(title: "Product Quiz", message: errorMessage, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
}
}
}
RACObserve(viewModel, keyPath: "gameViewModel").ignore(nil).subscribeNext { (gameViewModel) in
if let gameViewModel = gameViewModel as? GameViewModel {
let gameViewController = GameViewController(gameViewModel: gameViewModel as GameViewModel)
self.navigationController?.pushViewController(gameViewController, animated: true)
}
}
RACObserve(viewModel, keyPath: "productCategoriesCollection").ignore(nil).subscribeNext { (productCategoriesCollection) in
if let productCategoriesCollection = productCategoriesCollection as? [ProductCategory] {
self.categoryInputTextField.text = productCategoriesCollection[0].categoryName
self.selectedCategoryIdentifier = String(productCategoriesCollection[0].categoryIdentifier)
pickerView.reloadAllComponents()
pickerView.selectRow(0, inComponent: 0, animated: false)
self.categoryInputTextField.becomeFirstResponder()
}
}
self.rac_signalForSelector(#selector(viewDidAppear)).take(1).subscribeNext { [unowned self]
(_) in
if NSUserDefaults.standardUserDefaults().boolForKey(GameInstructionsViewDisplayedIndicator) == false {
self.showInstructionsView()
NSUserDefaults.standardUserDefaults().setBool(true, forKey: GameInstructionsViewDisplayedIndicator)
}
}
}
func showInstructionsView() {
self.presentViewController(instructionsNavigationViewController, animated: true, completion: nil)
}
func finishSelection() {
self.categoryInputTextField.resignFirstResponder()
self.viewModel.searchWithSelectedCategoryIdentifier(self.selectedCategoryIdentifier)
}
func cancelSelection() {
self.categoryInputTextField.resignFirstResponder()
}
func dismiss() {
self.instructionsNavigationViewController.dismissViewControllerAnimated(true, completion: nil)
}
func buttonsUserInteractionEnable(enable: Bool) {
let enableBeginGameButton = enable && viewModel.defaultGameModeStatus == false
self.beginGameButton.userInteractionEnabled = enableBeginGameButton
self.beginGameButton.alpha = enableBeginGameButton == true ? 1.0 : 0.5
self.beginGameWithDefaultsButton.userInteractionEnabled = enable
self.beginGameWithDefaultsButton.alpha = enable == true ? 1.0 : 0.5
}
//MARK: UIPickerView datasource and delegate methods
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.viewModel.productCategoriesCollection.count
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.categoryInputTextField.text = self.viewModel.productCategoriesCollection[row].categoryName
self.selectedCategoryIdentifier = String(self.viewModel.productCategoriesCollection[row].categoryIdentifier)
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.viewModel.productCategoriesCollection[row].categoryName
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
} | mit | 20219a8f3ba792777c1ffaf79173502f | 58.641732 | 440 | 0.720491 | 6.115462 | false | false | false | false |
vladislav-k/VKCheckbox | VKCheckbox.swift | 1 | 10980 | //
// VKCheckbox.swift
// VKCheckbox
//
// Created by Vladislav Kovalyov on 8/22/16.
// Copyright © 2016 WOOPSS.com http://woopss.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
typealias CheckboxValueChangedBlock = (_ isOn: Bool) -> Void
@objc enum VKCheckboxLine: Int
{
case normal
case thin
}
class VKCheckbox: UIView
{
// MARK: - Properties
/**
Private property which indicates current state of checkbox
Default value is false
- See: isOn()
*/
fileprivate var on: Bool = false
{
didSet
{
self.checkboxValueChangedBlock?(on)
}
}
/**
Closure which called when property 'on' is changed
*/
var checkboxValueChangedBlock: CheckboxValueChangedBlock?
// MARK: Customization
/**
Set background color of checkbox
*/
var bgColor: UIColor = UIColor.clear
{
didSet
{
if !self.isOn
{
self.setBackground(bgColor)
}
}
}
/**
Set background color of checkbox in selected state
*/
var bgColorSelected = UIColor.clear
{
didSet
{
if self.isOn
{
self.setBackground(bgColorSelected)
}
}
}
/**
Set checkmark color
*/
var color: UIColor = UIColor.blue
{
didSet
{
self.checkmark.color = color
}
}
/**
Set checkbox border width
*/
var borderWidth: CGFloat = 0
{
didSet
{
self.layer.borderWidth = borderWidth
}
}
/**
Set checkbox border color
*/
var borderColor: UIColor!
{
didSet
{
self.layer.borderColor = borderColor.cgColor
}
}
/**
Set checkbox corner radius
*/
var cornerRadius: CGFloat = 0
{
didSet
{
self.layer.cornerRadius = cornerRadius
self.backgroundView.layer.cornerRadius = cornerRadius
}
}
/**
Set line type
Default value is Normal
- See: VKCheckboxLine enum
*/
var line = VKCheckboxLine.normal
// MARK: Private properties
fileprivate var button = UIButton()
fileprivate var checkmark = VKCheckmarkView()
internal var backgroundView = UIImageView()
// MARK: - Init
override init(frame: CGRect)
{
super.init(frame: frame)
self.setupView()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.setupView()
}
fileprivate func setupView()
{
// Init base properties
self.cornerRadius = 8
self.borderWidth = 3
self.borderColor = UIColor.darkGray
self.color = UIColor(red: 46/255, green: 119/255, blue: 217/255, alpha: 1)
self.setBackground(UIColor.clear)
self.backgroundView.frame = self.bounds
self.backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight];
self.backgroundView.layer.masksToBounds = true
self.addSubview(self.backgroundView)
// Setup checkmark
self.checkmark.frame = self.bounds
self.checkmark.autoresizingMask = [.flexibleWidth, .flexibleHeight];
self.addSubview(self.checkmark)
// Setup button
self.button.frame = self.bounds
self.button.autoresizingMask = [.flexibleWidth, .flexibleHeight];
self.button.addTarget(self, action: #selector(VKCheckbox.buttonDidSelected), for: .touchUpInside)
self.addSubview(self.button)
}
override func layoutSubviews()
{
super.layoutSubviews()
self.button.bounds = self.bounds
self.checkmark.bounds = self.bounds
}
}
// MARK: - Public
extension VKCheckbox
{
/**
Function allows you to set checkbox state
- Parameter on Checkbox state
*/
func setOn(_ on: Bool)
{
self.setOn(on, animated: false)
}
/**
Function allows you to set checkbox state with animation
- Parameter on Checkbox state
- Parameter animated Enable anomation
*/
func setOn(_ on: Bool, animated: Bool)
{
self.on = on
self.showCheckmark(on, animated: animated)
if animated
{
UIView.animate(withDuration: 0.275, animations:
{
self.setBackground(on ? self.bgColorSelected : self.bgColor)
})
}
else
{
self.setBackground(on ? self.bgColorSelected : self.bgColor)
}
}
/**
Function allows to check current checkbox state
- Returns: State as Bool value
*/
var isOn: Bool
{
return self.on
}
/// Set checkbox background color
///
/// - Parameter backgroundColor: New color
internal func setBackground(_ backgroundColor: UIColor)
{
self.backgroundView.image = UIImage.from(color: backgroundColor)
}
}
// MARK: - Private
extension VKCheckbox
{
@objc fileprivate func buttonDidSelected()
{
self.setOn(!self.on, animated: true)
}
fileprivate func showCheckmark(_ show: Bool, animated: Bool)
{
if show == true
{
self.checkmark.strokeWidth = self.bounds.width / (self.line == .normal ? 10 : 20)
self.checkmark.show(animated)
}
else
{
self.checkmark.hide(animated)
}
}
}
//
// VKCheckbox.swift
// VKCheckmarkView
//
// Created by Vladislav Kovalyov on 8/22/16.
// Copyright © 2016 WOOPSS.com http://woopss.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.
//
private class VKCheckmarkView: UIView
{
var color: UIColor = UIColor.blue
fileprivate var animationDuration: TimeInterval = 0.275
fileprivate var strokeWidth: CGFloat = 0
fileprivate var checkmarkLayer: CAShapeLayer!
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.setupCheckmark()
}
required override init(frame: CGRect)
{
super.init(frame: frame)
self.setupCheckmark()
}
fileprivate func setupCheckmark()
{
self.checkmarkLayer = CAShapeLayer()
self.checkmarkLayer.fillColor = nil
}
}
extension VKCheckmarkView
{
func show(_ animated: Bool = true)
{
self.alpha = 1
self.checkmarkLayer.removeAllAnimations()
let checkmarkPath = UIBezierPath()
checkmarkPath.move(to: CGPoint(x: self.bounds.width * 0.28, y: self.bounds.height * 0.5))
checkmarkPath.addLine(to: CGPoint(x: self.bounds.width * 0.42, y: self.bounds.height * 0.66))
checkmarkPath.addLine(to: CGPoint(x: self.bounds.width * 0.72, y: self.bounds.height * 0.36))
checkmarkPath.lineCapStyle = .square
self.checkmarkLayer.path = checkmarkPath.cgPath
self.checkmarkLayer.strokeColor = self.color.cgColor
self.checkmarkLayer.lineWidth = self.strokeWidth
self.layer.addSublayer(self.checkmarkLayer)
if animated == false
{
checkmarkLayer.strokeEnd = 1
}
else
{
let checkmarkAnimation: CABasicAnimation = CABasicAnimation(keyPath:"strokeEnd")
checkmarkAnimation.duration = animationDuration
checkmarkAnimation.isRemovedOnCompletion = false
checkmarkAnimation.fillMode = CAMediaTimingFillMode.forwards
checkmarkAnimation.fromValue = 0
checkmarkAnimation.toValue = 1
checkmarkAnimation.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeIn)
self.checkmarkLayer.add(checkmarkAnimation, forKey:"strokeEnd")
}
}
func hide(_ animated: Bool = true)
{
var duration = self.animationDuration
if animated == false
{
duration = 0
}
UIView.animate(withDuration: duration, animations:
{
self.alpha = 0
}, completion: {
(completed) in
self.checkmarkLayer.removeFromSuperlayer()
})
}
}
extension UIImage
{
static func from(color: UIColor) -> UIImage
{
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
| mit | faf395c31711da1125fdca6baccef358 | 27.005102 | 108 | 0.615868 | 4.851083 | false | false | false | false |
lastobelus/eidolon | Kiosk/App/Views/RegisterFlowView.swift | 5 | 3473 | import UIKit
import ORStackView
import ReactiveCocoa
class RegisterFlowView: ORStackView {
dynamic var highlightedIndex = 0
let jumpToIndexSignal = RACSubject()
var details: BidDetails? {
didSet {
self.update()
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = .whiteColor()
self.bottomMarginHeight = CGFloat(NSNotFound)
self.updateConstraints()
}
var titles = ["Mobile", "Email", "Credit Card", "Postal/Zip"]
var keypaths = [["phoneNumber"], ["email"], ["creditCardName", "creditCardType"], ["zipCode"]]
func update() {
let user = details!.newUser
removeAllSubviews()
for i in 0 ..< titles.count {
let itemView = ItemView(frame: self.bounds)
itemView.createTitleViewWithTitle(titles[i])
addSubview(itemView, withTopMargin: "10", sideMargin: "0")
if let value = (keypaths[i].flatMap { user.valueForKey($0) as? String }.first) {
itemView.createInfoLabel(value)
let button = itemView.createJumpToButtonAtIndex(i)
button.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
itemView.constrainHeight("44")
} else {
itemView.constrainHeight("20")
}
if i == highlightedIndex {
itemView.highlight()
}
}
let spacer = UIView(frame: bounds)
spacer.setContentHuggingPriority(12, forAxis: .Horizontal)
addSubview(spacer, withTopMargin: "0", sideMargin: "0")
self.bottomMarginHeight = 0
}
func pressed(sender: UIButton!) {
jumpToIndexSignal.sendNext(sender.tag)
}
class ItemView : UIView {
var titleLabel: UILabel?
func highlight() {
titleLabel?.textColor = .artsyPurple()
}
func createTitleViewWithTitle(title: String) {
let label = UILabel(frame:self.bounds)
label.font = UIFont.sansSerifFontWithSize(16)
label.text = title.uppercaseString
titleLabel = label
self.addSubview(label)
label.constrainWidthToView(self, predicate: "0")
label.alignLeadingEdgeWithView(self, predicate: "0")
label.alignTopEdgeWithView(self, predicate: "0")
}
func createInfoLabel(info: String) {
let label = UILabel(frame:self.bounds)
label.font = UIFont.serifFontWithSize(16)
label.text = info
self.addSubview(label)
label.constrainWidthToView(self, predicate: "-52")
label.alignLeadingEdgeWithView(self, predicate: "0")
label.constrainTopSpaceToView(titleLabel!, predicate: "8")
}
func createJumpToButtonAtIndex(index: NSInteger) -> UIButton {
let button = UIButton(type: .Custom)
button.tag = index
button.setImage(UIImage(named: "edit_button"), forState: .Normal)
button.userInteractionEnabled = true
button.enabled = true
self.addSubview(button)
button.alignTopEdgeWithView(self, predicate: "0")
button.alignTrailingEdgeWithView(self, predicate: "0")
button.constrainWidth("36")
button.constrainHeight("36")
return button
}
}
}
| mit | 3962a0e84a46211c06646fe77b26f441 | 29.734513 | 98 | 0.58854 | 5.070073 | false | false | false | false |
ismailgulek/IGPagerView | IGPagerViewDemo/ViewController.swift | 1 | 1223 | //
// ViewController.swift
// IGPagerViewDemo
//
// Created by Ismail GULEK on 19/03/2017.
// Copyright © 2017 Ismail Gulek. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var pagerView: IGPagerView! {
didSet {
pagerView.dataSource = self
pagerView.delegate = self
}
}
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) {
pagerView.goToPage(sender.selectedSegmentIndex)
}
}
extension ViewController: IGPagerViewDataSource {
func pagerViewNumberOfPages(_ pager: IGPagerView) -> Int {
return 3
}
func pagerView(_ pager: IGPagerView, viewAt index: Int) -> UIView {
if index == 0 {
let view = UIView()
view.backgroundColor = UIColor.red
return view
} else if index == 1 {
let view = UIView()
view.backgroundColor = UIColor.green
return view
} else {
let view = UIView()
view.backgroundColor = UIColor.blue
return view
}
}
}
extension ViewController: IGPagerViewDelegate {
func pagerView(_ pager: IGPagerView, didScrollToPageAt index: Int) {
print("Index: \(index)")
segmentedControl.selectedSegmentIndex = index
}
}
| mit | dcbeacaedfce66143d07db30c37e97bc | 20.438596 | 76 | 0.713584 | 3.830721 | false | false | false | false |
BlenderSleuth/Circles | Circles/SKTUtils/SKAction+SpecialEffects.swift | 1 | 4172 | /*
* Copyright (c) 2013-2014 Razeware LLC
*
* 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 SpriteKit
public extension SKAction {
/**
* Creates a screen shake animation.
*
* @param node The node to shake. You cannot apply this effect to an SKScene.
* @param amount The vector by which the node is displaced.
* @param oscillations The number of oscillations; 10 is a good value.
* @param duration How long the effect lasts. Shorter is better.
*/
public class func screenShakeWithNode(_ node: SKNode, amount: CGPoint, oscillations: Int, duration: TimeInterval) -> SKAction {
let oldPosition = node.position
let newPosition = oldPosition + amount
let effect = SKTMoveEffect(node: node, duration: duration, startPosition: newPosition, endPosition: oldPosition)
effect.timingFunction = SKTCreateShakeFunction(oscillations)
return SKAction.actionWithEffect(effect)
}
/**
* Creates a screen rotation animation.
*
* @param node You usually want to apply this effect to a pivot node that is
* centered in the scene. You cannot apply the effect to an SKScene.
* @param angle The angle in radians.
* @param oscillations The number of oscillations; 10 is a good value.
* @param duration How long the effect lasts. Shorter is better.
*/
public class func screenRotateWithNode(_ node: SKNode, angle: CGFloat, oscillations: Int, duration: TimeInterval) -> SKAction {
let oldAngle = node.zRotation
let newAngle = oldAngle + angle
let effect = SKTRotateEffect(node: node, duration: duration, startAngle: newAngle, endAngle: oldAngle)
effect.timingFunction = SKTCreateShakeFunction(oscillations)
return SKAction.actionWithEffect(effect)
}
/**
* Creates a screen zoom animation.
*
* @param node You usually want to apply this effect to a pivot node that is
* centered in the scene. You cannot apply the effect to an SKScene.
* @param amount How much to scale the node in the X and Y directions.
* @param oscillations The number of oscillations; 10 is a good value.
* @param duration How long the effect lasts. Shorter is better.
*/
public class func screenZoomWithNode(_ node: SKNode, amount: CGPoint, oscillations: Int, duration: TimeInterval) -> SKAction {
let oldScale = CGPoint(x: node.xScale, y: node.yScale)
let newScale = oldScale * amount
let effect = SKTScaleEffect(node: node, duration: duration, startScale: newScale, endScale: oldScale)
effect.timingFunction = SKTCreateShakeFunction(oscillations)
return SKAction.actionWithEffect(effect)
}
/**
* Causes the scene background to flash for duration seconds.
*/
public class func colorGlitchWithScene(_ scene: SKScene, originalColor: SKColor, duration: TimeInterval) -> SKAction {
return SKAction.customAction(withDuration: duration) {(node, elapsedTime) in
if elapsedTime < CGFloat(duration) {
let random = Int.random(0..<256)
scene.backgroundColor = SKColorWithRGB(random, g: random, b: random)
} else {
scene.backgroundColor = originalColor
}
}
}
}
| gpl-3.0 | d8b8f9ac85a71e61187887b7a33b8ee5 | 42.915789 | 129 | 0.72675 | 4.49085 | false | false | false | false |
bizz84/ReviewTime | ReviewTime/Extensions/UINavigationControllerExtension/UINavigationControllerExtension.swift | 2 | 1937 | //
// UINavigationControllerExtension.swift
//
// Created by Nathan Hegedus on 12/3/14.
// Copyright (c) 2014 Nathan Hegedus. All rights reserved.
//
import UIKit
extension UINavigationController {
func pushViewControllerWithFade(viewController viewController: UIViewController) {
let transition: CATransition = CATransition()
transition.duration = 0.3
transition.type = kCATransitionFade
self.view.layer.addAnimation(transition, forKey: nil)
if self.navigationController?.viewControllers.last != viewController {
self.pushViewController(viewController, animated: false)
}
}
func popViewControllerAnimatedWithFade() {
let transition: CATransition = CATransition()
transition.duration = 0.3
transition.type = kCATransitionFade
self.view.layer.addAnimation(transition, forKey: nil)
self.popViewControllerAnimated(false)
}
func popToRootViewControllerAnimatedWithFade() {
let transition: CATransition = CATransition()
transition.duration = 0.3
transition.type = kCATransitionFade
self.view.layer.addAnimation(transition, forKey: nil)
self.popToRootViewControllerAnimated(false)
}
func popToViewControllerWithFade(viewController viewController: UIViewController) {
let transition: CATransition = CATransition()
transition.duration = 0.5
transition.type = kCATransitionFade
self.view.layer.addAnimation(transition, forKey: nil)
self.popToViewController(viewController, animated: false)
}
func removeFirstViewController() {
var viewControllers = self.viewControllers
viewControllers.removeAtIndex(0)
self.viewControllers = viewControllers
}
}
| mit | 3c52415c38fe36698178bc8f856be0e2 | 27.072464 | 87 | 0.655137 | 5.96 | false | false | false | false |
spritekitbook/spritekitbook-swift | Chapter 11/Start/SpaceRunner/SpaceRunner/GameScene.swift | 2 | 5135 | //
// GameScene.swift
// SpaceRunner
//
// Created by Jeremy Novak on 8/18/16.
// Copyright © 2016 Spritekit Book. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
// MARK: - State enum
private enum State {
case waiting, running, paused, gameOver
}
// MARK: - Private instance constants
private let background = Background()
private let player = Player()
private let meteorController = MeteorController()
private let starController = StarController()
private let startButton = StartButton()
private let interfaceNode = SKNode()
// MARK: - Private class variables
private var lastUpdateTime:TimeInterval = 0.0
private var state:State = .waiting
private var frameCount:TimeInterval = 0.0
private var statusBar = StatusBar()
// MARK: - Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(size: CGSize) {
super.init(size: size)
}
override func didMove(to view: SKView) {
self.setup()
}
// MARK: - Setup
private func setup() {
self.backgroundColor = Colors.colorFromRGB(rgbvalue: Colors.background)
// Physics
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
self.physicsWorld.contactDelegate = self
self.addChild(background)
self.addChild(player)
self.addChild(meteorController)
self.addChild(starController)
self.addChild(startButton)
self.addChild(interfaceNode)
statusBar = StatusBar(lives: player.getLives(), score: player.getScore(), stars: player.getStars())
interfaceNode.addChild(statusBar)
}
// MARK: - Update
override func update(_ currentTime: TimeInterval) {
let delta = currentTime - self.lastUpdateTime
self.lastUpdateTime = currentTime
if state != .running {
return
} else {
if player.getLives() > 0 {
player.update()
frameCount += delta
if frameCount >= 1.0 {
player.updateDistanceScore()
statusBar.updateScore(score: player.getScore())
frameCount = 0.0
}
meteorController.update(delta: delta)
starController.update(delta: delta)
} else {
stateGameOver()
}
}
}
// MARK: - Touch Handling
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first! as UITouch
let touchLocation = touch.location(in: self)
switch state {
case .waiting:
if startButton.contains(touchLocation) {
stateRunning()
}
case .running:
player.updateTargetPosition(position: touchLocation)
case .paused:
return
case .gameOver:
return
}
}
// MARK: - Contact
func didBegin(_ contact: SKPhysicsContact) {
if state != .running {
return
} else {
// Which body is not the player?
let other = contact.bodyA.categoryBitMask == Contact.player ? contact.bodyB : contact.bodyA
if other.categoryBitMask == Contact.meteor {
if !player.getImmunity() {
player.contact(body: (other.node?.name)!)
statusBar.updateLives(lives: player.getLives())
if let meteor = other.node as? Meteor {
meteor.contact(body: player.name!)
}
} else {
return
}
}
if other.categoryBitMask == Contact.star {
if let star = other.node as? Star {
star.contact()
player.pickup()
statusBar.updateStars(collected: player.getStars())
}
}
}
}
// MARK: - State
func stateRunning() {
state = .running
background.startBackground()
player.updateTargetPosition(position: kScreenCenter)
startButton.buttonTapped()
}
func statePaused() {
// Addressed in later chapter on pausing
}
func stateResume() {
// Addressed in later chapter on pausing
}
func stateGameOver() {
state = .gameOver
background.stopBackground()
}
// MARK: - Load Scene
private func loadScene() {
let scene = GameOverScene(size: kViewSize)
let transition = SKTransition.fade(with: SKColor.black, duration: 0.5)
self.view?.presentScene(scene, transition: transition)
}
}
| apache-2.0 | e482776d16ee2420af5b312f15210183 | 27.364641 | 107 | 0.53058 | 5.281893 | false | false | false | false |
Monnoroch/Cuckoo | Generator/Dependencies/SourceKitten/Carthage/Checkouts/SWXMLHash/Tests/SWXMLHashTests/TypeConversionArrayOfNonPrimitiveTypesTests.swift | 25 | 9566 | //
// TypeConversionArrayOfNonPrimitiveTypesTests.swift
//
// Copyright (c) 2016 David Mohundro
//
// 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 SWXMLHash
import XCTest
// swiftlint:disable force_try
// swiftlint:disable line_length
// swiftlint:disable type_name
class TypeConversionArrayOfNonPrimitiveTypesTests: XCTestCase {
var parser: XMLIndexer?
let xmlWithArraysOfTypes = "<root>" +
"<arrayOfGoodBasicItems>" +
" <basicItem>" +
" <name>item 1</name>" +
" <price>1</price>" +
" </basicItem>" +
" <basicItem>" +
" <name>item 2</name>" +
" <price>2</price>" +
" </basicItem>" +
" <basicItem>" +
" <name>item 3</name>" +
" <price>3</price>" +
" </basicItem>" +
"</arrayOfGoodBasicItems>" +
"<arrayOfBadBasicItems>" +
" <basicItem>" +
" <name>item 1</name>" +
" <price>1</price>" +
" </basicItem>" +
" <basicItem>" + // it's missing the name node
" <price>2</price>" +
" </basicItem>" +
" <basicItem>" +
" <name>item 3</name>" +
" <price>3</price>" +
" </basicItem>" +
"</arrayOfBadBasicItems>" +
"<arrayOfGoodAttributeItems>" +
" <attributeItem name=\"attr 1\" price=\"1.1\"/>" +
" <attributeItem name=\"attr 2\" price=\"2.2\"/>" +
" <attributeItem name=\"attr 3\" price=\"3.3\"/>" +
"</arrayOfGoodAttributeItems>" +
"<arrayOfBadAttributeItems>" +
" <attributeItem name=\"attr 1\" price=\"1.1\"/>" +
" <attributeItem price=\"2.2\"/>" + // it's missing the name attribute
" <attributeItem name=\"attr 3\" price=\"3.3\"/>" +
"</arrayOfBadAttributeItems>" +
"</root>"
let correctBasicItems = [
BasicItem(name: "item 1", price: 1),
BasicItem(name: "item 2", price: 2),
BasicItem(name: "item 3", price: 3)
]
let correctAttributeItems = [
AttributeItem(name: "attr 1", price: 1.1),
AttributeItem(name: "attr 2", price: 2.2),
AttributeItem(name: "attr 3", price: 3.3)
]
override func setUp() {
parser = SWXMLHash.parse(xmlWithArraysOfTypes)
}
func testShouldConvertArrayOfGoodBasicitemsItemsToNonOptional() {
do {
let value: [BasicItem] = try parser!["root"]["arrayOfGoodBasicItems"]["basicItem"].value()
XCTAssertEqual(value, correctBasicItems)
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfGoodBasicitemsItemsToOptional() {
do {
let value: [BasicItem]? = try parser!["root"]["arrayOfGoodBasicItems"]["basicItem"].value()
XCTAssertNotNil(value)
if let value = value {
XCTAssertEqual(value, correctBasicItems)
}
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfGoodBasicitemsItemsToArrayOfOptionals() {
do {
let value: [BasicItem?] = try parser!["root"]["arrayOfGoodBasicItems"]["basicItem"].value()
XCTAssertEqual(value.flatMap({ $0 }), correctBasicItems)
} catch {
XCTFail("\(error)")
}
}
func testShouldThrowWhenConvertingArrayOfBadBasicitemsToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadBasicItems"]["basicItem"].value() as [BasicItem])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfBadBasicitemsToOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadBasicItems"]["basicItem"].value() as [BasicItem]?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfBadBasicitemsToArrayOfOptionals() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadBasicItems"]["basicItem"].value() as [BasicItem?])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldConvertArrayOfGoodAttributeItemsToNonOptional() {
do {
let value: [AttributeItem] = try parser!["root"]["arrayOfGoodAttributeItems"]["attributeItem"].value()
XCTAssertEqual(value, correctAttributeItems)
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfGoodAttributeItemsToOptional() {
do {
let value: [AttributeItem]? = try parser!["root"]["arrayOfGoodAttributeItems"]["attributeItem"].value()
XCTAssertNotNil(value)
if let value = value {
XCTAssertEqual(value, correctAttributeItems)
}
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfGoodAttributeItemsToArrayOfOptionals() {
do {
let value: [AttributeItem?] = try parser!["root"]["arrayOfGoodAttributeItems"]["attributeItem"].value()
XCTAssertEqual(value.flatMap({ $0 }), correctAttributeItems)
} catch {
XCTFail("\(error)")
}
}
func testShouldThrowWhenConvertingArrayOfBadAttributeItemsToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadAttributeItems"]["attributeItem"].value() as [AttributeItem])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfBadAttributeItemsToOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadAttributeItems"]["attributeItem"].value() as [AttributeItem]?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfBadAttributeItemsToArrayOfOptionals() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadAttributeItems"]["attributeItem"].value() as [AttributeItem?])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
}
extension TypeConversionArrayOfNonPrimitiveTypesTests {
static var allTests: [(String, (TypeConversionArrayOfNonPrimitiveTypesTests) -> () throws -> Void)] {
return [
("testShouldConvertArrayOfGoodBasicitemsItemsToNonOptional", testShouldConvertArrayOfGoodBasicitemsItemsToNonOptional),
("testShouldConvertArrayOfGoodBasicitemsItemsToOptional", testShouldConvertArrayOfGoodBasicitemsItemsToOptional),
("testShouldConvertArrayOfGoodBasicitemsItemsToArrayOfOptionals", testShouldConvertArrayOfGoodBasicitemsItemsToArrayOfOptionals),
("testShouldThrowWhenConvertingArrayOfBadBasicitemsToNonOptional", testShouldThrowWhenConvertingArrayOfBadBasicitemsToNonOptional),
("testShouldThrowWhenConvertingArrayOfBadBasicitemsToOptional", testShouldThrowWhenConvertingArrayOfBadBasicitemsToOptional),
("testShouldThrowWhenConvertingArrayOfBadBasicitemsToArrayOfOptionals", testShouldThrowWhenConvertingArrayOfBadBasicitemsToArrayOfOptionals),
("testShouldConvertArrayOfGoodAttributeItemsToNonOptional", testShouldConvertArrayOfGoodAttributeItemsToNonOptional),
("testShouldConvertArrayOfGoodAttributeItemsToOptional", testShouldConvertArrayOfGoodAttributeItemsToOptional),
("testShouldConvertArrayOfGoodAttributeItemsToArrayOfOptionals", testShouldConvertArrayOfGoodAttributeItemsToArrayOfOptionals),
("testShouldThrowWhenConvertingArrayOfBadAttributeItemsToNonOptional", testShouldThrowWhenConvertingArrayOfBadAttributeItemsToNonOptional),
("testShouldThrowWhenConvertingArrayOfBadAttributeItemsToOptional", testShouldThrowWhenConvertingArrayOfBadAttributeItemsToOptional),
("testShouldThrowWhenConvertingArrayOfBadAttributeItemsToArrayOfOptionals", testShouldThrowWhenConvertingArrayOfBadAttributeItemsToArrayOfOptionals),
]
}
}
| mit | 893a98ff895f1b107f9a97d62ce10cfe | 42.285068 | 161 | 0.644575 | 5.843616 | false | true | false | false |
Noobish1/KeyedAPIParameters | KeyedAPIParametersTests/Protocols/KeyedAPIParametersSpec.swift | 1 | 1353 | import Quick
import Nimble
import Fakery
@testable import KeyedAPIParameters
fileprivate struct KeyedAPIParamsThing {
fileprivate let property: String
}
extension KeyedAPIParamsThing: KeyedAPIParameters {
public enum Key: String, ParamJSONKey {
case property
}
public func param(for key: Key) -> APIParamConvertible {
switch key {
case .property: return property
}
}
}
internal final class KeyedAPIParametersSpec: QuickSpec {
internal override func spec() {
describe("KeyedAPIParameters") {
let faker = Faker()
describe("it's toParamDictionary") {
it("should return its conformers keys as strings mapped to their param values") {
let thing = KeyedAPIParamsThing(property: faker.lorem.characters())
let keysAndValues = KeyedAPIParamsThing.Key.allCases.map { ($0, thing.param(for: $0)) }
let expected = Dictionary(uniqueKeysWithValues: keysAndValues).mapKeys { $0.stringValue }
let actual = thing.toParamDictionary().mapValues { $0.value(forHTTPMethod: .get) }
expect(actual as? [String : String]) == (expected as? [String : String])
}
}
}
}
}
| mit | 796e6e30f375090ef5ba6d7d54798e88 | 32.825 | 109 | 0.594235 | 5.10566 | false | false | false | false |
daferpi/p5App | p5App/Pods/HDAugmentedReality/HDAugmentedReality/Classes/Debug/DebugMapViewController.swift | 2 | 4347 | //
// MapViewController.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 20/06/15.
// Copyright (c) 2015 Danijel Huis. All rights reserved.
//
import UIKit
import MapKit
/// Called from ARViewController for debugging purposes
open class DebugMapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate
{
@IBOutlet weak var mapView: MKMapView!
fileprivate var annotations: [ARAnnotation]?
fileprivate var locationManager = CLLocationManager()
fileprivate var heading: Double = 0
fileprivate var interactionInProgress = false
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
open override func viewDidLoad()
{
super.viewDidLoad()
self.mapView.isRotateEnabled = false
if let annotations = self.annotations
{
addAnnotationsOnMap(annotations)
}
locationManager.delegate = self
}
open override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
locationManager.startUpdatingHeading()
}
open override func viewDidDisappear(_ animated: Bool)
{
super.viewDidDisappear(animated)
locationManager.stopUpdatingHeading()
}
open func addAnnotations(_ annotations: [ARAnnotation])
{
self.annotations = annotations
if self.isViewLoaded
{
addAnnotationsOnMap(annotations)
}
}
fileprivate func addAnnotationsOnMap(_ annotations: [ARAnnotation])
{
var mapAnnotations: [MKPointAnnotation] = []
for annotation in annotations
{
let coordinate = annotation.location.coordinate
let mapAnnotation = MKPointAnnotation()
mapAnnotation.coordinate = coordinate
let text = String(format: "%@, AZ: %.0f, %.0fm", annotation.title != nil ? annotation.title! : "", annotation.azimuth, annotation.distanceFromUser)
mapAnnotation.title = text
mapAnnotations.append(mapAnnotation)
}
mapView.addAnnotations(mapAnnotations)
mapView.showAnnotations(mapAnnotations, animated: false)
}
@IBAction func longTap(_ sender: UILongPressGestureRecognizer)
{
if sender.state == UIGestureRecognizerState.began
{
let point = sender.location(in: self.mapView)
let coordinate = self.mapView.convert(point, toCoordinateFrom: self.mapView)
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
let userInfo: [AnyHashable: Any] = ["location" : location]
self.presentingViewController?.dismiss(animated: true, completion: nil)
// Delay to allow trackingManager to update heading/pitch etc
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC))
{
NotificationCenter.default.post(name: Notification.Name(rawValue: "kNotificationLocationSet"), object: nil, userInfo: userInfo)
}
}
}
@IBAction func closeButtonTap(_ sender: AnyObject)
{
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
open func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading)
{
heading = newHeading.trueHeading
// Rotate map
/*if(!self.interactionInProgress && CLLocationCoordinate2DIsValid(mapView.centerCoordinate))
{
let camera = mapView.camera.copy() as! MKMapCamera
camera.heading = CLLocationDirection(heading);
self.mapView.setCamera(camera, animated: false)
}*/
}
open func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool)
{
self.interactionInProgress = true
}
open func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool)
{
self.interactionInProgress = false
}
}
| mit | 22242896ea4ef34ff0ed253edbedf163 | 32.183206 | 159 | 0.647343 | 5.447368 | false | false | false | false |
rymcol/Server-Side-Swift-Benchmarks-Summer-2017 | KituraPress/Sources/IndexHandler.swift | 1 | 1800 | #if os(Linux)
import Glibc
#else
import Darwin
#endif
struct IndexHandler {
func loadPageContent() -> String {
var post = "No matching post was found"
let randomContent = ContentGenerator().generate()
if let firstPost = randomContent["Test Post 1"] {
post = "\(firstPost)"
}
let imageNumber = Int(arc4random_uniform(25) + 1)
var finalContent = "<section id=\"content\"><div class=\"container\"><div class=\"row\"><div class=\"banner center-block\"><div><img src=\"/img/[email protected]\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-1.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-2.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-3.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-4.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-5.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div></div></div><div class=\"row\"><div class=\"col-xs-12\"><h1>"
finalContent += "Test Post 1"
finalContent += "</h1><img src=\""
finalContent += "/img/random/random-\(imageNumber).jpg\" alt=\"Random Image \(imageNumber)\" class=\"alignleft feature-image img-responsive\" />"
finalContent += "<div class=\"content\">"
finalContent += post
finalContent += "</div>"
finalContent += "</div></div</div></section>"
return finalContent
}
}
| apache-2.0 | 71203e2fea71dab8fb5393df77f266ce | 55.25 | 917 | 0.611111 | 4.109589 | false | true | false | false |
hyperoslo/Tabby | Sources/Views/TabbyBadge.swift | 1 | 2496 | import UIKit
open class TabbyBadge: UIView {
public lazy var containerView: UIView = UIView()
public lazy var numberLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = Constant.Font.badge
label.textColor = Constant.Color.Badge.text
return label
}()
public var number: Int = 0 {
didSet {
var text = "\(number)"
if number >= 99 {
text = "+99"
}
visible = number > 0
numberLabel.text = text
setupConstraints()
}
}
public var visible: Bool = false {
didSet {
alpha = visible ? 1 : 0
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
defer {
number = 0
}
backgroundColor = Constant.Color.Badge.border
containerView.backgroundColor = Constant.Color.Badge.background
setupConstraints()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Constraints
open func setupConstraints() {
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.removeFromSuperview()
addSubview(containerView)
constraint(containerView, attributes: .centerX, .centerY)
addConstraints([
NSLayoutConstraint(item: self,
attribute: .width, relatedBy: .equal,
toItem: containerView, attribute: .width,
multiplier: 1, constant: Constant.Dimension.Badge.border * 2),
NSLayoutConstraint(item: self,
attribute: .height, relatedBy: .equal,
toItem: containerView, attribute: .height,
multiplier: 1, constant: Constant.Dimension.Badge.border * 2)
])
numberLabel.translatesAutoresizingMaskIntoConstraints = false
numberLabel.removeFromSuperview()
containerView.addSubview(numberLabel)
containerView.constraint(numberLabel, attributes: .centerX, .centerY)
numberLabel.sizeToFit()
addConstraints([
NSLayoutConstraint(item: containerView,
attribute: .width, relatedBy: .equal,
toItem: numberLabel, attribute: .width,
multiplier: 1, constant: 6),
NSLayoutConstraint(item: containerView,
attribute: .height, relatedBy: .equal,
toItem: numberLabel, attribute: .height,
multiplier: 1, constant: 1)
])
containerView.layer.cornerRadius = (numberLabel.frame.height + 1) / 2
layer.cornerRadius = containerView.layer.cornerRadius + Constant.Dimension.Badge.border
}
}
| mit | 34495e151e96c2792ecf193dfc8f50d7 | 25 | 91 | 0.669872 | 4.8 | false | false | false | false |
CosmicMind/Samples | Projects/Programmatic/NavigationController/NavigationController/ViewController.swift | 1 | 3334 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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 UIKit
import Material
class ViewController: UIViewController {
fileprivate let transitionViewController = TransitionViewController()
fileprivate var menuButton: IconButton!
fileprivate var starButton: IconButton!
fileprivate var searchButton: IconButton!
fileprivate var fabButton: FABButton!
let v1 = UIView()
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Color.grey.lighten5
v1.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
v1.motionIdentifier = "v1"
v1.backgroundColor = .purple
view.addSubview(v1)
prepareMenuButton()
prepareStarButton()
prepareSearchButton()
prepareNavigationItem()
prepareFABButton()
}
}
fileprivate extension ViewController {
func prepareMenuButton() {
menuButton = IconButton(image: Icon.cm.menu)
}
func prepareStarButton() {
starButton = IconButton(image: Icon.cm.star)
}
func prepareSearchButton() {
searchButton = IconButton(image: Icon.cm.search)
}
func prepareNavigationItem() {
navigationItem.titleLabel.text = "Material"
navigationItem.detailLabel.text = "Build Beautiful Software"
navigationItem.leftViews = [menuButton]
navigationItem.rightViews = [starButton, searchButton]
}
func prepareFABButton() {
fabButton = FABButton(image: Icon.cm.moreHorizontal)
fabButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)
view.layout(fabButton).width(64).height(64).bottom(24).right(24)
}
}
fileprivate extension ViewController {
@objc
func handleNextButton() {
navigationController?.pushViewController(transitionViewController, animated: true)
}
}
| bsd-3-clause | 26d8dd8611edffe83623d05a87c6a577 | 34.094737 | 88 | 0.745051 | 4.560876 | false | false | false | false |
rockgarden/swift_language | Playground/Temp.playground/Pages/collection Array.xcplaygroundpage/Contents.swift | 1 | 15843 | //: [Previous](@previous)
import UIKit
import Foundation
protocol Flier { }
struct Bird : Flier {
var name = "Tweety"
}
struct Insect : Flier { }
class Dog { }
class NoisyDog : Dog { }
class DogNOT : Equatable {
// make ourselves equatable
static func ==(lhs:DogNOT, rhs:DogNOT) -> Bool {
return lhs === rhs
}
}
class NoisyDogNOT : DogNOT {
}
do {
let dog1: Dog = NoisyDog()
let dog2: Dog = NoisyDog()
let arr = [dog1, dog2]
if arr is [NoisyDog] {
("yep") // meaning it can be cast down
}
let arr2 = arr as! [NoisyDog]
}
do {
let dog1 = NoisyDog()
let dog2 = NoisyDog()
let dog3 = Dog()
let arr = [dog1, dog2]
//let arr2 = arr as? [NoisyDog] // Optional wrapping an array of NoisyDog
let arr3 = [dog2, dog3]
let arr4 = arr3 as? [NoisyDog] // nil
}
do {
let i1 = 1
let i2 = 2
let i3 = 3
if [1, 2, 3].elementsEqual([i1, i2, i3]) { // they are equal!
("equal")
}
let nd1 = NoisyDog()
let d1 = nd1 as Dog
let nd2 = NoisyDog()
let d2 = nd2 as Dog
// if [d1,d2] == [nd1,nd2] { // they are equal!
// print("equal")
// }
// TODO: elementsEqual 处理类
// if [d1, d2].elementsEqual([nd1, nd2], by: { (_, _) -> Bool in
// }) { // they are equal!
// ("equal")
// }
}
do {
let arr: [Int?] = [1, 2, 3]
// print(arr) // [Optional(1), Optional(2), Optional(3)]
}
do {
let dogs = [Dog(), NoisyDog()]
let objs = [1, "howdy"] as [Any] // explicit type annotation needed *
// let arrr = [Insect(), Bird()] // compile error
let arr : [Flier] = [Insect(), Bird()]
do {
let arr2 : [Flier] = [Insect()]
// WARNING next line is legal (compiles) but you'll crash at runtime
// can't use array-casting to cast down from protocol type to adopter type
// Wait, they fixed that in Xcode 8 seed 6!
let arr3 = arr2 as! [Insect]
print("I didn't crash! I kiss the sweet ground...")
_ = (arr2, arr3)
}
/*
do {
let arr2 : [Flier] = [Insect()]
// instead of above, to cast down, must cast individual elements down
let arr3 = arr2.map{$0 as! Insect}
_ = arr2
_ = arr3
}
*/
let rs = Array(1...3)
print(rs)
let chars = Array("howdy".characters)
print(chars)
let kvs = Array(["hey":"ho", "nonny":"nonny no"])
print(kvs)
let strings : [String?] = Array(repeating:nil, count:100)
_ = arr
_ = strings
_ = dogs
_ = objs
}
do {
let arr = ["manny", "moe", "jack"]
let slice = arr[1...2]
print(slice)
print("slice:", slice[1]) // moe
let arr2 = Array(slice)
print("array:", arr2[1]) // jack
// let base = slice.base
// print("base:", slice.base)
}
do {
var arr = [1,2,3]
arr[1] = 4 // arr is now [1,4,3]
arr[1..<2] = [7,8] // arr is now [1,7,8,3]
arr[1..<2] = [] // arr is now [1,8,3]
arr[1..<1] = [10] // arr is now [1,10,8,3] (no element was removed!)
let arr2 = [20,21]
// arr[1..<1] = arr2 // compile error!
arr[1..<1] = ArraySlice(arr2)
print("after all that:", arr)
let slice = arr[1..<2]
_ = slice
}
do {
var arr = [[1,2,3], [4,5,6], [7,8,9]]
let i = arr[1][1] // 5
arr[1][1] = 100
_ = i
}
do {
let arr = [1,2,3]
print(arr.first as Any)
print(arr.last as Any)
let slice = arr[arr.count-2...arr.count-1] // [2,3]
let slice2 = arr.suffix(2) // [2,3]
let slice3 = arr.suffix(10) // [1,2,3] with no penalty
let slice4 = arr.prefix(2)
print(slice3)
// new in beta 6
do {
let slice = arr.suffix(from:1)
print(slice)
let slice2 = arr.prefix(upTo:1)
print(slice2)
let slice3 = arr.prefix(through:1)
print(slice3)
}
// let arr5 = arr[0..<10]
do {
let slice = arr.suffix(from:1)
print(arr.startIndex)
print(slice.startIndex) // 1
print(slice.indices) // 1..<3
}
do {
let arr = [1,2,3]
let slice = arr[arr.endIndex-2..<arr.endIndex] // [2,3]
print(slice)
print(slice.indices)
print(slice.startIndex)
}
_ = (slice, slice2, slice3, slice4)
}
do {
let arr : [Int?] = [1,2,3]
let i = arr.last // a double-wrapped Optional
_ = i
}
do {
let arr = [1,2,3]
let ok = arr.contains(2) // ***
let okk = arr.contains {$0 > 3} // false
let ix = arr.index(of:2) // *** Optional wrapping 1
let which = arr.index(where:{$0>2})
let which2 = arr.first(where:{$0>2})
let aviary = [Bird(name:"Tweety"), Bird(name:"Flappy"), Bird(name:"Lady")]
let ix2 = aviary.index {$0.name.characters.count < 5} // index(where:)
print(ix2 as Any)
do {
let ok = arr.starts(with:[1,2])
let ok2 = arr.starts(with:[1,2]) {$0 == $1} // ***
let ok3 = arr.starts(with:[1,2], by:==) // ***
let ok4 = arr.starts(with:[1,2])
let ok5 = arr.starts(with:1...2)
let ok6 = arr.starts(with:[1,-2]) {abs($0) == abs($1)}
_ = ok
_ = ok2
_ = ok3
_ = ok4
_ = ok5
_ = ok6
}
_ = ok
_ = okk
_ = ix
_ = (which, which2)
}
do {
let arr = [3,1,-2]
let min = arr.min() // *** -2
print(min as Any)
let min2 = arr.min {abs($0)<abs($1)}
print(min2 as Any)
}
do {
var arr = [1,2,3]
arr.append(4)
arr.append(contentsOf:[5,6])
arr.append(contentsOf:7...8) // arr is now [1,2,3,4,5,6,7,8]
let arr2 = arr + [4] // arr2 is now [1,2,3,4]
var arr3 = [1,2,3]
arr3 += [4] // arr3 is now [1,2,3,4]
_ = arr2
}
do {
var arr = [1,2,3]
arr.insert(4, at:1)
print(arr)
arr.insert(contentsOf:[10,9,8], at:1)
print(arr)
let i = arr.remove(at:3)
let ii = arr.removeLast() // returns a result
arr.removeLast(1) // doesn't return a result
let iii = arr.removeFirst() // returns a result
arr.removeFirst(1) // doesn't return a result
let iiii = arr.popLast()
// arr.popLast(1) // nope, no such thing
// let iiiii = arr.popFirst()
print(arr)
do {
// let iiii = arr.popFirst() // nope
var arrslice = arr[arr.indices] // is this weird or what
let i = arrslice.popFirst()
// let ii = arrslice.popFirst(1)
print(i as Any)
print(arrslice)
print(arr) // untouched, of course
}
print(arr)
_ = i
_ = ii
_ = iii
let slice = arr.dropFirst()
let slice2 = arr.dropLast()
let slice3 = arr.dropFirst(100)
print("slice3", slice3)
_ = slice
_ = slice2
_ = slice3
_ = iiii
}
do {
let arr = [[1,2], [3,4], [5,6]]
let joined = arr.joined(separator: [10,11]) // [1, 2, 10, 11, 3, 4, 10, 11, 5, 6]
let joined2 = arr.joined(separator: []) // [1, 2, 3, 4, 5, 6]
let joined3 = arr.joined(separator: 8...9) // just proving that other sequences are legal
let arr4 = arr.flatMap {$0} // new in Swift 1.2
let arr5 = Array(arr.joined()) // renamed in Xcode 8 seed 6 *
_ = joined
_ = joined2
_ = joined3
_ = arr4
_ = arr5
}
do {
let arr = [1,2,3,4,5,6]
let arr2 = arr.split {$0 % 2 == 0} // split at evens: [[1], [3], [5]]
print(arr2)
_ = arr2
}
let pepboys = ["Manny", "Moe", "Jack"]
for pepboy in pepboys {
print(pepboy) // prints Manny, then Moe, then Jack
}
for (ix,pepboy) in pepboys.enumerated() { // ***
print("Pep boy \(ix) is \(pepboy)") // Pep boy 0 is Manny, etc.
}
let arr = [1,2,3]
let arr2 = arr.map {$0 * 2} // [2,4,6]
let arr3 = arr.map {Double($0)} // [1.0, 2.0, 3.0]
pepboys.forEach {print($0)} // prints Manny, then Moe, then Jack
pepboys.enumerated().forEach {print("Pep boy \($0.0) is \($0.1)")}
// pepboys.map(print) // no longer compiles
let arr4 = pepboys.filter{$0.hasPrefix("M")} // [Manny, Moe]
let arrr = [1, 4, 9, 13, 112]
let sum = arrr.reduce(0) {$0 + $1} // 139
let sum2 = arrr.reduce(0, +)
_ = arr2
_ = arr3
_ = arr4
_ = sum
_ = sum2
do {
let arr = [[1,2], [3,4], [5,6]]
let flat = arr.reduce([], +) // [1, 2, 3, 4, 5, 6]
_ = flat
let arr2 : [Any] = [[1,2], [3,4], [5,6], 7] // must be explicit [Any]
let arr3 = arr2.flatMap {$0}
print(arr3)
}
do {
let arr = [[1, 2], [3, 4]]
let arr2 = arr.flatMap{$0.map{String($0)}} // ["1", "2", "3", "4"]
print(arr2)
}
// flatMap has another use that I really should talk about:
// it unwraps Optionals safely while eliminating nils
do {
let arr : [String?] = ["Manny", nil, nil, "Moe", nil, "Jack", nil]
let arr2 = arr.flatMap{$0}
print(arr2)
}
do {
let arr : [Any] = [1, "hey", 2, "ho"] // NOT AnyObject! No automatic bridge-crossing
let arr2 = arr.flatMap{$0 as? String} // ["hey", "ho"]
print(arr2)
// let arrr : [AnyObject] = ["howdy"] // illegal
}
do {
let arr = [["Manny", "Moe", "Jack"], ["Harpo", "Chico", "Groucho"]]
let target = "m"
let arr2 = arr.map {
$0.filter {
let found = $0.range(of:target, options: .caseInsensitive)
return (found != nil)
}
}.filter {$0.count > 0}
print(arr2)
}
do {
let lay = CAGradientLayer()
lay.locations = [0.25, 0.5, 0.75]
}
do {
var arr = ["Manny", "Moe", "Jack"]
// let ss = arr.componentsJoined(by:", ") // compile error
let s = (arr as NSArray).componentsJoined(by:", ")
let arr2 = NSMutableArray(array:arr)
arr2.remove("Moe")
arr = arr2 as NSArray as! [String]
print(arr)
_ = s
}
do {
let arrCGPoints = [CGPoint()]
let arr = arrCGPoints as NSArray // this is now LEGAL (Xcode 8, seed 6)
// let arrNSValues = arrCGPoints.map { NSValue(cgPoint:$0) }
// let arr = arrNSValues as NSArray
print(arr)
}
do {
let arr = [String?]()
// let arr2 = arr.map{if $0 == nil {return NSNull()} else {return $0!}} // compile error
// let arr2 = arr.map{s -> AnyObject in if s == nil {return NSNull()} else {return s!}}
let arr2 : [Any] =
arr.map {if $0 != nil {return $0!} else {return NSNull()}} // * NB change to [Any]
_ = arr2
}
do {
let arr = [AnyObject]()
let arr2 : [String] = arr.map {
if $0 is String {
return $0 as! String
} else {
return ""
}
}
_ = arr2
}
do {
// there seems to be some doubt now as to whether the medium of exchange...
// ... is AnyObject or NSObject
// ooooookay, in Xcode 8 seed 6, the matter is settled — it's Any
let s = "howdy" as NSObject
let s2 = "howdy" as AnyObject
let s3 = s as! String
let s4 = s2 as! String
print(s3, s4)
let arr = [Dog()]
let nsarr = arr as NSArray
// there is no problem even if it is NOT an NSObject, so what's the big deal?
print(nsarr.object(at:0))
let arr2 : [Any] = ["howdy", Dog()]
let nsarr2 = arr2 as NSArray
print(nsarr2)
}
do {
let arr : [Any] = [1,2,3]
let arr2 = arr as NSArray // no downcast; they are equivalent
let arr3 = arr as! [Int] // downcast needed
let _ = (arr, arr2, arr3)
}
do {
// showing one common way to lose element typing
let arr = [1,2,3]
let fm = FileManager.default
let f = fm.temporaryDirectory.appendingPathComponent("test.plist")
(arr as NSArray).write(to: f, atomically: true)
let arr2 = NSArray(contentsOf: f)
print(type(of:arr2))
}
do {
class Cat {}
let cat1 = Cat()
let cat2 = Cat()
let ok = cat1 === cat2 // but `==` no longer compiles
}
do {
var arr = [1, 2, 3]
arr[1] = 4 // arr is now [1,4,3]
arr
arr[1..<2] = [7, 8] // arr is now [1,7,8,3]
arr
arr[1..<2] = [] // arr is now [1,8,3]
arr
arr[1..<1] = [10] // arr is now [1,10,8,3] (no element was removed!)
arr
let slice = arr[1..<2]
}
do {
var arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let i = arr[1][1] // 5
arr[1][1] = 100
arr
}
do {
let arr = [1, 2, 3]
(arr.first)
(arr.last)
let arr2 = arr[arr.count - 2...arr.count - 1] // [2,3]
arr[1...2]
let arr3 = arr.suffix(2) // [2,3]
arr.suffix(1) // [2,3]
let arr4 = arr.suffix(10) // [1,2,3] with no penalty
// new in beta 6
do {
let arr2 = arr.suffix(from: 1)
let arr3 = arr.prefix(upTo: 1)
let arr4 = arr.prefix(through: 1)
}
do {
let arr = [1, 2, 3]
var r = arr.indices
let newStartIndex = r.endIndex - 2
let arr2 = arr[newStartIndex] // [2,3]
}
}
do {
let arr: [Int?] = [1, 2, 3]
let i = arr.last // a double-wrapped Optional
}
do {
let arr = [1, 2, 3]
let ok = arr.contains(2) // ***
let okk = arr.contains { $0 > 3 } // false
let ix = arr.index(of: 2) // *** Optional wrapping 1
let aviary = [Bird(name: "Tweety"), Bird(name: "Flappy"), Bird(name: "Lady")]
let ix2 = aviary.index { $0.name.characters.count < 5 }
print(ix2 as Any)
do {
let ok = arr.starts(with: [1, 2])
let ok2 = arr.starts(with: [1, 2]) { $0 == $1 } // ***
let ok3 = arr.starts(with:[1, 2], by: == ) // ***
let ok4 = arr.starts(with: [1, 2])
let ok5 = arr.starts(with: 1...2)
let ok6 = arr.starts(with: [1, -2]) { abs($0) == abs($1) }
}
}
do {
let arr = [3, 1, -2]
let min = arr.min() //.minElement() // *** -2
let min2 = arr.min { abs($0) < abs($1) }
(min2)
}
do {
var arr = [1, 2, 3]
arr.append(4)
arr.append(contentsOf:[5, 6])
arr.append(contentsOf:7...8) // arr is now [1,2,3,4,5,6,7,8]
let arr2 = arr + [4] // arr2 is now [1,2,3,4]
var arr3 = [1, 2, 3]
arr3 += [4] // arr3 is now [1,2,3,4]
}
do {
var arr = [1, 2, 3]
arr.insert(4, at: 1)
arr.insert(contentsOf:[10, 9, 8], at: 1)
let i = arr.remove(at:3)
let ii = arr.removeLast()
let iii = arr.popLast()
(arr)
do {
// let iiii = arr.popFirst() // not sure what happened to this
var arrslice = arr[arr.indices] // is this weird or what
let i = arrslice.popFirst()
(arr) // untouched, of course
}
let arr2 = arr.dropFirst()
let arr3 = arr.dropLast()
}
do {
let arr = [[1, 2], [3, 4], [5, 6]]
let arr2 = arr.joined(separator:[10, 11]) // [1, 2, 10, 11, 3, 4, 10, 11, 5, 6]
let arr3 = arr.joined(separator:[]) // [1, 2, 3, 4, 5, 6]
let arr4 = arr.flatMap { $0 } // new in Swift 1.2
let arr5 = Array(arr.joined()) // new in Xcode 7 beta 6
}
do {
let arr = [1, 2, 3, 4, 5, 6]
let arr2 = arr.split { $0 % 2 == 0 } // split at evens: [[1], [3], [5]]
(arr2)
}
do {
var arr = ["Manny", "Moe", "Jack"]
// let ss = arr.componentsJoinedByString(", ") // compile error
let s = (arr as NSArray).componentsJoined(by:", ")
let arr2 = NSMutableArray(array: arr)
arr2.remove("Moe")
arr = arr2 as NSArray as! [String]
}
do {
// there seems to be some doubt now as to whether the medium of exchange...
// ... is AnyObject or NSObject
let s = "howdy" as NSObject
let s2 = "howdy" as AnyObject
let s3 = s as! String
let s4 = s2 as! String
let arr = [Dog()]
let nsarr = arr as NSArray
// there is no problem even if it is NOT an NSObject, so what's the big deal?
(nsarr.object(at:0))
let arr2 = ["howdy", Dog()] as [Any]
let nsarr2 = arr2 as NSArray
(nsarr2)
}
do {
let arrCGPoints = [CGPoint]()
// let arrr = arrCGPoints as NSArray // compiler stops you
let arrNSValues = arrCGPoints.map { NSValue(cgPoint: $0) }
let arr = arrNSValues as NSArray
_ = arrNSValues
_ = arr
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
do {
let views = self.view.subviews
_ = views
}
}
}
//: [Next](@next)
| mit | d744f573ad1ef91f4d0fd445a56ad26e | 23.474498 | 93 | 0.524408 | 2.918356 | false | false | false | false |
tdmartin4/EventCalendar | EventCalendar/ScrollAndReplaceViewController.swift | 1 | 9611 | //
// ScrollAndReplaceViewController.swift
// CalenderTesting
//
// Created by Thomas Martin on 1/17/17.
// Copyright © 2017 Thomas Martin. All rights reserved.
//
import UIKit
public class ScrollAndReplaceViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet private weak var scrollView: UIScrollView!
private var currentMonth = 0
private var currentYear = 0
private var currentScrollPos = 1
private let controllers = NSMutableArray(capacity: 0)
private var controllersArr:[UIViewController] = [UIViewController(), UIViewController(), UIViewController()]
private var screenCount = 0
private var firstTime = true
private var EventArr:[Event] = []
private var hasMonthLabel: Bool? = true
override public func viewDidLoad() {
super.viewDidLoad()
//let calendar = Calendar.current
//let date = Date()
//let date2 = calendar.date(from: DateComponents(calendar: calendar, year: 2017, month: 2, day: 25, hour: 10))
//addEvent(title: "Event 1", date: date)
//addEvent(title: "Event 2", date: date2!)
//addEvent(title: "Event 3", date: date2!)
// Do any additional setup after loading the view.
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if firstTime {
firstTime = false
setup()
}
}
private func setup () {
//let storyboard = UIStoryboard(name: "Main", bundle: nil)
let podBundle = Bundle(for: EventCalendar.ScrollAndReplaceViewController.self)
let storyboard = UIStoryboard(name: "Main", bundle: podBundle)
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
scrollView.bounces = false
scrollView.isPagingEnabled = true
scrollView.delegate = self
scrollView.contentSize = CGSize(width: 3 * screenWidth, height: screenHeight)
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
let myComponentsMonth = myCalendar.components(.month, from: Date())
let myComponentsYear = myCalendar.components(.year, from: Date())
let month = myComponentsMonth.month
currentMonth = month!
let year = myComponentsYear.year
currentYear = year!
print("the month is \(month)")
let startNum: Int = month! - 1
let endNum: Int = month! + 1
var count = 0
for i in startNum...endNum {
let calendar = Calendar.current
var monthStart = Date()
if i <= 0 {
monthStart = DateComponents(calendar: calendar, year: year! - 1, month: i).date!
} else {
monthStart = DateComponents(calendar: calendar, year: year, month: i).date!
}
let monthEnd = calendar.date(byAdding: .month, value: 1, to: monthStart)
var monthsEvents: [Event] = []
for event in EventArr {
if (event.date! == monthStart || event.date! > monthStart) && event.date! < monthEnd! {
monthsEvents.append(event)
}
}
let first: CollectionViewController = storyboard.instantiateViewController(withIdentifier: "monthVC") as! CollectionViewController
first.eventsArr = monthsEvents
first.showMonthLabel = hasMonthLabel!
//first.removeMonthLabel()
scrollView.addSubview((first.view)!)
first.view.frame = CGRect(x: screenWidth*(CGFloat(count)), y: 0, width: screenWidth, height: screenHeight)
controllers.add(first)
self.addChildViewController(first)
if i <= 0 {
print("month \(12-i)")
first.initMonth(month: 12+i, year: year!-1)
} else {
print("month \(i)")
first.initMonth(month: i, year: year!)
}
controllersArr[count] = first
count += 1
screenCount+=1
}
scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0.0), animated: false)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let width = scrollView.frame.size.width
let xPos = scrollView.contentOffset.x+10
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if currentScrollPos != Int(xPos/width) {
if currentScrollPos < Int(xPos/width) {
currentMonth += 1
if currentMonth == 13 {
currentMonth = 1
currentYear += 1
}
controllersArr[0].view.removeFromSuperview()
controllersArr[1].view.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
controllersArr[2].view.frame = CGRect(x: screenWidth, y: 0, width: screenWidth, height: screenHeight)
controllersArr[0] = controllersArr[1]
controllersArr[1] = controllersArr[2]
if currentMonth+1 < 13 {
controllersArr[2] = addMonth(month: currentMonth+1, year: currentYear, position: 2)
} else {
controllersArr[2] = addMonth(month: 1, year: currentYear+1, position: 2)
}
scrollView.layoutIfNeeded()
scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0.0), animated: false)
} else {
currentMonth -= 1
if currentMonth == 0 {
currentMonth = 12
currentYear -= 1
}
controllersArr[2].view.removeFromSuperview()
controllersArr[1].view.frame = CGRect(x: 2*screenWidth, y: 0, width: screenWidth, height: screenHeight)
controllersArr[0].view.frame = CGRect(x: screenWidth, y: 0, width: screenWidth, height: screenHeight)
controllersArr[2] = controllersArr[1]
controllersArr[1] = controllersArr[0]
if currentMonth-1 > 0 {
controllersArr[0] = addMonth(month: currentMonth-1, year: currentYear, position: 0)
} else {
controllersArr[0] = addMonth(month: 12, year: currentYear-1, position: 0)
}
scrollView.layoutIfNeeded()
scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0.0), animated: false)
}
//scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0.0), animated: false)
}
print("The current position is \(currentScrollPos)")
}
private func addMonth(month: Int, year: Int, position: Int) -> UIViewController{
//let storyboard = UIStoryboard(name: "Main", bundle: nil)
let podBundle = Bundle(for: EventCalendar.ScrollAndReplaceViewController.self)
let storyboard = UIStoryboard(name: "Main", bundle: podBundle)
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let calendar = Calendar.current
let monthStart = DateComponents(calendar: calendar, year: year, month: month).date
let monthEnd = calendar.date(byAdding: .month, value: 1, to: monthStart!)
var monthsEvents: [Event] = []
for event in EventArr {
if (event.date! == monthStart || event.date! > monthStart!) && event.date! < monthEnd! {
monthsEvents.append(event)
}
}
let first: CollectionViewController = storyboard.instantiateViewController(withIdentifier: "monthVC") as! CollectionViewController
first.eventsArr = monthsEvents
first.showMonthLabel = hasMonthLabel!
scrollView.addSubview((first.view)!)
first.view.frame = CGRect(x: screenWidth*(CGFloat(position)), y: 0, width: screenWidth, height: screenHeight)
controllers.removeObject(at: position)
controllers.insert(first, at: position)
self.addChildViewController(first)
first.initMonth(month: month, year: year)
return first
}
public func addEvent(title: String, date: Date) {
let event: Event = Event(date: date, title: title)
EventArr.append(event)
EventArr = EventArr.sorted(by: {$0.date! > $1.date!})
}
public func removeMonthYearLabel() {
hasMonthLabel = false
}
public func getcurrentMonthYear() -> String {
return ""
}
/*
// 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 | 6b5893f4d4406e05d8570f43fe43ae8b | 37.906883 | 142 | 0.580437 | 5.175013 | false | false | false | false |
yanil3500/acoustiCast | AcoustiCastr/AcoustiCastr/SearchViewController.swift | 1 | 5480 | //
// SearchViewController.swift
// AcoustiCastr
//
// Created by Elyanil Liranzo Castro on 4/12/17.
// Copyright © 2017 Elyanil Liranzo Castro. All rights reserved.
//
import UIKit
class SearchViewController: UIViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var allPodcasts = [Podcast](){
didSet{
print("FirsCall: \(self.allPodcasts.count)")
self.tableView.reloadData()
}
}
var rowHeight = 50
var searchTerm = [String]() {
didSet {
self.update()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.searchBar.delegate = self
self.navigationController?.navigationBar.barTintColor = UIColor.black
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
//Register nib
let podcastNib = UINib(nibName: SearchResultsCell.identifier, bundle: nil)
print("Reuse ID: \(SearchResultsCell.identifier)")
self.tableView.register(podcastNib, forCellReuseIdentifier: SearchResultsCell.identifier)
self.tableView.estimatedRowHeight = CGFloat(rowHeight)
self.tableView.rowHeight = UITableViewAutomaticDimension
self.update()
}
func update(){
print("Inside of update:")
iTunes.shared.getPodcasts { (podcasts) in
if let pods = podcasts {
self.allPodcasts = pods
self.activityIndicator.stopAnimating()
}
}
}
}
extension SearchViewController: UITableViewDelegate, UITableViewDataSource {
//TODO: Finish delegate methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allPodcasts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let searchResultsCell = tableView.dequeueReusableCell(withIdentifier: SearchResultsCell.identifier, for: indexPath) as! SearchResultsCell
searchResultsCell.podcastAuthor?.text = self.allPodcasts[indexPath.row].artistName
searchResultsCell.podcastName?.text = self.allPodcasts[indexPath.row].collectionName
searchResultsCell.podcastArt.image = self.allPodcasts[indexPath.row].podcastAlbumArt
return searchResultsCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: DetailPodcastViewController.identifier, sender: nil)
//Thanks Robert!
self.tableView.deselectRow(at: indexPath, animated: false)
}
}
//MARK: FirstTimeViewController conforms to UISearchBarDelegate
extension SearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if !searchText.validate() {
let lastIndex = searchText.index(before: searchText.endIndex)
searchBar.text = searchText.substring(to: lastIndex)
}
if searchText == "" {
self.allPodcasts.removeAll()
self.tableView.reloadData()
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("Inside of scrollViewDidScroll")
self.searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
//Dismissed the keyboard from the view once user clicks on cancel button
self.searchBar.resignFirstResponder()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//Dismisses the keyboard from the view once user clicks search bar
print("Stuff in search bar: \(String(describing: searchBar.text))")
if let terms = searchBar.text?.lowercased() {
iTunes.shared.getSearchText(searchRequest: [terms])
self.searchTerm = [terms]
print(iTunes.searchTerms)
}
self.activityIndicator.startAnimating()
self.searchBar.resignFirstResponder()
}
}
//MARK: Extension for segue preparation
extension SearchViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == DetailPodcastViewController.identifier {
//prepares podcast info.
if let selectedIndex = self.tableView.indexPathForSelectedRow?.row {
let selectedPodcast = self.allPodcasts[selectedIndex]
guard let destinationController = segue.destination as? DetailPodcastViewController else { print("Failed to prepare segue."); return}
let backItem = UIBarButtonItem()
backItem.title = " "
navigationItem.backBarButtonItem = backItem
destinationController.selectedPod = selectedPodcast
}
}
}
}
| mit | 31e0531a7e1e5d684a8d33b3f7ec873d | 32.820988 | 149 | 0.651031 | 5.719207 | false | false | false | false |
hemantasapkota/OpenSansSwift | OpenSansSwift/OpenSans.swift | 1 | 3775 | //
// OpenSansSwift.swift
// OpenSansSwift
//
// Created by Hemanta Sapkota on 17/02/2015.
// Copyright (c) 2015 Open Learning Pty Ltd. All rights reserved.
//
import UIKit
import CoreText
protocol UIFontOpenSans {
static func openSansFontOfSize(_ size: Float) -> UIFont!
static func openSansBoldFontOfSize(_ size: Float) -> UIFont!
static func openSansBoldItalicFontOfSize(_ size: Float) -> UIFont!
static func openSansExtraBoldFontOfSize(_ size: Float) -> UIFont!
static func openSansExtraBoldItalicFontOfSize(_ size: Float) -> UIFont!
static func openSansItalicFontOfSize(_ size: Float) -> UIFont!
static func openSansLightFontOfSize(_ size: Float) -> UIFont!
static func openSansLightItalicFontOfSize(_ size: Float) -> UIFont!
static func openSansSemiboldFontOfSize(_ size: Float) -> UIFont!
static func openSansSemiboldItalicFontOfSize(_ size: Float) -> UIFont!
}
extension UIFont : UIFontOpenSans {
public class func openSansFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSans", size: makeSize(size))
}
public class func openSansBoldFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSans-Bold", size: makeSize(size))
}
public class func openSansBoldItalicFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSans-BoldItalic", size: makeSize(size))
}
public class func openSansExtraBoldFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSans-Extrabold", size: makeSize(size))
}
public class func openSansExtraBoldItalicFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSans-ExtraboldItalic", size: makeSize(size))
}
public class func openSansItalicFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSans-Italic", size: makeSize(size))
}
public class func openSansLightFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSans-Light", size: makeSize(size))
}
public class func openSansLightItalicFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSansLight-Italic", size: makeSize(size))
}
public class func openSansSemiboldFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSans-Semibold", size: makeSize(size))
}
public class func openSansSemiboldItalicFontOfSize(_ size: Float) -> UIFont! {
return UIFont(name: "OpenSans-SemiboldItalic", size: makeSize(size))
}
class func makeSize(_ size: Float) -> CGFloat {
if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad {
return CGFloat(size * OpenSans.retinaScaleFactor)
}
return CGFloat(size)
}
}
open class OpenSans {
/// scale factor for retina devices. Default 2.0
open static var retinaScaleFactor: Float = 2.0
open class func registerFonts() -> Bool {
let fontNames = [
"OpenSans-Regular",
"OpenSans-Bold",
"OpenSans-BoldItalic",
"OpenSans-ExtraBold",
"OpenSans-ExtraBoldItalic",
"OpenSans-Italic",
"OpenSans-Light",
"OpenSans-LightItalic",
"OpenSans-Semibold",
"OpenSans-SemiboldItalic"
]
var error: Unmanaged<CFError>? = nil
for font in fontNames {
let url = Bundle(for: OpenSans.self).url(forResource: font, withExtension: "ttf")
if (url != nil) {
CTFontManagerRegisterFontsForURL(url! as CFURL, CTFontManagerScope.none, &error)
}
}
return error == nil
}
}
| mit | 93576bc64e5356bc9aa77b3723e5b138 | 30.991525 | 96 | 0.633907 | 4.724656 | false | false | false | false |
frodoking/GithubIOSClient | Github/Core/Module/Users/UserDetailViewModule.swift | 1 | 4011 | //
// UserDetailViewModule.swift
// Github
//
// Created by frodo on 15/10/27.
// Copyright © 2015年 frodo. All rights reserved.
//
import Foundation
public class UserDetailViewModule {
static let Indicator: NSMutableArray = ["Repositories", "Following", "Followers"]
var userRepositoriesDataSource = DataSource()
var userFollowingDataSource = DataSource()
var userFollowersDataSource = DataSource()
var currentTabViewIndex: Int = 0
public func loadUserFromApi(userName: String, handler: (user: User?) -> Void) {
Server.shareInstance.userDetailWithUserName(userName,
completoinHandler: { user in
handler(user: user)
},
errorHandler: { errors in
handler(user: nil)
})
}
public func loadDataFromApiWithIsFirst(isFirst: Bool, currentIndex: Int, userName: String, handler: (array: NSArray) -> Void) {
switch currentIndex {
case 0:
var page:Int = 0
if (isFirst) {
page = 1;
} else {
page = userRepositoriesDataSource.page!+1;
}
Server.shareInstance.userRepositoriesWithPage(page, userName: userName, sort: "updated",
completoinHandler: { (repositories, page) in
if (page <= 1) {
self.userRepositoriesDataSource.reset()
}
self.userRepositoriesDataSource.page = page
self.userRepositoriesDataSource.dsArray?.addObjectsFromArray(repositories)
handler(array: self.userRepositoriesDataSource.dsArray!)
},
errorHandler: { errors in
// do nothing
handler(array: NSArray())
})
break
case 1:
var page:Int = 0
if (isFirst) {
page = 1;
} else {
page = userFollowingDataSource.page!+1;
}
Server.shareInstance.userFollowingWithPage(page, userName: userName,
completoinHandler: { (users, page) in
if (page <= 1) {
self.userFollowingDataSource.reset()
}
self.userFollowingDataSource.page = page
self.userFollowingDataSource.dsArray?.addObjectsFromArray(users)
handler(array: self.userFollowingDataSource.dsArray!)
},
errorHandler: { errors in
// do nothing
handler(array: NSArray())
})
break
case 2:
var page:Int = 0
if (isFirst) {
page = 1;
} else {
page = userFollowersDataSource.page!+1;
}
Server.shareInstance.userFollowersWithPage(page, userName: userName,
completoinHandler: { (users, page) in
if (page <= 1) {
self.userFollowersDataSource.reset()
}
self.userFollowersDataSource.page = page
self.userFollowersDataSource.dsArray?.addObjectsFromArray(users)
handler(array: self.userFollowersDataSource.dsArray!)
},
errorHandler: { errors in
// do nothing
handler(array: NSArray())
})
break
default: break
}
}
} | apache-2.0 | a81c4005026c169824516ea9be6192bd | 36.46729 | 131 | 0.459331 | 6.223602 | false | false | false | false |
LipliStyle/Liplis-iOS | Liplis/ViewWidgetCtrl.swift | 1 | 12138 | //
// ViewWidgetCtrl.swift
// Liplis
//
// Liplisのウィジェット全体を操作する画面(全削除、全復帰)
//
//
//アップデート履歴
// 2015/05/07 ver0.1.0 作成
// 2015/05/09 ver1.0.0 リリース
// 2015/05/14 ver1.3.0 リファクタリング
// 2015/05/16 ver1.4.0 swift1.2対応
//
// Created by sachin on 2015/05/07.
// Copyright (c) 2015年 sachin. All rights reserved.
//
import UIKit
class ViewWidgetCtrl : UIViewController, UITableViewDelegate, UITableViewDataSource{
///=============================
///アプリケーションデリゲート
internal var app : AppDelegate!
///=============================
///テーブル要素
private var tblItems : Array<MsgSettingViewCell>! = []
//=================================
//リプリスベース設定
private var baseSetting : LiplisPreference!
///=============================
///ビュータイトル
private var viewTitle = "ウィジェット操作"
///=============================
///画面要素
private var lblTitle : UILabel!
private var btnBack : UIButton!
private var tblSetting: UITableView!
//============================================================
//
//初期化処理
//
//============================================================
/*
コンストラクター
*/
convenience init(app : AppDelegate!) {
self.init(nibName: nil, bundle: nil)
//アプリケーションデリゲート取得
self.app = app
//クラスの初期化
self.initClass()
//ビューの初期化
self.initView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/*
クラスの初期化
*/
private func initClass()
{
baseSetting = LiplisPreference.SharedInstance
}
/*
アクティビティの初期化
*/
private func initView()
{
//ビューの初期化
self.view.opaque = true //背景透過許可
self.view.backgroundColor = UIColor(red:255,green:255,blue:255,alpha:255) //白透明背景
//タイトルラベルの作成
self.createLblTitle()
//閉じるボタン作成
self.createBtnClose()
//テーブル作成
self.createTableView()
//サイズ調整
self.setSize()
}
/*
タイトルラベルの初期化
*/
private func createLblTitle()
{
self.lblTitle = UILabel(frame: CGRectMake(0,0,0,0))
self.lblTitle.backgroundColor = UIColor.hexStr("ffa500", alpha: 255)
self.lblTitle.text = self.viewTitle
self.lblTitle.textColor = UIColor.whiteColor()
self.lblTitle.shadowColor = UIColor.grayColor()
self.lblTitle.textAlignment = NSTextAlignment.Center
self.view.addSubview(self.lblTitle)
}
/*
閉じるボタンの初期化
*/
private func createBtnClose()
{
//戻るボタン
self.btnBack = UIButton()
self.btnBack.titleLabel?.font = UIFont.systemFontOfSize(12)
self.btnBack.backgroundColor = UIColor.hexStr("DF7401", alpha: 255)
self.btnBack.layer.masksToBounds = true
self.btnBack.setTitle("閉じる", forState: UIControlState.Normal)
self.btnBack.addTarget(self, action: "closeMe:", forControlEvents: .TouchDown)
self.btnBack.layer.cornerRadius = 3.0
self.view.addSubview(btnBack)
}
/*
設定要素テーブルの初期化
*/
private func createTableView()
{
//TableViewの生成
self.tblSetting = UITableView()
self.tblSetting.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
self.tblSetting.dataSource = self
self.tblSetting.delegate = self
self.tblSetting.allowsSelection = false
self.tblSetting.rowHeight = 20
self.tblSetting.registerClass(CtvCellMenuTitle.self, forCellReuseIdentifier: "CtvCellMenuTitle")
self.tblSetting.registerClass(CtvCellWidgetCtrlDelWidget.self, forCellReuseIdentifier: "CtvCellWidgetCtrlDelWidget")
self.tblSetting.registerClass(CtvCellWidgetCtrlRescueWIdget.self, forCellReuseIdentifier: "CtvCellWidgetCtrlRescueWIdget")
self.view.addSubview(tblSetting)
//テーブルビューアイテム作成
self.tblItems = Array<MsgSettingViewCell>()
self.tblItems.append(
MsgSettingViewCell(
title: "全ウィジェット削除",
content: "",
partsType: LiplisDefine.PARTS_TYPE_TITLE,settingIdx: -1,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(26)
)
)
self.tblItems.append(
MsgSettingViewCell(
title: "",
content: "",
partsType: 1,
settingIdx: -1,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(100)
)
)
self.tblItems.append(
MsgSettingViewCell(
title: "ウィジェットの画面復帰",
content: "",
partsType: LiplisDefine.PARTS_TYPE_TITLE,settingIdx: -1,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(26)
)
)
self.tblItems.append(
MsgSettingViewCell(
title: "",
content: "",
partsType: 2,
settingIdx: -1,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(70)
)
)
}
//============================================================
//
//イベントハンドラ
//
//============================================================
internal override func viewDidLoad() {
super.viewDidLoad()
}
internal override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
ビュー呼び出し時
*/
internal override func viewWillAppear(animated: Bool) {
//サイズ設定
setSize()
}
/*
画面を閉じる
*/
internal func closeMe(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
/*
Cellが選択された際に呼び出される.
*/
internal func tableView(tableView: UITableView, indexPath: NSIndexPath)->NSIndexPath? {
print("Num: \(indexPath.row)")
print("Value: \(tblItems[indexPath.row].title)")
return nil;
}
/*
Cellの総数を返す.
*/
internal func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsInSection")
return tblItems.count
}
/*
Editableの状態にする.
*/
internal func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
print("canEditRowAtIndexPath")
return true
}
/*
特定の行のボタン操作を有効にする.
*/
internal func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
print("commitEdittingStyle:\(editingStyle)")
}
/*
Cellに値を設定する.
*/
internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("cellForRowAtIndexPath")
return settingCell(indexPath)
}
/*
セル設定
*/
internal func settingCell(indexPath : NSIndexPath) -> UITableViewCell!
{
let cellSetting : MsgSettingViewCell = tblItems[indexPath.row]
switch(cellSetting.partsType)
{
case 0://タイトル
let cell : CtvCellMenuTitle = self.tblSetting.dequeueReusableCellWithIdentifier("CtvCellMenuTitle", forIndexPath: indexPath) as! CtvCellMenuTitle
cell.lblTitle.text = cellSetting.title
return cell
case 1://イントロダクション
let cell : CtvCellWidgetCtrlDelWidget = self.tblSetting.dequeueReusableCellWithIdentifier("CtvCellWidgetCtrlDelWidget", forIndexPath: indexPath) as! CtvCellWidgetCtrlDelWidget
cell.setView(self)
cell.setSize(self.view.frame.width)
return cell
case 2://設定画面
let cell : CtvCellWidgetCtrlRescueWIdget = self.tblSetting.dequeueReusableCellWithIdentifier("CtvCellWidgetCtrlRescueWIdget", forIndexPath: indexPath) as! CtvCellWidgetCtrlRescueWIdget
cell.setView(self)
cell.setSize(self.view.frame.width)
return cell
default:
let cell : CtvCellMenuTitle = self.tblSetting.dequeueReusableCellWithIdentifier("CtvCellMenuTitle", forIndexPath: indexPath) as! CtvCellMenuTitle
cell.lblTitle.text = cellSetting.title
return cell
}
}
internal func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
print("estimatedHeightForRowAtIndexPath" + String(indexPath.row))
return CGFloat(30)
}
internal func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
print("estimatedHeightForRowAtIndexPath" + String(indexPath.row))
let cellSetting : MsgSettingViewCell = tblItems[indexPath.row]
return cellSetting.rowHeight
}
/*
ボタン操作
*/
//============================================================
//
//アクティビティ操作
//
//============================================================
/*
サイズ設定
*/
private func setSize()
{
// 現在のデバイスの向きを取得
let deviceOrientation: UIDeviceOrientation! = UIDevice.currentDevice().orientation
//方向別の処理
if UIDeviceOrientationIsLandscape(deviceOrientation) {
//横向きの判定
} else if UIDeviceOrientationIsPortrait(deviceOrientation){
//縦向きの判定
}
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
//let barHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height
self.lblTitle.frame = CGRect(x: 0, y: 0, width: displayWidth, height: LiplisDefine.labelHight)
self.btnBack.frame = CGRectMake(self.lblTitle.frame.origin.x + 5,self.lblTitle.frame.origin.y + 25, displayWidth/6, 30)
self.tblSetting.frame = CGRect(x: 0, y: self.lblTitle.frame.height, width: displayWidth, height: displayHeight - self.lblTitle.frame.height)
//テーブルのリロード
self.tblSetting.reloadData()
}
//============================================================
//
//回転ハンドラ
//
//============================================================
/*
画面の向き変更時イベント
*/
override func viewDidAppear(animated: Bool) {
// 端末の向きがかわったらNotificationを呼ばす設定.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onOrientationChange:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
internal func onOrientationChange(notification: NSNotification){
self.setSize()
}
}
| mit | 22124185ab3d73b75280057fa3da5714 | 29.172507 | 196 | 0.563248 | 5.156149 | false | false | false | false |
zavsby/ProjectHelpersSwift | Classes/Categories/NSDate+Extensions.swift | 1 | 1387 | //
// NSDate+Extensions.swift
// ProjectHelpers-Swift
//
// Created by Sergey on 05.11.15.
// Copyright © 2015 Sergey Plotkin. All rights reserved.
//
import Foundation
public extension NSDate {
// MARK:- Initializers
public static func dateWithDay(day: Int, month: Int, year: Int) -> NSDate? {
let components = NSDateComponents()
components.day = day
components.month = month
components.year = year
return NSCalendar.currentCalendar().dateFromComponents(components)
}
public static func dateFromString(dateString: String, format: String) -> NSDate? {
guard dateString.anyText && format.anyText else {
return nil
}
let dateFormatter = DateFormatter.dateFormatterWithFormat(format)
return dateFormatter.dateFromString(dateString)
}
// MARK:- Formatting
public func formattedDate(format: String) -> String {
let dateFormatter = DateFormatter.dateFormatterWithFormat(format)
return dateFormatter.stringFromDate(self)
}
// MARK:- Converting dates
public func dateOfDayBeginning() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day, .Month, .Year], fromDate: self)
return calendar.dateFromComponents(components)!
}
} | mit | 189a6d7a36dc107ef79b38cf2498886a | 28.510638 | 86 | 0.652237 | 5.095588 | false | true | false | false |
garethpaul/furni-ios | Furni/OrderSuccessfulViewController.swift | 1 | 3385 | //
// Copyright (C) 2015 Twitter, Inc. and other contributors.
//
// 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
import TwitterKit
import Crashlytics
final class OrderSuccessfulViewController: UIViewController {
// MARK: Properties
@IBOutlet private weak var thanksLabel: UILabel!
@IBOutlet private weak var orderNumberLabel: UILabel!
@IBOutlet private weak var customerServiceLabel: UILabel!
@IBOutlet private weak var twitterButton: UIButton!
// MARK: IBActions
@IBAction private func twitterButtonTapped(sender: AnyObject) {
if AccountManager.defaultAccountManager.twitterIdentity != nil {
tweetToFurni()
} else {
AccountManager.defaultAccountManager.authenticateWithService(.Twitter) { success in
self.updateTwitterLabels()
}
}
}
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Assign the labels.
let name = AccountManager.defaultAccountManager.user!.fullName ?? ""
thanksLabel.text = !name.isEmpty ? "\(name)!" : ""
orderNumberLabel.text = "#10212015"
customerServiceLabel.layer.masksToBounds = true
customerServiceLabel.drawTopBorderWithColor(UIColor.furniBrownColor(), height: 0.5)
// Customize the Twitter button.
twitterButton.decorateForFurni()
twitterButton.setImage(UIImage(named: "Twitter")?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
// Update Twitter / Customer Service labels.
updateTwitterLabels()
}
private func updateTwitterLabels() {
if AccountManager.defaultAccountManager.twitterIdentity != nil {
customerServiceLabel.text = "Thank you for connecting your Twitter account! Tweet any questions @furni, we’re here to help! 💁"
twitterButton.setTitle(" TWEET TO @FURNI", forState: .Normal)
} else {
customerServiceLabel.text = "Did you know you can link your Twitter account for a great customer experience? 💁"
twitterButton.setTitle(" CONNECT WITH TWITTER", forState: .Normal)
}
}
private func tweetToFurni() {
// Use the TwitterKit to create a Tweet composer.
let composer = TWTRComposer()
// Prepare the Tweet.
composer.setText("Hey @furni! ")
// Present the composer to the user.
composer.showFromViewController(self) { result in
if result == .Done {
// Log Custom Event in Answers.
Answers.logCustomEventWithName("Tweet Completed", customAttributes: nil)
} else if result == .Cancelled {
// Log Custom Event in Answers.
Answers.logCustomEventWithName("Tweet Cancelled", customAttributes: nil)
}
}
}
}
| apache-2.0 | 53e2300b0906a7ced43fb17e50b01619 | 35.311828 | 138 | 0.665976 | 5.002963 | false | false | false | false |
dreamsxin/swift | stdlib/public/core/RandomAccessCollection.swift | 3 | 10439 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 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
//
//===----------------------------------------------------------------------===//
/// A collection that supports efficient random-access index traversal.
///
/// In most cases, it's best to ignore this protocol and use the
/// `RandomAccessCollection` protocol instead, because it has a more complete
/// interface.
public protocol RandomAccessIndexable : BidirectionalIndexable {
// FIXME(ABI)(compiler limitation): there is no reason for this protocol
// to exist apart from missing compiler features that we emulate with it.
//
// This protocol is almost an implementation detail of the standard
// library.
}
/// A collection that supports efficient random-access index traversal.
///
/// Random-access collections can measure move indices any distance and can
/// measure the distance between indices in O(1) time. Therefore, the
/// fundamental difference between random-access and bidirectional collections
/// is that operations that depend on index movement or distance measurement
/// offer significantly improved efficiency. For example, a random-access
/// collection's `count` property is calculated in O(1) instead of requiring
/// iteration of an entire collection.
///
/// Conforming to the RandomAccessCollection Protocol
/// =================================================
///
/// The `RandomAccessCollection` protocol adds further constraints on the
/// associated `Indices` and `SubSequence` types, but otherwise imposes no
/// additional requirements over the `BidirectionalCollection` protocol.
/// However, in order to meet the complexity guarantees of a random-access
/// collection, either the index for your custom type must conform to the
/// `Strideable` protocol or you must implement the `index(_:offsetBy:)` and
/// `distance(from:to:)` methods with O(1) efficiency.
public protocol RandomAccessCollection :
RandomAccessIndexable, BidirectionalCollection
{
/// A collection that represents a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence : RandomAccessIndexable, BidirectionalCollection
= RandomAccessSlice<Self>
// FIXME(compiler limitation):
// associatedtype SubSequence : RandomAccessCollection
/// A type that can represent the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices : RandomAccessIndexable, BidirectionalCollection
= DefaultRandomAccessIndices<Self>
// FIXME(compiler limitation):
// associatedtype Indices : RandomAccessCollection
}
/// Supply the default "slicing" `subscript` for `RandomAccessCollection`
/// models that accept the default associated `SubSequence`,
/// `RandomAccessSlice<Self>`.
extension RandomAccessCollection where SubSequence == RandomAccessSlice<Self> {
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
public subscript(bounds: Range<Index>) -> RandomAccessSlice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return RandomAccessSlice(base: self, bounds: bounds)
}
}
// TODO: swift-3-indexing-model - Make sure RandomAccessCollection has
// documented complexity guarantees, e.g. for index(_:offsetBy:).
// TODO: swift-3-indexing-model - (By creating an ambiguity?), try to
// make sure RandomAccessCollection models implement
// index(_:offsetBy:) and distance(from:to:), or they will get the
// wrong complexity.
/// Default implementation for random access collections.
extension RandomAccessIndexable {
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position. The
/// operation doesn't require going beyond the limiting `numbers.endIndex`
/// value, so it succeeds.
///
/// let numbers = [10, 20, 30, 40, 50]
/// let i = numbers.index(numbers.startIndex, offsetBy: 4)
/// print(numbers[i])
/// // Prints "50"
///
/// The next example attempts to retrieve an index ten positions from
/// `numbers.startIndex`, but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = numbers.index(numbers.startIndex,
/// offsetBy: 10,
/// limitedBy: numbers.endIndex)
/// print(j)
/// // Prints "nil"
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. The
/// value passed as `n` must not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - n: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// `limit` should be greater than `i` to have any effect. Likewise, if
/// `n < 0`, `limit` should be less than `i` to have any effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(1)
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: tests.
let l = distance(from: i, to: limit)
if n > 0 ? l >= 0 && l < n : l <= 0 && n < l {
return nil
}
return index(i, offsetBy: n)
}
}
extension RandomAccessCollection
where Index : Strideable,
Index.Stride == IndexDistance,
Indices == CountableRange<Index> {
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be non-uniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can cause an unexpected copy of the collection. To avoid the
/// unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
public var indices: CountableRange<Index> {
return startIndex..<endIndex
}
internal func _validityChecked(_ i: Index) -> Index {
_precondition(i >= startIndex && i <= endIndex, "index out of range")
return i
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Index) -> Index {
return _validityChecked(i.advanced(by: 1))
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
public func index(before i: Index) -> Index {
return _validityChecked(i.advanced(by: -1))
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position.
///
/// let numbers = [10, 20, 30, 40, 50]
/// let i = numbers.index(numbers.startIndex, offsetBy: 4)
/// print(numbers[i])
/// // Prints "50"
///
/// Advancing an index beyond a collection's ending index or offsetting it
/// before a collection's starting index may trigger a runtime error. The
/// value passed as `n` must not result in such an operation.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
/// - Complexity: O(1)
public func index(_ i: Index, offsetBy n: Index.Stride) -> Index {
return _validityChecked(i.advanced(by: n))
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
///
/// - Complexity: O(1)
public func distance(from start: Index, to end: Index) -> Index.Stride {
return start.distance(to: end)
}
}
| apache-2.0 | 21acf05af3236d251317566aee409f9b | 41.092742 | 80 | 0.659354 | 4.345962 | false | false | false | false |
zadr/conservatory | Code/Internal/CocoaTextBridging.swift | 1 | 3869 | import CoreText
import Foundation
#if os(OSX)
import AppKit
#elseif os(iOS)
import UIKit
#endif
internal extension String {
func cocoaValue(_ effects: [TextEffect]) -> NSAttributedString {
let result = NSMutableAttributedString(string: self)
for effect in effects {
var fontDescriptor = CTFontDescriptorCreateWithNameAndSize(effect.font.name as CFString, CGFloat(effect.font.size))
if effect.bold {
var attribute: Int = 0
if let copiedAttribute = CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontSymbolicTrait) {
attribute = copiedAttribute as! Int
}
fontDescriptor = CTFontDescriptorCreateCopyWithAttributes(fontDescriptor, [
String(kCTFontSymbolicTrait): Int(attribute | Int(CTFontSymbolicTraits.boldTrait.rawValue))
] as CFDictionary)
}
if effect.italic {
var attribute: Int = 0
if let copiedAttribute = CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontSymbolicTrait) {
attribute = copiedAttribute as! Int
}
fontDescriptor = CTFontDescriptorCreateCopyWithAttributes(fontDescriptor, [
String(kCTFontSymbolicTrait): Int(attribute | Int(CTFontSymbolicTraits.italicTrait.rawValue))
] as CFDictionary)
}
var attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key(String(kCTFontAttributeName)): CTFontCreateWithFontDescriptor(fontDescriptor, CGFloat(effect.font.size), nil),
NSAttributedString.Key(String(kCTLigatureAttributeName)): effect.ligature,
NSAttributedString.Key(String(kCTKernAttributeName)): effect.kerning
]
if effect.underline != .none {
attributes[NSAttributedString.Key(String(kCTUnderlineStyleAttributeName))] = Int(effect.underline.coreTextView)
}
/*
if $0.strikethrough != .None {
attributes[NSStrikethroughStyleAttributeName] = $0.strikethrough.cocoaValue
}
if $0.aura.shouldApplyAura {
attributes[NSShadowAttributeName] = $0.aura.cocoaValue
}
*/
for (key, value) in effect.metadata {
attributes[NSAttributedString.Key(key)] = value
}
result.addAttributes(attributes, range: toNSRange(effect.range))
}
return result
}
fileprivate func toNSRange(_ range: Range<String.Index>) -> NSRange {
let start = distance(from: startIndex, to: range.lowerBound)
let length = distance(from: range.lowerBound, to: range.upperBound)
return NSMakeRange(start, length)
}
}
// MARK: -
#if os(OSX)
fileprivate extension Aura {
fileprivate var cocoaValue: NSShadow {
let shadow = NSShadow()
shadow.shadowOffset = CGSize(width: offset.width, height: offset.height)
shadow.shadowColor = color.cocoaValue
shadow.shadowBlurRadius = CGFloat(blur)
return shadow
}
}
fileprivate extension Color {
fileprivate var cocoaValue: NSColor {
let rgb = RGBView
return NSColor(red: CGFloat(rgb.red), green: CGFloat(rgb.green), blue: CGFloat(rgb.blue), alpha: CGFloat(AView))
}
}
#elseif os(iOS)
fileprivate extension Color {
var cocoaValue: UIColor {
let rgb = RGBView
return UIColor(red: CGFloat(rgb.red), green: CGFloat(rgb.green), blue: CGFloat(rgb.blue), alpha: CGFloat(AView))
}
}
#endif
fileprivate extension LinePattern {
var coreTextView: Int32 {
switch self {
case .none:
return CTUnderlineStyle().rawValue
case .single:
return CTUnderlineStyle.single.rawValue
case .thick:
return CTUnderlineStyle.thick.rawValue
case .double:
return CTUnderlineStyle.double.rawValue
case .dotted:
return CTUnderlineStyle.single.rawValue | CTUnderlineStyleModifiers.patternDot.rawValue
case .dashed:
return CTUnderlineStyle.single.rawValue | CTUnderlineStyleModifiers.patternDash.rawValue
case .dashedAndDotted:
return CTUnderlineStyle.single.rawValue | CTUnderlineStyleModifiers.patternDashDot.rawValue
case .dashedAndDottedTwice:
return CTUnderlineStyle.single.rawValue | CTUnderlineStyleModifiers.patternDashDotDot.rawValue
}
}
}
| bsd-2-clause | 666d6a8ee8998148dda2a45e8f7898a9 | 30.713115 | 137 | 0.75756 | 4.009326 | false | false | false | false |
informmegp2/inform-me | InformME/Authentication.swift | 1 | 9956 | //
// Authentication.swift
// InformME
//
// Created by Amal Ibrahim on 2/4/16.
// Copyright © 2016 King Saud University. All rights reserved.
//
import UIKit
import Foundation
class Authentication {
func login(email: String, Passoword: String, Type: Int, completionHandler: (login:Bool) -> ()){
struct f { static var flag = false }
let MYURL = NSURL(string:"http://bemyeyes.co/API/login.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
let postString = "email=\(email)&password=\(Passoword)&type=\(Type)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// var err: NSError?
// var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as NSDictionary
else {
if let urlContent = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)
let l = jsonResult["account"]!!["status"]
let s = String (l)
print (s+"Hi")
if( s == "Optional(true)") {
let id = jsonResult["account"]!!["ID"]
let email = jsonResult["account"]!!["email"]
let type = jsonResult["account"]!!["type"]
let session = jsonResult["account"]!!["session"]
print(id, email, type, session)
NSUserDefaults.standardUserDefaults().setObject(id, forKey: "id")
NSUserDefaults.standardUserDefaults().setObject(email, forKey: "email")
NSUserDefaults.standardUserDefaults().setObject(type, forKey: "type")
NSUserDefaults.standardUserDefaults().setObject(session, forKey: "session")
NSUserDefaults.standardUserDefaults().synchronize()
/* for jawaher to check
print(id, email, type, session)
print("lol")
*/
f.flag = true
}//end if
else if( s == "Optional(false)") {
f.flag = false
print (s)
} //end else
} catch {
print("JSON serialization failed")
}
}
}
// You can print out response object
// print("response = \(response)")
//completion handler values.
completionHandler(login: f.flag)
}
task.resume()
/*
var cID = ""
var cemail = ""
var ctype = ""
var csession = ""
let current = NSUserDefaults.standardUserDefaults()
cID = current.stringForKey("id")!
cemail = current.stringForKey("email")!
ctype = current.stringForKey("type")!
csession = current.stringForKey("session")!
print(cID)
print(cemail)
print(ctype)
print(ctype)
if (!cID.isEmpty && !cemail.isEmpty && !ctype.isEmpty && !csession.isEmpty) {
flag.self = true } */
/* for jawaher to check its save the in defaults let defaults = NSUserDefaults.standardUserDefaults()
if let name = defaults.stringForKey("id")
{
print("reading")
print(name)
}
*/ } // end fun login
func logout( completionHandler: (login:Bool) -> ()){
struct f { static var flag = false }
let session = NSUserDefaults.standardUserDefaults().stringForKey("session")!
print("from defult= "+session)
let MYURL = NSURL(string:"http://bemyeyes.co/API/logout.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
let postString = "&sessionID=\(session)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
else{
if let urlContent = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)
let l = jsonResult["status"]!!
let s = String (l)
print (s+"hi this status")
if( s == "success") {
NSUserDefaults.standardUserDefaults().removeObjectForKey("id")
NSUserDefaults.standardUserDefaults().removeObjectForKey("email")
NSUserDefaults.standardUserDefaults().removeObjectForKey("type")
NSUserDefaults.standardUserDefaults().removeObjectForKey("session")
NSUserDefaults.standardUserDefaults().synchronize()
f.flag = true
print (s+"hi 1111")
} //end if
else if( s == "unsuccess") {
f.flag = false
print (s+"hi 222")
} //end else
} catch {
print("JSON serialization failed")
}
}
}//end els
// You can print out response object
// print("response = \(response)")
completionHandler(login: f.flag)
}
task.resume()
} // end log out
func forgetPassword(){
}
func requestPassword(email: String){}
func recoverPassword(email: String , Type: Int, completionHandler: (login:Bool) -> ()){
struct f { static var flag = false }
let MYURL = NSURL(string:"http://bemyeyes.co/API/rest.php")
let request = NSMutableURLRequest(URL:MYURL!)
request.HTTPMethod = "POST";
let postString = "&email=\(email)&type=\(Type)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
else{
if let urlContent = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)
let l = jsonResult["status"]!!
let s = String (l)
print (s+"hi this status")
if( s == "success") {
f.flag = true
print (s+"hi 1111")
} //end if
else if( s == "unsuccess") {
f.flag = false
print (s+"hi 222")
} //end else
} catch {
print("JSON serialization failed")
}
}
}//end els
// You can print out response object
// print("response = \(response)")
completionHandler(login: f.flag)
}
task.resume()
} // end recover password fun
}//end class | mit | 9b7ea16a5616c1c6a5360fae514886a5 | 28.196481 | 144 | 0.394977 | 6.94212 | false | false | false | false |
macemmi/HBCI4Swift | HBCI4Swift/HBCI4Swift/Source/Syntax/HBCIDataElementGroupDescription.swift | 1 | 7536 | //
// HBCIDataElementGroupDescription.swift
// HBCIBackend
//
// Created by Frank Emminghaus on 22.12.14.
// Copyright (c) 2014 Frank Emminghaus. All rights reserved.
//
import Foundation
class HBCIDataElementGroupDescription: HBCISyntaxElementDescription {
override init(syntax: HBCISyntax, element: XMLElement) throws {
try super.init(syntax: syntax, element: element)
self.delimiter = HBCIChar.dpoint.rawValue;
self.elementType = .dataElementGroup
}
override func elementDescription() -> String {
if self.identifier == nil {
let type = self.type ?? "none"
let name = self.name ?? "none"
return "DEG type: \(type), name: \(name) \n"
} else {
return "DEG id: \(self.identifier!) \n"
}
}
func parseDEG(_ bytes: UnsafePointer<CChar>, length: Int, binaries:Array<Data>, optional:Bool)->HBCISyntaxElement? {
let deg = HBCIDataElementGroup(description: self);
var ref:HBCISyntaxElementReference;
var refIdx = 0;
var num = 0;
var count = 0;
var delimiter = CChar(":");
var p: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>(mutating: bytes);
var resLength = length;
while(refIdx < self.children.count) {
ref = self.children[refIdx];
// check if optional tail is cut
if delimiter == HBCIChar.plus.rawValue || delimiter == HBCIChar.quote.rawValue {
if num >= ref.minnum {
refIdx += 1;
continue; // check next
} else {
// error: non-optional element but end of DEG
logInfo("Parse error: non-optional element \(ref.name ?? "?") is missing at the end of data element group");
return nil;
}
}
// DE or nested DEG?
var parsedElem:HBCISyntaxElement?
if ref.elemDescr.elementType == ElementType.dataElementGroup {
if let descr = ref.elemDescr as? HBCIDataElementGroupDescription {
parsedElem = descr.parseDEG(p, length: resLength, binaries: binaries, optional: ref.minnum == 0 || optional);
} else {
logInfo("Unexpected HBCI syntax error");
return nil;
}
} else {
parsedElem = ref.elemDescr.parse(p, length: resLength, binaries: binaries)
}
if let element = parsedElem {
if element.isEmpty {
// check if element was optional
if ref.minnum > num && !optional {
// error: minimal occurence
logInfo("Parse error: element \(element.name) is empty but not optional");
return nil;
}
}
if ref.name != nil {
element.name = ref.name;
} else {
logInfo("Parse error: reference without name");
return nil;
}
if !element.isEmpty {
deg.children.append(element);
}
num += 1;
if num == ref.maxnum {
// new object
num = 0;
refIdx += 1;
}
p = p.advanced(by: element.length);
delimiter = p.pointee;
p = p.advanced(by: 1); // consume delimiter
count += element.length + 1;
resLength = length - count;
} else {
// parse error for children
return nil;
}
}
deg.length = count-1;
return deg;
}
override func parse(_ bytes: UnsafePointer<CChar>, length: Int, binaries:Array<Data>)->HBCISyntaxElement? {
return parseDEG(bytes, length: length, binaries: binaries, optional: false);
/*
var deg = HBCIDataElementGroup(description: self);
var ref:HBCISyntaxElementReference;
var refIdx = 0;
var num = 0;
var count = 0;
var delimiter:CChar = ":";
var p: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>(bytes);
var resLength = length;
while(refIdx < self.children.count) {
ref = self.children[refIdx];
// check if optional tail is cut
if delimiter == "+" || delimiter == "'" {
if num >= ref.minnum {
refIdx++;
continue; // check next
} else {
// error: non-optional element but end of DEG
logInfo("Parse error: non-optional element \(ref.name) is missing at the end of data element group");
return nil;
}
}
if p.memory == ":" && refIdx > 0 {
// empty element - check if element was optional
if ref.minnum < num {
// error: minimal occurence
logInfo("Parse error: element \(ref.name) is empty but not optional");
return nil;
} else {
num = 0;
refIdx++;
p = p.advancedBy(1); // consume delimiter
count += 1;
resLength = length - count;
}
} else {
if let element = ref.elemDescr.parse(p, length: resLength, binaries: binaries) {
if ref.name != nil {
element.name = ref.name;
} else {
logInfo("Parse error: reference without name");
return nil;
}
deg.children.append(element);
if element.isEmpty {
// check if element was optional
if ref.minnum < num {
// error: minimal occurence
logInfo("Parse error: element \(element.name) is empty but not optional");
return nil;
} else {
num = 0;
refIdx++;
}
} else {
num++;
if num == ref.maxnum {
// new object
num = 0;
refIdx++;
}
}
p = p.advancedBy(element.length);
delimiter = p.memory;
p = p.advancedBy(1); // consume delimiter
count += element.length + 1;
resLength = length - count;
} else {
// parse error for children
return nil;
}
}
}
deg.length = count-1;
return deg;
*/
}
override func getElement() -> HBCISyntaxElement? {
return HBCIDataElementGroup(description: self);
}
}
| gpl-2.0 | a1440420bb521b1a845fec478f231734 | 35.582524 | 129 | 0.444666 | 5.590504 | false | false | false | false |
dbaldwin/DronePan | DronePan/ViewControllers/SegmentTableViewCell.swift | 1 | 2211 | /*
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
protocol SegmentTableViewCellDelegate {
func displayMessage(title: String, message: String)
func newValueForKey(key: SettingsViewKey, value: String)
}
class SegmentTableViewCell: UITableViewCell {
var delegate : SegmentTableViewCellDelegate?
var title : String?
var values : [String]?
var helpText : String?
var key : SettingsViewKey?
var currentValue : String?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var segmentControl: UISegmentedControl!
func prepareForDisplay(initialSelection: String) {
if let title = self.title {
self.titleLabel.text = title
}
if let values = self.values {
self.segmentControl.removeAllSegments()
for (index, value) in values.enumerate() {
self.segmentControl.insertSegmentWithTitle(value, atIndex: index, animated: false)
if value == initialSelection {
self.segmentControl.selectedSegmentIndex = index
}
}
}
}
@IBAction func helpButtonClicked(sender: UIButton) {
if let helpText = self.helpText, titleText = self.titleLabel.text {
self.delegate?.displayMessage(titleText, message: helpText)
}
}
@IBAction func segmentValueChanged(sender: UISegmentedControl) {
if let key = self.key, value = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex) {
self.delegate?.newValueForKey(key, value: value)
}
}
}
| gpl-3.0 | d59496a7e8a4f2d64b8a214c0616be60 | 33.546875 | 99 | 0.672999 | 5.025 | false | false | false | false |
zhuyunfeng1224/XiheMtxx | XiheMtxx/VC/EditImage/EditImageViewController.swift | 1 | 28255 | //
// EditImageViewController.swift
// EasyCard
//
// Created by echo on 2017/2/21.
// Copyright © 2017年 羲和. All rights reserved.
//
import UIKit
class EditImageViewController: BaseViewController {
// 编辑模式
enum EditMode {
case cut
case rotate
}
// 编辑模式
var editMode: EditMode = .cut
// imageView占屏幕高度的比例
let imageAndScreenHeightRatio: CGFloat = 0.7
// 底部menuBar高度
let menuBarHeight: CGFloat = 50
// 初始图片
var originImage: UIImage?
var image: UIImage? {
didSet {
self.cutCtrlView.originImage = image
}
}
var completation:((UIImage)->())?
// 底部背景View
lazy var bottomView: UIView = {
let _bottomView = UIView(frame: CGRect.zero)
_bottomView.backgroundColor = UIColor.white.withAlphaComponent(0.95)
_bottomView.translatesAutoresizingMaskIntoConstraints = false
return _bottomView
}()
// MARK: - Cut View
// 操作背景View
lazy var cutOperationView: UIView = {
let _cutOperationView = UIView(frame: CGRect.zero)
_cutOperationView.backgroundColor = UIColor.white.withAlphaComponent(0.95)
_cutOperationView.translatesAutoresizingMaskIntoConstraints = false
return _cutOperationView
}()
// 重置按钮
lazy var cutResetButton: UIButton = {
let _cutResetButton = UIButton(frame: CGRect.zero)
_cutResetButton.setTitle("重置", for: .normal)
_cutResetButton.setTitleColor(UIColor.white, for: .normal)
_cutResetButton.setBackgroundImage(UIImage(named:"btn_60_gray_normal_36x30_"), for: .normal)
_cutResetButton.setBackgroundImage(UIImage(named:"btn_60_gray_disabled_36x30_"), for: .disabled)
_cutResetButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
_cutResetButton.isEnabled = false
_cutResetButton.translatesAutoresizingMaskIntoConstraints = false
_cutResetButton.addTarget(self, action: #selector(cutResetButtonClicked(sender:)), for: .touchUpInside)
return _cutResetButton
}()
// 裁剪按钮
lazy var cutConfirmButton: UIButton = {
let _cutConfirmButton = UIButton(frame: CGRect.zero)
_cutConfirmButton.setTitle("确定裁剪", for: .normal)
_cutConfirmButton.setTitleColor(UIColor.white, for: .normal)
_cutConfirmButton
.setBackgroundImage(UIImage(named:"btn_60_blue_36x30_"), for: .normal)
_cutConfirmButton
.setBackgroundImage(UIImage(named:"btn_60_blue_highlighted_36x30_"), for: .highlighted)
_cutConfirmButton
.setBackgroundImage(UIImage(named:"btn_60_blue_highlighted_36x30_"), for: .disabled)
_cutConfirmButton
.setImage(UIImage(named:"icon_meihua_edit_clip_confirm_normal_30x30_"), for: .normal)
_cutConfirmButton
.setImage(UIImage(named:"icon_meihua_edit_clip_confirm_highlighted_30x30_"), for: .highlighted)
_cutConfirmButton
.setImage(UIImage(named:"icon_meihua_edit_clip_confirm_highlighted_30x30_"), for: .selected)
_cutConfirmButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
_cutConfirmButton.translatesAutoresizingMaskIntoConstraints = false
_cutConfirmButton.addTarget(self, action: #selector(cutButtonClicked(sender:)), for: .touchUpInside)
return _cutConfirmButton
}()
// 比例选择列表
lazy var cutRatioSelectionView: RatioSelectionView = {
let _cutRatioSelectionView = RatioSelectionView(frame: CGRect.zero)
_cutRatioSelectionView.translatesAutoresizingMaskIntoConstraints = false
_cutRatioSelectionView.delegate = self
return _cutRatioSelectionView
}()
lazy var cutCtrlView: CutCtrlView = {
let _cutCtrlView = CutCtrlView(frame: CGRect.zero)
_cutCtrlView.cutResizableView.delegate = self
return _cutCtrlView
}()
// 旋转图片展示View
lazy var rotateCtrlView: RotateCtrlView = {
let _rotateCtrlView = RotateCtrlView(frame: CGRect.zero)
_rotateCtrlView.isHidden = true
_rotateCtrlView.alpha = 0
_rotateCtrlView.delegate = self
_rotateCtrlView.dismissCompletation = { image in
self.image = image
}
return _rotateCtrlView
}()
// MARK: - Rotate View
lazy var rotateOperationView: UIView = {
let _rotateOperationView = UIView(frame: CGRect.zero)
_rotateOperationView.backgroundColor = UIColor.white.withAlphaComponent(0.95)
_rotateOperationView.translatesAutoresizingMaskIntoConstraints = false
_rotateOperationView.isHidden = true
return _rotateOperationView
}()
// 旋转重置按钮
lazy var rotateResetButton: UIButton = {
let _rotateResetButton = UIButton(frame: CGRect.zero)
_rotateResetButton.setTitle("重置", for: .normal)
_rotateResetButton.setTitleColor(UIColor.white, for: .normal)
_rotateResetButton
.setBackgroundImage(UIImage(named:"btn_60_gray_normal_36x30_"), for: .normal)
_rotateResetButton
.setBackgroundImage(UIImage(named:"btn_60_gray_disabled_36x30_"), for: .disabled)
_rotateResetButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
_rotateResetButton.isEnabled = false
_rotateResetButton.translatesAutoresizingMaskIntoConstraints = false
_rotateResetButton.addTarget(self, action: #selector(rotateResetButtonClicked(sender:)), for: .touchUpInside)
return _rotateResetButton
}()
// 向左旋转按钮
lazy var rotateLeftButton: UIButton = {
let _rotateLeftButton = UIButton(frame: CGRect.zero)
_rotateLeftButton.setImage(UIImage(named:"icon_meihua_edit_rotate_left_normal_30x30_"), for: .normal)
_rotateLeftButton.setImage(UIImage(named:"icon_meihua_edit_rotate_left_highlighted_30x30_"), for: .highlighted)
_rotateLeftButton.addTarget(self, action: #selector(rotateLeftButtonClicked(sender:)), for: .touchUpInside)
_rotateLeftButton.translatesAutoresizingMaskIntoConstraints = false
return _rotateLeftButton
}()
// 向右旋转按钮
lazy var rotateRightButton: UIButton = {
let _rotateRightButton = UIButton(frame: CGRect.zero)
_rotateRightButton.setImage(UIImage(named:"icon_meihua_edit_rotate_right_normal_30x30_"), for: .normal)
_rotateRightButton.setImage(UIImage(named:"icon_meihua_edit_rotate_right_highlighted_30x30_"), for: .highlighted)
_rotateRightButton.addTarget(self, action: #selector(rotateRightButtonClicked(sender:)), for: .touchUpInside)
_rotateRightButton.translatesAutoresizingMaskIntoConstraints = false
return _rotateRightButton
}()
// 水平向右反转按钮
lazy var rotateHorizontalButton: UIButton = {
let _rotateHorizontalButton = UIButton(frame: CGRect.zero)
_rotateHorizontalButton
.setImage(UIImage(named:"icon_meihua_edit_rotate_horizontal_normal_30x30_"), for: .normal)
_rotateHorizontalButton
.setImage(UIImage(named:"icon_meihua_edit_rotate_horizontal_highlighted_30x30_"), for: .highlighted)
_rotateHorizontalButton.addTarget(self, action: #selector(rotateHorizontalButtonClicked(sender:)), for: .touchUpInside)
_rotateHorizontalButton.translatesAutoresizingMaskIntoConstraints = false
return _rotateHorizontalButton
}()
// 水平向下反转按钮
lazy var rotateVerticalButton: UIButton = {
let _rotateVerticalButton = UIButton(frame: CGRect.zero)
_rotateVerticalButton
.setImage(UIImage(named:"icon_meihua_edit_rotate_vertical_normal_30x30_"), for: .normal)
_rotateVerticalButton
.setImage(UIImage(named:"icon_meihua_edit_rotate_vertical_highlighted_30x30_"), for: .highlighted)
_rotateVerticalButton.addTarget(self, action: #selector(rotateVerticalButtonClicked(sender:)), for: .touchUpInside)
_rotateVerticalButton.translatesAutoresizingMaskIntoConstraints = false
return _rotateVerticalButton
}()
// MARK: - Menu
// menuBar
lazy var menuBar: UIView = {
let _menuBar = UIView(frame: CGRect.zero)
_menuBar.backgroundColor = UIColor.white
_menuBar.translatesAutoresizingMaskIntoConstraints = false
_menuBar.layer.masksToBounds = false
_menuBar.layer.shadowColor = UIColor.lightGray.withAlphaComponent(0.3).cgColor
_menuBar.layer.shadowOffset = CGSize(width: 0, height: -0.5)
_menuBar.layer.shadowRadius = 0.5
_menuBar.layer.shadowOpacity = 0.8
return _menuBar
}()
// 裁剪menubutton
lazy var cutMenuButton: VerticalButton = {
let _cutMenuButton = VerticalButton(frame: CGRect.zero)
_cutMenuButton.imageView?.contentMode = .center
_cutMenuButton.titleLabel?.font = UIFont.systemFont(ofSize: 10)
_cutMenuButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 5, 0)
_cutMenuButton.setTitle("裁剪", for: .normal)
_cutMenuButton.setTitle("裁剪", for: .selected)
_cutMenuButton.setTitleColor(UIColor.colorWithHexString(hex: "#578fff"), for: .highlighted)
_cutMenuButton.setTitleColor(UIColor.colorWithHexString(hex: "#578fff"), for: .selected)
_cutMenuButton.setTitleColor(UIColor.gray, for: .normal)
_cutMenuButton
.setImage(UIImage(named:"icon_meihua_edit_clip_normal_30x30_"), for: .normal)
_cutMenuButton
.setImage(UIImage(named:"icon_meihua_edit_clip_highlighted_30x30_"), for: .highlighted)
_cutMenuButton
.setImage(UIImage(named:"icon_meihua_edit_clip_highlighted_30x30_"), for: .selected)
_cutMenuButton
.addTarget(self, action: #selector(cutMenuButtonClicked(sender:)), for: .touchUpInside)
_cutMenuButton.translatesAutoresizingMaskIntoConstraints = false
return _cutMenuButton
}()
// 旋转menubutton
lazy var rotateMenuButton: VerticalButton = {
let _rotateMenuButton = VerticalButton(frame: CGRect.zero)
_rotateMenuButton.imageView?.contentMode = .center
_rotateMenuButton.titleLabel?.font = UIFont.systemFont(ofSize: 10)
_rotateMenuButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 5, 0)
_rotateMenuButton.setTitle("旋转", for: .normal)
_rotateMenuButton.setTitle("旋转", for: .selected)
_rotateMenuButton.setTitleColor(UIColor.colorWithHexString(hex: "#578fff"), for: .highlighted)
_rotateMenuButton.setTitleColor(UIColor.colorWithHexString(hex: "#578fff"), for: .selected)
_rotateMenuButton.setTitleColor(UIColor.gray, for: .normal)
_rotateMenuButton
.setImage(UIImage(named:"icon_meihua_edit_rotate_normal_30x30_"), for: .normal)
_rotateMenuButton
.setImage(UIImage(named:"icon_meihua_edit_rotate_highlighted_30x30_"), for: .highlighted)
_rotateMenuButton
.setImage(UIImage(named:"icon_meihua_edit_rotate_highlighted_30x30_"), for: .selected)
_rotateMenuButton
.addTarget(self, action: #selector(rotateMenuButtonClicked(sender:)), for: .touchUpInside)
_rotateMenuButton.translatesAutoresizingMaskIntoConstraints = false
return _rotateMenuButton
}()
// 取消
lazy var cancelButton: UIButton = {
let _cancelButton = UIButton(frame: CGRect.zero)
_cancelButton.setImage(UIImage(named:"icon_cancel_normal_30x30_"), for: .normal)
_cancelButton.setImage(UIImage(named:"icon_cancel_highlighted_30x30_"), for: .disabled)
_cancelButton.addTarget(self, action: #selector(cancelButtonClicked(sender:)), for: .touchUpInside)
_cancelButton.translatesAutoresizingMaskIntoConstraints = false
return _cancelButton
}()
// 确定按钮
lazy var confirmButton: UIButton = {
let _confirmButton = UIButton(frame: CGRect.zero)
_confirmButton.setImage(UIImage(named:"icon_confirm_normal_30x30_") , for: .normal)
_confirmButton.setImage(UIImage(named:"icon_confirm_highlighted_30x30_"), for: .disabled)
_confirmButton.translatesAutoresizingMaskIntoConstraints = false
_confirmButton.addTarget(self, action: #selector(confirmButtonClicked(sender:)), for: .touchUpInside)
return _confirmButton
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.colorWithHexString(hex: "#2c2e30")
self.image = self.originImage
self.cutCtrlView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height * self.imageAndScreenHeightRatio)
self.view.addSubview(self.cutCtrlView)
self.rotateCtrlView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height * self.imageAndScreenHeightRatio)
self.view.addSubview(self.rotateCtrlView)
self.view.addSubview(self.bottomView)
self.bottomView.addSubview(self.cutOperationView)
self.cutOperationView.addSubview(self.cutResetButton)
self.cutOperationView.addSubview(self.cutConfirmButton)
self.cutOperationView.addSubview(self.cutRatioSelectionView)
self.bottomView.addSubview(self.menuBar)
self.cutMenuButton.isSelected = true
self.menuBar.addSubview(self.cutMenuButton)
self.menuBar.addSubview(self.rotateMenuButton)
self.menuBar.addSubview(self.cancelButton)
self.menuBar.addSubview(self.confirmButton)
self.bottomView.addSubview(self.rotateOperationView)
self.rotateOperationView.addSubview(self.rotateResetButton)
self.rotateOperationView.addSubview(self.rotateLeftButton)
self.rotateOperationView.addSubview(self.rotateRightButton)
self.rotateOperationView.addSubview(self.rotateHorizontalButton)
self.rotateOperationView.addSubview(self.rotateVerticalButton)
self.view.setNeedsUpdateConstraints()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.bottomView.frame = self.cutOperationView.frame.offsetBy(dx: 0, dy: UIScreen.main.bounds.size.height * (1.0-self.imageAndScreenHeightRatio))
UIView.animate(withDuration: 0.3, animations: {
self.bottomView.frame = self.cutOperationView.frame.offsetBy(dx: 0, dy: -UIScreen.main.bounds.size.height * (1.0-self.imageAndScreenHeightRatio))
})
}
override func updateViewConstraints() {
super.updateViewConstraints()
// bottomView
let bottomViewHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[bottomView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["bottomView": self.bottomView])
let bottomViewVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-y-[bottomView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: ["y": UIScreen.main.bounds.size.height * self.imageAndScreenHeightRatio], views: ["bottomView": self.bottomView])
self.view.addConstraints(bottomViewHConstraints)
self.view.addConstraints(bottomViewVConstraints)
// ------------------------------cutOperationView-------------------
// cutOperationView
let operationHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[cutOperationView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["cutOperationView": self.cutOperationView])
let operationVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[cutOperationView]-0-[menuBar]", options: NSLayoutFormatOptions(rawValue:0), metrics:nil, views: ["cutOperationView": self.cutOperationView, "menuBar": self.menuBar])
self.view.addConstraints(operationHConstraints)
self.view.addConstraints(operationVConstraints)
// cutResetButton and cutButton
let operationButtonsHContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[cutResetButton(==60)]->=0-[cutButton(==100)]-10-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["cutResetButton": self.cutResetButton, "cutButton": self.cutConfirmButton])
let operationResetButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[cutResetButton(==30)]-10-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["cutResetButton": self.cutResetButton])
let operationCutButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[cutButton(==30)]-10-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["cutButton": self.cutConfirmButton])
self.cutOperationView.addConstraints(operationButtonsHContraints)
self.cutOperationView.addConstraints(operationResetButtonVConstraints)
self.cutOperationView.addConstraints(operationCutButtonVConstraints)
// selectionView
let selectionViewHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[selectionView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["selectionView": self.cutRatioSelectionView])
let selectionViewVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[selectionView]-10-[cutResetButton]", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["selectionView": self.cutRatioSelectionView, "cutResetButton": self.cutResetButton])
self.cutOperationView.addConstraints(selectionViewHConstraints)
self.cutOperationView.addConstraints(selectionViewVConstraints)
// ------------------------- rotateOperationView -------------------
// rotateOperationView
let rotateOperationHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[rotateOperationView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["rotateOperationView": self.rotateOperationView])
let rotateOperationVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[rotateOperationView]-0-[menuBar]", options: NSLayoutFormatOptions(rawValue:0), metrics:nil, views: ["rotateOperationView": self.rotateOperationView, "menuBar": self.menuBar])
self.view.addConstraints(rotateOperationHConstraints)
self.view.addConstraints(rotateOperationVConstraints)
let rotateOperationButtonsHContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[rotateResetButton(==60)]->=20-[rotateLeftButton(==30)]-25-[rotateRightButton(==30)]-25-[rotateHorizontalButton(==30)]-25-[rotateVerticalButton(==30)]-15-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["rotateResetButton": self.rotateResetButton, "rotateLeftButton": self.rotateLeftButton, "rotateRightButton" : self.rotateRightButton, "rotateHorizontalButton" : self.rotateHorizontalButton, "rotateVerticalButton": self.rotateVerticalButton])
let bottom = (UIScreen.main.bounds.height * (1 - self.imageAndScreenHeightRatio) - self.menuBarHeight) / 2 - 15
let rotateResetButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[rotateResetButton(==30)]-bottom-|", options: NSLayoutFormatOptions(rawValue:0), metrics: ["bottom": bottom], views: ["rotateResetButton": self.rotateResetButton])
let rotateRightButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[rotateRightButton(==30)]-bottom-|", options: NSLayoutFormatOptions(rawValue:0), metrics: ["bottom": bottom], views: ["rotateRightButton": self.rotateRightButton])
let rotateLeftButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[rotateLeftButton(==30)]-bottom-|", options: NSLayoutFormatOptions(rawValue:0), metrics: ["bottom": bottom], views: ["rotateLeftButton": self.rotateLeftButton])
let rotateHorizontalButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[rotateHorizontalButton(==30)]-bottom-|", options: NSLayoutFormatOptions(rawValue:0), metrics: ["bottom": bottom], views: ["rotateHorizontalButton": self.rotateHorizontalButton])
let rotateVerticalButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[rotateVerticalButton(==30)]-bottom-|", options: NSLayoutFormatOptions(rawValue:0), metrics: ["bottom": bottom], views: ["rotateVerticalButton": self.rotateVerticalButton])
self.rotateOperationView.addConstraints(rotateOperationButtonsHContraints)
self.rotateOperationView.addConstraints(rotateResetButtonVConstraints)
self.rotateOperationView.addConstraints(rotateLeftButtonVConstraints)
self.rotateOperationView.addConstraints(rotateRightButtonVConstraints)
self.rotateOperationView.addConstraints(rotateHorizontalButtonVConstraints)
self.rotateOperationView.addConstraints(rotateVerticalButtonVConstraints)
// ---------------------------menuBar----------------------------
// cancelButton and confirmButton
let cancelAndConfirmButtonsHContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[cancelButton(==50)]-30-[cutMenuButton(==50)]->=0-[rotateMenuButton(==50)]-30-[confirmButton(==50)]-10-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["cancelButton": self.cancelButton, "confirmButton": self.confirmButton, "cutMenuButton": self.cutMenuButton, "rotateMenuButton": self.rotateMenuButton])
let cancelButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[cancelButton]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["cancelButton": self.cancelButton])
let confirmButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[confirmButton]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["confirmButton": self.confirmButton])
let cutMenuButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[cutMenuButton]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["cutMenuButton": self.cutMenuButton])
let rotateMenuButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[rotateMenuButton]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["rotateMenuButton": self.rotateMenuButton])
// menuBar
let menuBarHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[menuBar]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["menuBar": self.menuBar])
let menuBarVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[menuBar(==menuBarHeight)]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: ["menuBarHeight": self.menuBarHeight], views: ["menuBar": self.menuBar])
self.view.addConstraints(menuBarHConstraints)
self.view.addConstraints(menuBarVConstraints)
self.menuBar.addConstraints(cancelAndConfirmButtonsHContraints)
self.menuBar.addConstraints(cancelButtonVConstraints)
self.menuBar.addConstraints(confirmButtonVConstraints)
self.menuBar.addConstraints(cutMenuButtonVConstraints)
self.menuBar.addConstraints(rotateMenuButtonVConstraints)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Actions
// 取消按钮点击
func cancelButtonClicked(sender: UIButton) -> Void {
self.dismiss(animated: true) {
}
}
// 确定按钮点击
func confirmButtonClicked(sender: UIButton) -> Void {
if self.editMode == .cut, let completation = self.completation{
completation(self.image!)
}
else if self.editMode == .rotate, let completation = self.completation {
self.rotateCtrlView.generateNewTransformImage()
completation(self.rotateCtrlView.image!)
}
self.dismiss(animated: true) {
}
}
// 裁剪菜单按钮点击
func cutMenuButtonClicked(sender: UIButton) -> Void {
self.editMode = .cut
self.cutMenuButton.isSelected = true
self.rotateMenuButton.isSelected = false
self.cutCtrlView.resetLayoutOfSubviews()
UIView.animate(withDuration: 0.2, animations: {
self.cutCtrlView.isHidden = false
self.cutOperationView.alpha = 1
self.rotateOperationView.alpha = 0
self.rotateCtrlView.alpha = 0
}) { (finished) in
if finished {
self.cutOperationView.isHidden = false
self.rotateOperationView.isHidden = true
self.rotateCtrlView.isHidden = true
}
}
}
// 旋转菜单按钮点击
func rotateMenuButtonClicked(sender: UIButton) -> Void {
self.editMode = .rotate
self.rotateMenuButton.isSelected = true
self.cutMenuButton.isSelected = false
self.rotateCtrlView.originImage = self.image
self.rotateCtrlView.resetLayoutOfSubviews()
UIView.animate(withDuration: 0.2, animations: {
self.cutCtrlView.isHidden = true
self.rotateCtrlView.isHidden = false
self.rotateCtrlView.alpha = 1
self.cutOperationView.alpha = 0
self.rotateOperationView.alpha = 1
}) { (finished) in
if finished {
self.cutOperationView.isHidden = true
self.rotateOperationView.isHidden = false
}
}
}
// 重置按钮点击
func cutResetButtonClicked(sender: UIButton) -> Void {
self.image = self.originImage
self.cutRatioSelectionView.selectIndex = 0
self.cutResetButton.isEnabled = false
}
// 裁剪按钮点击
func cutButtonClicked(sender: UIButton) -> Void {
self.image = self.cutCtrlView.generateClipImage()
self.cutRatioSelectionView.selectIndex = self.cutRatioSelectionView.selectIndex
self.cutConfirmButton.isEnabled = false
}
// 旋转重置按钮
func rotateResetButtonClicked(sender: UIButton) -> Void {
self.rotateCtrlView.rotateReset()
self.rotateResetButton.isEnabled = false
}
// 向左旋转按钮
func rotateLeftButtonClicked(sender: UIButton) -> Void {
self.rotateCtrlView.rotateLeft()
}
// 向右旋转按钮
func rotateRightButtonClicked(sender: UIButton) -> Void {
self.rotateCtrlView.rotateRight()
}
// 向右反转按钮
func rotateHorizontalButtonClicked(sender: UIButton) -> Void {
self.rotateCtrlView.rotateHorizontalMirror()
}
// 向下反转按钮
func rotateVerticalButtonClicked(sender: UIButton) -> Void {
self.rotateCtrlView.rotateVerticalnMirror()
}
}
// MARK: RatioSelectionViewDelegate
extension EditImageViewController: RatioSelectionViewDelegate {
func ratioSelected(ratioType: RatioType) {
self.cutCtrlView.ratioType = ratioType
self.cutResetButton.isEnabled = true
self.cutConfirmButton.isEnabled = true
if ratioType == .ratio_free && self.cutRatioSelectionView.selectIndex != 0 {
self.cutRatioSelectionView.selectIndex = ratioType.rawValue
}
}
}
// MARK: UserResizableViewDelegate
extension EditImageViewController: UserResizableViewDelegate {
func resizeView() {
self.cutResetButton.isEnabled = true
self.cutConfirmButton.isEnabled = true
}
}
// MARK: RotateCtrlViewDelegate
extension EditImageViewController: RotateCtrlViewDelegate {
func rotateImageChanged() {
self.rotateResetButton.isEnabled = true
}
}
| mit | 859115bf05342c8d0b054a4484518c5a | 50.163303 | 570 | 0.694126 | 5.180011 | false | false | false | false |
ollieatkinson/Expectation | Tests/Source/Expectation_Spec.swift | 1 | 4958 | //
// Expectation.swift
// Expectation
//
// Created by Atkinson, Oliver (Developer) on 01/04/2016.
// Copyright © 2016 Oliver. All rights reserved.
//
import XCTest
@testable import Expectation
class Expectation_Spec: XCTestCase {
override func tearDown() {
super.tearDown()
ExpectationAssertFunctions.assertTrue = ExpectationAssertFunctions.ExpectationAssertTrue
ExpectationAssertFunctions.assertFalse = ExpectationAssertFunctions.ExpectationAssertFalse
ExpectationAssertFunctions.assertNil = ExpectationAssertFunctions.ExpectationAssertNil
ExpectationAssertFunctions.assertNotNil = ExpectationAssertFunctions.ExpectationAssertNotNil
ExpectationAssertFunctions.fail = ExpectationAssertFunctions.ExpectationFail
}
func testFunctions() {
ExpectationAssertFunctions.ExpectationAssertTrue(true, "", file: #file, line: #line)
ExpectationAssertFunctions.ExpectationAssertFalse(false, "", file: #file, line: #line)
ExpectationAssertFunctions.ExpectationAssertNil(nil, "", file: #file, line: #line)
ExpectationAssertFunctions.ExpectationAssertNotNil(NSObject(), "", file: #file, line: #line)
}
func testFailure() {
let failExpectation = expectation(description: "should call fail")
ExpectationAssertFunctions.fail = { message, file, line in
failExpectation.fulfill()
}
fail()
waitForExpectations(timeout: 1) {
XCTAssert($0 == nil)
}
}
struct A {
}
func testAssertTrue() {
let expectation = expect(5)
let assertTrue = self.expectation(description: "assertTrue is called")
ExpectationAssertFunctions.assertTrue = { expression, message, file, line in
assertTrue.fulfill()
}
_ = expectation.to
expectation.assertTrue(true, "")
waitForExpectations(timeout: 1) {
XCTAssert($0 == nil)
}
}
func testAssertTrueInverse() {
let expectation = expect(5)
let assertFalse = self.expectation(description: "assertFalse is called")
ExpectationAssertFunctions.assertFalse = { expression, message, file, line in
assertFalse.fulfill()
}
_ = expectation.toNot
expectation.assertTrue(true, "")
waitForExpectations(timeout: 1) {
XCTAssert($0 == nil)
}
}
func testAssertFalse() {
let expectation = expect(5)
let assertFalse = self.expectation(description: "assertFalse is called")
ExpectationAssertFunctions.assertFalse = { expression, message, file, line in
assertFalse.fulfill()
}
_ = expectation.to
expectation.assertFalse(true, "message")
waitForExpectations(timeout: 1) {
XCTAssert($0 == nil)
}
}
func testAssertFalseInverse() {
let expectation = expect(5)
let assertTrue = self.expectation(description: "assertTrue is called")
ExpectationAssertFunctions.assertTrue = { expression, message, file, line in
assertTrue.fulfill()
}
_ = expectation.toNot
expectation.assertFalse(true, "")
waitForExpectations(timeout: 1) {
XCTAssert($0 == nil)
}
}
func testAssertNil() {
let expectation = expect(5)
let assertNil = self.expectation(description: "assertNil is called")
ExpectationAssertFunctions.assertNil = { expression, message, file, line in
assertNil.fulfill()
}
let a: A? = A()
_ = expectation.to
expectation.assertNil(a, "")
waitForExpectations(timeout: 1) {
XCTAssert($0 == nil)
}
}
func testAssertNilInverse() {
let expectation = expect(5)
let assertNotNil = self.expectation(description: "assertNotNil is called")
ExpectationAssertFunctions.assertNotNil = { expression, message, file, line in
assertNotNil.fulfill()
}
let a: A? = A()
_ = expectation.toNot
expectation.assertNil(a, "")
waitForExpectations(timeout: 1) {
XCTAssert($0 == nil)
}
}
func testAssertNotNil() {
let expectation = expect(5)
let assertNotNil = self.expectation(description: "assertNotNil is called")
ExpectationAssertFunctions.assertNotNil = { expression, message, file, line in
assertNotNil.fulfill()
}
let a: A? = A()
_ = expectation.to
expectation.assertNotNil(a, "")
waitForExpectations(timeout: 1) {
XCTAssert($0 == nil)
}
}
func testAssertNotNilInverse() {
let expectation = expect(5)
let assertNil = self.expectation(description: "assertNil is called")
ExpectationAssertFunctions.assertNil = { expression, message, file, line in
assertNil.fulfill()
}
let a: A? = A()
_ = expectation.toNot
expectation.assertNotNil(a, "")
waitForExpectations(timeout: 1) {
XCTAssert($0 == nil)
}
}
}
| mit | d642074e014a35be81be013b3284ca21 | 22.94686 | 96 | 0.646964 | 5.027383 | false | true | false | false |
annatovstyga/REA-Schedule | Raspisaniye/LoginViewTwoController.swift | 1 | 6612 | //
// LoginViewTwoController.swift
//
//
// Created by rGradeStd on 1/24/16.
//
//
import UIKit
import Foundation
import CCAutocomplete
import RealmSwift
class LoginViewTwoController: UIViewController,UITextFieldDelegate{
// MARK: - Properties
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var label_IT_lab_: UILabel!
@IBOutlet weak var REALogo: UIImageView!
var autoCompleteViewController: AutoCompleteViewController!//внутренний контроллер поля с автодополнением.Нигде не используется кроме внутреннего инициализатора.
@IBOutlet weak var placeholderView: UIView!
// MARK: - View methods
var isStudent = false
var isFirstLoad = true
override func viewDidLoad() {
textField.delegate = self
textField.autocorrectionType = .no
let realm = try! Realm()
lectorsArray = [String]()
groupsArray = [String]()
if(isStudent){
let result = realm.objects(Unit.self).filter("type = 0")
for item in result{
groupsArray.append(item.name)
}
groupsArray.sort(by: before)
textField.placeholder = "Введите вашу группу"
}
else{
textField.placeholder = "Введите имя преподавателя"
let result = realm.objects(Unit.self).filter("type = 1")
for item in result{
lectorsArray.append(item.name)
}
lectorsArray.sort(by: before)
}
/*!!! НЕ ЗАБЫВАТЬ УДАЛЯТЬ !!!*/
NotificationCenter.default.addObserver(self, selector: #selector(LoginViewTwoController.keyboardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(LoginViewTwoController.keyboardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil);
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.isFirstLoad {
self.isFirstLoad = false
Autocomplete.setupAutocompleteForViewcontroller(self) // Устанавливать всегда только один раз,либо будет постоянно вылетать автодополнения
}
}
@IBAction func enterClick(_ sender: AnyObject) {
view.endEditing(true)
let realm = try! Realm()
let predicate = NSPredicate(format: "name = %@",self.textField.text!)
let lectorIDObject = realm.objects(Unit.self).filter(predicate)
let lectorID = lectorIDObject.first?.ID
defaults.set(lectorID, forKey: "subjectID")
defaults.set(lectorIDObject.first?.name, forKey: "subjectName")
if(lectorID != nil){
self.enter(ID: lectorID!,type:(lectorIDObject.first?.type)!)
}else{
showWarning()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func showWarning() {
let alertController = UIAlertController(title: "Не найдено данных!", message:
"Попробуйте проверить имя/название", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
func enter(ID:Int,type:Int)
{
defaults.set(true, forKey: "isLogined")
DispatchQueue.main.async(execute: {
updateSchedule(itemID: ID,type:type, successBlock: {
successBlock in
DispatchQueue.main.async(execute: {
parse(jsonDataList!,realmName:"default", successBlock: { (parsed) in
let aDelegate = UIApplication.shared.delegate
let mainVcIntial = kConstantObj.SetIntialMainViewController("mainTabBar")
aDelegate!.window?!.rootViewController = mainVcIntial
aDelegate!.window?!.makeKeyAndVisible()
})
})
})
})
}
func keyboardWillShow(_ sender: Notification) {
if let keyboardSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
}
func keyboardWillHide(_ sender: Notification) {
if let keyboardSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
}
extension LoginViewTwoController: AutocompleteDelegate {
func autoCompleteTextField() -> UITextField {
return self.textField
}
func autoCompleteThreshold(_ textField: UITextField) -> Int {
return 1
}
func autoCompleteItemsForSearchTerm(_ term: String) -> [AutocompletableOption] {
//FIXME переименовать переменные
var filteredCountries = [String]()
if(isStudent){
filteredCountries = groupsArray.filter { (country) -> Bool in
return country.lowercased().contains(term.lowercased())
}
}else{
filteredCountries = lectorsArray.filter { (country) -> Bool in
return country.lowercased().contains(term.lowercased())
}
}
let countriesAndFlags: [AutocompletableOption] = filteredCountries.map { ( country) -> AutocompleteCellData in
var country = country
country.replaceSubrange(country.startIndex...country.startIndex, with: String(country.characters[country.startIndex]).capitalized)
return AutocompleteCellData(text: country, image: UIImage(named: country))
}.map( { $0 as AutocompletableOption })
return countriesAndFlags
}
func autoCompleteHeight() -> CGFloat {
return self.view.frame.height / 3.0
}
func didSelectItem(_ item: AutocompletableOption) {
self.textField.text = item.text
}
}
| mit | 2da572d867be326dba65c2eda60687cc | 33.950276 | 177 | 0.630888 | 4.678994 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/ElastiCache/ElastiCache_Error.swift | 1 | 18791 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for ElastiCache
public struct ElastiCacheErrorType: AWSErrorType {
enum Code: String {
case aPICallRateForCustomerExceededFault = "APICallRateForCustomerExceeded"
case authorizationAlreadyExistsFault = "AuthorizationAlreadyExists"
case authorizationNotFoundFault = "AuthorizationNotFound"
case cacheClusterAlreadyExistsFault = "CacheClusterAlreadyExists"
case cacheClusterNotFoundFault = "CacheClusterNotFound"
case cacheParameterGroupAlreadyExistsFault = "CacheParameterGroupAlreadyExists"
case cacheParameterGroupNotFoundFault = "CacheParameterGroupNotFound"
case cacheParameterGroupQuotaExceededFault = "CacheParameterGroupQuotaExceeded"
case cacheSecurityGroupAlreadyExistsFault = "CacheSecurityGroupAlreadyExists"
case cacheSecurityGroupNotFoundFault = "CacheSecurityGroupNotFound"
case cacheSecurityGroupQuotaExceededFault = "QuotaExceeded.CacheSecurityGroup"
case cacheSubnetGroupAlreadyExistsFault = "CacheSubnetGroupAlreadyExists"
case cacheSubnetGroupInUse = "CacheSubnetGroupInUse"
case cacheSubnetGroupNotFoundFault = "CacheSubnetGroupNotFoundFault"
case cacheSubnetGroupQuotaExceededFault = "CacheSubnetGroupQuotaExceeded"
case cacheSubnetQuotaExceededFault = "CacheSubnetQuotaExceededFault"
case clusterQuotaForCustomerExceededFault = "ClusterQuotaForCustomerExceeded"
case defaultUserAssociatedToUserGroupFault = "DefaultUserAssociatedToUserGroup"
case defaultUserRequired = "DefaultUserRequired"
case duplicateUserNameFault = "DuplicateUserName"
case globalReplicationGroupAlreadyExistsFault = "GlobalReplicationGroupAlreadyExistsFault"
case globalReplicationGroupNotFoundFault = "GlobalReplicationGroupNotFoundFault"
case insufficientCacheClusterCapacityFault = "InsufficientCacheClusterCapacity"
case invalidARNFault = "InvalidARN"
case invalidCacheClusterStateFault = "InvalidCacheClusterState"
case invalidCacheParameterGroupStateFault = "InvalidCacheParameterGroupState"
case invalidCacheSecurityGroupStateFault = "InvalidCacheSecurityGroupState"
case invalidGlobalReplicationGroupStateFault = "InvalidGlobalReplicationGroupState"
case invalidKMSKeyFault = "InvalidKMSKeyFault"
case invalidParameterCombinationException = "InvalidParameterCombination"
case invalidParameterValueException = "InvalidParameterValue"
case invalidReplicationGroupStateFault = "InvalidReplicationGroupState"
case invalidSnapshotStateFault = "InvalidSnapshotState"
case invalidSubnet = "InvalidSubnet"
case invalidUserGroupStateFault = "InvalidUserGroupState"
case invalidUserStateFault = "InvalidUserState"
case invalidVPCNetworkStateFault = "InvalidVPCNetworkStateFault"
case noOperationFault = "NoOperationFault"
case nodeGroupNotFoundFault = "NodeGroupNotFoundFault"
case nodeGroupsPerReplicationGroupQuotaExceededFault = "NodeGroupsPerReplicationGroupQuotaExceeded"
case nodeQuotaForClusterExceededFault = "NodeQuotaForClusterExceeded"
case nodeQuotaForCustomerExceededFault = "NodeQuotaForCustomerExceeded"
case replicationGroupAlreadyExistsFault = "ReplicationGroupAlreadyExists"
case replicationGroupAlreadyUnderMigrationFault = "ReplicationGroupAlreadyUnderMigrationFault"
case replicationGroupNotFoundFault = "ReplicationGroupNotFoundFault"
case replicationGroupNotUnderMigrationFault = "ReplicationGroupNotUnderMigrationFault"
case reservedCacheNodeAlreadyExistsFault = "ReservedCacheNodeAlreadyExists"
case reservedCacheNodeNotFoundFault = "ReservedCacheNodeNotFound"
case reservedCacheNodeQuotaExceededFault = "ReservedCacheNodeQuotaExceeded"
case reservedCacheNodesOfferingNotFoundFault = "ReservedCacheNodesOfferingNotFound"
case serviceLinkedRoleNotFoundFault = "ServiceLinkedRoleNotFoundFault"
case serviceUpdateNotFoundFault = "ServiceUpdateNotFoundFault"
case snapshotAlreadyExistsFault = "SnapshotAlreadyExistsFault"
case snapshotFeatureNotSupportedFault = "SnapshotFeatureNotSupportedFault"
case snapshotNotFoundFault = "SnapshotNotFoundFault"
case snapshotQuotaExceededFault = "SnapshotQuotaExceededFault"
case subnetInUse = "SubnetInUse"
case subnetNotAllowedFault = "SubnetNotAllowedFault"
case tagNotFoundFault = "TagNotFound"
case tagQuotaPerResourceExceeded = "TagQuotaPerResourceExceeded"
case testFailoverNotAvailableFault = "TestFailoverNotAvailableFault"
case userAlreadyExistsFault = "UserAlreadyExists"
case userGroupAlreadyExistsFault = "UserGroupAlreadyExists"
case userGroupNotFoundFault = "UserGroupNotFound"
case userGroupQuotaExceededFault = "UserGroupQuotaExceeded"
case userNotFoundFault = "UserNotFound"
case userQuotaExceededFault = "UserQuotaExceeded"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize ElastiCache
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The customer has exceeded the allowed rate of API calls.
public static var aPICallRateForCustomerExceededFault: Self { .init(.aPICallRateForCustomerExceededFault) }
/// The specified Amazon EC2 security group is already authorized for the specified cache security group.
public static var authorizationAlreadyExistsFault: Self { .init(.authorizationAlreadyExistsFault) }
/// The specified Amazon EC2 security group is not authorized for the specified cache security group.
public static var authorizationNotFoundFault: Self { .init(.authorizationNotFoundFault) }
/// You already have a cluster with the given identifier.
public static var cacheClusterAlreadyExistsFault: Self { .init(.cacheClusterAlreadyExistsFault) }
/// The requested cluster ID does not refer to an existing cluster.
public static var cacheClusterNotFoundFault: Self { .init(.cacheClusterNotFoundFault) }
/// A cache parameter group with the requested name already exists.
public static var cacheParameterGroupAlreadyExistsFault: Self { .init(.cacheParameterGroupAlreadyExistsFault) }
/// The requested cache parameter group name does not refer to an existing cache parameter group.
public static var cacheParameterGroupNotFoundFault: Self { .init(.cacheParameterGroupNotFoundFault) }
/// The request cannot be processed because it would exceed the maximum number of cache security groups.
public static var cacheParameterGroupQuotaExceededFault: Self { .init(.cacheParameterGroupQuotaExceededFault) }
/// A cache security group with the specified name already exists.
public static var cacheSecurityGroupAlreadyExistsFault: Self { .init(.cacheSecurityGroupAlreadyExistsFault) }
/// The requested cache security group name does not refer to an existing cache security group.
public static var cacheSecurityGroupNotFoundFault: Self { .init(.cacheSecurityGroupNotFoundFault) }
/// The request cannot be processed because it would exceed the allowed number of cache security groups.
public static var cacheSecurityGroupQuotaExceededFault: Self { .init(.cacheSecurityGroupQuotaExceededFault) }
/// The requested cache subnet group name is already in use by an existing cache subnet group.
public static var cacheSubnetGroupAlreadyExistsFault: Self { .init(.cacheSubnetGroupAlreadyExistsFault) }
/// The requested cache subnet group is currently in use.
public static var cacheSubnetGroupInUse: Self { .init(.cacheSubnetGroupInUse) }
/// The requested cache subnet group name does not refer to an existing cache subnet group.
public static var cacheSubnetGroupNotFoundFault: Self { .init(.cacheSubnetGroupNotFoundFault) }
/// The request cannot be processed because it would exceed the allowed number of cache subnet groups.
public static var cacheSubnetGroupQuotaExceededFault: Self { .init(.cacheSubnetGroupQuotaExceededFault) }
/// The request cannot be processed because it would exceed the allowed number of subnets in a cache subnet group.
public static var cacheSubnetQuotaExceededFault: Self { .init(.cacheSubnetQuotaExceededFault) }
/// The request cannot be processed because it would exceed the allowed number of clusters per customer.
public static var clusterQuotaForCustomerExceededFault: Self { .init(.clusterQuotaForCustomerExceededFault) }
public static var defaultUserAssociatedToUserGroupFault: Self { .init(.defaultUserAssociatedToUserGroupFault) }
/// You must add default user to a user group.
public static var defaultUserRequired: Self { .init(.defaultUserRequired) }
/// A user with this username already exists.
public static var duplicateUserNameFault: Self { .init(.duplicateUserNameFault) }
/// The Global Datastore name already exists.
public static var globalReplicationGroupAlreadyExistsFault: Self { .init(.globalReplicationGroupAlreadyExistsFault) }
/// The Global Datastore does not exist
public static var globalReplicationGroupNotFoundFault: Self { .init(.globalReplicationGroupNotFoundFault) }
/// The requested cache node type is not available in the specified Availability Zone. For more information, see InsufficientCacheClusterCapacity in the ElastiCache User Guide.
public static var insufficientCacheClusterCapacityFault: Self { .init(.insufficientCacheClusterCapacityFault) }
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
public static var invalidARNFault: Self { .init(.invalidARNFault) }
/// The requested cluster is not in the available state.
public static var invalidCacheClusterStateFault: Self { .init(.invalidCacheClusterStateFault) }
/// The current state of the cache parameter group does not allow the requested operation to occur.
public static var invalidCacheParameterGroupStateFault: Self { .init(.invalidCacheParameterGroupStateFault) }
/// The current state of the cache security group does not allow deletion.
public static var invalidCacheSecurityGroupStateFault: Self { .init(.invalidCacheSecurityGroupStateFault) }
/// The Global Datastore is not available or in primary-only state.
public static var invalidGlobalReplicationGroupStateFault: Self { .init(.invalidGlobalReplicationGroupStateFault) }
/// The KMS key supplied is not valid.
public static var invalidKMSKeyFault: Self { .init(.invalidKMSKeyFault) }
/// Two or more incompatible parameters were specified.
public static var invalidParameterCombinationException: Self { .init(.invalidParameterCombinationException) }
/// The value for a parameter is invalid.
public static var invalidParameterValueException: Self { .init(.invalidParameterValueException) }
/// The requested replication group is not in the available state.
public static var invalidReplicationGroupStateFault: Self { .init(.invalidReplicationGroupStateFault) }
/// The current state of the snapshot does not allow the requested operation to occur.
public static var invalidSnapshotStateFault: Self { .init(.invalidSnapshotStateFault) }
/// An invalid subnet identifier was specified.
public static var invalidSubnet: Self { .init(.invalidSubnet) }
/// The user group is not in an active state.
public static var invalidUserGroupStateFault: Self { .init(.invalidUserGroupStateFault) }
/// The user is not in active state.
public static var invalidUserStateFault: Self { .init(.invalidUserStateFault) }
/// The VPC network is in an invalid state.
public static var invalidVPCNetworkStateFault: Self { .init(.invalidVPCNetworkStateFault) }
/// The operation was not performed because no changes were required.
public static var noOperationFault: Self { .init(.noOperationFault) }
/// The node group specified by the NodeGroupId parameter could not be found. Please verify that the node group exists and that you spelled the NodeGroupId value correctly.
public static var nodeGroupNotFoundFault: Self { .init(.nodeGroupNotFoundFault) }
/// The request cannot be processed because it would exceed the maximum allowed number of node groups (shards) in a single replication group. The default maximum is 90
public static var nodeGroupsPerReplicationGroupQuotaExceededFault: Self { .init(.nodeGroupsPerReplicationGroupQuotaExceededFault) }
/// The request cannot be processed because it would exceed the allowed number of cache nodes in a single cluster.
public static var nodeQuotaForClusterExceededFault: Self { .init(.nodeQuotaForClusterExceededFault) }
/// The request cannot be processed because it would exceed the allowed number of cache nodes per customer.
public static var nodeQuotaForCustomerExceededFault: Self { .init(.nodeQuotaForCustomerExceededFault) }
/// The specified replication group already exists.
public static var replicationGroupAlreadyExistsFault: Self { .init(.replicationGroupAlreadyExistsFault) }
/// The targeted replication group is not available.
public static var replicationGroupAlreadyUnderMigrationFault: Self { .init(.replicationGroupAlreadyUnderMigrationFault) }
/// The specified replication group does not exist.
public static var replicationGroupNotFoundFault: Self { .init(.replicationGroupNotFoundFault) }
/// The designated replication group is not available for data migration.
public static var replicationGroupNotUnderMigrationFault: Self { .init(.replicationGroupNotUnderMigrationFault) }
/// You already have a reservation with the given identifier.
public static var reservedCacheNodeAlreadyExistsFault: Self { .init(.reservedCacheNodeAlreadyExistsFault) }
/// The requested reserved cache node was not found.
public static var reservedCacheNodeNotFoundFault: Self { .init(.reservedCacheNodeNotFoundFault) }
/// The request cannot be processed because it would exceed the user's cache node quota.
public static var reservedCacheNodeQuotaExceededFault: Self { .init(.reservedCacheNodeQuotaExceededFault) }
/// The requested cache node offering does not exist.
public static var reservedCacheNodesOfferingNotFoundFault: Self { .init(.reservedCacheNodesOfferingNotFoundFault) }
/// The specified service linked role (SLR) was not found.
public static var serviceLinkedRoleNotFoundFault: Self { .init(.serviceLinkedRoleNotFoundFault) }
/// The service update doesn't exist
public static var serviceUpdateNotFoundFault: Self { .init(.serviceUpdateNotFoundFault) }
/// You already have a snapshot with the given name.
public static var snapshotAlreadyExistsFault: Self { .init(.snapshotAlreadyExistsFault) }
/// You attempted one of the following operations: Creating a snapshot of a Redis cluster running on a cache.t1.micro cache node. Creating a snapshot of a cluster that is running Memcached rather than Redis. Neither of these are supported by ElastiCache.
public static var snapshotFeatureNotSupportedFault: Self { .init(.snapshotFeatureNotSupportedFault) }
/// The requested snapshot name does not refer to an existing snapshot.
public static var snapshotNotFoundFault: Self { .init(.snapshotNotFoundFault) }
/// The request cannot be processed because it would exceed the maximum number of snapshots.
public static var snapshotQuotaExceededFault: Self { .init(.snapshotQuotaExceededFault) }
/// The requested subnet is being used by another cache subnet group.
public static var subnetInUse: Self { .init(.subnetInUse) }
/// At least one subnet ID does not match the other subnet IDs. This mismatch typically occurs when a user sets one subnet ID to a regional Availability Zone and a different one to an outpost. Or when a user sets the subnet ID to an Outpost when not subscribed on this service.
public static var subnetNotAllowedFault: Self { .init(.subnetNotAllowedFault) }
/// The requested tag was not found on this resource.
public static var tagNotFoundFault: Self { .init(.tagNotFoundFault) }
/// The request cannot be processed because it would cause the resource to have more than the allowed number of tags. The maximum number of tags permitted on a resource is 50.
public static var tagQuotaPerResourceExceeded: Self { .init(.tagQuotaPerResourceExceeded) }
/// The TestFailover action is not available.
public static var testFailoverNotAvailableFault: Self { .init(.testFailoverNotAvailableFault) }
/// A user with this ID already exists.
public static var userAlreadyExistsFault: Self { .init(.userAlreadyExistsFault) }
/// The user group with this ID already exists.
public static var userGroupAlreadyExistsFault: Self { .init(.userGroupAlreadyExistsFault) }
/// The user group was not found or does not exist
public static var userGroupNotFoundFault: Self { .init(.userGroupNotFoundFault) }
/// The number of users exceeds the user group limit.
public static var userGroupQuotaExceededFault: Self { .init(.userGroupQuotaExceededFault) }
/// The user does not exist or could not be found.
public static var userNotFoundFault: Self { .init(.userNotFoundFault) }
/// The quota of users has been exceeded.
public static var userQuotaExceededFault: Self { .init(.userQuotaExceededFault) }
}
extension ElastiCacheErrorType: Equatable {
public static func == (lhs: ElastiCacheErrorType, rhs: ElastiCacheErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ElastiCacheErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | b779c1a971fe0aa0ccb153caf0cd42ca | 72.980315 | 281 | 0.769358 | 5.760576 | false | false | false | false |
Eliothu/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/ReaderStreamViewController.swift | 5 | 36064 | import Foundation
@objc public class ReaderStreamViewController : UIViewController, UIActionSheetDelegate,
WPContentSyncHelperDelegate,
WPTableViewHandlerDelegate,
ReaderPostCellDelegate,
ReaderStreamHeaderDelegate
{
// MARK: - Properties
private var tableView: UITableView!
private var refreshControl: UIRefreshControl!
private var tableViewHandler: WPTableViewHandler!
private var syncHelper: WPContentSyncHelper!
private var tableViewController: UITableViewController!
private var cellForLayout: ReaderPostCardCell!
private var resultsStatusView: WPNoResultsView!
private var footerView: PostListFooterView!
private var objectIDOfPostForMenu: NSManagedObjectID?
private var anchorViewForMenu: UIView?
private let footerViewNibName = "PostListFooterView"
private let readerCardCellNibName = "ReaderPostCardCell"
private let readerCardCellReuseIdentifier = "ReaderCardCellReuseIdentifier"
private let readerBlockedCellNibName = "ReaderBlockedSiteCell"
private let readerBlockedCellReuseIdentifier = "ReaderBlockedCellReuseIdentifier"
private let estimatedRowHeight = CGFloat(100.0)
private let blockedRowHeight = CGFloat(66.0)
private let loadMoreThreashold = 4
private let refreshInterval = 300
private var displayContext: NSManagedObjectContext?
private var cleanupAndRefreshAfterScrolling = false
private let recentlyBlockedSitePostObjectIDs = NSMutableArray()
private var showShareActivityAfterActionSheetIsDismissed = false
private let frameForEmptyHeaderView = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 30.0)
private let heightForFooterView = CGFloat(34.0)
private var siteID:NSNumber? {
didSet {
if siteID != nil {
fetchSiteTopic()
}
}
}
public var readerTopic: ReaderAbstractTopic? {
didSet {
if readerTopic != nil {
if isViewLoaded() {
configureControllerForTopic()
}
// Discard the siteID (if there was one) now that we have a good topic
siteID = nil
}
}
}
/**
Convenience method for instantiating an instance of ReaderListViewController
for a particular topic.
@param topic The reader topic for the list.
@return A ReaderListViewController instance.
*/
public class func controllerWithTopic(topic:ReaderAbstractTopic) -> ReaderStreamViewController {
let storyboard = UIStoryboard(name: "Reader", bundle: NSBundle.mainBundle())
let controller = storyboard.instantiateViewControllerWithIdentifier("ReaderStreamViewController") as! ReaderStreamViewController
controller.readerTopic = topic
return controller
}
public class func controllerWithSiteID(siteID:NSNumber) -> ReaderStreamViewController {
let storyboard = UIStoryboard(name: "Reader", bundle: NSBundle.mainBundle())
let controller = storyboard.instantiateViewControllerWithIdentifier("ReaderStreamViewController") as! ReaderStreamViewController
controller.siteID = siteID
return controller
}
// MARK: - LifeCycle Methods
public override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
tableViewController = segue.destinationViewController as? UITableViewController
}
public override func viewDidLoad() {
super.viewDidLoad()
setupCellForLayout()
setupTableView()
setupFooterView()
setupTableViewHandler()
setupSyncHelper()
setupResultsStatusView()
WPStyleGuide.configureColorsForView(view, andTableView: tableView)
if readerTopic != nil {
configureControllerForTopic()
} else if siteID != nil {
displayLoadingStream()
}
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
refreshTableViewHeaderLayout()
}
// MARK: -
public override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
private func fetchSiteTopic() {
if isViewLoaded() {
displayLoadingStream()
}
assert(siteID != nil, "A siteID is required before fetching a site topic")
let service = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext)
service.siteTopicForSiteWithID(siteID!,
success: { [weak self] (objectID:NSManagedObjectID!, isFollowing:Bool) -> Void in
do {
let topic = try self?.managedObjectContext().existingObjectWithID(objectID) as? ReaderAbstractTopic
self?.readerTopic = topic
} catch let error as NSError {
DDLogSwift.logError(error.localizedDescription)
}
},
failure: {[weak self] (error:NSError!) -> Void in
self?.displayLoadingStreamFailed()
})
}
// MARK: - Setup
private func setupTableView() {
assert(tableViewController != nil, "The tableViewController must be assigned before configuring the tableView")
tableView = tableViewController.tableView
tableView.separatorStyle = .None
refreshControl = tableViewController.refreshControl!
refreshControl.addTarget(self, action: Selector("handleRefresh:"), forControlEvents: .ValueChanged)
var nib = UINib(nibName: readerCardCellNibName, bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: readerCardCellReuseIdentifier)
nib = UINib(nibName: readerBlockedCellNibName, bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: readerBlockedCellReuseIdentifier)
}
private func setupTableViewHandler() {
assert(tableView != nil, "A tableView must be assigned before configuring a handler")
tableViewHandler = WPTableViewHandler(tableView: tableView)
tableViewHandler.cacheRowHeights = true
tableViewHandler.updateRowAnimation = .None
tableViewHandler.delegate = self
}
private func setupSyncHelper() {
syncHelper = WPContentSyncHelper()
syncHelper.delegate = self
}
private func setupCellForLayout() {
cellForLayout = NSBundle.mainBundle().loadNibNamed(readerCardCellNibName, owner: nil, options: nil).first as! ReaderPostCardCell
// Add layout cell to superview (briefly) so constraint constants reflect the correct size class.
view.addSubview(cellForLayout)
cellForLayout.removeFromSuperview()
}
private func setupResultsStatusView() {
resultsStatusView = WPNoResultsView()
}
private func setupFooterView() {
footerView = NSBundle.mainBundle().loadNibNamed(footerViewNibName, owner: nil, options: nil).first as! PostListFooterView
footerView.showSpinner(false)
var frame = footerView.frame
frame.size.height = heightForFooterView
footerView.frame = frame
tableView.tableFooterView = footerView
}
// MARK: - Handling Loading and No Results
func displayLoadingStream() {
resultsStatusView.titleText = NSLocalizedString("Loading stream...", comment:"A short message to inform the user the requested stream is being loaded.")
resultsStatusView.messageText = ""
displayResultsStatus()
}
func displayLoadingStreamFailed() {
resultsStatusView.titleText = NSLocalizedString("Problem loading stream", comment:"Error message title informing the user that a stream could not be loaded.");
resultsStatusView.messageText = NSLocalizedString("Sorry. The stream could not be loaded.", comment:"A short error message leting the user know the requested stream could not be loaded.");
displayResultsStatus()
}
func displayLoadingViewIfNeeded() {
let count = tableViewHandler.resultsController.fetchedObjects?.count ?? 0
if count > 0 {
return
}
resultsStatusView.titleText = NSLocalizedString("Fetching posts...", comment:"A brief prompt shown when the reader is empty, letting the user know the app is currently fetching new posts.")
resultsStatusView.messageText = ""
let boxView = WPAnimatedBox.newAnimatedBox()
resultsStatusView.accessoryView = boxView
displayResultsStatus()
boxView.prepareAndAnimateAfterDelay(0.3)
}
func displayNoResultsView() {
// Its possible the topic was deleted before a sync could be completed,
// so make certain its not nil.
if readerTopic == nil {
return
}
let response:NoResultsResponse = ReaderStreamViewController.responseForNoResults(readerTopic!)
resultsStatusView.titleText = response.title
resultsStatusView.messageText = response.message
resultsStatusView.accessoryView = nil
displayResultsStatus()
}
func displayResultsStatus() {
if resultsStatusView.isDescendantOfView(tableView) {
resultsStatusView.centerInSuperview()
} else {
tableView.addSubviewWithFadeAnimation(resultsStatusView)
}
footerView.hidden = true
}
func hideResultsStatus() {
resultsStatusView.removeFromSuperview()
footerView.hidden = false
}
// MARK: - Topic Presentation
func configureStreamHeader() {
assert(readerTopic != nil, "A reader topic is required")
let header:ReaderStreamHeader? = ReaderStreamViewController.headerForStream(readerTopic!)
if header == nil {
if UIDevice.isPad() {
let headerView = UIView(frame: frameForEmptyHeaderView)
headerView.backgroundColor = UIColor.clearColor()
tableView.tableHeaderView = headerView
} else {
tableView.tableHeaderView = nil
}
return
}
header!.configureHeader(readerTopic!)
header!.delegate = self
tableView.tableHeaderView = header as? UIView
refreshTableViewHeaderLayout()
}
func configureControllerForTopic() {
assert(readerTopic != nil, "A reader topic is required")
assert(isViewLoaded(), "The controller's view must be loaded before displaying the topic")
hideResultsStatus()
recentlyBlockedSitePostObjectIDs.removeAllObjects()
updateAndPerformFetchRequest()
configureStreamHeader()
tableView.setContentOffset(CGPointZero, animated: false)
tableViewHandler.refreshTableView()
syncIfAppropriate()
let count = tableViewHandler.resultsController.fetchedObjects?.count ?? 0
// Make sure we're showing the no results view if appropriate
if !syncHelper.isSyncing && count == 0 {
displayNoResultsView()
}
WPAnalytics.track(.ReaderLoadedTag, withProperties: propertyForStats())
if ReaderHelpers.topicIsFreshlyPressed(readerTopic!) {
WPAnalytics.track(.ReaderLoadedFreshlyPressed)
}
}
// MARK: - Instance Methods
func refreshTableViewHeaderLayout() {
if tableView.tableHeaderView == nil {
return
}
let headerView = tableView.tableHeaderView!
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
tableView.tableHeaderView = headerView
}
public func scrollViewToTop() {
tableView.setContentOffset(CGPoint.zero, animated: true)
}
private func propertyForStats() -> [NSObject: AnyObject] {
assert(readerTopic != nil, "A reader topic is required")
let title = readerTopic!.title ?? ""
var key: String = "list"
if ReaderHelpers.isTopicTag(readerTopic!) {
key = "tag"
} else if ReaderHelpers.isTopicSite(readerTopic!) {
key = "site"
}
return [key : title]
}
private func shouldShowBlockSiteMenuItem() -> Bool {
return ReaderHelpers.isTopicTag(readerTopic!) || ReaderHelpers.topicIsFreshlyPressed(readerTopic!)
}
private func showMenuForPost(post:ReaderPost, fromView anchorView:UIView) {
objectIDOfPostForMenu = post.objectID
anchorViewForMenu = anchorView
let cancel = NSLocalizedString("Cancel", comment:"The title of a cancel button.")
let blockSite = NSLocalizedString("Block This Site", comment:"The title of a button that triggers blocking a site from the user's reader.")
let share = NSLocalizedString("Share", comment:"Verb. Title of a button. Pressing the lets the user share a post to others.")
let actionSheet = UIActionSheet(title: nil,
delegate: self,
cancelButtonTitle: cancel,
destructiveButtonTitle: shouldShowBlockSiteMenuItem() ? blockSite : nil
)
actionSheet.addButtonWithTitle(share)
if UIDevice.isPad() {
actionSheet.showFromRect(anchorViewForMenu!.bounds, inView:anchorViewForMenu!, animated:true)
} else {
actionSheet.showFromTabBar(tabBarController!.tabBar)
}
}
private func sharePost(post: ReaderPost) {
let controller = ReaderHelpers.shareController(
post.titleForDisplay(),
summary: post.contentPreviewForDisplay(),
tags: post.tags,
link: post.permaLink
)
if !UIDevice.isPad() {
presentViewController(controller, animated: true, completion: nil)
return
}
// Gah! Stupid iPad and UIPopovoers!!!!
let popover = UIPopoverController(contentViewController: controller)
popover.presentPopoverFromRect(anchorViewForMenu!.bounds,
inView: anchorViewForMenu!,
permittedArrowDirections: UIPopoverArrowDirection.Unknown,
animated: false)
}
private func showAttributionForPost(post: ReaderPost) {
// Fail safe. If there is no attribution exit.
if post.sourceAttribution == nil {
return
}
// If there is a blogID preview the site
if post.sourceAttribution!.blogID != nil {
let controller = ReaderStreamViewController.controllerWithSiteID(post.sourceAttribution!.blogID)
navigationController?.pushViewController(controller, animated: true)
return
}
if post.sourceAttribution!.attributionType != SourcePostAttributionTypeSite {
return
}
let linkURL = NSURL(string: post.sourceAttribution.blogURL)
let controller = WPWebViewController(URL: linkURL)
let navController = UINavigationController(rootViewController: controller)
presentViewController(navController, animated: true, completion: nil)
}
private func toggleLikeForPost(post: ReaderPost) {
let service = ReaderPostService(managedObjectContext: managedObjectContext())
service.toggleLikedForPost(post, success: nil, failure: { (error:NSError?) in
if let anError = error {
DDLogSwift.logError("Error (un)liking post: \(anError.localizedDescription)")
}
})
}
private func updateAndPerformFetchRequest() {
assert(NSThread.isMainThread(), "ReaderStreamViewController Error: updating fetch request on a background thread.")
tableViewHandler.resultsController.fetchRequest.predicate = predicateForFetchRequest()
do {
try tableViewHandler.resultsController.performFetch()
} catch let error as NSError {
DDLogSwift.logError("Error fetching posts after updating the fetch reqeust predicate: \(error.localizedDescription)")
}
}
// MARK: - Blocking
private func blockSiteForPost(post: ReaderPost) {
let objectID = post.objectID
recentlyBlockedSitePostObjectIDs.addObject(objectID)
updateAndPerformFetchRequest()
let indexPath = tableViewHandler.resultsController.indexPathForObject(post)!
tableViewHandler.invalidateCachedRowHeightAtIndexPath(indexPath)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
let service = ReaderSiteService(managedObjectContext: managedObjectContext())
service.flagSiteWithID(post.siteID,
asBlocked: true,
success: nil,
failure: { [weak self] (error:NSError!) in
self?.recentlyBlockedSitePostObjectIDs.removeObject(objectID)
self?.tableViewHandler.invalidateCachedRowHeightAtIndexPath(indexPath)
self?.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
let alertView = UIAlertView(
title: NSLocalizedString("Error Blocking Site", comment:"Title of a prompt letting the user know there was an error trying to block a site from appearing in the reader."),
message: error.localizedDescription,
delegate: nil,
cancelButtonTitle: NSLocalizedString("OK", comment:"Text for an alert's dismissal button.")
)
alertView.show()
})
}
private func unblockSiteForPost(post: ReaderPost) {
let objectID = post.objectID
recentlyBlockedSitePostObjectIDs.removeObject(objectID)
let indexPath = tableViewHandler.resultsController.indexPathForObject(post)!
tableViewHandler.invalidateCachedRowHeightAtIndexPath(indexPath)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
let service = ReaderSiteService(managedObjectContext: managedObjectContext())
service.flagSiteWithID(post.siteID,
asBlocked: false,
success: nil,
failure: { [weak self] (error:NSError!) in
self?.recentlyBlockedSitePostObjectIDs.addObject(objectID)
self?.tableViewHandler.invalidateCachedRowHeightAtIndexPath(indexPath)
self?.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
let alertView = UIAlertView(
title: NSLocalizedString("Error Unblocking Site", comment:"Title of a prompt letting the user know there was an error trying to unblock a site from appearing in the reader."),
message: error.localizedDescription,
delegate: nil,
cancelButtonTitle: NSLocalizedString("OK", comment:"Text for an alert's dismissal button.")
)
alertView.show()
})
}
// MARK: - Actions
/**
Handles the user initiated pull to refresh action.
*/
func handleRefresh(sender:UIRefreshControl) {
if !canSync() {
cleanupAfterSync()
return
}
syncHelper.syncContentWithUserInteraction(true)
}
// MARK: - Sync Methods
func canSync() -> Bool {
let appDelegate = WordPressAppDelegate.sharedInstance()
return (readerTopic != nil) && appDelegate.connectionAvailable
}
func canLoadMore() -> Bool {
let fetchedObjects = tableViewHandler.resultsController.fetchedObjects ?? []
if fetchedObjects.count == 0 {
return false
}
return canSync()
}
/**
Kicks off a "background" sync without updating the UI if certain conditions
are met.
- The app must have a internet connection.
- The current time must be greater than the last sync interval.
*/
func syncIfAppropriate() {
let lastSynced = readerTopic?.lastSynced == nil ? NSDate(timeIntervalSince1970: 0) : readerTopic!.lastSynced
if canSync() && Int(lastSynced.timeIntervalSinceNow) < refreshInterval {
syncHelper.syncContentWithUserInteraction(false)
}
}
func syncItems(success:((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
let syncContext = ContextManager.sharedInstance().newDerivedContext()
let service = ReaderPostService(managedObjectContext: syncContext)
syncContext.performBlock {[weak self] () -> Void in
do {
let topic = try syncContext.existingObjectWithID(self!.readerTopic!.objectID) as! ReaderAbstractTopic
service.fetchPostsForTopic(topic,
earlierThan: NSDate(),
success: {[weak self] (count:Int, hasMore:Bool) in
dispatch_async(dispatch_get_main_queue(), {
if let strongSelf = self {
if strongSelf.recentlyBlockedSitePostObjectIDs.count > 0 {
strongSelf.recentlyBlockedSitePostObjectIDs.removeAllObjects()
strongSelf.updateAndPerformFetchRequest()
}
}
success?(hasMore: hasMore)
})
}, failure: { (error:NSError!) in
dispatch_async(dispatch_get_main_queue(), {
failure?(error: error)
})
})
} catch let error as NSError {
DDLogSwift.logError(error.localizedDescription)
}
}
}
func backfillItems(success:((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
let syncContext = ContextManager.sharedInstance().newDerivedContext()
let service = ReaderPostService(managedObjectContext: syncContext)
syncContext.performBlock {[weak self] () -> Void in
do {
let topic = try syncContext.existingObjectWithID(self!.readerTopic!.objectID) as! ReaderAbstractTopic
service.backfillPostsForTopic(topic,
success: { (count:Int, hasMore:Bool) -> Void in
dispatch_async(dispatch_get_main_queue(), {
success?(hasMore: hasMore)
})
}, failure: { (error:NSError!) -> Void in
dispatch_async(dispatch_get_main_queue(), {
failure?(error: error)
})
})
} catch let error as NSError {
DDLogSwift.logError(error.localizedDescription)
}
}
}
func loadMoreItems(success:((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
let post = tableViewHandler.resultsController.fetchedObjects?.last as? ReaderPost
if post == nil {
// failsafe
return
}
footerView.showSpinner(true)
let earlierThan = post!.sortDate
let syncContext = ContextManager.sharedInstance().newDerivedContext()
let service = ReaderPostService(managedObjectContext: syncContext)
syncContext.performBlock { [weak self] () -> Void in
do {
let topic = try syncContext.existingObjectWithID(self!.readerTopic!.objectID) as! ReaderAbstractTopic
service.fetchPostsForTopic(topic,
earlierThan: earlierThan,
success: { (count:Int, hasMore:Bool) -> Void in
dispatch_async(dispatch_get_main_queue(), {
success?(hasMore: hasMore)
})
},
failure: { (error:NSError!) -> Void in
dispatch_async(dispatch_get_main_queue(), {
failure?(error: error)
})
})
} catch let error as NSError {
DDLogSwift.logError(error.localizedDescription)
}
}
WPAnalytics.track(.ReaderInfiniteScroll, withProperties: propertyForStats())
}
func syncHelper(syncHelper: WPContentSyncHelper, syncContentWithUserInteraction userInteraction: Bool, success: ((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
displayLoadingViewIfNeeded()
if userInteraction {
syncItems(success, failure: failure)
} else {
backfillItems(success, failure: failure)
}
}
func syncHelper(syncHelper: WPContentSyncHelper, syncMoreWithSuccess success: ((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
loadMoreItems(success, failure: failure)
}
public func syncContentEnded() {
if tableViewHandler.isScrolling {
cleanupAndRefreshAfterScrolling = true
return
}
cleanupAfterSync()
}
public func cleanupAfterSync() {
cleanupAndRefreshAfterScrolling = false
tableViewHandler.refreshTableViewPreservingOffset()
refreshControl.endRefreshing()
footerView.showSpinner(false)
}
public func tableViewHandlerWillRefreshTableViewPreservingOffset(tableViewHandler: WPTableViewHandler!) {
// Reload the table view to reflect new content.
managedObjectContext().reset()
updateAndPerformFetchRequest()
}
public func tableViewHandlerDidRefreshTableViewPreservingOffset(tableViewHandler: WPTableViewHandler!) {
if self.tableViewHandler.resultsController.fetchedObjects?.count == 0 {
displayNoResultsView()
} else {
hideResultsStatus()
}
}
// MARK: - Helpers for TableViewHandler
func predicateForFetchRequest() -> NSPredicate {
if readerTopic == nil {
return NSPredicate(format: "topic = NULL")
}
var topic: ReaderAbstractTopic!
do {
topic = try managedObjectContext().existingObjectWithID(readerTopic!.objectID) as! ReaderAbstractTopic
} catch let error as NSError {
DDLogSwift.logError(error.description)
}
if recentlyBlockedSitePostObjectIDs.count > 0 {
return NSPredicate(format: "topic = %@ AND (isSiteBlocked = NO OR SELF in %@)", topic, recentlyBlockedSitePostObjectIDs)
}
return NSPredicate(format: "topic = %@ AND isSiteBlocked = NO", topic)
}
func sortDescriptorsForFetchRequest() -> [NSSortDescriptor] {
let sortDescriptor = NSSortDescriptor(key: "sortDate", ascending: false)
return [sortDescriptor]
}
// MARK: - TableViewHandler Delegate Methods
public func scrollViewWillBeginDragging(scrollView: UIScrollView!) {
if refreshControl.refreshing {
refreshControl.endRefreshing()
}
}
public func scrollViewDidEndDragging(scrollView: UIScrollView!, willDecelerate decelerate: Bool) {
if decelerate {
return
}
if cleanupAndRefreshAfterScrolling {
cleanupAfterSync()
}
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView!) {
if cleanupAndRefreshAfterScrolling {
cleanupAfterSync()
}
}
public func managedObjectContext() -> NSManagedObjectContext {
if let context = displayContext {
return context
}
displayContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
displayContext!.parentContext = ContextManager.sharedInstance().mainContext
return displayContext!
}
public func fetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: ReaderPost.classNameWithoutNamespaces())
fetchRequest.predicate = predicateForFetchRequest()
fetchRequest.sortDescriptors = sortDescriptorsForFetchRequest()
return fetchRequest
}
public func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return estimatedRowHeight
}
public func tableView(aTableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let width = aTableView.bounds.width
return tableView(aTableView, heightForRowAtIndexPath: indexPath, forWidth: width)
}
public func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!, forWidth width: CGFloat) -> CGFloat {
if tableViewHandler.resultsController.fetchedObjects == nil {
return 0.0
}
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
if recentlyBlockedSitePostObjectIDs.containsObject(post.objectID) {
return blockedRowHeight
}
configureCell(cellForLayout, atIndexPath: indexPath)
let size = cellForLayout.sizeThatFits(CGSize(width:width, height:CGFloat.max))
return size.height
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell? {
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
if recentlyBlockedSitePostObjectIDs.containsObject(post.objectID) {
let cell = tableView.dequeueReusableCellWithIdentifier(readerBlockedCellReuseIdentifier) as! ReaderBlockedSiteCell
configureBlockedCell(cell, atIndexPath: indexPath)
return cell
}
let cell = tableView.dequeueReusableCellWithIdentifier(readerCardCellReuseIdentifier) as! ReaderPostCardCell
configureCell(cell, atIndexPath: indexPath)
return cell
}
public func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
// Check to see if we need to load more.
let criticalRow = tableView.numberOfRowsInSection(indexPath.section) - loadMoreThreashold
if (indexPath.section == tableView.numberOfSections - 1) && (indexPath.row >= criticalRow) {
if syncHelper.hasMoreContent {
syncHelper.syncMoreContent()
}
}
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
if recentlyBlockedSitePostObjectIDs.containsObject(post.objectID) {
unblockSiteForPost(post)
return
}
var controller: ReaderPostDetailViewController?
if post.sourceAttributionStyle() == .Post &&
post.sourceAttribution.postID != nil &&
post.sourceAttribution.blogID != nil {
controller = ReaderPostDetailViewController.detailControllerWithPostID(post.sourceAttribution.postID!, siteID: post.sourceAttribution.blogID!)
} else {
controller = ReaderPostDetailViewController.detailControllerWithPost(post)
}
navigationController?.pushViewController(controller!, animated: true)
}
public func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
if tableViewHandler.resultsController.fetchedObjects == nil {
return
}
cell.accessoryType = .None
cell.selectionStyle = .None
let postCell = cell as! ReaderPostCardCell
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
let shouldLoadMedia = postCell != cellForLayout
postCell.blogNameButtonIsEnabled = !ReaderHelpers.isTopicSite(readerTopic!)
postCell.configureCell(post, loadingMedia: shouldLoadMedia)
postCell.delegate = self
}
public func configureBlockedCell(cell: ReaderBlockedSiteCell, atIndexPath indexPath: NSIndexPath) {
if tableViewHandler.resultsController.fetchedObjects == nil {
return
}
cell.accessoryType = .None
cell.selectionStyle = .None
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
cell.setSiteName(post.blogName)
}
// MARK: - ReaderStreamHeader Delegate Methods
public func handleFollowActionForHeader(header:ReaderStreamHeader) {
// TODO: Pending data model improvements
}
// MARK: - ReaderCard Delegate Methods
public func readerCell(cell: ReaderPostCardCell, headerActionForProvider provider: ReaderPostContentProvider) {
let post = provider as! ReaderPost
let controller = ReaderStreamViewController.controllerWithSiteID(post.siteID)
navigationController?.pushViewController(controller, animated: true)
WPAnalytics.track(.ReaderPreviewedSite)
}
public func readerCell(cell: ReaderPostCardCell, commentActionForProvider provider: ReaderPostContentProvider) {
let post = provider as! ReaderPost
let controller = ReaderCommentsViewController(post: post)
navigationController?.pushViewController(controller, animated: true)
}
public func readerCell(cell: ReaderPostCardCell, likeActionForProvider provider: ReaderPostContentProvider) {
let post = provider as! ReaderPost
toggleLikeForPost(post)
}
public func readerCell(cell: ReaderPostCardCell, visitActionForProvider provider: ReaderPostContentProvider) {
// TODO: No longer needed. Remove when cards are updated
}
public func readerCell(cell: ReaderPostCardCell, tagActionForProvider provider: ReaderPostContentProvider) {
// TODO: Waiting on Core Data support
}
public func readerCell(cell: ReaderPostCardCell, menuActionForProvider provider: ReaderPostContentProvider, fromView sender: UIView) {
let post = provider as! ReaderPost
showMenuForPost(post, fromView:sender)
}
public func readerCell(cell: ReaderPostCardCell, attributionActionForProvider provider: ReaderPostContentProvider) {
let post = provider as! ReaderPost
showAttributionForPost(post)
}
// MARK: - UIActionSheet Delegate Methods
public func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == actionSheet.cancelButtonIndex {
return
}
if objectIDOfPostForMenu == nil {
return
}
var post: ReaderPost?
do {
post = try managedObjectContext().existingObjectWithID(objectIDOfPostForMenu!) as? ReaderPost
} catch let error as NSError {
DDLogSwift.logError(error.localizedDescription)
}
if post == nil {
return
}
if buttonIndex == actionSheet.destructiveButtonIndex {
blockSiteForPost(post!)
return
}
showShareActivityAfterActionSheetIsDismissed = true
}
public func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
if showShareActivityAfterActionSheetIsDismissed {
do {
let post = try managedObjectContext().existingObjectWithID(objectIDOfPostForMenu!) as? ReaderPost
if let readerPost = post {
sharePost(readerPost)
}
} catch let error as NSError {
DDLogSwift.logError(error.localizedDescription)
}
}
showShareActivityAfterActionSheetIsDismissed = false
objectIDOfPostForMenu = nil
anchorViewForMenu = nil
}
}
| gpl-2.0 | cf53a2915a3882d10e5e3f214b6b14f0 | 37.862069 | 197 | 0.658052 | 6.004662 | false | false | false | false |
JohnnyHao/Timer-Extention | TonnyTimer/TodayViewController.swift | 1 | 3140 | //
// TodayViewController.swift
// TonnyTimer
//
// Created by Tonny.hao on 3/17/15.
// Copyright (c) 2015 OneV's Den. All rights reserved.
//
import UIKit
import NotificationCenter
import TonnyTimerKit
private let kSharedGroupIndentifier = "group.iWatchResearch"
private let kTimerLeftTimeKey = "com.tonny.research.com.SimpleTimer.lefttime"
private let kTimerQuitDateKey = "com.tonny.research.com.SimpleTimer.quitdate"
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet weak var lblTImer: UILabel!
var timer:Timer!
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = NSUserDefaults(suiteName: kSharedGroupIndentifier)
let leftTimeWhenQuit = userDefaults!.integerForKey(kTimerLeftTimeKey)
let quitDate = userDefaults!.integerForKey(kTimerQuitDateKey)
let passedTimeFromQuit = NSDate().timeIntervalSinceDate(NSDate(timeIntervalSince1970: NSTimeInterval(quitDate)))
let leftTime = leftTimeWhenQuit - Int(passedTimeFromQuit)
lblTImer.text = "\(leftTime)"
if (leftTime > 0) {
timer = Timer(timeInteral: NSTimeInterval(leftTime))
timer.start(updateTick: {
[weak self] leftTick in self!.updateLabel()
}, stopHandler: {
[weak self] finished in
self!.showOpenAppButton()
})
} else {
// showOpenAppButton()
}
// Do any additional setup after loading the view from its nib.
}
private func updateLabel() {
lblTImer.text = timer.leftTimeString
}
private func showOpenAppButton() {
lblTImer.text = "Finished"
preferredContentSize = CGSizeMake(0, 100)
let button = UIButton(frame: CGRectMake(0, 50, 50, 63))
button.setTitle("Open", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button)
}
@objc private func buttonPressed(sender: AnyObject!) {
extensionContext!.openURL(NSURL(string: "simpleTimer://finished")!, completionHandler: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// set the layout(margin) for the extention parent view
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
var defaultEdge = defaultMarginInsets
return UIEdgeInsetsMake(0, 0, 0, 0);
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.NewData)
}
}
| apache-2.0 | 9b0ffb6445ce936828aa6ecf37bfe3c2 | 33.130435 | 120 | 0.657325 | 4.968354 | false | false | false | false |
SeptAi/Cooperate | Cooperate/Cooperate/Class/ViewModel/ProjectListViewModel.swift | 1 | 3222 | //
// HomeListViewModel.swift
// Cooperate
//
// Created by J on 2017/1/4.
// Copyright © 2017年 J. All rights reserved.
//
import Foundation
/// 数据列表视图模型
/*
父类的选择
- 如果类需要使用 `KVC` 或者字典转模型框架设置对象值,类就需要继承自 NSObject
- 如果类只是包装一些代码逻辑(写了一些函数),可以不用任何父类,好处:更加轻量级
- 提示:如果用 OC 写,一律都继承自 NSObject 即可
使命:负责的数据处理
1. 字典转模型
2. 下拉/上拉刷新数据处理
*/
private let MaxPullNum = 3
class ProjectListViewModel {
private var PullNum = 0
// 视图模型数组懒加载
// 按照编号排序,方便进行上拉下拉刷新
lazy var projectList = [ProjectViewModel]()
/// 请求数据
///
/// - Parameter comletion: 请求是否成功
func loadStatus(pullup:Bool = false,comletion:@escaping (_ isSuccess:Bool,_ isHasMore:Bool) -> ()) {
// 判断上拉刷新次数
if pullup && PullNum > MaxPullNum{
// 次数超限
comletion(true,false)
return
}
// 获取上限、下限
let since_id = pullup ? 0 : (projectList.first?.project.projectid ?? 0)
let max_id = !pullup ? 0 : (projectList.last?.project.projectid ?? 0)
// FIXME: - 数据缓存,通过DAL访问数据
// 数据请求
NetworkManager.sharedInstance.projectList(since_id: since_id, max_id: max_id){
(list,isSuccess) in
// 0.判断请求是否成功
if !isSuccess{
comletion(false, false)
return
}
// 字典转模型
// yy_model(第三方框架支持嵌套的字典转模型 -- 与返回的属性值key需要一致)
var array = [ProjectViewModel]()
// 便利服务器返回字典数组,字典转模型
for dict in list ?? []{
// 创建模型
guard let model = Project.yy_model(with:dict) else{
continue
}
// 将model添加到数组
array.append(ProjectViewModel(model: model))
}
print("刷新到\(array.count)的数据,内容为\(array)")
// 拼接参数
// FIXME: - 拼接参数
// self.projectList = pullup ? (self.projectList + array) : (array + self.projectList)
self.projectList = array
// 完成回调
if pullup && array.count == 0{
self.PullNum += 1
comletion(isSuccess, false)
}else{
self.cacheSingleImage(list: array,finish:comletion)
// 真正的回调 - 移到完成单张缓存之后执行
}
}
}
// 缓存本次下载微博数据数组的单张图像
// - 缓存完成后,并修改配图视图大小后...再回调
private func cacheSingleImage(list:[ProjectViewModel],finish:@escaping (_ isSuccess:Bool,_ isHasMore:Bool) -> ()){
finish(true, true)
}
}
| mit | 16aec3aa82f39f801adba392f9edd116 | 28.034091 | 118 | 0.524462 | 3.768437 | false | false | false | false |
CharlinFeng/TextField-InputView | UITextField+InputView/TextField+InputView/Common/InputViewTextField.swift | 1 | 2253 | //
// InputViewTextField.swift
// TextField+InputView
//
// Created by 成林 on 15/8/31.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
class InputViewTextField: UITextField {
lazy var accessoryView: AccessoryView = {AccessoryView.instance()}()
private lazy var btn = UIButton()
var emptyDataClickClosure:(Void->Void)?
override init(frame: CGRect) {
super.init(frame: frame)
//视图准备
self.viewPrepare()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//视图准备
self.viewPrepare()
}
/** 视图准备 */
func viewPrepare(){
self.inputAccessoryView = accessoryView
accessoryView.doneBtnActionClosure={
self.endEditing(true)
}
accessoryView.cancelBtnActionClosure={
self.endEditing(true)
}
//添加监听
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(noti_textFieldDidBeginEditing), name: UITextFieldTextDidBeginEditingNotification, object: self)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(noti_textFieldDidEndEditing), name: UITextFieldTextDidEndEditingNotification, object: self)
btn.addTarget(self, action: #selector(btnClick), forControlEvents: UIControlEvents.TouchUpInside)
addSubview(btn)
placeholder = "正在加载数据..."
}
deinit{NSNotificationCenter.defaultCenter().removeObserver(self)}
override func layoutSubviews() {
super.layoutSubviews()
btn.frame = bounds
}
}
extension InputViewTextField{
func noti_textFieldDidBeginEditing(textField: UITextField) {}
func noti_textFieldDidEndEditing(textField: UITextField) {}
override func caretRectForPosition(position: UITextPosition) -> CGRect {return CGRectZero}
func btnClick(){emptyDataClickClosure?()}
func dataPrepare(){
assert(NSThread.isMainThread(), "请在主线程中执行方法")
btn.hidden = true
placeholder = "请选择"
}
} | mit | 8c8fe391c9080d460ff4e80f4ba9d1c5 | 26.15 | 178 | 0.636573 | 5.269417 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Stats/Insights/Posting Activity/PostingActivityViewController.swift | 2 | 4388 | import UIKit
class PostingActivityViewController: UIViewController, StoryboardLoadable {
// MARK: - StoryboardLoadable Protocol
static var defaultStoryboardName = defaultControllerID
// MARK: - Properties
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var separatorLine: UIView!
@IBOutlet weak var dayDataView: UIView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var postCountLabel: UILabel!
@IBOutlet weak var legendView: UIView!
var yearData = [[PostingStreakEvent]]()
private var selectedDay: PostingActivityDay?
private typealias Style = WPStyleGuide.Stats
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Posting Activity", comment: "Title for stats Posting Activity view.")
addLegend()
applyStyles()
collectionView.register(PostingActivityCollectionViewCell.self, forCellWithReuseIdentifier: PostingActivityCollectionViewCell.reuseIdentifier)
// Hide the day data view until a day is selected.
dayDataView.isHidden = true
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.collectionViewLayout.invalidateLayout()
}
}
// MARK: - UICollectionViewDataSource
extension PostingActivityViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return yearData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PostingActivityCollectionViewCell.reuseIdentifier, for: indexPath) as! PostingActivityCollectionViewCell
cell.configure(withData: yearData[indexPath.row], postingActivityDayDelegate: self)
return cell
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension PostingActivityViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return Style.cellSizeForFrameWidth(collectionView.frame.size.width)
}
}
// MARK: - PostingActivityDayDelegate
extension PostingActivityViewController: PostingActivityDayDelegate {
func daySelected(_ day: PostingActivityDay) {
selectedDay?.unselect()
selectedDay = day
guard let dayData = day.dayData else {
return
}
dayDataView.isHidden = false
dateLabel.text = formattedDate(dayData.date)
postCountLabel.text = formattedPostCount(dayData.postCount)
}
}
// MARK: - Private Extension
private extension PostingActivityViewController {
func addLegend() {
let legend = PostingActivityLegend.loadFromNib()
legend.backgroundColor = .listForeground
legendView.addSubview(legend)
}
func applyStyles() {
view.backgroundColor = .listForeground
collectionView.backgroundColor = .listForeground
Style.configureLabelAsPostingDate(dateLabel)
Style.configureLabelAsPostingCount(postCountLabel)
Style.configureViewAsSeparator(separatorLine)
}
func formattedDate(_ date: Date) -> String {
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
return formatter
}()
return dateFormatter.string(from: date)
}
func formattedPostCount(_ count: Int) -> String {
let postCountText = (count == 1 ? PostCountLabels.singular : PostCountLabels.plural)
return String(format: postCountText, count)
}
struct PostCountLabels {
static let singular = NSLocalizedString("%d Post", comment: "Number of posts displayed in Posting Activity when a day is selected. %d will contain the actual number (singular).")
static let plural = NSLocalizedString("%d Posts", comment: "Number of posts displayed in Posting Activity when a day is selected. %d will contain the actual number (plural).")
}
}
| gpl-2.0 | 0b0012a61670cc74f5c820bd48d3c52a | 31.992481 | 186 | 0.717867 | 5.640103 | false | false | false | false |
syoung-smallwisdom/ResearchUXFactory-iOS | ResearchUXFactory/SBASurveyItemType.swift | 1 | 8292 | //
// SBASurveyItemType.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// 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.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// 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 OWNER 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 ResearchKit
/**
List of all the currently supported step types with the key name for each class type.
This is used by the `SBABaseSurveyFactory` to determine which subclass of `ORKStep` to return
for a given `SBASurveyItem`.
*/
public enum SBASurveyItemType {
case custom(String?)
case subtask // SBASubtaskStep
public static let subtaskKey = "subtask"
case instruction(InstructionSubtype)
public enum InstructionSubtype: String {
case instruction = "instruction" // ORKInstructionStep
case completion = "completion" // ORKCompletionStep
}
case form(FormSubtype) // ORKFormStep
public enum FormSubtype: String {
case compound = "compound" // ORKFormItems > 1
case toggle = "toggle" // SBABooleanToggleFormStep
case boolean = "boolean" // ORKBooleanAnswerFormat
case singleChoice = "singleChoiceText" // ORKTextChoiceAnswerFormat of style SingleChoiceTextQuestion
case multipleChoice = "multipleChoiceText" // ORKTextChoiceAnswerFormat of style MultipleChoiceTextQuestion
case text = "textfield" // ORKTextAnswerFormat
case multipleLineText = "multilineText" // ORKTextAnswerFormat with multiple lines
case date = "datePicker" // ORKDateAnswerFormat of style Date
case dateTime = "timeAndDatePicker" // ORKDateAnswerFormat of style DateTime
case time = "timePicker" // ORKTimeOfDayAnswerFormat
case duration = "timeInterval" // ORKTimeIntervalAnswerFormat
case integer = "numericInteger" // ORKNumericAnswerFormat of style Integer
case decimal = "numericDecimal" // ORKNumericAnswerFormat of style Decimal
case scale = "scaleInteger" // ORKScaleAnswerFormat
case continuousScale = "continuousScale" // ORKContinuousScaleAnswerFormat
case timingRange = "timingRange" // Timing Range: ORKTextChoiceAnswerFormat of style SingleChoiceTextQuestion
}
case consent(ConsentSubtype)
public enum ConsentSubtype: String {
case sharingOptions = "consentSharingOptions" // ORKConsentSharingStep
case review = "consentReview" // ORKConsentReviewStep
case visual = "consentVisual" // ORKVisualConsentStep
}
case account(AccountSubtype)
public enum AccountSubtype: String {
case registration = "registration" // ORKRegistrationStep
case login = "login" // SBAProfileFormStep
case emailVerification = "emailVerification" // Custom
case externalID = "externalID" // SBAProfileFormStep
case permissions = "permissions" // SBAPermissionsStep
case dataGroups = "dataGroups" // SBADataGroupsStep
case profile = "profile" // SBAProfileFormStep
}
case passcode(ORKPasscodeType)
public enum PasscodeSubtype: String {
case type6Digit = "passcodeType6Digit" // ORKPasscodeType6Digit
case type4Digit = "passcodeType4Digit" // ORKPasscodeType4Digit
}
public init(rawValue: String?) {
guard let type = rawValue else { self = .custom(nil); return }
if let subtype = InstructionSubtype(rawValue: type) {
self = .instruction(subtype)
}
else if let subtype = FormSubtype(rawValue: type) {
self = .form(subtype)
}
else if let subtype = ConsentSubtype(rawValue: type) {
self = .consent(subtype)
}
else if let subtype = AccountSubtype(rawValue: type) {
self = .account(subtype)
}
else if let subtype = ORKPasscodeType(key: type) {
self = .passcode(subtype)
}
else if type == SBASurveyItemType.subtaskKey {
self = .subtask
}
else {
self = .custom(type)
}
}
public func formSubtype() -> FormSubtype? {
if case .form(let subtype) = self {
return subtype
}
return nil
}
public func consentSubtype() -> ConsentSubtype? {
if case .consent(let subtype) = self {
return subtype
}
return nil
}
public func accountSubtype() -> AccountSubtype? {
if case .account(let subtype) = self {
return subtype
}
return nil
}
public func isNilType() -> Bool {
if case .custom(let customType) = self {
return (customType == nil)
}
return false
}
public var usesPlaceholderText: Bool {
return self == SBASurveyItemType.form(.text) || self == SBASurveyItemType.form(.multipleLineText)
}
}
extension SBASurveyItemType: Equatable {
}
public func ==(lhs: SBASurveyItemType, rhs: SBASurveyItemType) -> Bool {
switch (lhs, rhs) {
case (.instruction(let lhsValue), .instruction(let rhsValue)):
return lhsValue == rhsValue;
case (.form(let lhsValue), .form(let rhsValue)):
return lhsValue == rhsValue;
case (.consent(let lhsValue), .consent(let rhsValue)):
return lhsValue == rhsValue;
case (.account(let lhsValue), .account(let rhsValue)):
return lhsValue == rhsValue;
case (.passcode(let lhsValue), .passcode(let rhsValue)):
return lhsValue == rhsValue;
case (.subtask, .subtask):
return true
case (.custom(let lhsValue), .custom(let rhsValue)):
return lhsValue == rhsValue;
default:
return false
}
}
extension SBASurveyItemType: SBACustomTypeStep {
public var customTypeIdentifier: String? {
if case .custom(let type) = self {
return type
}
return nil
}
}
extension ORKPasscodeType {
init?(key: String) {
guard let type = SBASurveyItemType.PasscodeSubtype(rawValue: key) else {
return nil
}
switch (type) {
case .type6Digit:
self = .type6Digit
case .type4Digit:
self = .type4Digit
}
}
}
| bsd-3-clause | d78b298c5e6ce652abd1770a4efba5fb | 40.044554 | 132 | 0.621517 | 5.102154 | false | false | false | false |
szpnygo/firefox-ios | Client/Frontend/Home/TopSitesPanel.swift | 4 | 18223 | /* 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
import Shared
import XCGLogger
import Storage
private let log = XCGLogger.defaultInstance()
private let ThumbnailIdentifier = "Thumbnail"
class Tile: Site {
let backgroundColor: UIColor
let trackingId: Int
init(url: String, color: UIColor, image: String, trackingId: Int, title: String) {
self.backgroundColor = color
self.trackingId = trackingId
super.init(url: url, title: title)
self.icon = Favicon(url: image, date: NSDate(), type: IconType.Icon)
}
init(json: JSON) {
let colorString = json["bgcolor"].asString!
var colorInt: UInt32 = 0
NSScanner(string: colorString).scanHexInt(&colorInt)
self.backgroundColor = UIColor(rgb: (Int) (colorInt ?? 0xaaaaaa))
self.trackingId = json["trackingid"].asInt ?? 0
super.init(url: json["url"].asString!, title: json["title"].asString!)
self.icon = Favicon(url: json["imageurl"].asString!, date: NSDate(), type: .Icon)
}
}
private class SuggestedSitesData<T: Tile>: Cursor<T> {
var tiles = [T]()
init() {
// TODO: Make this list localized. That should be as simple as making sure its in the lproj directory.
var err: NSError? = nil
let path = NSBundle.mainBundle().pathForResource("suggestedsites", ofType: "json")
let data = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err)
let json = JSON.parse(data as! String)
println("\(data) \(json)")
for i in 0..<json.length {
let t = T(json: json[i])
tiles.append(t)
}
}
override var count: Int {
return tiles.count
}
override subscript(index: Int) -> T? {
get {
return tiles[index]
}
}
}
class TopSitesPanel: UIViewController {
weak var homePanelDelegate: HomePanelDelegate?
private var collection: TopSitesCollectionView? = nil
private lazy var dataSource: TopSitesDataSource = {
return TopSitesDataSource(profile: self.profile, data: Cursor(status: .Failure, msg: "Nothing loaded yet"))
}()
private lazy var layout: TopSitesLayout = { return TopSitesLayout() }()
var editingThumbnails: Bool = false {
didSet {
if editingThumbnails != oldValue {
dataSource.editingThumbnails = editingThumbnails
if editingThumbnails {
homePanelDelegate?.homePanelWillEnterEditingMode?(self)
}
updateRemoveButtonStates()
}
}
}
let profile: Profile
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
layout.setupForOrientation(toInterfaceOrientation)
collection?.setNeedsLayout()
}
init(profile: Profile) {
self.profile = profile
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "firefoxAccountChanged:", name: NotificationFirefoxAccountChanged, object: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
var collection = TopSitesCollectionView(frame: self.view.frame, collectionViewLayout: layout)
collection.backgroundColor = UIConstants.PanelBackgroundColor
collection.delegate = self
collection.dataSource = dataSource
collection.registerClass(ThumbnailCell.self, forCellWithReuseIdentifier: ThumbnailIdentifier)
collection.keyboardDismissMode = .OnDrag
view.addSubview(collection)
collection.snp_makeConstraints { make in
make.edges.equalTo(self.view)
}
self.collection = collection
self.refreshHistory(layout.thumbnailCount)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
func firefoxAccountChanged(notification: NSNotification) {
if notification.name == NotificationFirefoxAccountChanged {
refreshHistory(self.layout.thumbnailCount)
}
}
//MARK: Private Helpers
private func updateDataSourceWithSites(result: Result<Cursor<Site>>) {
if let data = result.successValue {
self.dataSource.data = data
self.dataSource.profile = self.profile
}
}
private func updateRemoveButtonStates() {
for i in 0..<layout.thumbnailCount {
if let cell = collection?.cellForItemAtIndexPath(NSIndexPath(forItem: i, inSection: 0)) as? ThumbnailCell {
//TODO: Only toggle the remove button for non-suggested tiles for now
if i < dataSource.data.count {
cell.toggleRemoveButton(editingThumbnails)
} else {
cell.toggleRemoveButton(false)
}
}
}
}
private func deleteHistoryTileForURL(url: String, atIndexPath indexPath: NSIndexPath) {
profile.history.removeHistoryForURL(url) >>== {
self.profile.history.getSitesByFrecencyWithLimit(100).uponQueue(dispatch_get_main_queue(), block: { result in
self.updateDataSourceWithSites(result)
self.deleteOrUpdateSites(result, indexPath: indexPath)
})
}
}
private func refreshHistory(frequencyLimit: Int) {
self.profile.history.getSitesByFrecencyWithLimit(frequencyLimit).uponQueue(dispatch_get_main_queue(), block: { result in
self.updateDataSourceWithSites(result)
self.collection?.reloadData()
})
}
private func deleteOrUpdateSites(result: Result<Cursor<Site>>, indexPath: NSIndexPath) {
if let data = result.successValue {
let numOfThumbnails = self.layout.thumbnailCount
collection?.performBatchUpdates({
// If we have enough data to fill the tiles after the deletion, then delete and insert the next one from data
if (data.count + self.dataSource.suggestedSites.count >= numOfThumbnails) {
self.collection?.deleteItemsAtIndexPaths([indexPath])
self.collection?.insertItemsAtIndexPaths([NSIndexPath(forItem: numOfThumbnails - 1, inSection: 0)])
}
// If we don't have enough to fill the thumbnail tile area even with suggested tiles, just delete
else if (data.count + self.dataSource.suggestedSites.count) < numOfThumbnails {
self.collection?.deleteItemsAtIndexPaths([indexPath])
}
}, completion: { _ in
self.updateRemoveButtonStates()
})
}
}
}
extension TopSitesPanel: HomePanel {
func endEditing() {
editingThumbnails = false
}
}
extension TopSitesPanel: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if editingThumbnails {
return
}
if let site = dataSource[indexPath.item] {
// We're gonna call Top Sites bookmarks for now.
let visitType = VisitType.Bookmark
homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: site.url)!, visitType: visitType)
}
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let thumbnailCell = cell as? ThumbnailCell {
thumbnailCell.delegate = self
if editingThumbnails && indexPath.item < dataSource.data.count && thumbnailCell.removeButton.hidden {
thumbnailCell.removeButton.hidden = false
}
}
}
}
extension TopSitesPanel: ThumbnailCellDelegate {
func didRemoveThumbnail(thumbnailCell: ThumbnailCell) {
if let indexPath = collection?.indexPathForCell(thumbnailCell) {
let site = dataSource[indexPath.item]
if let url = site?.url {
self.deleteHistoryTileForURL(url, atIndexPath: indexPath)
}
}
}
func didLongPressThumbnail(thumbnailCell: ThumbnailCell) {
editingThumbnails = true
}
}
private class TopSitesCollectionView: UICollectionView {
private override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// Hide the keyboard if this view is touched.
window?.rootViewController?.view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
}
private class TopSitesLayout: UICollectionViewLayout {
private var thumbnailRows: Int {
return Int((self.collectionView?.frame.height ?? self.thumbnailHeight) / self.thumbnailHeight)
}
private var thumbnailCols = 2
private var thumbnailCount: Int {
return thumbnailRows * thumbnailCols
}
private var width: CGFloat { return self.collectionView?.frame.width ?? 0 }
// The width and height of the thumbnail here are the width and height of the tile itself, not the image inside the tile.
private var thumbnailWidth: CGFloat {
let insets = ThumbnailCellUX.Insets
return (width - insets.left - insets.right) / CGFloat(thumbnailCols) }
// The tile's height is determined the aspect ratio of the thumbnails width. We also take into account
// some padding between the title and the image.
private var thumbnailHeight: CGFloat { return thumbnailWidth / CGFloat(ThumbnailCellUX.ImageAspectRatio) }
// Used to calculate the height of the list.
private var count: Int {
if let dataSource = self.collectionView?.dataSource as? TopSitesDataSource {
return dataSource.collectionView(self.collectionView!, numberOfItemsInSection: 0)
}
return 0
}
private var topSectionHeight: CGFloat {
let maxRows = ceil(Float(count) / Float(thumbnailCols))
let rows = min(Int(maxRows), thumbnailRows)
let insets = ThumbnailCellUX.Insets
return thumbnailHeight * CGFloat(rows) + insets.top + insets.bottom
}
override init() {
super.init()
setupForOrientation(UIApplication.sharedApplication().statusBarOrientation)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupForOrientation(orientation: UIInterfaceOrientation) {
if orientation.isLandscape {
thumbnailCols = 5
} else if UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact {
thumbnailCols = 3
} else {
thumbnailCols = 4
}
}
private func getIndexAtPosition(#y: CGFloat) -> Int {
if y < topSectionHeight {
let row = Int(y / thumbnailHeight)
return min(count - 1, max(0, row * thumbnailCols))
}
return min(count - 1, max(0, Int((y - topSectionHeight) / UIConstants.DefaultRowHeight + CGFloat(thumbnailCount))))
}
override func collectionViewContentSize() -> CGSize {
if count <= thumbnailCount {
let row = floor(Double(count / thumbnailCols))
return CGSize(width: width, height: topSectionHeight)
}
let bottomSectionHeight = CGFloat(count - thumbnailCount) * UIConstants.DefaultRowHeight
return CGSize(width: width, height: topSectionHeight + bottomSectionHeight)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
let start = getIndexAtPosition(y: rect.origin.y)
let end = getIndexAtPosition(y: rect.origin.y + rect.height)
var attrs = [UICollectionViewLayoutAttributes]()
if start == -1 || end == -1 {
return attrs
}
for i in start...end {
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let attr = layoutAttributesForItemAtIndexPath(indexPath)
attrs.append(attr)
}
return attrs
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let attr = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
// Set the top thumbnail frames.
let row = floor(Double(indexPath.item / thumbnailCols))
let col = indexPath.item % thumbnailCols
let insets = ThumbnailCellUX.Insets
let x = insets.left + thumbnailWidth * CGFloat(col)
let y = insets.top + CGFloat(row) * thumbnailHeight
attr.frame = CGRectMake(ceil(x), ceil(y), thumbnailWidth, thumbnailHeight)
return attr
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
private class TopSitesDataSource: NSObject, UICollectionViewDataSource {
var data: Cursor<Site>
var profile: Profile
var editingThumbnails: Bool = false
lazy var suggestedSites: SuggestedSitesData<Tile> = {
return SuggestedSitesData<Tile>()
}()
init(profile: Profile, data: Cursor<Site>) {
self.data = data
self.profile = profile
}
@objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if data.status != .Success {
return 0
}
// If there aren't enough data items to fill the grid, look for items in suggested sites.
if let layout = collectionView.collectionViewLayout as? TopSitesLayout {
return min(data.count + suggestedSites.count, layout.thumbnailCount)
}
return 0
}
private func setDefaultThumbnailBackground(cell: ThumbnailCell) {
cell.imageView.image = UIImage(named: "defaultTopSiteIcon")!
cell.imageView.contentMode = UIViewContentMode.Center
}
private func getFavicon(cell: ThumbnailCell, site: Site) {
// TODO: This won't work well with recycled views. Thankfully, TopSites doesn't really recycle much.'
cell.imageView.image = nil
cell.backgroundImage.image = nil
FaviconFetcher.getForUrl(site.url.asURL!, profile: profile) >>== { icons in
if (icons.count > 0) {
cell.imageView.sd_setImageWithURL(icons[0].url.asURL!) { (img, err, type, url) -> Void in
if let img = img {
cell.backgroundImage.image = img
cell.image = img
} else {
let icon = Favicon(url: "", date: NSDate(), type: IconType.NoneFound)
self.profile.favicons.addFavicon(icon, forSite: site)
self.setDefaultThumbnailBackground(cell)
}
}
}
}
}
private func createTileForSite(cell: ThumbnailCell, site: Site) -> ThumbnailCell {
cell.textLabel.text = site.title.isEmpty ? site.url : site.title
cell.imageWrapper.backgroundColor = UIColor.clearColor()
if let icon = site.icon {
// We've looked before recently and didn't find a favicon
switch icon.type {
case .NoneFound:
let t = NSDate().timeIntervalSinceDate(icon.date)
if t < FaviconFetcher.ExpirationTime {
self.setDefaultThumbnailBackground(cell)
}
default:
cell.imageView.sd_setImageWithURL(icon.url.asURL, completed: { (img, err, type, url) -> Void in
if let img = img {
cell.backgroundImage.image = img
cell.image = img
} else {
self.getFavicon(cell, site: site)
}
})
}
} else {
getFavicon(cell, site: site)
}
cell.isAccessibilityElement = true
cell.accessibilityLabel = cell.textLabel.text
cell.removeButton.hidden = !editingThumbnails
return cell
}
private func createTileForSuggestedSite(cell: ThumbnailCell, tile: Tile) -> ThumbnailCell {
cell.textLabel.text = tile.title.isEmpty ? tile.url : tile.title
cell.imageWrapper.backgroundColor = tile.backgroundColor
cell.backgroundImage.image = nil
if let iconString = tile.icon?.url {
let icon = NSURL(string: iconString)!
if icon.scheme == "asset" {
cell.imageView.image = UIImage(named: icon.host!)
} else {
cell.imageView.sd_setImageWithURL(icon, completed: { img, err, type, key in
if img == nil {
self.setDefaultThumbnailBackground(cell)
}
})
}
} else {
self.setDefaultThumbnailBackground(cell)
}
cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
cell.isAccessibilityElement = true
cell.accessibilityLabel = cell.textLabel.text
return cell
}
subscript(index: Int) -> Site? {
if data.status != .Success {
return nil
}
if index >= data.count {
return suggestedSites[index - data.count]
}
return data[index] as Site?
}
@objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// Cells for the top site thumbnails.
let site = self[indexPath.item]!
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ThumbnailIdentifier, forIndexPath: indexPath) as! ThumbnailCell
if indexPath.item >= data.count {
return createTileForSuggestedSite(cell, tile: site as! Tile)
}
return createTileForSite(cell, site: site)
}
}
| mpl-2.0 | f7ea9cfd9fa9d26b69cb1479e5bfe48d | 36.650826 | 152 | 0.634034 | 5.193217 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Tests/AKOscillatorBankTests.swift | 1 | 2618 | //
// AKOscillatorBankTests.swift
// AudioKitTestSuiteTests
//
// Created by Aurelius Prochazka on 7/21/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import AudioKit
import XCTest
class AKOscillatorBankTests: AKTestCase {
var inputBank: AKOscillatorBank!
override func setUp() {
super.setUp()
// Need to have a longer test duration to allow for envelope to progress
duration = 1.0
afterStart = {
self.inputBank.play(noteNumber: 60, velocity: 120)
self.inputBank.play(noteNumber: 64, velocity: 110)
self.inputBank.play(noteNumber: 67, velocity: 100)
}
}
func testAttackDuration() {
inputBank = AKOscillatorBank(waveform: AKTable(.square), attackDuration: 0.123)
output = inputBank
AKTestMD5("dbe8924aa51c874c8785e4e2b43cad32")
}
func testDecayDuration() {
inputBank = AKOscillatorBank(waveform: AKTable(.square), decayDuration: 0.234)
output = inputBank
AKTestMD5("9b1d91ec29a4042c7ad050e9b574802e")
}
func testDefault() {
inputBank = AKOscillatorBank()
output = inputBank
AKTestMD5("3bbacd39af8272266b2e4a5a05257800")
}
// Known Failing Test (inconsistencies in iOS/macOS)
// func testParameters() {
// inputBank = AKOscillatorBank(waveform: AKTable(.square),
// attackDuration: 0.123,
// decayDuration: 0.234,
// sustainLevel: 0.345,
// pitchBend: 1,
// vibratoDepth: 1.1,
// vibratoRate: 1.2)
// output = inputBank
// AKTestMD5("93a8e6f26e3f3326202348855caa0051")
// }
func testPitchBend() {
inputBank = AKOscillatorBank(waveform: AKTable(.square), pitchBend: 1.1)
output = inputBank
AKTestMD5("db148878395ded60b26772e8f410fc6b")
}
func testSustainLevel() {
inputBank = AKOscillatorBank(waveform: AKTable(.square), sustainLevel: 0.345)
output = inputBank
AKTestMD5("f60e7eb749054f53d93f9dd0969a4f56")
}
func testVibrato() {
inputBank = AKOscillatorBank(waveform: AKTable(.square), vibratoDepth: 1, vibratoRate: 10)
output = inputBank
AKTestMD5("ca6b355d0116190474476a66d9ddb31c")
}
func testWaveform() {
inputBank = AKOscillatorBank(waveform: AKTable(.square))
output = inputBank
AKTestMD5("bf088a9d8142cb119b05cdd31254b86e")
}
}
| mit | f7dca8e0c8b3fc1e9cb0de1da03c1113 | 30.53012 | 98 | 0.607184 | 4.076324 | false | true | false | false |
iSapozhnik/FamilyPocket | FamilyPocket/ViewControllers/EditCategoryViewController.swift | 1 | 2221 | //
// EditCategoryViewController.swift
// FamilyPocket
//
// Created by Ivan Sapozhnik on 5/17/17.
// Copyright © 2017 Ivan Sapozhnik. All rights reserved.
//
import UIKit
class EditCategoryViewController: NewCategoryViewController {
var category: Category?
init(withCategory category: Category?, completion: CategoryHandler?) {
super.init(withCompletion: nil)
self.completion = completion
self.category = category
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
categoryNameTextfield.paddingRight = 35.0
guard let category = self.category else { return }
self.deleteButton.isHidden = false
self.deleteButton.layer.borderColor = UIColor(white: 1.0, alpha: 0.3).cgColor
self.deleteButton.layer.borderWidth = 1.0
titleLabel.text = NSLocalizedString("Edit category:", comment: "")
self.view.layer.backgroundColor = category.color?.hexColor.cgColor
self.colorButton.layer.backgroundColor = category.color?.hexColor.cgColor
self.categoryNameTextfield.text = category.name
self.saveButton.setTitle(NSLocalizedString("Update", comment: ""), for: .normal)
self.iconView.image = UIImage(named: category.iconName ?? "")
}
override func saveCategory(_ sender: Any) {
guard
let category = self.category,
let name = categoryNameTextfield.text else { return }
categoryNameTextfield.resignFirstResponder()
guard let newName = name.characters.count > 0 ? name : category.name else {
completion?(self, nil, false)
return
}
CategoryManager().update(object: category, name: newName, colorString: self.categoryColorName ?? category.color!)
completion?(self, category, false)
}
override func deleteCategory(_ sender: Any) {
guard let category = self.category else { return }
CategoryManager().delete(object: category)
completion?(self, nil, false)
}
}
| mit | 0ee8e7c556ea92bb07f4da240fdd6ab9 | 32.134328 | 121 | 0.642793 | 4.933333 | false | false | false | false |
milseman/swift | validation-test/Reflection/reflect_Array.swift | 11 | 1428 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Array
// RUN: %target-run %target-swift-reflection-test %t/reflect_Array 2>&1 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
import SwiftReflectionTest
class TestClass {
var t: Array<Int>
init(t: Array<Int>) {
self.t = t
}
}
var obj = TestClass(t: [1, 2, 3])
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Array.TestClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=1
// (unstable implementation details omitted)
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Array.TestClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=12
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=1
// (unstable implementation details omitted)
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 | 3e8cc3128f0ba9a6f7ab93e8a5d5b691 | 30.043478 | 124 | 0.696078 | 3.131579 | false | true | false | false |
krzkaczor/SwiftAST | test/fixtures/BunchOfTuples.swift | 1 | 488 | let intAndDouble = (10, 10.5);
let (intConst, doubleConst) = intAndDouble;
let complexTuple = ((1, "abc"), 3.0);
let ((a, b), c) = (intAndDouble, 11);
let intAndInt: (Int, Int) = (4,5);
let doubleAndDouble: (Double, Double) = (5, 5);
let singleTuple = (6.6);
let singleTupleExplicitTyped: (Double) = (6.6);
let namedTuple: (x:Int, y:Double) = (5, 19);
let intConst2:Int = namedTuple.0;
let doubleConst2:Double = namedTuple.1;
let x:Int = namedTuple.x;
let y:Double = namedTuple.y; | mit | f209eaab83d79bf72a88fe974825a6bf | 22.285714 | 47 | 0.659836 | 2.652174 | false | false | false | false |
xremix/SwiftGS1Barcode | SwiftGS1Barcode/DateExtension.swift | 1 | 751 | //
// DateExtension.swift
// SwiftGS1Barcode
//
// Created by Toni Hoffmann on 26.06.17.
// Copyright © 2017 Toni Hoffmann. All rights reserved.
//
import Foundation
extension Date{
/** Wrapper function to create a date based on a year, month and day */
static func from(year: Int?, month: Int?, day: Int?)->Date{
// Setting paramters to component
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
// Create date from components
let userCalendar = NSCalendar.current
let someDateTime = userCalendar.date(from: dateComponents)
// Return Date
return someDateTime! as Date
}
}
| mit | e5fb03af30003effd3ad380fa98b111d | 27.846154 | 75 | 0.648 | 4.573171 | false | false | false | false |
IvanVorobei/RequestPermission | Example/SPPermission/SPPermission/Frameworks/SparrowKit/UI/Collections/Views/SPPageCollectionView.swift | 1 | 3266 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// 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
class SPPageCollectionView: UICollectionView {
var layout = SPCollectionViewLayout()
private var cacheImages: [(link: String, image: UIImage)] = []
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
init(frame: CGRect) {
super.init(frame: frame, collectionViewLayout: self.layout)
commonInit()
}
init() {
super.init(frame: CGRect.zero, collectionViewLayout: self.layout)
commonInit()
}
internal func commonInit() {
self.layout.scrollDirection = .vertical
self.backgroundColor = UIColor.clear
self.collectionViewLayout = self.layout
self.decelerationRate = UIScrollView.DecelerationRate.fast
self.delaysContentTouches = false
self.isPagingEnabled = false
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
}
}
//MARK: - cache
extension SPPageCollectionView {
func setCachedImage(link: String, indexPath: IndexPath, on imageView: SPDownloadingImageView, cell: SPCollectionViewCell) {
if let image = self.fromCahce(link: link) {
imageView.setImage(image: image, animatable: false)
} else {
SPDownloader.image(link: link) { (response) in
if let image = response {
if cell.currentIndexPath == indexPath {
imageView.setImage(image: image, animatable: true)
self.toCache(link: link, image: image)
}
}
}
}
}
func toCache(link: String, image: UIImage?) {
if image == nil {
return
}
if self.fromCahce(link: link) == nil {
self.cacheImages.append((link: link, image: image!))
}
}
func fromCahce(link: String) -> UIImage? {
let cachedData = self.cacheImages.first(where: {
$0.link == link
})
return cachedData?.image
}
}
| mit | ff9742dcd4663fe2da0d772cb3b18dd0 | 34.48913 | 127 | 0.643492 | 4.873134 | false | false | false | false |
yeziahehe/Gank | Pods/JTAppleCalendar/Sources/InternalActionFunctions.swift | 1 | 17904 | //
// InternalActionFunctions.swift
//
// Copyright (c) 2016-2017 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar)
//
// 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.
//
extension JTAppleCalendarView {
/// Lays out subviews.
override open func layoutSubviews() {
super.layoutSubviews()
if !generalDelayedExecutionClosure.isEmpty, isCalendarLayoutLoaded {
executeDelayedTasks(.general)
}
}
func setupMonthInfoAndMap(with data: ConfigurationParameters? = nil) {
theData = setupMonthInfoDataForStartAndEndDate(with: data)
}
func developerError(string: String) {
print(string)
print(developerErrorMessage)
assert(false)
}
func setupNewLayout(from oldLayout: JTAppleCalendarLayoutProtocol) {
let newLayout = JTAppleCalendarLayout(withDelegate: self)
newLayout.scrollDirection = oldLayout.scrollDirection
newLayout.sectionInset = oldLayout.sectionInset
newLayout.minimumInteritemSpacing = oldLayout.minimumInteritemSpacing
newLayout.minimumLineSpacing = oldLayout.minimumLineSpacing
collectionViewLayout = newLayout
scrollDirection = newLayout.scrollDirection
sectionInset = newLayout.sectionInset
minimumLineSpacing = newLayout.minimumLineSpacing
minimumInteritemSpacing = newLayout.minimumInteritemSpacing
if #available(iOS 9.0, *) {
transform.a = semanticContentAttribute == .forceRightToLeft ? -1 : 1
}
super.dataSource = self
super.delegate = self
decelerationRate = .fast
#if os(iOS)
if isPagingEnabled {
scrollingMode = .stopAtEachCalendarFrame
} else {
scrollingMode = .none
}
#endif
}
func scrollTo(indexPath: IndexPath, triggerScrollToDateDelegate: Bool, isAnimationEnabled: Bool, position: UICollectionView.ScrollPosition, extraAddedOffset: CGFloat, completionHandler: (() -> Void)?) {
isScrollInProgress = true
if let validCompletionHandler = completionHandler { scrollDelayedExecutionClosure.append(validCompletionHandler) }
self.triggerScrollToDateDelegate = triggerScrollToDateDelegate
DispatchQueue.main.async {
self.scrollToItem(at: indexPath, at: position, animated: isAnimationEnabled)
if (isAnimationEnabled && self.calendarOffsetIsAlreadyAtScrollPosition(forIndexPath: indexPath)) ||
!isAnimationEnabled {
self.scrollViewDidEndScrollingAnimation(self)
}
self.isScrollInProgress = false
}
}
func scrollToHeaderInSection(_ section: Int,
triggerScrollToDateDelegate: Bool = false,
withAnimation animation: Bool = true,
extraAddedOffset: CGFloat,
completionHandler: (() -> Void)? = nil) {
if !calendarViewLayout.thereAreHeaders { return }
let indexPath = IndexPath(item: 0, section: section)
guard let attributes = calendarViewLayout.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) else { return }
isScrollInProgress = true
if let validHandler = completionHandler { scrollDelayedExecutionClosure.append(validHandler) }
self.triggerScrollToDateDelegate = triggerScrollToDateDelegate
let maxYCalendarOffset = max(0, self.contentSize.height - self.frame.size.height)
var topOfHeader = CGPoint(x: attributes.frame.origin.x,y: min(maxYCalendarOffset, attributes.frame.origin.y))
if scrollDirection == .horizontal { topOfHeader.x += extraAddedOffset} else { topOfHeader.y += extraAddedOffset }
DispatchQueue.main.async {
self.setContentOffset(topOfHeader, animated: animation)
if (animation && self.calendarOffsetIsAlreadyAtScrollPosition(forOffset: topOfHeader)) ||
!animation {
self.scrollViewDidEndScrollingAnimation(self)
}
self.isScrollInProgress = false
}
}
// Subclasses cannot use this function
@available(*, unavailable)
open override func reloadData() {
super.reloadData()
}
func handleScroll(point: CGPoint? = nil,
indexPath: IndexPath? = nil,
triggerScrollToDateDelegate: Bool = true,
isAnimationEnabled: Bool,
position: UICollectionView.ScrollPosition? = .left,
extraAddedOffset: CGFloat = 0,
completionHandler: (() -> Void)?) {
if isScrollInProgress { return }
// point takes preference
if let validPoint = point {
scrollTo(point: validPoint,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
isAnimationEnabled: isAnimationEnabled,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
} else {
guard let validIndexPath = indexPath else { return }
var isNonConinuousScroll = true
switch scrollingMode {
case .none, .nonStopToCell: isNonConinuousScroll = false
default: break
}
if calendarViewLayout.thereAreHeaders,
scrollDirection == .vertical,
isNonConinuousScroll {
scrollToHeaderInSection(validIndexPath.section,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
withAnimation: isAnimationEnabled,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
} else {
scrollTo(indexPath:validIndexPath,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
isAnimationEnabled: isAnimationEnabled,
position: position ?? .left,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
}
}
func scrollTo(point: CGPoint, triggerScrollToDateDelegate: Bool? = nil, isAnimationEnabled: Bool, extraAddedOffset: CGFloat, completionHandler: (() -> Void)?) {
isScrollInProgress = true
if let validCompletionHandler = completionHandler { scrollDelayedExecutionClosure.append(validCompletionHandler) }
self.triggerScrollToDateDelegate = triggerScrollToDateDelegate
var point = point
if scrollDirection == .horizontal { point.x += extraAddedOffset } else { point.y += extraAddedOffset }
DispatchQueue.main.async() {
self.setContentOffset(point, animated: isAnimationEnabled)
if (isAnimationEnabled && self.calendarOffsetIsAlreadyAtScrollPosition(forOffset: point)) ||
!isAnimationEnabled {
self.scrollViewDidEndScrollingAnimation(self)
}
}
}
func setupMonthInfoDataForStartAndEndDate(with config: ConfigurationParameters? = nil) -> CalendarData {
var months = [Month]()
var monthMap = [Int: Int]()
var totalSections = 0
var totalDays = 0
var validConfig = config
if validConfig == nil { validConfig = calendarDataSource?.configureCalendar(self) }
if let validConfig = validConfig {
let comparison = validConfig.calendar.compare(validConfig.startDate, to: validConfig.endDate, toGranularity: .nanosecond)
if comparison == ComparisonResult.orderedDescending {
assert(false, "Error, your start date cannot be greater than your end date\n")
return (CalendarData(months: [], totalSections: 0, sectionToMonthMap: [:], totalDays: 0))
}
// Set the new cache
_cachedConfiguration = validConfig
if let
startMonth = calendar.startOfMonth(for: validConfig.startDate),
let endMonth = calendar.endOfMonth(for: validConfig.endDate) {
startOfMonthCache = startMonth
endOfMonthCache = endMonth
// Create the parameters for the date format generator
let parameters = ConfigurationParameters(startDate: startOfMonthCache,
endDate: endOfMonthCache,
numberOfRows: validConfig.numberOfRows,
calendar: calendar,
generateInDates: validConfig.generateInDates,
generateOutDates: validConfig.generateOutDates,
firstDayOfWeek: validConfig.firstDayOfWeek,
hasStrictBoundaries: validConfig.hasStrictBoundaries)
let generatedData = dateGenerator.setupMonthInfoDataForStartAndEndDate(parameters)
months = generatedData.months
monthMap = generatedData.monthMap
totalSections = generatedData.totalSections
totalDays = generatedData.totalDays
}
}
let data = CalendarData(months: months, totalSections: totalSections, sectionToMonthMap: monthMap, totalDays: totalDays)
return data
}
func batchReloadIndexPaths(_ indexPaths: [IndexPath]) {
let visiblePaths = indexPathsForVisibleItems
var visibleCellsToReload: [JTAppleCell: IndexPath] = [:]
for path in indexPaths {
if calendarViewLayout.cachedValue(for: path.item, section: path.section) == nil { continue }
pathsToReload.insert(path)
if visiblePaths.contains(path) {
visibleCellsToReload[cellForItem(at: path) as! JTAppleCell] = path
}
}
// Reload the visible paths
if !visibleCellsToReload.isEmpty {
for (cell, path) in visibleCellsToReload {
self.collectionView(self, willDisplay: cell, forItemAt: path)
}
}
}
func addCellToSelectedSet(_ indexPath: IndexPath, date: Date, cellState: CellState) {
selectedCellData[indexPath] = SelectedCellData(indexPath: indexPath, date: date, cellState: cellState)
}
func deleteCellFromSelectedSetIfSelected(_ indexPath: IndexPath) {
selectedCellData.removeValue(forKey: indexPath)
}
// Returns an indexPath if valid one was found
func deselectCounterPartCellIndexPath(_ indexPath: IndexPath, date: Date, dateOwner: DateOwner) -> IndexPath? {
guard let counterPartCellIndexPath = indexPathOfdateCellCounterPath(date, dateOwner: dateOwner) else { return nil }
deleteCellFromSelectedSetIfSelected(counterPartCellIndexPath)
deselectItem(at: counterPartCellIndexPath, animated: false)
return counterPartCellIndexPath
}
func selectCounterPartCellIndexPath(_ indexPath: IndexPath, date: Date, dateOwner: DateOwner) -> IndexPath? {
guard let counterPartCellIndexPath = indexPathOfdateCellCounterPath(date, dateOwner: dateOwner) else { return nil }
let counterPartCellState = cellStateFromIndexPath(counterPartCellIndexPath, isSelected: true)
addCellToSelectedSet(counterPartCellIndexPath, date: date, cellState: counterPartCellState)
// Update the selectedCellData counterIndexPathData
selectedCellData[indexPath]?.counterIndexPath = counterPartCellIndexPath
selectedCellData[counterPartCellIndexPath]?.counterIndexPath = indexPath
if allowsMultipleSelection {
// only if multiple selection is enabled. With single selection, we do not want the counterpart cell to be
// selected in place of the main cell. With multiselection, however, all can be selected
selectItem(at: counterPartCellIndexPath, animated: false, scrollPosition: [])
}
return counterPartCellIndexPath
}
func executeDelayedTasks(_ type: DelayedTaskType) {
let tasksToExecute: [(() -> Void)]
switch type {
case .scroll:
tasksToExecute = scrollDelayedExecutionClosure
scrollDelayedExecutionClosure.removeAll()
case .general:
tasksToExecute = generalDelayedExecutionClosure
generalDelayedExecutionClosure.removeAll()
}
for aTaskToExecute in tasksToExecute { aTaskToExecute() }
}
// Only reload the dates if the datasource information has changed
func reloadDelegateDataSource() -> (shouldReload: Bool, configParameters: ConfigurationParameters?) {
var retval: (Bool, ConfigurationParameters?) = (false, nil)
if let
newDateBoundary = calendarDataSource?.configureCalendar(self) {
// Jt101 do a check in each var to see if
// user has bad star/end dates
let newStartOfMonth = calendar.startOfMonth(for: newDateBoundary.startDate)
let newEndOfMonth = calendar.endOfMonth(for: newDateBoundary.endDate)
let oldStartOfMonth = calendar.startOfMonth(for: startDateCache)
let oldEndOfMonth = calendar.endOfMonth(for: endDateCache)
let newLastMonth = sizesForMonthSection()
let calendarLayout = calendarViewLayout
if
// ConfigParameters were changed
newStartOfMonth != oldStartOfMonth ||
newEndOfMonth != oldEndOfMonth ||
newDateBoundary.calendar != _cachedConfiguration.calendar ||
newDateBoundary.numberOfRows != _cachedConfiguration.numberOfRows ||
newDateBoundary.generateInDates != _cachedConfiguration.generateInDates ||
newDateBoundary.generateOutDates != _cachedConfiguration.generateOutDates ||
newDateBoundary.firstDayOfWeek != _cachedConfiguration.firstDayOfWeek ||
newDateBoundary.hasStrictBoundaries != _cachedConfiguration.hasStrictBoundaries ||
// Other layout information were changed
minimumInteritemSpacing != calendarLayout.minimumInteritemSpacing ||
minimumLineSpacing != calendarLayout.minimumLineSpacing ||
sectionInset != calendarLayout.sectionInset ||
lastMonthSize != newLastMonth ||
allowsDateCellStretching != calendarLayout.allowsDateCellStretching ||
scrollDirection != calendarLayout.scrollDirection ||
calendarLayout.isDirty {
lastMonthSize = newLastMonth
retval = (true, newDateBoundary)
}
}
return retval
}
func remapSelectedDatesWithCurrentLayout() -> (selected:(indexPaths:[IndexPath], counterPaths:[IndexPath]), selectedDates: [Date]) {
var retval = (selected:(indexPaths:[IndexPath](), counterPaths:[IndexPath]()), selectedDates: [Date]())
if !selectedDates.isEmpty {
let selectedDates = self.selectedDates
// Get the new paths
let newPaths = pathsFromDates(selectedDates)
// Get the new counter Paths
var newCounterPaths: [IndexPath] = []
for date in selectedDates {
if let counterPath = indexPathOfdateCellCounterPath(date, dateOwner: .thisMonth) {
newCounterPaths.append(counterPath)
}
}
// Append paths
retval.selected.indexPaths.append(contentsOf: newPaths)
retval.selected.counterPaths.append(contentsOf: newCounterPaths)
// Append dates to retval
for allPaths in [newPaths, newCounterPaths] {
for path in allPaths {
guard let dateFromPath = dateOwnerInfoFromPath(path)?.date else { continue }
retval.selectedDates.append(dateFromPath)
}
}
}
return retval
}
}
| gpl-3.0 | 509d2c4f81c29a0f31a7c1c3b8fc9cec | 48.052055 | 206 | 0.622319 | 6.317572 | false | true | false | false |
Zewo/TodoBackend | Sources/TodoBackend/Storage/PostgreSQLTodoStore.swift | 1 | 1947 | import Axis
import PostgreSQL
class PostgreSQLTodoStore : TodoStore {
let connection: Connection
init(info: Connection.ConnectionInfo) throws {
self.connection = Connection(info: info)
try connection.open()
try Todo.createTable(connection: connection)
}
deinit {
connection.close()
}
func get(id: Int) throws -> PersistedEntity<Todo>? {
return try Entity<Todo>.get(id, connection: connection)
}
func getAll() throws -> [PersistedEntity<Todo>] {
return try Entity<Todo>.fetch(connection: connection)
}
func insert(todo: Todo) throws -> PersistedEntity<Todo> {
return try Entity(model: todo).create(connection: connection)
}
func update(id: Int, todo: Todo) throws -> PersistedEntity<Todo> {
guard var entity = try Entity<Todo>.get(id, connection: connection) else {
// model does not exist yet
//TODO: clean up
//TODO: add to sql - upsert
var values = todo.serialize()
values[Todo.Field.primaryKey] = id
let query = Todo.insert(values)
try connection.execute(query)
return try PersistedEntity(model: todo, primaryKey: id).refresh(connection: connection)
}
// model exists, update it
entity.model = todo
return try entity.save(connection: connection)
}
func remove(id: Int) throws -> PersistedEntity<Todo>? {
//TODO: maybe make entity.delete return persistedentity?
guard let entity = try Entity<Todo>.get(id, connection: connection) else {
return nil
}
let deleted = try entity.delete(connection: connection)
return PersistedEntity(model: deleted.model, primaryKey: id)
}
func clear() throws -> [PersistedEntity<Todo>] {
let deleted = try getAll()
try connection.execute(Todo.delete)
return deleted
}
}
| mit | 711d3f930fde3d9a20c924eccbf347ea | 32 | 99 | 0.626091 | 4.549065 | false | false | false | false |
zon/that-bus | ios/That Bus/RegisterLayout.swift | 1 | 1660 | import Foundation
import UIKit
class RegisterLayout : UIView {
let content: UIView
let email: TextField
required init() {
let frame = Unit.screen
let m2 = Unit.m2
let font = Font.medium
email = TextField(frame: CGRect(x: 0, y: 0, width: frame.width, height: font.lineHeight + m2 * 2))
email.backgroundColor = Palette.white
email.addBorder(width: Unit.one, color: Palette.border, visible: BorderVisible(top: true, bottom: true))
email.placeholder = "Email"
email.padding = UIEdgeInsets(top: 0, left: m2, bottom: 0, right: m2)
email.keyboardType = .emailAddress
email.autocapitalizationType = .none
email.autocorrectionType = .no
email.returnKeyType = .next
email.spellCheckingType = .no
let details = UILabel(frame: CGRect(x: m2, y: email.frame.maxY + m2, width: frame.width - m2 * 2, height: 10))
details.font = Font.small
details.textColor = UIColor.gray
details.text = "Save your tickets online."
details.resizeHeight()
content = UIView(frame: CGRect(x: 0, y: m2, width: frame.width, height: details.frame.maxY + m2))
content.addSubview(email)
content.addSubview(details)
super.init(frame: frame)
backgroundColor = Palette.background
addSubview(content)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setInsets(top: CGFloat?, bottom: CGFloat?) {
content.frame.origin.y = (top ?? 0) + Unit.m2
}
}
| gpl-3.0 | eaea284c20835d6926100d7297a67693 | 33.583333 | 118 | 0.610843 | 4.160401 | false | false | false | false |
SummerHF/SinaPractice | sina/Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Fall.swift | 2 | 5728 | //
// LTMorphingLabel+Fall.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2016 Lex Tang, http://lexrus.com
//
// 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
extension LTMorphingLabel {
func FallLoad() {
progressClosures["Fall\(LTMorphingPhases.Progress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
if isNewChar {
return min(
1.0,
max(
0.0,
progress
- self.morphingCharacterDelay
* Float(index)
/ 1.7
)
)
}
let j: Float = Float(sin(Double(index))) * 1.7
return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * Float(j)))
}
effectClosures["Fall\(LTMorphingPhases.Disappear)"] = {
char, index, progress in
return LTCharacterLimbo(
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress))
}
effectClosures["Fall\(LTMorphingPhases.Appear)"] = {
char, index, progress in
let currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0.0, Float(self.font.pointSize))
)
let yOffset = CGFloat(self.font.pointSize - currentFontSize)
return LTCharacterLimbo(
char: char,
rect: CGRectOffset(self.newRects[index], 0.0, yOffset),
alpha: CGFloat(self.morphingProgress),
size: currentFontSize,
drawingProgress: 0.0
)
}
drawingClosures["Fall\(LTMorphingPhases.Draw)"] = {
limbo in
if limbo.drawingProgress > 0.0 {
let context = UIGraphicsGetCurrentContext()
var charRect = limbo.rect
CGContextSaveGState(context)
let charCenterX = charRect.origin.x + (charRect.size.width / 2.0)
var charBottomY = charRect.origin.y + charRect.size.height - self.font.pointSize / 6
var charColor = self.textColor
// Fall down if drawingProgress is more than 50%
if limbo.drawingProgress > 0.5 {
let ease = CGFloat(
LTEasing.easeInQuint(
Float(limbo.drawingProgress - 0.4),
0.0,
1.0,
0.5
)
)
charBottomY = charBottomY + ease * 10.0
let fadeOutAlpha = min(
1.0,
max(
0.0,
limbo.drawingProgress * -2.0 + 2.0 + 0.01
)
)
charColor = self.textColor.colorWithAlphaComponent(fadeOutAlpha)
}
charRect = CGRect(
x: charRect.size.width / -2.0,
y: charRect.size.height * -1.0 + self.font.pointSize / 6,
width: charRect.size.width,
height: charRect.size.height)
CGContextTranslateCTM(context, charCenterX, charBottomY)
let angle = Float(sin(Double(limbo.rect.origin.x)) > 0.5 ? 168 : -168)
let rotation = CGFloat(
LTEasing.easeOutBack(
min(
1.0,
Float(limbo.drawingProgress)
),
0.0,
1.0
) * angle
)
CGContextRotateCTM(context, rotation * CGFloat(M_PI) / 180.0)
let s = String(limbo.char)
s.drawInRect(charRect, withAttributes: [
NSFontAttributeName: self.font.fontWithSize(limbo.size),
NSForegroundColorAttributeName: charColor
])
CGContextRestoreGState(context)
return true
}
return false
}
}
}
| mit | 595a334557d343a30f27b12ad10e1126 | 37.133333 | 100 | 0.493531 | 5.426945 | false | false | false | false |
groue/GRDB.swift | GRDB/Core/Database+Statements.swift | 1 | 20844 | import Foundation
extension Database {
// MARK: - Statements
/// Returns a new prepared statement that can be reused.
///
/// For example:
///
/// ```swift
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// ```
///
/// - parameter sql: An SQL string.
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func makeStatement(sql: String) throws -> Statement {
try makeStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// For example:
///
/// ```swift
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// ```
///
/// In the provided literal, no argument must be set, or all arguments must
/// be set. An error is raised otherwise. For example:
///
/// ```swift
/// // OK
/// try makeStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > ?
/// """)
/// try makeStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
/// """)
///
/// // NOT OK (first argument is not set, but second is)
/// try makeStatement(literal: """
/// SELECT COUNT(*) FROM player
/// WHERE color = ? AND score > \(1000)
/// """)
/// ```
///
/// - parameter sqlLiteral: An ``SQL`` literal.
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func makeStatement(literal sqlLiteral: SQL) throws -> Statement {
let (sql, arguments) = try sqlLiteral.build(self)
let statement = try makeStatement(sql: sql)
if arguments.isEmpty == false {
// Throws if arguments do not match
try statement.setArguments(arguments)
}
return statement
}
/// Returns a new prepared statement that can be reused.
///
/// For example:
///
/// let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// - parameter sql: An SQL string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
func makeStatement(sql: String, prepFlags: CUnsignedInt) throws -> Statement {
let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags)
guard let statement = try statements.next() else {
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql)
}
do {
guard try statements.next() == nil else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: """
Multiple statements found. To execute multiple statements, use \
Database.execute(sql:) or Database.allStatements(sql:) instead.
""",
sql: sql)
}
} catch {
// Something while would not compile was found after the first statement.
// Complain about multiple statements anyway.
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: """
Multiple statements found. To execute multiple statements, use \
Database.execute(sql:) or Database.allStatements(sql:) instead.
""",
sql: sql)
}
return statement
}
/// Returns a prepared statement that can be reused.
///
/// For example:
///
/// ```swift
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// ```
///
/// The returned statement may have already been used: it may or may not
/// contain values for its eventual arguments.
///
/// - parameter sql: An SQL string.
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func cachedStatement(sql: String) throws -> Statement {
try publicStatementCache.statement(sql)
}
/// Returns a prepared statement that can be reused.
///
/// For example:
///
/// ```swift
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// ```
///
/// In the provided literal, no argument must be set, or all arguments must
/// be set. An error is raised otherwise. For example:
///
/// ```swift
/// // OK
/// try cachedStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > ?
/// """)
/// try cachedStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
/// """)
///
/// // NOT OK (first argument is not set, but second is)
/// try cachedStatement(literal: """
/// SELECT COUNT(*) FROM player
/// WHERE color = ? AND score > \(1000)
/// """)
/// ```
///
/// - parameter sqlLiteral: An ``SQL`` literal.
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func cachedStatement(literal sqlLiteral: SQL) throws -> Statement {
let (sql, arguments) = try sqlLiteral.build(self)
let statement = try cachedStatement(sql: sql)
if arguments.isEmpty == false {
// Throws if arguments do not match
try statement.setArguments(arguments)
}
return statement
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedStatement(sql: String) throws -> Statement {
try internalStatementCache.statement(sql)
}
/// Returns a cursor of prepared statements.
///
/// For example:
///
/// ```swift
/// let statements = try db.allStatements(sql: """
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
/// while let statement = try statements.next() {
/// try statement.execute()
/// }
/// ```
///
/// The `arguments` parameter must be nil, or all arguments must be set. The
/// returned cursor will throw an error otherwise. For example:
///
/// ```swift
/// // OK
/// try allStatements(sql: """
/// SELECT COUNT(*) FROM player WHERE score < ?;
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """)
///
/// try allStatements(sql: """
/// SELECT COUNT(*) FROM player WHERE score < ?;
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """, arguments: [1000, 1000])
///
/// // NOT OK (first argument is set, but second is not)
/// try allStatements(sql: """
/// SELECT COUNT(*) FROM player WHERE score < ?;
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """, arguments: [1000])
/// ```
///
/// - parameters:
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - returns: A cursor of prepared ``Statement``.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func allStatements(sql: String, arguments: StatementArguments? = nil)
throws -> SQLStatementCursor
{
SQLStatementCursor(database: self, sql: sql, arguments: arguments)
}
/// Returns a cursor of prepared statements.
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// let statements = try db.allStatements(literal: """
/// INSERT INTO player (name) VALUES (\("Arthur"));
/// INSERT INTO player (name) VALUES (\("Barbara"));
/// INSERT INTO player (name) VALUES (\("O'Brien"));
/// """)
/// while let statement = try statements.next() {
/// try statement.execute()
/// }
/// ```
///
/// In the provided literal, no argument must be set, or all arguments must
/// be set. The returned cursor will throw an error otherwise. For example:
///
/// ```swift
/// // OK
/// try allStatements(literal: """
/// SELECT COUNT(*) FROM player WHERE score < ?;
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """)
///
/// try allStatements(literal: """
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
/// """)
///
/// // NOT OK (first argument is set, but second is not)
/// try allStatements(literal: """
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """)
/// ```
///
/// - parameter sqlLiteral: An ``SQL`` literal.
/// - returns: A cursor of prepared ``Statement``.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor {
let context = SQLGenerationContext(self)
let sql = try sqlLiteral.sql(context)
let arguments = context.arguments.isEmpty
? nil // builds statements without arguments
: context.arguments // force arguments to match
return SQLStatementCursor(database: self, sql: sql, arguments: arguments)
}
/// Executes one or several SQL statements.
///
/// For example:
///
/// ```swift
/// try db.execute(
/// sql: "INSERT INTO player (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try db.execute(sql: """
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
/// ```
///
/// - parameters:
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
try execute(literal: SQL(sql: sql, arguments: arguments))
}
/// Executes one or several SQL statements.
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// try db.execute(literal: """
/// INSERT INTO player (name) VALUES (\("Arthur"))
/// """)
///
/// try db.execute(literal: """
/// INSERT INTO player (name) VALUES (\("Arthur"));
/// INSERT INTO player (name) VALUES (\("Barbara"));
/// INSERT INTO player (name) VALUES (\("O'Brien"));
/// """)
/// ```
///
/// - parameter sqlLiteral: An ``SQL`` literal.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func execute(literal sqlLiteral: SQL) throws {
let statements = try allStatements(literal: sqlLiteral)
while let statement = try statements.next() {
try statement.execute()
}
}
}
/// A cursor over all statements in an SQL string.
public class SQLStatementCursor {
private let database: Database
private let cString: ContiguousArray<CChar>
private let prepFlags: CUnsignedInt
private let initialArgumentCount: Int?
// Mutated by iteration
private var offset: Int // offset in the C string
private var arguments: StatementArguments? // Nil when arguments are set later
init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CUnsignedInt = 0) {
self.database = database
self.cString = sql.utf8CString
self.prepFlags = prepFlags
self.initialArgumentCount = arguments?.values.count
self.offset = 0
self.arguments = arguments
}
}
extension SQLStatementCursor: Cursor {
public func next() throws -> Statement? {
guard offset < cString.count - 1 /* trailing \0 */ else {
// End of C string -> end of cursor.
try checkArgumentsAreEmpty()
return nil
}
return try cString.withUnsafeBufferPointer { buffer in
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
// Compile next statement
var statementEnd: UnsafePointer<Int8>? = nil
let statement = try Statement(
database: database,
statementStart: baseAddress + offset,
statementEnd: &statementEnd,
prepFlags: prepFlags)
// Advance to next statement
offset = statementEnd! - baseAddress // never nil because statement compilation did not fail.
guard let statement else {
// No statement found -> end of cursor.
try checkArgumentsAreEmpty()
return nil
}
if arguments != nil {
// Extract statement arguments
let bindings = try arguments!.extractBindings(
forStatement: statement,
allowingRemainingValues: true)
// unchecked is OK because we just extracted the correct
// number of arguments
statement.setUncheckedArguments(StatementArguments(bindings))
}
return statement
}
}
/// Check that all arguments were consumed: it is a programmer error to
/// provide arguments that do not match the statements.
private func checkArgumentsAreEmpty() throws {
if let arguments = arguments,
let initialArgumentCount = initialArgumentCount,
arguments.values.isEmpty == false
{
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(initialArgumentCount)")
}
}
}
extension Database {
/// Makes sure statement can be executed, and prepares database observation.
@usableFromInline
func statementWillExecute(_ statement: Statement) throws {
// Aborted transactions prevent statement execution (see the
// documentation of this method for more information).
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
// Suspended databases must not execute statements that create the risk
// of `0xdead10cc` exception (see the documentation of this method for
// more information).
try checkForSuspensionViolation(from: statement)
// Record the database region selected by the statement execution.
if isRecordingSelectedRegion {
selectedRegion.formUnion(statement.databaseRegion)
}
// Database observation: prepare transaction observers.
observationBroker?.statementWillExecute(statement)
}
/// May throw a cancelled commit error, if a transaction observer cancels
/// an empty transaction.
@usableFromInline
func statementDidExecute(_ statement: Statement) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
// Database observation: cleanup
try observationBroker?.statementDidExecute(statement)
}
/// Always throws an error
@usableFromInline
func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) throws -> Never {
// Failed statements can not be reused, because `sqlite3_reset` won't
// be able to restore the statement to its initial state:
// https://www.sqlite.org/c3ref/reset.html
//
// So make sure we clear this statement from the cache.
internalStatementCache.remove(statement)
publicStatementCache.remove(statement)
// Extract values that may be modified by the user in their
// `TransactionObserver.databaseDidRollback(_:)` implementation
// (see below).
let message = lastErrorMessage
let arguments = statement.arguments
// Database observation: cleanup.
//
// If the statement failure is due to a transaction observer that has
// cancelled a transaction, this calls `TransactionObserver.databaseDidRollback(_:)`,
// and throws the user-provided cancelled commit error.
try observationBroker?.statementDidFail(statement)
// Throw statement failure
throw DatabaseError(
resultCode: resultCode,
message: message,
sql: statement.sql,
arguments: arguments,
publicStatementArguments: configuration.publicStatementArguments)
}
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
private var statements: [String: Statement] = [:]
init(database: Database) {
self.db = database
}
mutating func statement(_ sql: String) throws -> Statement {
if let statement = statements[sql] {
return statement
}
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
#else
let statement: Statement
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
} else {
statement = try db.makeStatement(sql: sql)
}
#endif
statements[sql] = statement
return statement
}
mutating func clear() {
statements = [:]
}
mutating func remove(_ statement: Statement) {
statements.removeFirst { $0.value === statement }
}
mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) }
}
}
| mit | a7891fb867a39aea29b2209f83c68826 | 37.88806 | 114 | 0.58674 | 4.887222 | false | false | false | false |
nathawes/swift | stdlib/public/Darwin/Foundation/NSCoder.swift | 9 | 8180 | //===----------------------------------------------------------------------===//
//
// 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
@_implementationOnly import _SwiftFoundationOverlayShims
//===----------------------------------------------------------------------===//
// NSCoder
//===----------------------------------------------------------------------===//
@available(macOS 10.11, iOS 9.0, *)
internal func resolveError(_ error: NSError?) throws {
if let error = error, error.code != NSCoderValueNotFoundError {
throw error
}
}
extension NSCoder {
@available(*, unavailable, renamed: "decodeObject(of:forKey:)")
public func decodeObjectOfClass<DecodedObjectType>(
_ cls: DecodedObjectType.Type, forKey key: String
) -> DecodedObjectType?
where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
fatalError("This API has been renamed")
}
public func decodeObject<DecodedObjectType>(
of cls: DecodedObjectType.Type, forKey key: String
) -> DecodedObjectType?
where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
let result = __NSCoderDecodeObjectOfClassForKey(self, cls, key, nil)
return result as? DecodedObjectType
}
@available(*, unavailable, renamed: "decodeObject(of:forKey:)")
@nonobjc
public func decodeObjectOfClasses(_ classes: NSSet?, forKey key: String) -> AnyObject? {
fatalError("This API has been renamed")
}
@nonobjc
public func decodeObject(of classes: [AnyClass]?, forKey key: String) -> Any? {
var classesAsNSObjects: NSSet?
if let theClasses = classes {
classesAsNSObjects = NSSet(array: theClasses.map { $0 as AnyObject })
}
return __NSCoderDecodeObjectOfClassesForKey(self, classesAsNSObjects, key, nil).map { $0 }
}
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject() throws -> Any? {
var error: NSError?
let result = __NSCoderDecodeObject(self, &error)
try resolveError(error)
return result.map { $0 }
}
@available(*, unavailable, renamed: "decodeTopLevelObject(forKey:)")
public func decodeTopLevelObjectForKey(_ key: String) throws -> AnyObject? {
fatalError("This API has been renamed")
}
@nonobjc
@available(swift, obsoleted: 4)
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject(forKey key: String) throws -> AnyObject? {
var error: NSError?
let result = __NSCoderDecodeObjectForKey(self, key, &error)
try resolveError(error)
return result as AnyObject?
}
@nonobjc
@available(swift, introduced: 4)
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject(forKey key: String) throws -> Any? {
var error: NSError?
let result = __NSCoderDecodeObjectForKey(self, key, &error)
try resolveError(error)
return result
}
@available(*, unavailable, renamed: "decodeTopLevelObject(of:forKey:)")
public func decodeTopLevelObjectOfClass<DecodedObjectType>(
_ cls: DecodedObjectType.Type, forKey key: String
) throws -> DecodedObjectType?
where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
fatalError("This API has been renamed")
}
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject<DecodedObjectType>(
of cls: DecodedObjectType.Type, forKey key: String
) throws -> DecodedObjectType?
where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
var error: NSError?
let result = __NSCoderDecodeObjectOfClassForKey(self, cls, key, &error)
try resolveError(error)
return result as? DecodedObjectType
}
@nonobjc
@available(*, unavailable, renamed: "decodeTopLevelObject(of:forKey:)")
public func decodeTopLevelObjectOfClasses(_ classes: NSSet?, forKey key: String) throws -> AnyObject? {
fatalError("This API has been renamed")
}
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject(of classes: [AnyClass]?, forKey key: String) throws -> Any? {
var error: NSError?
var classesAsNSObjects: NSSet?
if let theClasses = classes {
classesAsNSObjects = NSSet(array: theClasses.map { $0 as AnyObject })
}
let result = __NSCoderDecodeObjectOfClassesForKey(self, classesAsNSObjects, key, &error)
try resolveError(error)
return result.map { $0 }
}
}
//===----------------------------------------------------------------------===//
// NSKeyedArchiver
//===----------------------------------------------------------------------===//
extension NSKeyedArchiver {
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func encodeEncodable<T : Encodable>(_ value: T, forKey key: String) throws {
let plistEncoder = PropertyListEncoder()
let plist = try plistEncoder.encodeToTopLevelContainer(value)
self.encode(plist, forKey: key)
}
}
//===----------------------------------------------------------------------===//
// NSKeyedUnarchiver
//===----------------------------------------------------------------------===//
extension NSKeyedUnarchiver {
@nonobjc
@available(swift, obsoleted: 4)
@available(macOS 10.11, iOS 9.0, *)
public class func unarchiveTopLevelObjectWithData(_ data: NSData) throws -> AnyObject? {
var error: NSError?
let result = __NSKeyedUnarchiverUnarchiveObject(self, data, &error)
try resolveError(error)
return result as AnyObject?
}
@nonobjc
@available(swift, introduced: 4)
@available(macOS 10.11, iOS 9.0, *)
public class func unarchiveTopLevelObjectWithData(_ data: Data) throws -> Any? {
var error: NSError?
let result = __NSKeyedUnarchiverUnarchiveObject(self, data as NSData, &error)
try resolveError(error)
return result
}
@nonobjc
@available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
public static func unarchivedObject<DecodedObjectType>(ofClass cls: DecodedObjectType.Type, from data: Data) throws -> DecodedObjectType? where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
var error: NSError?
let result = __NSKeyedUnarchiverSecureUnarchiveObjectOfClass(cls as AnyClass, data, &error)
if let error = error { throw error }
return result as? DecodedObjectType
}
@nonobjc
@available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
public static func unarchivedObject(ofClasses classes: [AnyClass], from data: Data) throws -> Any? {
var error: NSError?
let classesAsNSObjects = NSSet(array: classes.map { $0 as AnyObject })
let result = __NSKeyedUnarchiverSecureUnarchiveObjectOfClasses(classesAsNSObjects, data, &error)
if let error = error { throw error }
return result
}
@nonobjc
private static let __plistClasses: [AnyClass] = [
NSArray.self,
NSData.self,
NSDate.self,
NSDictionary.self,
NSNumber.self,
NSString.self
]
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func decodeDecodable<T : Decodable>(_ type: T.Type, forKey key: String) -> T? {
guard let value = self.decodeObject(of: NSKeyedUnarchiver.__plistClasses, forKey: key) else {
return nil
}
let plistDecoder = PropertyListDecoder()
do {
return try plistDecoder.decode(T.self, fromTopLevel: value)
} catch {
self.failWithError(error)
return nil
}
}
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelDecodable<T : Decodable>(_ type: T.Type, forKey key: String) throws -> T? {
guard let value = try self.decodeTopLevelObject(of: NSKeyedUnarchiver.__plistClasses, forKey: key) else {
return nil
}
let plistDecoder = PropertyListDecoder()
do {
return try plistDecoder.decode(T.self, fromTopLevel: value)
} catch {
self.failWithError(error)
throw error;
}
}
}
| apache-2.0 | ef65fee4475a5524bcaced5eed65861b | 34.411255 | 206 | 0.647922 | 4.725592 | false | false | false | false |
TotalDigital/People-iOS | People at Total/Relation.swift | 1 | 3300 | //
// Relation.swift
// justOne
//
// Created by Florian Letellier on 29/01/2017.
// Copyright © 2017 Florian Letellier. All rights reserved.
//
import Foundation
class Relation: NSObject, NSCoding {
var isRelationAvailable: Bool = false
var relationshipID: Int = 0
var managers: [Int] = []
var assistant: [Int] = []
var teamMember: [Int] = []
var colleagues: [Int] = []
var managers_profile: [Profile] = []
var assistants_profile: [Profile] = []
var teamMembers_profile: [Profile] = []
var colleagues_profile: [Profile] = []
override init() {
}
init(isRelationAvailable: Bool, relationshipID: Int, managers: [Int],assistant: [Int],teamMember: [Int],colleagues: [Int],managers_profile: [Profile],assistants_profile: [Profile],teamMembers_profile: [Profile],colleagues_profile: [Profile]) {
self.isRelationAvailable = isRelationAvailable
self.relationshipID = relationshipID
self.managers = managers
self.assistant = assistant
self.teamMember = teamMember
self.colleagues = colleagues
self.managers_profile = managers_profile
self.assistants_profile = assistants_profile
self.teamMembers_profile = teamMembers_profile
self.colleagues_profile = colleagues_profile
}
required convenience init(coder aDecoder: NSCoder) {
let isRelationAvailable = aDecoder.decodeBool(forKey: "isRelationAvailable")
let relationshipID = aDecoder.decodeInteger(forKey: "relationshipID")
let managers = aDecoder.decodeObject(forKey: "managers") as! [Int]
let assistant = aDecoder.decodeObject(forKey: "assistant") as! [Int]
let teamMember = aDecoder.decodeObject(forKey: "teamMember") as! [Int]
let colleagues = aDecoder.decodeObject(forKey: "colleagues") as! [Int]
let managers_profile = aDecoder.decodeObject(forKey: "managers_profile") as! [Profile]
let assistants_profile = aDecoder.decodeObject(forKey: "assistants_profile") as! [Profile]
let teamMembers_profile = aDecoder.decodeObject(forKey: "teamMembers_profile") as! [Profile]
let colleagues_profile = aDecoder.decodeObject(forKey: "colleagues_profile") as! [Profile]
self.init(isRelationAvailable: isRelationAvailable, relationshipID: relationshipID, managers: managers,assistant: assistant,teamMember: teamMember,colleagues: colleagues,managers_profile: managers_profile,assistants_profile: assistants_profile,teamMembers_profile: teamMembers_profile,colleagues_profile: colleagues_profile)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(isRelationAvailable, forKey: "isRelationAvailable")
aCoder.encode(relationshipID, forKey: "relationshipID")
aCoder.encode(managers, forKey: "managers")
aCoder.encode(assistant, forKey: "assistant")
aCoder.encode(teamMember, forKey: "teamMember")
aCoder.encode(colleagues, forKey: "colleagues")
aCoder.encode(managers_profile, forKey: "managers_profile")
aCoder.encode(assistants_profile, forKey: "assistants_profile")
aCoder.encode(teamMembers_profile, forKey: "teamMembers_profile")
aCoder.encode(colleagues_profile, forKey: "colleagues_profile")
}
}
| apache-2.0 | d2abca5042038e1bb312934c4cfbcf69 | 47.514706 | 332 | 0.698697 | 4.531593 | false | false | false | false |
mohitathwani/swift-corelibs-foundation | Foundation/NSString.swift | 1 | 67612 | // 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 CoreFoundation
public typealias unichar = UInt16
extension unichar : ExpressibleByUnicodeScalarLiteral {
public typealias UnicodeScalarLiteralType = UnicodeScalar
public init(unicodeScalarLiteral scalar: UnicodeScalar) {
self.init(scalar.value)
}
}
#if os(OSX) || os(iOS)
internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.macRoman.rawValue
internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.windowsLatin1.rawValue
internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.isoLatin1.rawValue
internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.nextStepLatin.rawValue
internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue
internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.unicode.rawValue
internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue
internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.nonLossyASCII.rawValue
internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue
internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue
internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue
internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue
internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue
internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue
internal let kCFStringGraphemeCluster = CFStringCharacterClusterType.graphemeCluster
internal let kCFStringComposedCharacterCluster = CFStringCharacterClusterType.composedCharacterCluster
internal let kCFStringCursorMovementCluster = CFStringCharacterClusterType.cursorMovementCluster
internal let kCFStringBackwardDeletionCluster = CFStringCharacterClusterType.backwardDeletionCluster
internal let kCFStringNormalizationFormD = CFStringNormalizationForm.D
internal let kCFStringNormalizationFormKD = CFStringNormalizationForm.KD
internal let kCFStringNormalizationFormC = CFStringNormalizationForm.C
internal let kCFStringNormalizationFormKC = CFStringNormalizationForm.KC
#endif
extension NSString {
public struct EncodingConversionOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let allowLossy = EncodingConversionOptions(rawValue: 1)
public static let externalRepresentation = EncodingConversionOptions(rawValue: 2)
internal static let failOnPartialEncodingConversion = EncodingConversionOptions(rawValue: 1 << 20)
}
public struct EnumerationOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let byLines = EnumerationOptions(rawValue: 0)
public static let byParagraphs = EnumerationOptions(rawValue: 1)
public static let byComposedCharacterSequences = EnumerationOptions(rawValue: 2)
public static let byWords = EnumerationOptions(rawValue: 3)
public static let bySentences = EnumerationOptions(rawValue: 4)
public static let reverse = EnumerationOptions(rawValue: 1 << 8)
public static let substringNotRequired = EnumerationOptions(rawValue: 1 << 9)
public static let localized = EnumerationOptions(rawValue: 1 << 10)
internal static let forceFullTokens = EnumerationOptions(rawValue: 1 << 20)
}
}
extension NSString {
public struct CompareOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let caseInsensitive = CompareOptions(rawValue: 1)
public static let literal = CompareOptions(rawValue: 2)
public static let backwards = CompareOptions(rawValue: 4)
public static let anchored = CompareOptions(rawValue: 8)
public static let numeric = CompareOptions(rawValue: 64)
public static let diacriticInsensitive = CompareOptions(rawValue: 128)
public static let widthInsensitive = CompareOptions(rawValue: 256)
public static let forcedOrdering = CompareOptions(rawValue: 512)
public static let regularExpression = CompareOptions(rawValue: 1024)
internal func _cfValue(_ fixLiteral: Bool = false) -> CFStringCompareFlags {
#if os(OSX) || os(iOS)
return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue: rawValue) : CFStringCompareFlags(rawValue: rawValue).union(.compareNonliteral)
#else
return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue) : CFStringCompareFlags(rawValue) | UInt(kCFCompareNonliteral)
#endif
}
}
}
internal func _createRegexForPattern(_ pattern: String, _ options: NSRegularExpression.Options) -> NSRegularExpression? {
struct local {
static let __NSRegularExpressionCache: NSCache<NSString, NSRegularExpression> = {
let cache = NSCache<NSString, NSRegularExpression>()
cache.name = "NSRegularExpressionCache"
cache.countLimit = 10
return cache
}()
}
let key = "\(options):\(pattern)"
if let regex = local.__NSRegularExpressionCache.object(forKey: key._nsObject) {
return regex
}
do {
let regex = try NSRegularExpression(pattern: pattern, options: options)
local.__NSRegularExpressionCache.setObject(regex, forKey: key._nsObject)
return regex
} catch {
}
return nil
}
internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ fatalOnError: Bool, _ externalRep: Bool, _ lossy: Bool) -> UnsafePointer<Int8>? {
let theRange = NSMakeRange(0, str.length)
var cLength = 0
var used = 0
var options: NSString.EncodingConversionOptions = []
if externalRep {
options.formUnion(.externalRepresentation)
}
if lossy {
options.formUnion(.allowLossy)
}
if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
if fatalOnError {
fatalError("Conversion on encoding failed")
}
return nil
}
let buffer = malloc(cLength + 1)!.bindMemory(to: Int8.self, capacity: cLength + 1)
if !str.getBytes(buffer, maxLength: cLength, usedLength: &used, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
fatalError("Internal inconsistency; previously claimed getBytes returned success but failed with similar invocation")
}
buffer.advanced(by: cLength).initialize(to: 0)
return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here
}
internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x0085 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x0085 || ch == 0x2028 || ch == 0x2029
}
internal func isAParagraphSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x2029 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x2029
}
open class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID())
internal var _storage: String
open var length: Int {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
return _storage.utf16.count
}
open func character(at index: Int) -> unichar {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
let start = _storage.utf16.startIndex
return _storage.utf16[start.advanced(by: index)]
}
public override convenience init() {
let characters = Array<unichar>(repeating: 0, count: 1)
self.init(characters: characters, length: 0)
}
internal init(_ string: String) {
_storage = string
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.string") {
let str = aDecoder._decodePropertyListForKey("NS.string") as! String
self.init(string: str)
} else {
let decodedData : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") {
guard let buffer = $0 else { return nil }
return Data(buffer: buffer)
}
guard let data = decodedData else { return nil }
self.init(data: data, encoding: String.Encoding.utf8.rawValue)
}
}
public required convenience init(string aString: String) {
self.init(aString)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSString.self || type(of: self) === NSMutableString.self {
if let contents = _fastContents {
return NSMutableString(characters: contents, length: length)
}
}
let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length)
getCharacters(characters, range: NSMakeRange(0, length))
let result = NSMutableString(characters: characters, length: length)
characters.deinitialize()
characters.deallocate(capacity: length)
return result
}
public static var supportsSecureCoding: Bool {
return true
}
open func encode(with aCoder: NSCoder) {
if let aKeyedCoder = aCoder as? NSKeyedArchiver {
aKeyedCoder._encodePropertyList(self, forKey: "NS.string")
} else {
aCoder.encode(self)
}
}
public init(characters: UnsafePointer<unichar>, length: Int) {
_storage = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))
}
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required init(stringLiteral value: StaticString) {
_storage = String(describing: value)
}
public convenience init?(cString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) {
self.init(string: CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding))._swiftObject)
}
internal func _fastCStringContents(_ nullTerminated: Bool) -> UnsafePointer<Int8>? {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if _storage._core.isASCII {
return unsafeBitCast(_storage._core.startASCII, to: UnsafePointer<Int8>.self)
}
}
return nil
}
internal var _fastContents: UnsafePointer<UniChar>? {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if !_storage._core.isASCII {
return unsafeBitCast(_storage._core.startUTF16, to: UnsafePointer<UniChar>.self)
}
}
return nil
}
internal var _encodingCantBeStoredInEightBitCFString: Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return !_storage._core.isASCII
}
return false
}
override open var _cfTypeID: CFTypeID {
return CFStringGetTypeID()
}
open override func isEqual(_ object: Any?) -> Bool {
guard let string = (object as? NSString)?._swiftObject else { return false }
return self.isEqual(to: string)
}
open override var description: String {
return _swiftObject
}
open override var hash: Int {
return Int(bitPattern:CFStringHashNSString(self._cfObject))
}
}
extension NSString {
public func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range: NSRange) {
for idx in 0..<range.length {
buffer[idx] = character(at: idx + range.location)
}
}
public func substring(from: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.suffix(from: _storage.utf16.startIndex.advanced(by: from)))!
} else {
return substring(with: NSMakeRange(from, length - from))
}
}
public func substring(to: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.prefix(upTo: _storage.utf16.startIndex
.advanced(by: to)))!
} else {
return substring(with: NSMakeRange(0, to))
}
}
public func substring(with range: NSRange) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
let start = _storage.utf16.startIndex
let min = start.advanced(by: range.location)
let max = start.advanced(by: range.location + range.length)
if let substr = String(_storage.utf16[min..<max]) {
return substr
}
//If we come here, then the range has created unpaired surrogates on either end.
//An unpaired surrogate is replaced by OXFFFD - the Unicode Replacement Character.
//The CRLF ("\r\n") sequence is also treated like a surrogate pair, but its constinuent
//characters "\r" and "\n" can exist outside the pair!
let replacementCharacter = String(describing: UnicodeScalar(0xFFFD)!)
let CR: UInt16 = 13 //carriage return
let LF: UInt16 = 10 //new line
//make sure the range is of non-zero length
guard range.length > 0 else { return "" }
//if the range is pointing to a single unpaired surrogate
if range.length == 1 {
switch _storage.utf16[min] {
case CR: return "\r"
case LF: return "\n"
default: return replacementCharacter
}
}
//set the prefix and suffix characters
let prefix = _storage.utf16[min] == LF ? "\n" : replacementCharacter
let suffix = _storage.utf16[max.advanced(by: -1)] == CR ? "\r" : replacementCharacter
//if the range breaks a surrogate pair at the beginning of the string
if let substrSuffix = String(_storage.utf16[min.advanced(by: 1)..<max]) {
return prefix + substrSuffix
}
//if the range breaks a surrogate pair at the end of the string
if let substrPrefix = String(_storage.utf16[min..<max.advanced(by: -1)]) {
return substrPrefix + suffix
}
//the range probably breaks surrogate pairs at both the ends
guard min.advanced(by: 1) <= max.advanced(by: -1) else { return prefix + suffix }
let substr = String(_storage.utf16[min.advanced(by: 1)..<max.advanced(by: -1)])!
return prefix + substr + suffix
} else {
let buff = UnsafeMutablePointer<unichar>.allocate(capacity: range.length)
getCharacters(buff, range: range)
let result = String(describing: buff)
buff.deinitialize()
buff.deallocate(capacity: range.length)
return result
}
}
public func compare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSMakeRange(0, length))
}
public func compare(_ string: String, options mask: CompareOptions) -> ComparisonResult {
return compare(string, options: mask, range: NSMakeRange(0, length))
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange) -> ComparisonResult {
return compare(string, options: mask, range: compareRange, locale: nil)
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: Any?) -> ComparisonResult {
var res: CFComparisonResult
if let loc = locale {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), (loc as! NSLocale)._cfObject)
} else {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), nil)
}
return ComparisonResult._fromCF(res)
}
public func caseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length))
}
public func localizedCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedCaseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedStandardCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [.caseInsensitive, .numeric, .widthInsensitive, .forcedOrdering], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func isEqual(to aString: String) -> Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return _storage == aString
} else {
return length == aString.length && compare(aString, options: .literal, range: NSMakeRange(0, length)) == .orderedSame
}
}
public func hasPrefix(_ str: String) -> Bool {
return range(of: str, options: .anchored, range: NSMakeRange(0, length)).location != NSNotFound
}
public func hasSuffix(_ str: String) -> Bool {
return range(of: str, options: [.anchored, .backwards], range: NSMakeRange(0, length)).location != NSNotFound
}
public func commonPrefix(with str: String, options mask: CompareOptions = []) -> String {
var currentSubstring: CFMutableString?
let isLiteral = mask.contains(.literal)
var lastMatch = NSRange()
let selfLen = length
let otherLen = str.length
var low = 0
var high = selfLen
var probe = (low + high) / 2
if (probe > otherLen) {
probe = otherLen // A little heuristic to avoid some extra work
}
if selfLen == 0 || otherLen == 0 {
return ""
}
var numCharsBuffered = 0
var arrayBuffer = [unichar](repeating: 0, count: 100)
let other = str._nsObject
return arrayBuffer.withUnsafeMutablePointerOrAllocation(selfLen, fastpath: UnsafeMutablePointer<unichar>(mutating: _fastContents)) { (selfChars: UnsafeMutablePointer<unichar>) -> String in
// Now do the binary search. Note that the probe value determines the length of the substring to check.
while true {
let range = NSMakeRange(0, isLiteral ? probe + 1 : NSMaxRange(rangeOfComposedCharacterSequence(at: probe))) // Extend the end of the composed char sequence
if range.length > numCharsBuffered { // Buffer more characters if needed
getCharacters(selfChars, range: NSMakeRange(numCharsBuffered, range.length - numCharsBuffered))
numCharsBuffered = range.length
}
if currentSubstring == nil {
currentSubstring = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorSystemDefault, selfChars, range.length, range.length, kCFAllocatorNull)
} else {
CFStringSetExternalCharactersNoCopy(currentSubstring, selfChars, range.length, range.length)
}
if other.range(of: currentSubstring!._swiftObject, options: mask.union(.anchored), range: NSMakeRange(0, otherLen)).length != 0 { // Match
lastMatch = range
low = probe + 1
} else {
high = probe
}
if low >= high {
break
}
probe = (low + high) / 2
}
return lastMatch.length != 0 ? substring(with: lastMatch) : ""
}
}
public func contains(_ str: String) -> Bool {
return range(of: str, options: [], range: NSMakeRange(0, length), locale: nil).location != NSNotFound
}
public func localizedCaseInsensitiveContains(_ str: String) -> Bool {
return range(of: str, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardContains(_ str: String) -> Bool {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardRange(of str: String) -> NSRange {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current)
}
public func range(of searchString: String) -> NSRange {
return range(of: searchString, options: [], range: NSMakeRange(0, length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = []) -> NSRange {
return range(of: searchString, options: mask, range: NSMakeRange(0, length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
return range(of: searchString, options: mask, range: searchRange, locale: nil)
}
internal func _rangeOfRegularExpressionPattern(regex pattern: String, options mask: CompareOptions, range searchRange: NSRange, locale: Locale?) -> NSRange {
var matchedRange = NSMakeRange(NSNotFound, 0)
let regexOptions: NSRegularExpression.Options = mask.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSMatchingOptions = mask.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
matchedRange = regex.rangeOfFirstMatch(in: _swiftObject, options: matchingOptions, range: searchRange)
}
return matchedRange
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange, locale: Locale?) -> NSRange {
let findStrLen = searchString.length
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
if mask.contains(.regularExpression) {
return _rangeOfRegularExpressionPattern(regex: searchString, options: mask, range:searchRange, locale: locale)
}
if searchRange.length == 0 || findStrLen == 0 { // ??? This last item can't be here for correct Unicode compares
return NSMakeRange(NSNotFound, 0)
}
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
if let loc = locale {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), loc._cfObject, rangep)
} else {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), nil, rangep)
}
}
if res {
return NSMakeRange(result.location, result.length)
} else {
return NSMakeRange(NSNotFound, 0)
}
}
public func rangeOfCharacter(from searchSet: CharacterSet) -> NSRange {
return rangeOfCharacter(from: searchSet, options: [], range: NSMakeRange(0, length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = []) -> NSRange {
return rangeOfCharacter(from: searchSet, options: mask, range: NSMakeRange(0, length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
return CFStringFindCharacterFromSet(_cfObject, searchSet._cfObject, CFRange(searchRange), mask._cfValue(), rangep)
}
if res {
return NSMakeRange(result.location, result.length)
} else {
return NSMakeRange(NSNotFound, 0)
}
}
public func rangeOfComposedCharacterSequence(at index: Int) -> NSRange {
let range = CFStringGetRangeOfCharacterClusterAtIndex(_cfObject, index, kCFStringComposedCharacterCluster)
return NSMakeRange(range.location, range.length)
}
public func rangeOfComposedCharacterSequences(for range: NSRange) -> NSRange {
let length = self.length
var start: Int
var end: Int
if range.location == length {
start = length
} else {
start = rangeOfComposedCharacterSequence(at: range.location).location
}
var endOfRange = NSMaxRange(range)
if endOfRange == length {
end = length
} else {
if range.length > 0 {
endOfRange = endOfRange - 1 // We want 0-length range to be treated same as 1-length range.
}
end = NSMaxRange(rangeOfComposedCharacterSequence(at: endOfRange))
}
return NSMakeRange(start, end - start)
}
public func appending(_ aString: String) -> String {
return _swiftObject + aString
}
public var doubleValue: Double {
var start: Int = 0
var result = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Double) -> Void in
result = value
}
return result
}
public var floatValue: Float {
var start: Int = 0
var result: Float = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Float) -> Void in
result = value
}
return result
}
public var intValue: Int32 {
return Scanner(string: _swiftObject).scanInt() ?? 0
}
public var integerValue: Int {
let scanner = Scanner(string: _swiftObject)
var value: Int = 0
let _ = scanner.scanInteger(&value)
return value
}
public var longLongValue: Int64 {
return Scanner(string: _swiftObject).scanLongLong() ?? 0
}
public var boolValue: Bool {
let scanner = Scanner(string: _swiftObject)
// skip initial whitespace if present
let _ = scanner.scanCharactersFromSet(.whitespaces)
// scan a single optional '+' or '-' character, followed by zeroes
if scanner.scanString(string: "+") == nil {
let _ = scanner.scanString(string: "-")
}
// scan any following zeroes
let _ = scanner.scanCharactersFromSet(CharacterSet(charactersIn: "0"))
return scanner.scanCharactersFromSet(CharacterSet(charactersIn: "tTyY123456789")) != nil
}
public var uppercased: String {
return uppercased(with: nil)
}
public var lowercased: String {
return lowercased(with: nil)
}
public var capitalized: String {
return capitalized(with: nil)
}
public var localizedUppercase: String {
return uppercased(with: Locale.current)
}
public var localizedLowercase: String {
return lowercased(with: Locale.current)
}
public var localizedCapitalized: String {
return capitalized(with: Locale.current)
}
public func uppercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringUppercase(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
public func lowercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringLowercase(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
public func capitalized(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringCapitalize(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
internal func _getBlockStart(_ startPtr: UnsafeMutablePointer<Int>?, end endPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, forRange range: NSRange, stopAtLineSeparators line: Bool) {
let len = length
var ch: unichar
precondition(range.length <= len && range.location < len - range.length, "Range {\(range.location), \(range.length)} is out of bounds of length \(len)")
if range.location == 0 && range.length == len && contentsEndPtr == nil { // This occurs often
startPtr?.pointee = 0
endPtr?.pointee = range.length
return
}
/* Find the starting point first */
if startPtr != nil {
var start: Int = 0
if range.location == 0 {
start = 0
} else {
var buf = _NSStringBuffer(string: self, start: range.location, end: len)
/* Take care of the special case where start happens to fall right between \r and \n */
ch = buf.currentCharacter
buf.rewind()
if ch == 0x0a && buf.currentCharacter == 0x0d {
buf.rewind()
}
while true {
if line ? isALineSeparatorTypeCharacter(buf.currentCharacter) : isAParagraphSeparatorTypeCharacter(buf.currentCharacter) {
start = buf.location + 1
break
} else if buf.location <= 0 {
start = 0
break
} else {
buf.rewind()
}
}
startPtr!.pointee = start
}
}
if (endPtr != nil || contentsEndPtr != nil) {
var endOfContents = 1
var lineSeparatorLength = 1
var buf = _NSStringBuffer(string: self, start: NSMaxRange(range) - (range.length > 0 ? 1 : 0), end: len)
/* First look at the last char in the range (if the range is zero length, the char after the range) to see if we're already on or within a end of line sequence... */
ch = buf.currentCharacter
if ch == 0x0a {
endOfContents = buf.location
buf.rewind()
if buf.currentCharacter == 0x0d {
lineSeparatorLength = 2
endOfContents -= 1
}
} else {
while true {
if line ? isALineSeparatorTypeCharacter(ch) : isAParagraphSeparatorTypeCharacter(ch) {
endOfContents = buf.location /* This is actually end of contentsRange */
buf.advance() /* OK for this to go past the end */
if ch == 0x0d && buf.currentCharacter == 0x0a {
lineSeparatorLength = 2
}
break
} else if buf.location == len {
endOfContents = len
lineSeparatorLength = 0
break
} else {
buf.advance()
ch = buf.currentCharacter
}
}
}
contentsEndPtr?.pointee = endOfContents
endPtr?.pointee = endOfContents + lineSeparatorLength
}
}
public func getLineStart(_ startPtr: UnsafeMutablePointer<Int>?, end lineEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: lineEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: true)
}
public func lineRange(for range: NSRange) -> NSRange {
var start = 0
var lineEnd = 0
getLineStart(&start, end: &lineEnd, contentsEnd: nil, for: range)
return NSMakeRange(start, lineEnd - start)
}
public func getParagraphStart(_ startPtr: UnsafeMutablePointer<Int>?, end parEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: parEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: false)
}
public func paragraphRange(for range: NSRange) -> NSRange {
var start = 0
var parEnd = 0
getParagraphStart(&start, end: &parEnd, contentsEnd: nil, for: range)
return NSMakeRange(start, parEnd - start)
}
public func enumerateSubstrings(in range: NSRange, options opts: EnumerationOptions = [], using block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
NSUnimplemented()
}
public func enumerateLines(_ block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateSubstrings(in: NSMakeRange(0, length), options:.byLines) { substr, substrRange, enclosingRange, stop in
block(substr!, stop)
}
}
public var utf8String: UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding.utf8, false, false, false)
}
public var fastestEncoding: UInt {
return String.Encoding.unicode.rawValue
}
public var smallestEncoding: UInt {
if canBeConverted(to: String.Encoding.ascii.rawValue) {
return String.Encoding.ascii.rawValue
}
return String.Encoding.unicode.rawValue
}
public func data(using encoding: UInt, allowLossyConversion lossy: Bool = false) -> Data? {
let len = length
var reqSize = 0
let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding)
if !CFStringIsEncodingAvailable(cfStringEncoding) {
return nil
}
let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, nil, 0, &reqSize)
if convertedLen != len {
return nil // Not able to do it all...
}
if 0 < reqSize {
var data = Data(count: reqSize)
data.count = data.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int in
if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer<UInt8>(mutableBytes), reqSize, &reqSize) == convertedLen {
return reqSize
} else {
fatalError("didn't convert all characters")
}
}
return data
}
return Data()
}
public func data(using encoding: UInt) -> Data? {
return data(using: encoding, allowLossyConversion: false)
}
public func canBeConverted(to encoding: UInt) -> Bool {
if encoding == String.Encoding.unicode.rawValue || encoding == String.Encoding.nonLossyASCII.rawValue || encoding == String.Encoding.utf8.rawValue {
return true
}
return __CFStringEncodeByteStream(_cfObject, 0, length, false, CFStringConvertNSStringEncodingToEncoding(encoding), 0, nil, 0, nil) == length
}
public func cString(using encoding: UInt) -> UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding(rawValue: encoding), false, false, false)
}
public func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool {
var used = 0
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if _storage._core.isASCII {
used = min(self.length, maxBufferCount - 1)
buffer.moveAssign(from: unsafeBitCast(_storage._core.startASCII, to: UnsafeMutablePointer<Int8>.self)
, count: used)
buffer.advanced(by: used).initialize(to: 0)
return true
}
}
if getBytes(UnsafeMutableRawPointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSMakeRange(0, self.length), remaining: nil) {
buffer.advanced(by: used).initialize(to: 0)
return true
}
return false
}
public func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool {
var totalBytesWritten = 0
var numCharsProcessed = 0
let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding)
var result = true
if length > 0 {
if CFStringIsEncodingAvailable(cfStringEncoding) {
let lossyOk = options.contains(.allowLossy)
let externalRep = options.contains(.externalRepresentation)
let failOnPartial = options.contains(.failOnPartialEncodingConversion)
let bytePtr = buffer?.bindMemory(to: UInt8.self, capacity: maxBufferCount)
numCharsProcessed = __CFStringEncodeByteStream(_cfObject, range.location, range.length, externalRep, cfStringEncoding, lossyOk ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, bytePtr, bytePtr != nil ? maxBufferCount : 0, &totalBytesWritten)
if (failOnPartial && numCharsProcessed < range.length) || numCharsProcessed == 0 {
result = false
}
} else {
result = false /* ??? Need other encodings */
}
}
usedBufferCount?.pointee = totalBytesWritten
leftover?.pointee = NSMakeRange(range.location + numCharsProcessed, range.length - numCharsProcessed)
return result
}
public func maximumLengthOfBytes(using enc: UInt) -> Int {
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc)
let result = CFStringGetMaximumSizeForEncoding(length, cfEnc)
return result == kCFNotFound ? 0 : result
}
public func lengthOfBytes(using enc: UInt) -> Int {
let len = length
var numBytes: CFIndex = 0
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc)
let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, false, cfEnc, 0, nil, 0, &numBytes)
return convertedLen != len ? 0 : numBytes
}
open class var availableStringEncodings: UnsafePointer<UInt> {
struct once {
static let encodings: UnsafePointer<UInt> = {
let cfEncodings = CFStringGetListOfAvailableEncodings()!
var idx = 0
var numEncodings = 0
while cfEncodings.advanced(by: idx).pointee != kCFStringEncodingInvalidId {
idx += 1
numEncodings += 1
}
let theEncodingList = UnsafeMutablePointer<String.Encoding.RawValue>.allocate(capacity: numEncodings + 1)
theEncodingList.advanced(by: numEncodings).pointee = 0 // Terminator
numEncodings -= 1
while numEncodings >= 0 {
theEncodingList.advanced(by: numEncodings).pointee = CFStringConvertEncodingToNSStringEncoding(cfEncodings.advanced(by: numEncodings).pointee)
numEncodings -= 1
}
return UnsafePointer<UInt>(theEncodingList)
}()
}
return once.encodings
}
open class func localizedName(of encoding: UInt) -> String {
if let theString = CFStringGetNameOfEncoding(CFStringConvertNSStringEncodingToEncoding(encoding)) {
// TODO: read the localized version from the Foundation "bundle"
return theString._swiftObject
}
return ""
}
open class var defaultCStringEncoding: UInt {
return CFStringConvertEncodingToNSStringEncoding(CFStringGetSystemEncoding())
}
open var decomposedStringWithCanonicalMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormD)
return string._swiftObject
}
open var precomposedStringWithCanonicalMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormC)
return string._swiftObject
}
open var decomposedStringWithCompatibilityMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormKD)
return string._swiftObject
}
open var precomposedStringWithCompatibilityMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormKC)
return string._swiftObject
}
open func components(separatedBy separator: String) -> [String] {
let len = length
var lrange = range(of: separator, options: [], range: NSMakeRange(0, len))
if lrange.length == 0 {
return [_swiftObject]
} else {
var array = [String]()
var srange = NSMakeRange(0, len)
while true {
let trange = NSMakeRange(srange.location, lrange.location - srange.location)
array.append(substring(with: trange))
srange.location = lrange.location + lrange.length
srange.length = len - srange.location
lrange = range(of: separator, options: [], range: srange)
if lrange.length == 0 {
break
}
}
array.append(substring(with: srange))
return array
}
}
open func components(separatedBy separator: CharacterSet) -> [String] {
let len = length
var range = rangeOfCharacter(from: separator, options: [], range: NSMakeRange(0, len))
if range.length == 0 {
return [_swiftObject]
} else {
var array = [String]()
var srange = NSMakeRange(0, len)
while true {
let trange = NSMakeRange(srange.location, range.location - srange.location)
array.append(substring(with: trange))
srange.location = range.location + range.length
srange.length = len - srange.location
range = rangeOfCharacter(from: separator, options: [], range: srange)
if range.length == 0 {
break
}
}
array.append(substring(with: srange))
return array
}
}
open func trimmingCharacters(in set: CharacterSet) -> String {
let len = length
var buf = _NSStringBuffer(string: self, start: 0, end: len)
while !buf.isAtEnd,
let character = UnicodeScalar(buf.currentCharacter),
set.contains(character) {
buf.advance()
}
let startOfNonTrimmedRange = buf.location // This points at the first char not in the set
if startOfNonTrimmedRange == len { // Note that this also covers the len == 0 case, which is important to do here before the len-1 in the next line.
return ""
} else if startOfNonTrimmedRange < len - 1 {
buf.location = len - 1
while let character = UnicodeScalar(buf.currentCharacter),
set.contains(character),
buf.location >= startOfNonTrimmedRange {
buf.rewind()
}
let endOfNonTrimmedRange = buf.location
return substring(with: NSMakeRange(startOfNonTrimmedRange, endOfNonTrimmedRange + 1 - startOfNonTrimmedRange))
} else {
return substring(with: NSMakeRange(startOfNonTrimmedRange, 1))
}
}
open func padding(toLength newLength: Int, withPad padString: String, startingAt padIndex: Int) -> String {
let len = length
if newLength <= len { // The simple cases (truncation)
return newLength == len ? _swiftObject : substring(with: NSMakeRange(0, newLength))
}
let padLen = padString.length
if padLen < 1 {
fatalError("empty pad string")
}
if padIndex >= padLen {
fatalError("out of range padIndex")
}
let mStr = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, _cfObject)!
CFStringPad(mStr, padString._cfObject, newLength, padIndex)
return mStr._swiftObject
}
open func folding(options: CompareOptions = [], locale: Locale?) -> String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringFold(string, options._cfValue(), locale?._cfObject)
return string._swiftObject
}
internal func _stringByReplacingOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range: NSRange) -> String {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSMatchingOptions = options.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
return regex.stringByReplacingMatches(in: _swiftObject, options: matchingOptions, range: range, withTemplate: replacement)
}
return ""
}
open func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> String {
if options.contains(.regularExpression) {
return _stringByReplacingOccurrencesOfRegularExpressionPattern(target, withTemplate: replacement, options: options, range: searchRange)
}
let str = mutableCopy(with: nil) as! NSMutableString
if str.replaceOccurrences(of: target, with: replacement, options: options, range: searchRange) == 0 {
return _swiftObject
} else {
return str._swiftObject
}
}
open func replacingOccurrences(of target: String, with replacement: String) -> String {
return replacingOccurrences(of: target, with: replacement, options: [], range: NSMakeRange(0, length))
}
open func replacingCharacters(in range: NSRange, with replacement: String) -> String {
let str = mutableCopy(with: nil) as! NSMutableString
str.replaceCharacters(in: range, with: replacement)
return str._swiftObject
}
open func applyingTransform(_ transform: String, reverse: Bool) -> String? {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, _cfObject)
if (CFStringTransform(string, nil, transform._cfObject, reverse)) {
return string._swiftObject
} else {
return nil
}
}
internal func _getExternalRepresentation(_ data: inout Data, _ dest: URL, _ enc: UInt) throws {
let length = self.length
var numBytes = 0
let theRange = NSMakeRange(0, length)
if !getBytes(nil, maxLength: Int.max - 1, usedLength: &numBytes, encoding: enc, options: [], range: theRange, remaining: nil) {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteInapplicableStringEncoding.rawValue, userInfo: [
NSURLErrorKey: dest,
])
}
var mData = Data(count: numBytes)
// The getBytes:... call should hopefully not fail, given it succeeded above, but check anyway (mutable string changing behind our back?)
var used = 0
// This binds mData memory to UInt8 because Data.withUnsafeMutableBytes does not handle raw pointers.
try mData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Void in
if !getBytes(mutableBytes, maxLength: numBytes, usedLength: &used, encoding: enc, options: [], range: theRange, remaining: nil) {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [
NSURLErrorKey: dest,
])
}
}
data = mData
}
internal func _writeTo(_ url: URL, _ useAuxiliaryFile: Bool, _ enc: UInt) throws {
var data = Data()
try _getExternalRepresentation(&data, url, enc)
try data.write(to: url, options: useAuxiliaryFile ? .atomic : [])
}
open func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws {
try _writeTo(url, useAuxiliaryFile, enc)
}
open func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws {
try _writeTo(URL(fileURLWithPath: path), useAuxiliaryFile, enc)
}
public convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ {
// ignore the no-copy-ness
self.init(characters: characters, length: length)
if freeBuffer { // cant take a hint here...
free(UnsafeMutableRawPointer(characters))
}
}
public convenience init?(utf8String nullTerminatedCString: UnsafePointer<Int8>) {
let count = Int(strlen(nullTerminatedCString))
if let str = nullTerminatedCString.withMemoryRebound(to: UInt8.self, capacity: count, {
let buffer = UnsafeBufferPointer<UInt8>(start: $0, count: count)
return String._fromCodeUnitSequence(UTF8.self, input: buffer)
}) as String?
{
self.init(str)
} else {
return nil
}
}
public convenience init(format: String, arguments argList: CVaListPointer) {
let str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)!
self.init(str._swiftObject)
}
public convenience init(format: String, locale: AnyObject?, arguments argList: CVaListPointer) {
let str: CFString
if let loc = locale {
if type(of: loc) === NSLocale.self || type(of: loc) === NSDictionary.self {
str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, unsafeBitCast(loc, to: CFDictionary.self), format._cfObject, argList)
} else {
fatalError("locale parameter must be a NSLocale or a NSDictionary")
}
} else {
str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)
}
self.init(str._swiftObject)
}
public convenience init(format: NSString, _ args: CVarArg...) {
let str = withVaList(args) { (vaPtr) -> CFString! in
CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, vaPtr)
}!
self.init(str._swiftObject)
}
public convenience init?(data: Data, encoding: UInt) {
if data.isEmpty {
self.init("")
} else {
guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer<UInt8>) -> CFString? in
return CFStringCreateWithBytes(kCFAllocatorDefault, bytes, data.count, CFStringConvertNSStringEncodingToEncoding(encoding), true)
}) else { return nil }
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
}
public convenience init?(bytes: UnsafeRawPointer, length len: Int, encoding: UInt) {
let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: len)
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else {
return nil
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
public convenience init?(bytesNoCopy bytes: UnsafeMutableRawPointer, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ {
// just copy for now since the internal storage will be a copy anyhow
self.init(bytes: bytes, length: len, encoding: encoding)
if freeBuffer { // dont take the hint
free(bytes)
}
}
public convenience init?(CString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) {
guard let cf = CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding)) else {
return nil
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
public convenience init(contentsOf url: URL, encoding enc: UInt) throws {
let readResult = try NSData(contentsOf: url, options: [])
let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity: readResult.length)
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc), true) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to create a string using the specified encoding."
])
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to bridge CFString to String."
])
}
}
public convenience init(contentsOfFile path: String, encoding enc: UInt) throws {
try self.init(contentsOf: URL(fileURLWithPath: path), encoding: enc)
}
public convenience init(contentsOf url: URL, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws {
let readResult = try NSData(contentsOf: url, options:[])
let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity:readResult.length)
if readResult.length >= 2 && bytePtr[0] == 254 && bytePtr[1] == 255 {
enc?.pointee = String.Encoding.utf16BigEndian.rawValue
}
else if readResult.length >= 2 && bytePtr[0] == 255 && bytePtr[1] == 254 {
enc?.pointee = String.Encoding.utf16LittleEndian.rawValue
}
else {
//Need to work on more conditions. This should be the default
enc?.pointee = String.Encoding.utf8.rawValue
}
guard let enc = enc, let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc.pointee), true) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to create a string using the specified encoding."
])
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to bridge CFString to String."
])
}
}
public convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws {
NSUnimplemented()
}
}
extension NSString : ExpressibleByStringLiteral { }
open class NSMutableString : NSString {
open func replaceCharacters(in range: NSRange, with aString: String) {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
let start = _storage.utf16.startIndex
let min = _storage.utf16.index(start, offsetBy: range.location).samePosition(in: _storage)!
let max = _storage.utf16.index(start, offsetBy: range.location + range.length).samePosition(in: _storage)!
_storage.replaceSubrange(min..<max, with: aString)
}
public required override init(characters: UnsafePointer<unichar>, length: Int) {
super.init(characters: characters, length: length)
}
public required init(capacity: Int) {
super.init(characters: [], length: 0)
}
public convenience required init?(coder aDecoder: NSCoder) {
guard let str = NSString(coder: aDecoder) else {
return nil
}
self.init(string: String._unconditionallyBridgeFromObjectiveC(str))
}
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required init(stringLiteral value: StaticString) {
if value.hasPointerRepresentation {
super.init(String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.utf8CodeUnitCount))))
} else {
var uintValue = value.unicodeScalar.value
super.init(String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1)))
}
}
public required init(string aString: String) {
super.init(aString)
}
internal func appendCharacters(_ characters: UnsafePointer<unichar>, length: Int) {
if type(of: self) == NSMutableString.self {
_storage.append(String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)))
} else {
replaceCharacters(in: NSMakeRange(self.length, 0), with: String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)))
}
}
internal func _cfAppendCString(_ characters: UnsafePointer<Int8>, length: Int) {
if type(of: self) == NSMutableString.self {
_storage.append(String(cString: characters))
}
}
}
extension NSMutableString {
public func insert(_ aString: String, at loc: Int) {
replaceCharacters(in: NSMakeRange(loc, 0), with: aString)
}
public func deleteCharacters(in range: NSRange) {
replaceCharacters(in: range, with: "")
}
public func append(_ aString: String) {
replaceCharacters(in: NSMakeRange(length, 0), with: aString)
}
public func setString(_ aString: String) {
replaceCharacters(in: NSMakeRange(0, length), with: aString)
}
internal func _replaceOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range searchRange: NSRange) -> Int {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSMatchingOptions = options.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
return regex.replaceMatches(in: self, options: matchingOptions, range: searchRange, withTemplate: replacement)
}
return 0
}
public func replaceOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> Int {
let backwards = options.contains(.backwards)
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Search range is out of bounds")
if options.contains(.regularExpression) {
return _replaceOccurrencesOfRegularExpressionPattern(target, withTemplate:replacement, options:options, range: searchRange)
}
if let findResults = CFStringCreateArrayWithFindResults(kCFAllocatorSystemDefault, _cfObject, target._cfObject, CFRange(searchRange), options._cfValue(true)) {
let numOccurrences = CFArrayGetCount(findResults)
for cnt in 0..<numOccurrences {
let rangePtr = CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1)
replaceCharacters(in: NSRange(rangePtr!.load(as: CFRange.self)), with: replacement)
}
return numOccurrences
} else {
return 0
}
}
public func applyTransform(_ transform: String, reverse: Bool, range: NSRange, updatedRange resultingRange: NSRangePointer?) -> Bool {
var cfRange = CFRangeMake(range.location, range.length)
return withUnsafeMutablePointer(to: &cfRange) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
if CFStringTransform(_cfMutableObject, rangep, transform._cfObject, reverse) {
resultingRange?.pointee.location = rangep.pointee.location
resultingRange?.pointee.length = rangep.pointee.length
return true
}
return false
}
}
}
extension String {
// this is only valid for the usage for CF since it expects the length to be in unicode characters instead of grapheme clusters "✌🏾".utf16.count = 3 and CFStringGetLength(CFSTR("✌🏾")) = 3 not 1 as it would be represented with grapheme clusters
internal var length: Int {
return utf16.count
}
}
extension NSString : _CFBridgeable, _SwiftBridgeable {
typealias SwiftType = String
internal var _cfObject: CFString { return unsafeBitCast(self, to: CFString.self) }
internal var _swiftObject: String { return String._unconditionallyBridgeFromObjectiveC(self) }
}
extension NSMutableString {
internal var _cfMutableObject: CFMutableString { return unsafeBitCast(self, to: CFMutableString.self) }
}
extension CFString : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSString
typealias SwiftType = String
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSString.self) }
internal var _swiftObject: String { return _nsObject._swiftObject }
}
extension String : _NSBridgeable, _CFBridgeable {
typealias NSType = NSString
typealias CFType = CFString
internal var _nsObject: NSType { return _bridgeToObjectiveC() }
internal var _cfObject: CFType { return _nsObject._cfObject }
}
#if !(os(OSX) || os(iOS))
extension String {
public func hasPrefix(_ prefix: String) -> Bool {
if prefix.isEmpty {
return true
}
let cfstring = self._cfObject
let range = CFRangeMake(0, CFStringGetLength(cfstring))
let opts = CFStringCompareFlags(
kCFCompareAnchored | kCFCompareNonliteral)
return CFStringFindWithOptions(cfstring, prefix._cfObject,
range, opts, nil)
}
public func hasSuffix(_ suffix: String) -> Bool {
if suffix.isEmpty {
return true
}
let cfstring = self._cfObject
let range = CFRangeMake(0, CFStringGetLength(cfstring))
let opts = CFStringCompareFlags(
kCFCompareAnchored | kCFCompareBackwards | kCFCompareNonliteral)
return CFStringFindWithOptions(cfstring, suffix._cfObject,
range, opts, nil)
}
}
#endif
extension NSString : _StructTypeBridgeable {
public typealias _StructType = String
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 6a63d02c03dc224222d14fd6f6d8f859 | 43.126632 | 274 | 0.637185 | 5.156522 | false | false | false | false |
AlesTsurko/DNMKit | DNM_iOS/DNM_iOS/TimeSignatureNode.swift | 1 | 1299 | //
// TimeSignatureNode.swift
// denm_view
//
// Created by James Bean on 10/6/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import QuartzCore
public class TimeSignatureNode: ViewNode {
public var height: CGFloat = 0
public var timeSignatures: [TimeSignature] = []
public init(height: CGFloat = 0) {
self.height = height
super.init()
layoutFlow_vertical = .Middle
}
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public override init(layer: AnyObject) { super.init(layer: layer) }
public func getTimeSignatureAtX(x: CGFloat) -> TimeSignature? {
for timeSignature in timeSignatures {
if timeSignature.position.x == x { return timeSignature }
}
return nil
}
public func addTimeSignature(timeSignature: TimeSignature) {
timeSignatures.append(timeSignature)
addNode(timeSignature)
}
public func addTimeSignatureWithNumerator(
numerator: Int, andDenominator denominator: Int, atX x: CGFloat
)
{
let timeSignature = TimeSignature(
numerator: numerator, denominator: denominator, x: x, top: 0, height: height
)
addTimeSignature(timeSignature)
}
}
| gpl-2.0 | b8dbccf97480f97285f0223dfc2ee85b | 27.217391 | 88 | 0.643297 | 4.635714 | false | false | false | false |
jesshmusic/MarkovAnalyzer | MarkovAnalyzer/ChordEntryViewController.swift | 1 | 5621 | //
// ChordEntryViewController.swift
// MarkovAnalyzer
//
// Created by Fupduck Central MBP on 5/21/15.
// Copyright (c) 2015 Existential Music. All rights reserved.
//
import Cocoa
import CoreMIDI
struct GlobalVariables {
static var totalChords = 0.0
static let debugMode = true
}
class ChordEntryViewController: NSViewController {
@IBOutlet weak var chordTableView: NSTableView!
@IBOutlet weak var chordEntryField: NSTextField!
@IBOutlet weak var addChordButton: NSButton!
@IBOutlet weak var removeChordButton: NSButton!
@IBOutlet var chordTransitionsTextView: NSTextView!
var markovChain = MarkovGraph()
let midiManager = MIDIManager.sharedInstance
var chords = [Chord]()
var currentKeySig: KeySignature = kCMajor
var chordTransitionsText = ""
// MARK: Current Chord variables
@IBOutlet weak var chordComboBox: NSComboBox!
@IBOutlet weak var romanNumeralComboBox: NSComboBox!
override func viewDidAppear() {
super.viewDidAppear()
// Attempt to start MIDI
self.midiManager.initMIDI()
if self.chords.count == 0 {
self.removeChordButton.enabled = false
}
self.currentKeySig = kCMajor
}
func submitChord(chord:Chord) {
self.markovChain.putChord(chord)
self.chords = self.markovChain.getChordProgression()
self.addChordToTable()
self.updateViews()
}
private func addChordToTable() {
let newRowIndex = self.chords.count - 1
self.chordTableView.insertRowsAtIndexes(NSIndexSet(index: newRowIndex), withAnimation: NSTableViewAnimationOptions.EffectGap)
// Scroll the table to the new chord
self.chordTableView.selectRowIndexes(NSIndexSet(index: newRowIndex), byExtendingSelection: false)
self.chordTableView.scrollRowToVisible(newRowIndex)
self.chordTableView.deselectRow(newRowIndex)
}
private func reloadChordTableCell(index: NSIndexSet) {
self.chordTableView.reloadDataForRowIndexes(index, columnIndexes: NSIndexSet(index: 0))
}
private func updateViews() {
self.chordTransitionsText = self.markovChain.displayChords()
self.chordTransitionsTextView.string = self.chordTransitionsText
// self.chordTransitionsTextView.string == self.markovChain.displayChords()
}
private func getTransitionDisplayStrings() -> String {
return self.markovChain.displayChords()
}
func checkChords(chord:String)->(exists:Bool, chordIndex:Int) {
for index in 0..<chords.count {
if chords[index].chordName == chord {
return (true, index)
}
}
return (false, -1)
}
func selectedChord() -> Chord? {
let selectedRow = self.chordTableView.selectedRow
if selectedRow >= 0 && selectedRow < self.chords.count {
return self.chords[selectedRow]
}
return nil
}
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "MIDIChordEntry" {
if let midiChordEntryCtrl = segue.destinationController as? MIDIChordEntryViewController {
midiChordEntryCtrl.chordEntryViewController = self
midiChordEntryCtrl.currentKeySig = self.currentKeySig
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension ChordEntryViewController {
@IBAction func editingChanged(sender: AnyObject) {
if self.chordEntryField.stringValue != "" {
self.addChordButton.enabled = true
}
}
@IBAction func addChord(sender: AnyObject) {
// let chordName = (self.chordEntryField.stringValue)
// self.submitChord(Chord(chordName: chordName))
// self.chordEntryField.stringValue = ""
// self.addChordButton.enabled = false
// self.removeChordButton.enabled = true
}
@IBAction func removeChord(sender: AnyObject) {
if let chord = self.selectedChord() {
self.markovChain.removeChord(chord, indexInProgression: self.chordTableView.selectedRow)
if let _ = self.selectedChord() {
self.chords.removeAtIndex(self.chordTableView.selectedRow)
self.chordTableView.removeRowsAtIndexes(NSIndexSet(index: self.chordTableView.selectedRow), withAnimation: NSTableViewAnimationOptions.SlideRight)
updateViews()
}
}
}
}
extension ChordEntryViewController: NSTableViewDataSource {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return self.chords.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
// 1
let cellView = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! ChordCellView
// 2
if tableColumn!.identifier == "ChordColumn" {
// 3
let chordDoc = self.chords[row]
cellView.chordNameTextField!.stringValue = chordDoc.chordName
cellView.romanNumberalTextField!.stringValue = chordDoc.romanNumeral
cellView.chordNumberTextField!.integerValue = row + 1
cellView.keySignatureTextField!.stringValue = chordDoc.keySig.keyName
return cellView
}
return cellView
}
}
// MARK: - NSTableViewDelegate
extension ChordEntryViewController: NSTableViewDelegate {
}
| mit | 3b403a76608921f88f171c909c5e9f57 | 31.491329 | 162 | 0.660381 | 5.027728 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Pods/DynamicTabBarController/DynamicTabBarController/UIView+AutoLayout.swift | 1 | 6960 | //
// UIView+AutoLayout.swift
// DynamicTabBarController
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 10/28/17.
//
import UIKit
extension UIView {
func fillSuperview() {
guard let superview = self.superview else { return }
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
leftAnchor.constraint(equalTo: superview.leftAnchor),
rightAnchor.constraint(equalTo: superview.rightAnchor),
topAnchor.constraint(equalTo: superview.topAnchor),
bottomAnchor.constraint(equalTo: superview.bottomAnchor)
])
}
@discardableResult
func addConstraints(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, edgeInsets: UIEdgeInsets = .zero, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
guard self.superview != nil else { return [] }
translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
if let top = top {
let constraint = topAnchor.constraint(equalTo: top, constant: edgeInsets.top)
constraint.identifier = "top"
constraints.append(constraint)
}
if let left = left {
let constraint = leftAnchor.constraint(equalTo: left, constant: edgeInsets.left)
constraint.identifier = "left"
constraints.append(constraint)
}
if let bottom = bottom {
let constraint = bottomAnchor.constraint(equalTo: bottom, constant: -edgeInsets.bottom)
constraint.identifier = "bottom"
constraints.append(constraint)
}
if let right = right {
let constraint = rightAnchor.constraint(equalTo: right, constant: -edgeInsets.right)
constraint.identifier = "right"
constraints.append(constraint)
}
if widthConstant > 0 {
let constraint = widthAnchor.constraint(equalToConstant: widthConstant)
constraint.identifier = "width"
constraints.append(constraint)
}
if heightConstant > 0 {
let constraint = heightAnchor.constraint(equalToConstant: heightConstant)
constraint.identifier = "height"
constraints.append(constraint)
}
NSLayoutConstraint.activate(constraints)
return constraints
}
func removeAllConstraints() {
constraints.forEach { removeConstraint($0) }
}
@discardableResult
func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, insets: UIEdgeInsets = .zero, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
return anchor(top, left: left, bottom: bottom, right: right, topConstant: insets.top, leftConstant: insets.left, bottomConstant: insets.bottom, rightConstant: insets.right, widthConstant: widthConstant, heightConstant: heightConstant)
}
@discardableResult
func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
let constraint = topAnchor.constraint(equalTo: top, constant: topConstant)
constraint.identifier = "top"
anchors.append(constraint)
}
if let left = left {
let constraint = leftAnchor.constraint(equalTo: left, constant: leftConstant)
constraint.identifier = "left"
anchors.append(constraint)
}
if let bottom = bottom {
let constraint = bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant)
constraint.identifier = "bottom"
anchors.append(constraint)
}
if let right = right {
let constraint = rightAnchor.constraint(equalTo: right, constant: -rightConstant)
constraint.identifier = "right"
anchors.append(constraint)
}
if widthConstant > 0 {
let constraint = widthAnchor.constraint(equalToConstant: widthConstant)
constraint.identifier = "width"
anchors.append(constraint)
}
if heightConstant > 0 {
let constraint = heightAnchor.constraint(equalToConstant: heightConstant)
constraint.identifier = "height"
anchors.append(constraint)
}
NSLayoutConstraint.activate(anchors)
return anchors
}
func anchorCenterXToSuperview(constant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerXAnchor {
NSLayoutConstraint.activate([centerXAnchor.constraint(equalTo: anchor, constant: constant)])
}
}
func anchorCenterYToSuperview(constant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerYAnchor {
NSLayoutConstraint.activate([centerYAnchor.constraint(equalTo: anchor, constant: constant)])
}
}
func anchorCenterSuperview() {
anchorCenterXToSuperview()
anchorCenterYToSuperview()
}
}
| mit | 4bf2352a402612f1a4dedab342c94a22 | 40.921687 | 348 | 0.654548 | 5.424006 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureActivity/Sources/FeatureActivityUI/Details/ERC20/ERC20ActivityDetailsPresenter.swift | 1 | 8665 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Combine
import DIKit
import Localization
import PlatformKit
import PlatformUIKit
import RxRelay
import RxSwift
import ToolKit
final class ERC20ActivityDetailsPresenter: DetailsScreenPresenterAPI {
// MARK: - Types
private typealias LocalizedString = LocalizationConstants.Activity.Details
private typealias AccessibilityId = Accessibility.Identifier.Activity.Details
// MARK: - DetailsScreenPresenterAPI
let buttons: [ButtonViewModel]
let cells: [DetailsScreen.CellType]
let titleViewRelay: BehaviorRelay<Screen.Style.TitleView> = .init(value: .none)
let navigationBarAppearance: DetailsScreen.NavigationBarAppearance = .defaultDark
let navigationBarLeadingButtonAction: DetailsScreen.BarButtonAction = .default
let navigationBarTrailingButtonAction: DetailsScreen.BarButtonAction = .default
let reloadRelay: PublishRelay<Void> = .init()
// MARK: - Private Properties
private let event: TransactionalActivityItemEvent
private let router: ActivityRouterAPI
private let interactor: ERC20ActivityDetailsInteractor
private let alertViewPresenter: AlertViewPresenterAPI
private let disposeBag = DisposeBag()
private var cancellables: Set<AnyCancellable> = []
// MARK: Private Properties (Model Relay)
private let itemRelay: BehaviorRelay<ERC20ActivityDetailsViewModel?> = .init(value: nil)
// MARK: Private Properties (LabelContentPresenting)
private let cryptoAmountLabelPresenter: LabelContentPresenting
// MARK: Private Properties (Badge)
private let badgesModel = MultiBadgeViewModel()
private let statusBadge: DefaultBadgeAssetPresenter = .init()
private let confirmingBadge: DefaultBadgeAssetPresenter = .init()
private let badgeCircleModel: BadgeCircleViewModel = .init()
// MARK: Private Properties (LineItemCellPresenting)
private let orderIDPresenter: LineItemCellPresenting
private let dateCreatedPresenter: LineItemCellPresenting
private let totalPresenter: LineItemCellPresenting
private let networkFeePresenter: LineItemCellPresenting
private let toPresenter: LineItemCellPresenting
private let fromPresenter: LineItemCellPresenting
// MARK: Private Properties (Explorer Button)
private let explorerButton: ButtonViewModel
init(
event: TransactionalActivityItemEvent,
router: ActivityRouterAPI,
interactor: ERC20ActivityDetailsInteractor,
alertViewPresenter: AlertViewPresenterAPI = resolve(),
analyticsRecorder: AnalyticsEventRecorderAPI = resolve()
) {
self.event = event
self.router = router
self.interactor = interactor
self.alertViewPresenter = alertViewPresenter
cryptoAmountLabelPresenter = DefaultLabelContentPresenter(
descriptors: .h1(accessibilityIdPrefix: AccessibilityId.cryptoAmountPrefix)
)
orderIDPresenter = TransactionalLineItem.orderId(event.identifier).defaultCopyablePresenter(
analyticsRecorder: analyticsRecorder,
accessibilityIdPrefix: AccessibilityId.lineItemPrefix
)
dateCreatedPresenter = TransactionalLineItem.date().defaultPresenter(
accessibilityIdPrefix: AccessibilityId.lineItemPrefix
)
totalPresenter = TransactionalLineItem.total().defaultPresenter(
accessibilityIdPrefix: AccessibilityId.lineItemPrefix
)
networkFeePresenter = TransactionalLineItem.networkFee().defaultPresenter(
accessibilityIdPrefix: AccessibilityId.lineItemPrefix
)
toPresenter = TransactionalLineItem.to().defaultCopyablePresenter(
analyticsRecorder: analyticsRecorder,
accessibilityIdPrefix: AccessibilityId.lineItemPrefix
)
fromPresenter = TransactionalLineItem.from().defaultCopyablePresenter(
analyticsRecorder: analyticsRecorder,
accessibilityIdPrefix: AccessibilityId.lineItemPrefix
)
cells = [
.label(cryptoAmountLabelPresenter),
.badges(badgesModel),
.separator,
.lineItem(orderIDPresenter),
.separator,
.lineItem(dateCreatedPresenter),
.separator,
.lineItem(totalPresenter),
.separator,
.lineItem(networkFeePresenter),
.separator,
.lineItem(toPresenter),
.separator,
.lineItem(fromPresenter)
]
explorerButton = .secondary(with: LocalizedString.Button.viewOnExplorer)
switch event.type {
case .receive:
buttons = []
case .send:
buttons = [explorerButton]
}
bindAll(event: event)
}
func viewDidLoad() {
interactor
.details(event: event)
.handleEvents(
receiveOutput: { [weak self] model in
self?.itemRelay.accept(model)
},
receiveCompletion: { [weak self] completion in
switch completion {
case .finished:
break
case .failure:
self?.alertViewPresenter.error(in: nil, action: nil)
}
}
)
.subscribe()
.store(in: &cancellables)
}
func bindAll(event: TransactionalActivityItemEvent) {
let title: String
switch event.type {
case .send:
title = LocalizedString.Title.send
case .receive:
title = LocalizedString.Title.receive
}
titleViewRelay.accept(.text(value: title))
itemRelay
.map { $0?.amounts.gasFor?.cryptoAmount }
.mapToLabelContentStateInteraction()
.bindAndCatch(to: cryptoAmountLabelPresenter.interactor.stateRelay)
.disposed(by: disposeBag)
itemRelay
.compactMap { $0?.confirmation.statusBadge }
.map { .loaded(next: $0) }
.bindAndCatch(to: statusBadge.interactor.stateRelay)
.disposed(by: disposeBag)
itemRelay
.compactMap { $0?.confirmation.factor }
.bindAndCatch(to: badgeCircleModel.fillRatioRelay)
.disposed(by: disposeBag)
itemRelay
.compactMap { $0?.confirmation.title }
.distinctUntilChanged()
.map(weak: self) { (self, confirmation) in
.loaded(next: .init(type: .progress(self.badgeCircleModel), description: confirmation))
}
.bindAndCatch(to: confirmingBadge.interactor.stateRelay)
.disposed(by: disposeBag)
itemRelay
.compactMap { $0?.confirmation.needConfirmation }
.distinctUntilChanged()
.map(weak: self) { (self, needConfirmation) in
needConfirmation ? [self.statusBadge, self.confirmingBadge] : [self.statusBadge]
}
.bindAndCatch(to: badgesModel.badgesRelay)
.disposed(by: disposeBag)
itemRelay
.map { $0?.dateCreated }
.mapToLabelContentStateInteraction()
.bindAndCatch(to: dateCreatedPresenter.interactor.description.stateRelay)
.disposed(by: disposeBag)
itemRelay
.map { $0?.amounts.gasFor?.value }
.mapToLabelContentStateInteraction()
.bindAndCatch(to: totalPresenter.interactor.description.stateRelay)
.disposed(by: disposeBag)
itemRelay
.map { $0?.fee }
.mapToLabelContentStateInteraction()
.bindAndCatch(to: networkFeePresenter.interactor.description.stateRelay)
.disposed(by: disposeBag)
itemRelay
.map { $0?.to }
.mapToLabelContentStateInteraction()
.bindAndCatch(to: toPresenter.interactor.description.stateRelay)
.disposed(by: disposeBag)
itemRelay
.map { $0?.from }
.mapToLabelContentStateInteraction()
.bindAndCatch(to: fromPresenter.interactor.description.stateRelay)
.disposed(by: disposeBag)
itemRelay
.distinctUntilChanged()
.mapToVoid()
.bindAndCatch(to: reloadRelay)
.disposed(by: disposeBag)
explorerButton
.tapRelay
.bind { [weak self] in
self?.router.showBlockchainExplorer(for: event)
}
.disposed(by: disposeBag)
}
}
| lgpl-3.0 | 7e836c09fdfce9918ef0e78749eb5748 | 33.245059 | 103 | 0.644737 | 5.838275 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Metadata/Sources/MetadataKit/Models/Entry/Payloads/AccountCredentialsEntryPayload.swift | 1 | 1006 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct AccountCredentialsEntryPayload: MetadataNodeEntry, Hashable {
public enum CodingKeys: String, CodingKey {
case nabuUserId = "nabu_user_id"
case nabuLifetimeToken = "nabu_lifetime_token"
case exchangeUserId = "exchange_user_id"
case exchangeLifetimeToken = "exchange_lifetime_token"
}
public static let type: EntryType = .accountCredentials
public let nabuUserId: String
public let nabuLifetimeToken: String
public let exchangeUserId: String?
public let exchangeLifetimeToken: String?
public init(
nabuUserId: String,
nabuLifetimeToken: String,
exchangeUserId: String?,
exchangeLifetimeToken: String?
) {
self.nabuUserId = nabuUserId
self.nabuLifetimeToken = nabuLifetimeToken
self.exchangeUserId = exchangeUserId
self.exchangeLifetimeToken = exchangeLifetimeToken
}
}
| lgpl-3.0 | 2bbd3a739c169ba14375875f1b698ee5 | 30.40625 | 75 | 0.706468 | 5 | false | false | false | false |
hmx101607/mhweibo | weibo/weibo/App/viewcontrollers/public/WBPublicViewController.swift | 1 | 6875 | //
// WBPublicViewController.swift
// weibo
//
// Created by mason on 2017/8/20.
// Copyright © 2017年 mason. All rights reserved.
//
import UIKit
class WBPublicViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var collectionView: WBChoicePictrueCollectionView!
@IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
fileprivate lazy var emoticonVc : EmoticonController = EmoticonController { (emoticon) in
self.insertEmoticonIntoTextView(emoticon: emoticon)
}
fileprivate func insertEmoticonIntoTextView(emoticon : Emoticon) {
if emoticon.isEmpty {
return
}
if emoticon.isRemove {
textView.deleteBackward()
return
}
if emoticon.emojiCode != nil {
let textRange = textView.selectedTextRange
textView.replace(textRange!, withText: emoticon.emojiCode!)
return
}
let attachemnt = WBEmojiTextAttachment()
attachemnt.chs = emoticon.chs
attachemnt.image = UIImage(contentsOfFile: emoticon.pngPath!)
let font = textView.font
attachemnt.bounds = CGRect(x: 0, y: -4, width: font!.lineHeight, height: font!.lineHeight)
let imageTextAttributed = NSAttributedString(attachment: attachemnt)
let originTextAttributed = NSMutableAttributedString(attributedString: textView.attributedText)
let seletedRange = textView.selectedRange
originTextAttributed.replaceCharacters(in: seletedRange, with: imageTextAttributed)
textView.attributedText = originTextAttributed
textView.font = font
textView.selectedRange = NSRange(location: seletedRange.location + 1, length: 0)
}
fileprivate lazy var images : [UIImage] = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
title = "发微博"
textView.delegate = self
setupNavigationBar()
addNotificationCenter()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardNotification(note:)), name: .UIKeyboardWillChangeFrame, object: nil)
}
@objc fileprivate func keyboardNotification(note : Notification) {
let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
let frame = [note.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect]
let originY = frame.first?.origin.y
toolbarBottomConstraint.constant = UIScreen.main.bounds.height - originY!
UIView.animate(withDuration: duration) {
self.view.layoutIfNeeded()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textView.becomeFirstResponder()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@IBAction func choicePictureAction(_ sender: UIButton) {
textView.resignFirstResponder()
collectionViewHeightConstraint.constant = UIScreen.main.bounds.height * 0.65
UIView.animate(withDuration: 0.25) {
self.view.layoutIfNeeded()
}
}
@IBAction func emojiAction(_ sender: UIButton) {
textView.resignFirstResponder()
textView.inputView = emoticonVc.view
textView.becomeFirstResponder()
}
@IBAction func showKeyboardAction(_ sender: UIButton) {
textView.resignFirstResponder()
textView.inputView = nil
textView.becomeFirstResponder()
}
}
extension WBPublicViewController {
fileprivate func setupNavigationBar (){
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeAction))
let rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(publicAction))
rightBarButtonItem.isEnabled = false
navigationItem.rightBarButtonItem = rightBarButtonItem
}
fileprivate func addNotificationCenter () {
NotificationCenter.default.addObserver(self, selector: #selector(addPicture), name: NSNotification.Name(rawValue: ADD_PICTURE_NOTIFICATION), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(removePicture(note:)), name: NSNotification.Name(rawValue: ROMOVE_PICTURE_NOTIFICATION), object: nil)
}
}
extension WBPublicViewController {
@objc fileprivate func closeAction () {
textView.resignFirstResponder()
dismiss(animated: true, completion: nil)
}
@objc fileprivate func publicAction () {
let resultAttributed = NSMutableAttributedString(attributedString: textView.attributedText)
let ranges = NSRange(location: 0, length: resultAttributed.length)
resultAttributed.enumerateAttributes(in: ranges, options: []) { (dict, range, _) in
if let textAttachment = dict["NSAttachment"] as? WBEmojiTextAttachment {
resultAttributed.replaceCharacters(in: range, with: textAttachment.chs!)
}
}
MLog(message: resultAttributed.string)
}
@objc fileprivate func addPicture () {
if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
return
}
let imagePickerVC = UIImagePickerController()
imagePickerVC.sourceType = .photoLibrary
imagePickerVC.delegate = self
present(imagePickerVC, animated: true, completion: nil)
}
@objc fileprivate func removePicture (note : Notification) {
guard let image = note.object as? UIImage else {
return
}
let index = images.index(of: image)
images.remove(at: index!)
collectionView.images = images
}
}
extension WBPublicViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
images.append(image)
collectionView.images = images
picker.dismiss(animated: true, completion: nil)
}
}
extension WBPublicViewController : UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
tipLabel.isHidden = textView.hasText
navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
}
}
| mit | db89eeeab402f1c75751e2982ab29dd0 | 32.783251 | 174 | 0.658064 | 5.681856 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Neon/Source/NeonAnchorable.swift | 4 | 8566 | //
// NeonAnchorable.swift
// Neon
//
// Created by Mike on 10/1/15.
// Copyright © 2015 Mike Amaral. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import Cocoa
#endif
public protocol Anchorable : Frameable {}
public extension Anchorable {
/// Fill the superview, with optional padding values.
///
/// - note: If you don't want padding, simply call `fillSuperview()` with no parameters.
///
/// - parameters:
/// - left: The padding between the left side of the view and the superview.
///
/// - right: The padding between the right side of the view and the superview.
///
/// - top: The padding between the top of the view and the superview.
///
/// - bottom: The padding between the bottom of the view and the superview.
///
public func fillSuperview(left: CGFloat = 0, right: CGFloat = 0, top: CGFloat = 0, bottom: CGFloat = 0) {
let width : CGFloat = superFrame.width - (left + right)
let height : CGFloat = superFrame.height - (top + bottom)
frame = CGRect(x: left, y: top, width: width, height: height)
}
/// Anchor a view in the center of its superview.
///
/// - parameters:
/// - width: The width of the view.
///
/// - height: The height of the view.
///
public func anchorInCenter(width: CGFloat, height: CGFloat) {
let xOrigin : CGFloat = (superFrame.width / 2.0) - (width / 2.0)
let yOrigin : CGFloat = (superFrame.height / 2.0) - (height / 2.0)
frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height)
if height == AutoHeight {
self.setDimensionAutomatically()
self.anchorInCenter(width: width, height: self.height)
}
if width == AutoWidth {
self.setDimensionAutomatically()
self.anchorInCenter(width: self.width, height: height)
}
}
/// Anchor a view in one of the four corners of its superview.
///
/// - parameters:
/// - corner: The `CornerType` value used to specify in which corner the view will be anchored.
///
/// - xPad: The *horizontal* padding applied to the view inside its superview, which can be applied
/// to the left or right side of the view, depending upon the `CornerType` specified.
///
/// - yPad: The *vertical* padding applied to the view inside its supeview, which will either be on
/// the top or bottom of the view, depending upon the `CornerType` specified.
///
/// - width: The width of the view.
///
/// - height: The height of the view.
///
public func anchorInCorner(_ corner: Corner, xPad: CGFloat, yPad: CGFloat, width: CGFloat, height: CGFloat) {
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
switch corner {
case .topLeft:
xOrigin = xPad
yOrigin = yPad
case .bottomLeft:
xOrigin = xPad
yOrigin = superFrame.height - height - yPad
case .topRight:
xOrigin = superFrame.width - width - xPad
yOrigin = yPad
case .bottomRight:
xOrigin = superFrame.width - width - xPad
yOrigin = superFrame.height - height - yPad
}
frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height)
if height == AutoHeight {
self.setDimensionAutomatically()
self.anchorInCorner(corner, xPad: xPad, yPad: yPad, width: width, height: self.height)
}
if width == AutoWidth {
self.setDimensionAutomatically()
self.anchorInCorner(corner, xPad: xPad, yPad: yPad, width: self.width, height: height)
}
}
/// Anchor a view in its superview, centered on a given edge.
///
/// - parameters:
/// - edge: The `Edge` used to specify which face of the superview the view
/// will be anchored against and centered relative to.
///
/// - padding: The padding applied to the view inside its superview. How this padding is applied
/// will vary depending on the `Edge` provided. Views centered against the top or bottom of
/// their superview will have the padding applied above or below them respectively, whereas views
/// centered against the left or right side of their superview will have the padding applied to the
/// right and left sides respectively.
///
/// - width: The width of the view.
///
/// - height: The height of the view.
///
public func anchorToEdge(_ edge: Edge, padding: CGFloat, width: CGFloat, height: CGFloat) {
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
switch edge {
case .top:
xOrigin = (superFrame.width / 2.0) - (width / 2.0)
yOrigin = padding
case .left:
xOrigin = padding
yOrigin = (superFrame.height / 2.0) - (height / 2.0)
case .bottom:
xOrigin = (superFrame.width / 2.0) - (width / 2.0)
yOrigin = superFrame.height - height - padding
case .right:
xOrigin = superFrame.width - width - padding
yOrigin = (superFrame.height / 2.0) - (height / 2.0)
}
frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height)
if height == AutoHeight {
self.setDimensionAutomatically()
self.anchorToEdge(edge, padding: padding, width: width, height: self.height)
}
if width == AutoWidth {
self.setDimensionAutomatically()
self.anchorToEdge(edge, padding: padding, width: self.width, height: height)
}
}
/// Anchor a view in its superview, centered on a given edge and filling either the width or
/// height of that edge. For example, views anchored to the `.Top` or `.Bottom` will have
/// their widths automatically sized to fill their superview, with the xPad applied to both
/// the left and right sides of the view.
///
/// - parameters:
/// - edge: The `Edge` used to specify which face of the superview the view
/// will be anchored against, centered relative to, and expanded to fill.
///
/// - xPad: The horizontal padding applied to the view inside its superview. If the `Edge`
/// specified is `.Top` or `.Bottom`, this padding will be applied to the left and right sides
/// of the view when it fills the width superview.
///
/// - yPad: The vertical padding applied to the view inside its superview. If the `Edge`
/// specified is `.Left` or `.Right`, this padding will be applied to the top and bottom sides
/// of the view when it fills the height of the superview.
///
/// - otherSize: The size parameter that is *not automatically calculated* based on the provided
/// edge. For example, views anchored to the `.Top` or `.Bottom` will have their widths automatically
/// calculated, so `otherSize` will be applied to their height, and subsequently views anchored to
/// the `.Left` and `.Right` will have `otherSize` applied to their width as their heights are
/// automatically calculated.
///
public func anchorAndFillEdge(_ edge: Edge, xPad: CGFloat, yPad: CGFloat, otherSize: CGFloat) {
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var width : CGFloat = 0.0
var height : CGFloat = 0.0
var autoSize : Bool = false
switch edge {
case .top:
xOrigin = xPad
yOrigin = yPad
width = superFrame.width - (2 * xPad)
height = otherSize
autoSize = true
case .left:
xOrigin = xPad
yOrigin = yPad
width = otherSize
height = superFrame.height - (2 * yPad)
case .bottom:
xOrigin = xPad
yOrigin = superFrame.height - otherSize - yPad
width = superFrame.width - (2 * xPad)
height = otherSize
autoSize = true
case .right:
xOrigin = superFrame.width - otherSize - xPad
yOrigin = yPad
width = otherSize
height = superFrame.height - (2 * yPad)
}
frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height)
if height == AutoHeight && autoSize {
self.setDimensionAutomatically()
self.anchorAndFillEdge(edge, xPad: xPad, yPad: yPad, otherSize: self.height)
}
}
}
| mit | 889b082ffbd2160c1013141b7fa2f659 | 35.602564 | 113 | 0.597898 | 4.498424 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/WMFLoginViewController.swift | 1 | 16781 | import UIKit
class WMFLoginViewController: WMFScrollViewController, UITextFieldDelegate, WMFCaptchaViewControllerDelegate, Themeable {
@IBOutlet fileprivate var usernameField: ThemeableTextField!
@IBOutlet fileprivate var passwordField: ThemeableTextField!
@IBOutlet fileprivate var usernameTitleLabel: UILabel!
@IBOutlet fileprivate var passwordTitleLabel: UILabel!
@IBOutlet fileprivate var passwordAlertLabel: UILabel!
@IBOutlet fileprivate var createAccountButton: WMFAuthLinkLabel!
@IBOutlet fileprivate var forgotPasswordButton: UILabel!
@IBOutlet fileprivate var titleLabel: UILabel!
@IBOutlet fileprivate var captchaContainer: UIView!
@IBOutlet fileprivate var loginButton: WMFAuthButton!
@IBOutlet weak var scrollContainer: UIView!
public var loginSuccessCompletion: (() -> Void)?
public var loginDismissedCompletion: (() -> Void)?
@objc public var funnel: WMFLoginFunnel?
private var startDate: Date? // to calculate time elapsed between login start and login success
fileprivate var theme: Theme = Theme.standard
fileprivate lazy var captchaViewController: WMFCaptchaViewController? = WMFCaptchaViewController.wmf_initialViewControllerFromClassStoryboard()
private let loginInfoFetcher = WMFAuthLoginInfoFetcher()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
startDate = Date()
}
@objc func closeButtonPushed(_ : UIBarButtonItem?) {
dismiss(animated: true, completion: nil)
loginDismissedCompletion?()
}
@IBAction fileprivate func loginButtonTapped(withSender sender: UIButton) {
save()
}
override func accessibilityPerformEscape() -> Bool {
closeButtonPushed(nil)
return true
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:)))
navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
loginButton.setTitle(WMFLocalizedString("main-menu-account-login", value:"Log in", comment:"Button text for logging in.\n{{Identical|Log in}}"), for: .normal)
createAccountButton.strings = WMFAuthLinkLabelStrings(dollarSignString: WMFLocalizedString("login-no-account", value:"Don't have an account? %1$@", comment:"Text for create account button. %1$@ is the message {{msg-wikimedia|login-account-join-wikipedia}}"), substitutionString: WMFLocalizedString("login-join-wikipedia", value:"Join Wikipedia.", comment:"Join Wikipedia text to be used as part of a create account button"))
createAccountButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(createAccountButtonPushed(_:))))
forgotPasswordButton.text = WMFLocalizedString("login-forgot-password", value:"Forgot your password?", comment:"Button text for loading the password reminder interface")
forgotPasswordButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(forgotPasswordButtonPushed(_:))))
usernameField.placeholder = WMFLocalizedString("field-username-placeholder", value:"enter username", comment:"Placeholder text shown inside username field until user taps on it")
passwordField.placeholder = WMFLocalizedString("field-password-placeholder", value:"enter password", comment:"Placeholder text shown inside password field until user taps on it")
titleLabel.text = WMFLocalizedString("login-title", value:"Log in to your account", comment:"Title for log in interface")
usernameTitleLabel.text = WMFLocalizedString("field-username-title", value:"Username", comment:"Title for username field\n{{Identical|Username}}")
passwordTitleLabel.text = WMFLocalizedString("field-password-title", value:"Password", comment:"Title for password field\n{{Identical|Password}}")
view.wmf_configureSubviewsForDynamicType()
captchaViewController?.captchaDelegate = self
wmf_add(childController:captchaViewController, andConstrainToEdgesOfContainerView: captchaContainer)
apply(theme: theme)
}
@IBAction func textFieldDidChange(_ sender: UITextField) {
enableProgressiveButtonIfNecessary()
}
fileprivate func enableProgressiveButtonIfNecessary() {
loginButton.isEnabled = shouldProgressiveButtonBeEnabled()
}
fileprivate func disableProgressiveButton() {
loginButton.isEnabled = false
}
fileprivate func shouldProgressiveButtonBeEnabled() -> Bool {
var shouldEnable = areRequiredFieldsPopulated()
if captchaIsVisible() && shouldEnable {
shouldEnable = hasUserEnteredCaptchaText()
}
return shouldEnable
}
fileprivate func hasUserEnteredCaptchaText() -> Bool {
guard let text = captchaViewController?.solution else {
return false
}
return !(text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)).isEmpty
}
fileprivate func requiredInputFields() -> [UITextField] {
assert(isViewLoaded, "This method is only intended to be called when view is loaded, since they'll all be nil otherwise")
return [usernameField, passwordField]
}
fileprivate func areRequiredFieldsPopulated() -> Bool {
return requiredInputFields().wmf_allFieldsFilled()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Check if captcha is required right away. Things could be configured so captcha is required at all times.
getCaptcha()
updatePasswordFieldReturnKeyType()
enableProgressiveButtonIfNecessary()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
usernameField.becomeFirstResponder()
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField {
case usernameField:
passwordField.becomeFirstResponder()
case passwordField:
if captchaIsVisible() {
captchaViewController?.captchaTextFieldBecomeFirstResponder()
}else{
save()
}
default:
assertionFailure("Unhandled text field")
}
return true
}
@IBAction func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == passwordField {
passwordAlertLabel.isHidden = true
passwordField.textColor = theme.colors.primaryText
passwordField.keyboardAppearance = theme.keyboardAppearance
}
}
fileprivate func save() {
wmf_hideKeyboard()
passwordAlertLabel.isHidden = true
setViewControllerUserInteraction(enabled: false)
disableProgressiveButton()
WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("account-creation-logging-in", value:"Logging in...", comment:"Alert shown after account successfully created and the user is being logged in automatically.\n{{Identical|Logging in}}"), sticky: true, canBeDismissedByUser: false, dismissPreviousAlerts: true, tapCallBack: nil)
guard let username = usernameField.text, let password = passwordField.text else {
assertionFailure("One or more of the required parameters are nil")
return
}
WMFAuthenticationManager.sharedInstance.login(username: username, password: password, retypePassword: nil, oathToken: nil, captchaID: captchaViewController?.captcha?.captchaID, captchaWord: captchaViewController?.solution) { (loginResult) in
switch loginResult {
case .success(_):
let loggedInMessage = String.localizedStringWithFormat(WMFLocalizedString("main-menu-account-title-logged-in", value:"Logged in as %1$@", comment:"Header text used when account is logged in. %1$@ will be replaced with current username."), self.usernameField.text ?? "")
WMFAlertManager.sharedInstance.showSuccessAlert(loggedInMessage, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil)
self.loginSuccessCompletion?()
self.setViewControllerUserInteraction(enabled: true)
self.dismiss(animated: true)
self.funnel?.logSuccess()
if let start = self.startDate {
LoginFunnel.shared.logSuccess(timeElapsed: fabs(start.timeIntervalSinceNow))
} else {
assertionFailure("startDate is nil; startDate is required to calculate timeElapsed")
}
case .failure(let error):
self.setViewControllerUserInteraction(enabled: true)
// Captcha's appear to be one-time, so always try to get a new one on failure.
self.getCaptcha()
if let error = error as? WMFAccountLoginError {
switch error {
case .temporaryPasswordNeedsChange:
self.showChangeTempPasswordViewController()
return
case .needsOathTokenFor2FA:
self.showTwoFactorViewController()
return
case .statusNotPass:
self.passwordField.text = nil
self.passwordField.becomeFirstResponder()
case .wrongPassword:
self.passwordAlertLabel.text = error.localizedDescription
self.passwordAlertLabel.isHidden = false
self.passwordField.textColor = self.theme.colors.error
self.passwordField.keyboardAppearance = self.theme.keyboardAppearance
self.funnel?.logError(error.localizedDescription)
WMFAlertManager.sharedInstance.dismissAlert()
return
default: break
}
}
self.enableProgressiveButtonIfNecessary()
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
self.funnel?.logError(error.localizedDescription)
default:
break
}
}
}
func showChangeTempPasswordViewController() {
guard let presenter = presentingViewController else {
return
}
dismiss(animated: true, completion: {
let changePasswordVC = WMFChangePasswordViewController.wmf_initialViewControllerFromClassStoryboard()
changePasswordVC?.userName = self.usernameField!.text
changePasswordVC?.apply(theme: self.theme)
let navigationController = WMFThemeableNavigationController(rootViewController: changePasswordVC!, theme: self.theme)
presenter.present(navigationController, animated: true, completion: nil)
})
}
func showTwoFactorViewController() {
guard
let presenter = presentingViewController,
let twoFactorViewController = WMFTwoFactorPasswordViewController.wmf_initialViewControllerFromClassStoryboard()
else {
assertionFailure("Expected view controller(s) not found")
return
}
dismiss(animated: true, completion: {
twoFactorViewController.userName = self.usernameField!.text
twoFactorViewController.password = self.passwordField!.text
twoFactorViewController.captchaID = self.captchaViewController?.captcha?.captchaID
twoFactorViewController.captchaWord = self.captchaViewController?.solution
twoFactorViewController.apply(theme: self.theme)
let navigationController = WMFThemeableNavigationController(rootViewController: twoFactorViewController, theme: self.theme)
presenter.present(navigationController, animated: true, completion: nil)
})
}
@objc func forgotPasswordButtonPushed(_ recognizer: UITapGestureRecognizer) {
guard
recognizer.state == .ended,
let presenter = presentingViewController,
let forgotPasswordVC = WMFForgotPasswordViewController.wmf_initialViewControllerFromClassStoryboard()
else {
assertionFailure("Expected view controller(s) not found")
return
}
dismiss(animated: true, completion: {
let navigationController = WMFThemeableNavigationController(rootViewController: forgotPasswordVC, theme: self.theme)
forgotPasswordVC.apply(theme: self.theme)
presenter.present(navigationController, animated: true, completion: nil)
})
}
@objc func createAccountButtonPushed(_ recognizer: UITapGestureRecognizer) {
guard
recognizer.state == .ended,
let presenter = presentingViewController,
let createAcctVC = WMFAccountCreationViewController.wmf_initialViewControllerFromClassStoryboard()
else {
assertionFailure("Expected view controller(s) not found")
return
}
createAcctVC.apply(theme: theme)
funnel?.logCreateAccountAttempt()
LoginFunnel.shared.logCreateAccountAttempt()
dismiss(animated: true, completion: {
createAcctVC.funnel = CreateAccountFunnel()
createAcctVC.funnel?.logStart(fromLogin: self.funnel?.loginSessionToken)
let navigationController = WMFThemeableNavigationController(rootViewController: createAcctVC, theme: self.theme)
presenter.present(navigationController, animated: true, completion: nil)
})
}
fileprivate func getCaptcha() {
let captchaFailure: WMFErrorHandler = {error in
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
self.funnel?.logError(error.localizedDescription)
}
let siteURL = MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL()
loginInfoFetcher.fetchLoginInfoForSiteURL(siteURL!, success: { info in
DispatchQueue.main.async {
self.captchaViewController?.captcha = info.captcha
self.updatePasswordFieldReturnKeyType()
self.enableProgressiveButtonIfNecessary()
}
}, failure: captchaFailure)
}
func captchaReloadPushed(_ sender: AnyObject) {
enableProgressiveButtonIfNecessary()
}
func captchaSolutionChanged(_ sender: AnyObject, solutionText: String?) {
enableProgressiveButtonIfNecessary()
}
public func captchaSiteURL() -> URL {
return (MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL())!
}
func captchaKeyboardReturnKeyTapped() {
save()
}
public func captchaHideSubtitle() -> Bool {
return true
}
fileprivate func captchaIsVisible() -> Bool {
return captchaViewController?.captcha != nil
}
fileprivate func updatePasswordFieldReturnKeyType() {
passwordField.returnKeyType = captchaIsVisible() ? .next : .done
// Resign and become first responder so keyboard return key updates right away.
if passwordField.isFirstResponder {
passwordField.resignFirstResponder()
passwordField.becomeFirstResponder()
}
}
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
view.tintColor = theme.colors.link
titleLabel.textColor = theme.colors.primaryText
let labels = [usernameTitleLabel, passwordTitleLabel, passwordAlertLabel]
for label in labels {
label?.textColor = theme.colors.secondaryText
}
usernameField.apply(theme: theme)
passwordField.apply(theme: theme)
titleLabel.textColor = theme.colors.primaryText
forgotPasswordButton.textColor = theme.colors.link
captchaContainer.backgroundColor = theme.colors.baseBackground
createAccountButton.apply(theme: theme)
loginButton.apply(theme: theme)
passwordAlertLabel.textColor = theme.colors.error
scrollContainer.backgroundColor = theme.colors.paperBackground
captchaViewController?.apply(theme: theme)
}
}
| mit | b80ed814a3ff9d450fe5f130b535fc72 | 45.484765 | 432 | 0.675228 | 6.137893 | false | false | false | false |
ashleybrgr/surfPlay | surfPlay/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationSquareSpin.swift | 12 | 3524 | //
// NVActivityIndicatorAnimationSquareSpin.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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
class NVActivityIndicatorAnimationSquareSpin: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let duration: CFTimeInterval = 3
let timingFunction = CAMediaTimingFunction(controlPoints: 0.09, 0.57, 0.49, 0.9)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.keyTimes = [0, 0.25, 0.5, 0.75, 1]
animation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction]
animation.values = [
NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: 0), createRotateYTransform(angle: 0))),
NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: CGFloat(Double.pi)), createRotateYTransform(angle: 0))),
NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: CGFloat(Double.pi)), createRotateYTransform(angle: CGFloat(Double.pi)))),
NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: 0), createRotateYTransform(angle: CGFloat(Double.pi)))),
NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: 0), createRotateYTransform(angle: 0))),
]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw square
let square = NVActivityIndicatorShape.rectangle.layerWith(size: size, color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
square.frame = frame
square.add(animation, forKey: "animation")
layer.addSublayer(square)
}
func createRotateXTransform(angle: CGFloat) -> CATransform3D {
var transform = CATransform3DMakeRotation(angle, 1, 0, 0)
transform.m34 = CGFloat(-1) / 100
return transform
}
func createRotateYTransform(angle: CGFloat) -> CATransform3D {
var transform = CATransform3DMakeRotation(angle, 0, 1, 0)
transform.m34 = CGFloat(-1) / 100
return transform
}
}
| apache-2.0 | 878a0d5fd6994e69af7a7996eec279e9 | 43.607595 | 158 | 0.705732 | 4.781547 | false | false | false | false |
rhcad/ShapeAnimation-Swift | ShapeAnimation/View/CALayer+ID.swift | 3 | 1182 | //
// CALayer+ID.swift
// ShapeAnimation
//
// Created by Zhang Yungui on 15/2/4.
// Copyright (c) 2015 github.com/rhcad. All rights reserved.
//
import SwiftGraphics
import SwiftUtilities
private var LayerIDKey = 13
public extension CALayer {
public var identifier: String? {
get {
return getAssociatedObject(self, key: &LayerIDKey) as? String
}
set {
if newValue != identifier {
setAssociatedObject(self, key: &LayerIDKey, value: newValue!)
}
}
}
public func layerWithIdentifier(identifier:String) -> CALayer? {
var ret:CALayer?
enumerateLayers { layer in
if let lid = layer.identifier {
if lid == identifier {
ret = layer
}
}
}
return ret
}
public func layerWithIdentifier(identifier:String, layer:CALayer) -> CALayer? {
return layer.layerWithIdentifier(identifier)
}
}
public extension ShapeView {
public func layerWithIdentifier(identifier:String) -> CALayer? {
return sublayer.layerWithIdentifier(identifier)
}
}
| bsd-2-clause | 166dabadc60106556ad2d8070bd03b76 | 23.625 | 83 | 0.589679 | 4.671937 | false | false | false | false |
inamiy/VTree | Sources/Gesture+Ext.swift | 1 | 2129 | #if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
// MARK: UIView + GestureEvent
extension VTreePrefix where Base: View
{
internal typealias Gestures = [GestureEvent<AnyMsg>: GestureRecognizer]
internal typealias GestureTargets = [GestureEvent<AnyMsg>: CocoaTarget<GestureRecognizer>]
/// Indexed gestures storage.
internal var gestures: MutableBox<Gestures>
{
return self.associatedValue { _ in MutableBox<Gestures>([:]) }
}
/// `CocoaTarget` storage that has a reference type.
internal var gestureTargets: MutableBox<GestureTargets>
{
return self.associatedValue { _ in MutableBox<GestureTargets>([:]) }
}
internal func addGesture<Msg: Message>(for gestureEvent: GestureEvent<Msg>, handler: @escaping (Msg) -> ())
{
let anyMsgGestureEvent = gestureEvent.map(AnyMsg.init)
guard self.gestureTargets.value[anyMsgGestureEvent] == nil else {
return
}
let gestureHandler: (GestureRecognizer) -> () = { gesture in
let msg = gestureEvent._createMessage(from: gesture)
handler(msg)
}
let target = CocoaTarget<GestureRecognizer>(gestureHandler) { $0 as! GestureRecognizer }
let gesture = gestureEvent._createGesture()
#if os(iOS) || os(tvOS)
gesture.addTarget(target, action: #selector(target.sendNext))
#elseif os(macOS)
gesture.target = target
gesture.action = #selector(target.sendNext)
#endif
self.base.addGestureRecognizer(gesture)
self.gestures.value[anyMsgGestureEvent] = gesture
self.gestureTargets.value[anyMsgGestureEvent] = target
}
internal func removeGesture<Msg: Message>(for gestureEvent: GestureEvent<Msg>)
{
let anyMsgGestureEvent = gestureEvent.map(AnyMsg.init)
if let gesture = self.gestures.value[anyMsgGestureEvent] {
self.base.removeGestureRecognizer(gesture)
self.gestures.value[anyMsgGestureEvent] = nil
self.gestureTargets.value[anyMsgGestureEvent] = nil
}
}
}
| mit | b337d931bfd7963efa7539b73158fe4c | 31.753846 | 111 | 0.663222 | 4.710177 | false | false | false | false |
irreverentbits/IBAttributedString | Sources/IBAttributedString/NSAttributedString+IBParagraphStyle.swift | 1 | 2522 | // Copyright © 2017 Irreverent Bits. 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.
import Foundation
extension NSMutableAttributedString {
/// Convenience function for applying paragraph styling to the paragraphs that fall
/// in a given character range of the string.
/// - Note: This function does not clear all previous styles before applying the provided styles.
/// New styles are added and styles pre-existing on the paragraph are only changed if a new
/// value for the style is provided.
///
/// - Parameters:
/// - styles: An array of IBParagraphStyle enums that describe the styles to apply.
/// - onRange: The character range within the paragraphs on which the styles should be applied.
public func styleParagraphs(with styles: [IBParagraphStyle], onRange: NSRange? = nil) {
let range = onRange ?? NSRange(location: 0, length: self.length)
paragraphStyles(on: range).forEach { (arg) in
let (style, range) = arg
let newStyle = IBParagraphStyle.paragraphStyle(for: styles, overwriting: style)
addAttribute(NSAttributedString.Key.paragraphStyle, value: newStyle, range: range)
}
}
/// Convenience function for applying paragraph styling to the paragraph at the provided paragraph index in the string.
/// - Note: This function does not clear all previous styles before applying the provided styles.
/// New styles are added and styles pre-existing on the paragraph are only changed if a new
/// value for the style is provided.
///
/// - Parameters:
/// - styles: An array of IBParagraphStyle enums that describe the styles to apply to the single paragraph.
/// - index: The paragraph index (zero based) of the paragraph to which the styling should be applied.
public func styleParagraph(with styles: [IBParagraphStyle], at index: Int) {
let ranges = paragraphRanges()
guard ranges.count > 0, index >= 0, index < ranges.count else {
return
}
styleParagraphs(with: styles, onRange: ranges[index])
}
}
| apache-2.0 | 777d7a5ed844afa9bb0fe60e2f583a67 | 44.836364 | 120 | 0.734629 | 4.166942 | false | false | false | false |
VernonVan/SmartClass | SmartClass/Home Page/View/HomePageViewController.swift | 1 | 4221 | //
// HomePageViewController.swift
// SmartClass
//
// Created by Vernon on 16/7/25.
// Copyright © 2016年 Vernon. All rights reserved.
//
import UIKit
import RealmSwift
class HomePageViewController: UIViewController
{
@IBOutlet weak var paperCardView: CardView!
@IBOutlet weak var resourceCardView: CardView!
@IBOutlet weak var studentCardView: CardView!
@IBOutlet weak var quizCardView: CardView!
@IBOutlet weak var signUpSheetCardView: CardView!
let realm = try! Realm()
override func viewDidLoad()
{
super.viewDidLoad()
// print("Realm file path: \(Realm.Configuration.defaultConfiguration.fileURL!)")
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
refreshCardViewBadgeNumber()
}
func refreshCardViewBadgeNumber()
{
DispatchQueue.global(qos: .default).async {
let signUpSheetPath = ConvenientFileManager.signUpSheetURL.path
let pptPath = ConvenientFileManager.pptURL.path
let resourcePath = ConvenientFileManager.resourceURL.path
var resourceCount = 0, signUpSheetCount = 0
do {
let pptCount = try FileManager.default.contentsOfDirectory(atPath: pptPath).filter({ (fileName) -> Bool in
let url = ConvenientFileManager.pptURL.appendingPathComponent(fileName)
return url.pathExtension.contains("ppt")
}).count
let otherCount = try FileManager.default.contentsOfDirectory(atPath: resourcePath).count
resourceCount = pptCount + otherCount
signUpSheetCount = try FileManager.default.contentsOfDirectory(atPath: signUpSheetPath).count
} catch let error as NSError {
print("HomePageViewController refreshCardViewBadgeNumber error: \(error.localizedDescription)")
}
DispatchQueue.main.async(execute: {
self.paperCardView.number = self.realm.objects(Paper.self).count
self.resourceCardView.number = resourceCount
self.studentCardView.number = self.realm.objects(Student.self).count
self.quizCardView.number = self.realm.objects(Quiz.self).filter("date > %@", Date.today).count
self.signUpSheetCardView.number = signUpSheetCount
})
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
super.prepare(for: segue, sender: sender)
if segue.identifier == "showPaperList" {
if let desVC = segue.destination as? PaperListViewController {
let paperListViewModel = PaperListViewModel()
desVC.viewModel = paperListViewModel
}
} else if segue.identifier == "showResourceList" {
if let desVC = segue.destination as? ResourceListViewController {
let viewModel = ResourceListViewModel()
desVC.viewModel = viewModel
}
} else if segue.identifier == "StudentList" {
if let desVC = segue.destination as? StudentListViewController {
desVC.viewModel = StudentListViewModel()
}
} else if segue.identifier == "StudentQuiz" {
if let desVC = segue.destination as? QuizListViewController {
let today = Date.today
let tomorrow = Date.tomorrow
desVC.fromDate = today
desVC.toDate = tomorrow
}
} else if segue.identifier == "SignUpSheetList" {
if let desVC = segue.destination as? SignUpSheetListViewController {
desVC.viewModel = SignUpSheetListViewModel()
}
} else if segue.identifier == "showQRCode" {
if let desVC = segue.destination as? QRCodeViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
desVC.url = appDelegate.webUploaderURL
}
}
navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
}
}
| mit | 862ad9bf9b315d4debb651ccabe653b9 | 39.557692 | 122 | 0.622096 | 5.400768 | false | false | false | false |
mbernson/HomeControl.iOS | Pods/Promissum/src/Promissum/Combinators.swift | 1 | 4912 | //
// Combinators.swift
// Promissum
//
// Created by Tom Lokhorst on 2014-10-11.
// Copyright (c) 2014 Tom Lokhorst. All rights reserved.
//
import Foundation
/// Flattens a nested Promise of Promise into a single Promise.
///
/// The returned Promise resolves (or rejects) when the nested Promise resolves.
public func flatten<Value, Error>(_ promise: Promise<Promise<Value, Error>, Error>) -> Promise<Value, Error> {
return promise.flatMap { $0 }
}
/// Creates a Promise that resolves when both arguments resolve.
///
/// The new Promise's value is of a tuple type constructed from both argument promises.
///
/// If either of the two Promises fails, the returned Promise also fails.
public func whenBoth<A, B, Error>(_ promiseA: Promise<A, Error>, _ promiseB: Promise<B, Error>) -> Promise<(A, B), Error> {
let source = PromiseSource<(A, B), Error>()
promiseA.trap(source.reject)
promiseB.trap(source.reject)
promiseA.then { valueA in
promiseB.then { valueB in
source.resolve((valueA, valueB))
}
}
return source.promise
}
/// Creates a Promise that resolves when all of the provided Promises are resolved.
///
/// The new Promise's value is an array of all resolved values.
/// If any of the supplied Promises fails, the returned Promise immediately fails.
///
/// When called with an empty array of promises, this returns a Resolved Promise (with an empty array value).
public func whenAll<Value, Error>(_ promises: [Promise<Value, Error>]) -> Promise<[Value], Error> {
let source = PromiseSource<[Value], Error>()
var results = promises.map { $0.value }
var remaining = promises.count
if remaining == 0 {
source.resolve([])
}
for (ix, promise) in promises.enumerated() {
promise
.then { value in
results[ix] = value
remaining = remaining - 1
if remaining == 0 {
source.resolve(results.map { $0! })
}
}
promise
.trap { error in
source.reject(error)
}
}
return source.promise
}
/// Creates a Promise that resolves when either argument resolves.
///
/// The new Promise's value is the value of the first promise to resolve.
/// If both argument Promises are already Resolved, the first Promise's value is used.
///
/// If both Promises fail, the returned Promise also fails.
public func whenEither<Value, Error>(_ promise1: Promise<Value, Error>, _ promise2: Promise<Value, Error>) -> Promise<Value, Error> {
return whenAny([promise1, promise2])
}
/// Creates a Promise that resolves when any of the argument Promises resolves.
///
/// If all of the supplied Promises fail, the returned Promise fails.
///
/// When called with an empty array of promises, this returns a Promise that will never resolve.
public func whenAny<Value, Error>(_ promises: [Promise<Value, Error>]) -> Promise<Value, Error> {
let source = PromiseSource<Value, Error>()
var remaining = promises.count
for promise in promises {
promise
.then { value in
source.resolve(value)
}
promise
.trap { error in
remaining = remaining - 1
if remaining == 0 {
source.reject(error)
}
}
}
return source.promise
}
/// Creates a Promise that resolves when all provided Promises finalize.
///
/// When called with an empty array of promises, this returns a Resolved Promise.
public func whenAllFinalized<Value, Error>(_ promises: [Promise<Value, Error>]) -> Promise<Void, NoError> {
let source = PromiseSource<Void, NoError>()
var remaining = promises.count
if remaining == 0 {
source.resolve()
}
for promise in promises {
promise
.finally {
remaining = remaining - 1
if remaining == 0 {
source.resolve()
}
}
}
return source.promise
}
/// Creates a Promise that resolves when any of the provided Promises finalize.
///
/// When called with an empty array of promises, this returns a Promise that will never resolve.
public func whenAnyFinalized<Value, Error>(_ promises: [Promise<Value, Error>]) -> Promise<Void, NoError> {
let source = PromiseSource<Void, NoError>()
for promise in promises {
promise
.finally {
source.resolve()
}
}
return source.promise
}
extension Promise {
/// Returns a Promise where the value information is thrown away.
public func mapVoid() -> Promise<Void, Error> {
return self.map { _ in }
}
@available(*, unavailable, renamed: "mapVoid")
public func void() -> Promise<Void, Error> {
fatalError()
}
}
extension Promise where Error : Swift.Error {
/// Returns a Promise where the error is casted to an ErrorType.
public func mapError() -> Promise<Value, Swift.Error> {
return self.mapError { $0 }
}
@available(*, unavailable, renamed: "mapError")
public func mapErrorType() -> Promise<Value, Swift.Error> {
fatalError()
}
}
| mit | db51bd159bf071f55172f3376f29e7e3 | 25.551351 | 133 | 0.667345 | 4.145148 | false | false | false | false |
7Plum/PlumKit | PlumKit/UIKit/UIView+PlumKit.swift | 1 | 2078 | //
// UIView+PlumKit.swift
// PlumKit
//
// Created by Kingiol on 15/12/8.
// Copyright © 2015年 Kingiol. All rights reserved.
//
import Foundation
// MARK: - irregular rounding Corners
private let viewLayerBoundsContext = UnsafeMutablePointer<()>()
private let viewBorderLayerName = "PlumKitViewBorderCornerLayer"
public extension UIView {
/**
Set UIView roundingCorner and border with and borderColor
*/
public func roundingCorners(corners: UIRectCorner, cornerRai: CGFloat, borderWidth: CGFloat = 0.0, borderColor: UIColor = UIColor.clearColor()) {
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: cornerRai, height: cornerRai))
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.CGPath
layer.mask = maskLayer
// layer.addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions(rawValue: 0), context: viewLayerBoundsContext)
layer.sublayers?.filter { $0.name == viewBorderLayerName }.forEach { $0.removeFromSuperlayer() }
if borderWidth > 0.0 {
let borderLayer = CAShapeLayer()
borderLayer.name = viewBorderLayerName
borderLayer.frame = bounds
borderLayer.path = maskPath.CGPath
borderLayer.lineWidth = borderWidth
borderLayer.strokeColor = borderColor.CGColor
borderLayer.fillColor = UIColor.clearColor().CGColor
layer.addSublayer(borderLayer)
}
}
// public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//
// if context == viewLayerBoundsContext && keyPath == "bounds" {
// print("this should call roundingCorner func")
// }else {
// super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
// }
//
// }
} | mit | 30273a8e8d16e132a45fd3c7a9c42bab | 36.071429 | 166 | 0.654458 | 4.964115 | false | false | false | false |
mattrubin/Bases | Sources/Base32/BlockEncoding.swift | 1 | 4135 | //
// BlockEncoding.swift
// Bases
//
// Copyright (c) 2016-2019 Matt Rubin and the Bases authors
//
// 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.
//
internal typealias EncodedBlock = (EncodedChar, EncodedChar, EncodedChar, EncodedChar, EncodedChar,
EncodedChar, EncodedChar, EncodedChar)
internal func encodeBlock(bytes: UnsafeRawBufferPointer) -> EncodedBlock {
switch bytes.count {
case 1:
return encodeBlock(bytes[0])
case 2:
return encodeBlock(bytes[0], bytes[1])
case 3:
return encodeBlock(bytes[0], bytes[1], bytes[2])
case 4:
return encodeBlock(bytes[0], bytes[1], bytes[2], bytes[3])
case 5:
return encodeBlock(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4])
default:
fatalError("Cannot encode \(bytes.count) bytes. Max block size is five.")
}
}
private func encodeBlock(_ b0: Byte, _ b1: Byte, _ b2: Byte, _ b3: Byte, _ b4: Byte) -> EncodedBlock {
let q = quintetsFromBytes(b0, b1, b2, b3, b4)
let c0 = character(encoding: q.0)
let c1 = character(encoding: q.1)
let c2 = character(encoding: q.2)
let c3 = character(encoding: q.3)
let c4 = character(encoding: q.4)
let c5 = character(encoding: q.5)
let c6 = character(encoding: q.6)
let c7 = character(encoding: q.7)
return (c0, c1, c2, c3, c4, c5, c6, c7)
}
private func encodeBlock(_ b0: Byte, _ b1: Byte, _ b2: Byte, _ b3: Byte) -> EncodedBlock {
let q = quintetsFromBytes(b0, b1, b2, b3)
let c0 = character(encoding: q.0)
let c1 = character(encoding: q.1)
let c2 = character(encoding: q.2)
let c3 = character(encoding: q.3)
let c4 = character(encoding: q.4)
let c5 = character(encoding: q.5)
let c6 = character(encoding: q.6)
let c7 = paddingCharacter
return (c0, c1, c2, c3, c4, c5, c6, c7)
}
private func encodeBlock(_ b0: Byte, _ b1: Byte, _ b2: Byte) -> EncodedBlock {
let q = quintetsFromBytes(b0, b1, b2)
let c0 = character(encoding: q.0)
let c1 = character(encoding: q.1)
let c2 = character(encoding: q.2)
let c3 = character(encoding: q.3)
let c4 = character(encoding: q.4)
let c5 = paddingCharacter
let c6 = paddingCharacter
let c7 = paddingCharacter
return (c0, c1, c2, c3, c4, c5, c6, c7)
}
private func encodeBlock(_ b0: Byte, _ b1: Byte) -> EncodedBlock {
let q = quintetsFromBytes(b0, b1)
let c0 = character(encoding: q.0)
let c1 = character(encoding: q.1)
let c2 = character(encoding: q.2)
let c3 = character(encoding: q.3)
let c4 = paddingCharacter
let c5 = paddingCharacter
let c6 = paddingCharacter
let c7 = paddingCharacter
return (c0, c1, c2, c3, c4, c5, c6, c7)
}
private func encodeBlock(_ b0: Byte) -> EncodedBlock {
let q = quintetsFromBytes(b0)
let c0 = character(encoding: q.0)
let c1 = character(encoding: q.1)
let c2 = paddingCharacter
let c3 = paddingCharacter
let c4 = paddingCharacter
let c5 = paddingCharacter
let c6 = paddingCharacter
let c7 = paddingCharacter
return (c0, c1, c2, c3, c4, c5, c6, c7)
}
| mit | a916e6462fedd94386c7c6ed51278055 | 36.93578 | 102 | 0.670859 | 3.372757 | false | false | false | false |
wadevanne/UuusKit | UuusKit/Foundation/UuusStringsAndText_.swift | 1 | 1664 | //
// UuusStringsAndText_.swift
// Example
//
// Created by 范炜佳 on 19/10/2017.
// Copyright © 2017 com.uuus. All rights reserved.
//
import UIKit
extension NSAttributedString {
// MARK: - Public - Functions
public func numberOfLines(bounded: CGFloat = CGFloat(UInt8.min)) -> Int {
let emptyString = NSAttributedString(string: .empty)
let eachHeight = emptyString.upright(boundedAclinic: bounded)
let wholeHeight = upright(boundedAclinic: bounded)
return Int((wholeHeight / eachHeight).rounded(.up))
}
/// ________________
/// ┃ ┃
/// ┃________________┃ boundedUpright
/// aclinic
public func aclinic(boundedUpright: CGFloat = CGFloat(UInt8.min)) -> CGFloat {
return float(boundedUpright, isBoundedVertical: true)
}
/// ________________
/// : : upright
/// :________________:
/// boundedAclinic
public func upright(boundedAclinic: CGFloat = CGFloat(UInt8.min)) -> CGFloat {
return float(boundedAclinic, isBoundedVertical: false)
}
// MARK: - Private - Functions
private func float(_ float: CGFloat, isBoundedVertical: Bool) -> CGFloat {
let height = isBoundedVertical ? float : CGFloat.greatestFiniteMagnitude
let width = !isBoundedVertical ? float : CGFloat.greatestFiniteMagnitude
let size = CGSize(width: width, height: height)
let options = NSStringDrawingOptions.usesLineFragmentOrigin
let rect = boundingRect(with: size, options: options, context: nil)
return isBoundedVertical ? rect.width : rect.height
}
}
| mit | 5217a9a8f9d20e848ebdead0bcb5af44 | 34.085106 | 82 | 0.613099 | 4.505464 | false | false | false | false |
EasySwift/EasySwift | EasySwift_iOS/Core/String+YXJ.swift | 2 | 5577 | //
// String+YXJ.swift
// TSLSmartHome
//
// Created by yuanxiaojun on 16/3/25.
// Copyright © 2016年 特斯联. All rights reserved.
//
import UIKit
//#define IS_SCREEN_35_INCH ([UIScreen mainScreen].bounds.size.height == 480) ? YES : NO
//#define IS_SCREEN_4_INCH ([UIScreen mainScreen].bounds.size.height == 568) ? YES : NO
//#define IS_SCREEN_47_INCH ([UIScreen mainScreen].bounds.size.height == 667) ? YES : NO
//#define IS_SCREEN_55_INCH ([UIScreen mainScreen].bounds.size.height == 736) ? YES : NO
extension String {
// MARK:获取字符串的长度
public var length: Int {
let temp = (self as NSString).length
return temp
}
// MARK:字符串的截取
/**
swift3的方式截取
- parameter start: 开始位置
- parameter end: 结束位置
- returns: 截取后的string字符串
*/
public func substringWithRange(_ start: Int, end: Int) -> String {
let rage: Range<String.Index> = self.characters.index(self.startIndex, offsetBy: start) ..< self.characters.index(self.endIndex, offsetBy: end)
// let rage = start..<end
let str = self.substring(with: rage)
return str
}
/**
oc的方式截取字符串
- parameter start: 开始位置
- parameter length: 截取的长度
- returns: 截取后的string字符串
*/
public func substringWithRange(_ start: Int, length: Int) -> String {
let asNSString = self as NSString
let temp = asNSString.substring(with: NSRange(location: start, length: length))
return temp
}
// MARK: 去除HTML标签
public func filterHTML(_ html: String) -> String {
var temp = html
let scanner: Scanner = Scanner.init(string: temp)
var text: NSString?
while scanner.isAtEnd == false {
scanner.scanUpTo("<", into: nil)
scanner.scanUpTo("<", into: &text)
temp = temp.replacingOccurrences(of: "\(text)>", with: "")
}
return temp
}
// MARK:
public func empty() -> Bool {
return self.isEmpty
}
// MARK:
public func notEmpty() -> Bool {
return !self.isEmpty
}
// MARK:
// public func isTelephone2() -> Bool {
//
// let pred_Unicom:NSPredicate = NSPredicate.init(format: "SELF MATCHES ^(1)[0-9]{10}", argumentArray: nil)
// let isMatch_CMCC:Bool = pred_Unicom.evaluateWithObject(self)
// return isMatch_CMCC
// }
// MARK:
public func validateIdentityCard() -> Bool {
var flag: Bool
if self.isEmpty {
flag = false
return flag
}
let regex2 = "^(\\d{14}|\\d{17})(\\d|[xX])$"
let identityCardPredicate: NSPredicate = NSPredicate.init(format: "SELF MATCHES \(regex2)", argumentArray: nil)
return identityCardPredicate.evaluate(with: self)
}
// MARK: 拼音转换
public func pinYin() -> String {
let str: String = self
CFStringTransform(str as! CFMutableString, nil, kCFStringTransformStripDiacritics, false)
CFStringTransform(str as! CFMutableString, nil, kCFStringTransformStripDiacritics, false)
return str
}
// MARK: 根据宽度计算高度
public func sizeWithFontByWith(_ font: UIFont, byWith: CGFloat) -> CGSize {
let str: NSString = self as NSString
let attribute: [String: AnyObject] = [NSFontAttributeName: font]
let rct: CGRect = str.boundingRect(with: CGSize(width: byWith, height: 999999.0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attribute, context: nil)
return rct.size
}
// MARK: 根据高度计算宽度
public func sizeWithFontByHeight(_ font: UIFont, byHeight: CGFloat) -> CGSize {
let str: NSString = self as NSString
let attribute: [String: AnyObject] = [NSFontAttributeName: font]
let rct: CGRect = str.boundingRect(with: CGSize(width: 999999.0, height: byHeight), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attribute, context: nil)
return rct.size
}
// MARK: 返回显示字串所需要的尺寸
public func calculateSize(_ size: CGSize, font: UIFont) -> CGSize {
var expectedLabelSize: CGSize = CGSize.zero
let str: NSString = self as NSString
let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle.init()
paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
let attributes: [String: AnyObject] = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle];
expectedLabelSize = str.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil).size
return CGSize(width: ceil(expectedLabelSize.width), height: ceil(expectedLabelSize.height))
}
// MARK:字符串转int
/**
字符串转int string to int
- parameter str: string
- returns: int
*/
public func toInt() -> Int {
return Int((self as NSString).intValue)
}
// MARK:字符串转double
/**
字符串转double
- returns: double
*/
public func doubleValue() -> Double {
return (self as NSString).doubleValue
}
/**
String 转 NSString
- parameter str: string
- returns: NSString
*/
public func stringFormat(_ str: String) -> NSString {
return NSString(cString: str.cString(using: String.Encoding.utf8)!,
encoding: String.Encoding.utf8.rawValue)!
}
}
| apache-2.0 | 44a1ad0cb0c196fd15e4892c0aa993de | 30.821429 | 184 | 0.633932 | 4.2768 | false | false | false | false |
gewill/Feeyue | Feeyue/Main/Weibo/Views/GWRepostCell.swift | 1 | 5866 | //
// GWRepostCell.swift
// Feeyue
//
// Created by Will on 19/03/2018.
// Copyright © 2018 Will. All rights reserved.
//
import UIKit
import SnapKit
import Kingfisher
import IBAnimatable
@objc protocol GWRepostCellDelegate: class {
@objc optional func statusCellDidClickAvatarImageView(_ cell: GWRepostCell)
@objc optional func statusCell(_ cell: GWRepostCell, didTapUserName userName: String)
@objc optional func statusCell(_ cell: GWRepostCell, didTapHashtag hashtag: String)
@objc optional func statusCell(_ cell: GWRepostCell, didTapURL url: URL)
}
class GWRepostCell: UICollectionViewCell {
var avatarImageView: AnimatableImageView!
var userNameLabel: UILabel!
var createdAtLabel: UILabel!
var statusTextLabel: WBActiveLabel!
var separator: UIView!
var status: Status? {
didSet {
if let url = gw_stringToUrl(self.status?.user?.avatarHd) {
self.avatarImageView.kf.setImage(with: url, placeholder: Placeholder)
}
self.userNameLabel.text = self.status?.user?.screenName
if let data = status?.createdAt {
self.createdAtLabel.text = data.timeAgoUpToDay
}
self.statusTextLabel.text = status?.text
}
}
weak var delegate: GWRepostCellDelegate?
// MARK: - life cycle
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
private func setupViews() {
let avatarImageViewHeight: CGFloat = 20
avatarImageView = AnimatableImageView()
avatarImageView.layer.cornerRadius = avatarImageViewHeight / 2
avatarImageView.clipsToBounds = true
self.avatarImageView.layer.borderWidth = 0.1
self.avatarImageView.layer.borderColor = .none
avatarImageView.gw_addTapGestureRecognizer(target: self, action: #selector(self.avatarImageViewClick(_:)))
self.addSubview(avatarImageView)
avatarImageView.snp.makeConstraints { (make) in
make.leading.top.equalToSuperview().offset(16)
make.width.height.equalTo(avatarImageViewHeight)
}
userNameLabel = UILabel()
userNameLabel.font = GWFont.size17
userNameLabel.textColor = GWColor.color3
userNameLabel.gw_addTapGestureRecognizer(target: self, action: #selector(self.userNameLabelClick(_:)))
self.addSubview(userNameLabel)
userNameLabel.snp.makeConstraints { (make) in
make.leading.equalTo(avatarImageView.snp.trailing).offset(8)
make.top.equalTo(avatarImageView)
}
createdAtLabel = UILabel()
createdAtLabel.font = GWFont.size14
createdAtLabel.textColor = GWColor.color9
self.addSubview(createdAtLabel)
createdAtLabel.snp.makeConstraints { (make) in
make.leading.equalTo(userNameLabel.snp.trailing).offset(8)
make.trailing.equalToSuperview().offset(-16)
make.centerY.equalTo(userNameLabel)
}
statusTextLabel = WBActiveLabel()
statusTextLabel.font = GWFont.size15
statusTextLabel.textColor = GWColor.color4
statusTextLabel.adjustsFontSizeToFitWidth = false
statusTextLabel.numberOfLines = 0
statusTextLabel.customize { label in
label.handleCustomTap(for: WBHashtag) {
var hashtag = $0
if hashtag.hasPrefix("#") {
hashtag.remove(at: hashtag.startIndex)
}
if hashtag.hasSuffix("#") {
hashtag.remove(at: hashtag.index(before: hashtag.endIndex))
}
self.delegate?.statusCell?(self, didTapHashtag: hashtag)
}
label.handleMentionTap { self.delegate?.statusCell?(self, didTapUserName: $0) }
// label.handleURLTap { self.delegate?.statusCell?(self, didTapURL: $0) }
label.handleCustomTap(for: WBURL) {
guard let url = URL(string: $0) else { return }
self.delegate?.statusCell?(self, didTapURL: url)
}
}
self.addSubview(statusTextLabel)
statusTextLabel.snp.makeConstraints { (make) in
make.leading.equalToSuperview().offset(16)
make.trailing.equalToSuperview().offset(-16)
make.top.equalTo(avatarImageView.snp.bottom).offset(8)
}
separator = UIView()
separator.backgroundColor = SeparatorColor
self.addSubview(separator)
separator.snp.makeConstraints { (make) in
make.leading.trailing.bottom.equalToSuperview()
make.height.equalTo(0.3)
}
}
// MARK: - config methods
static func cellSize(_ text: String) -> CGSize {
let constrainedSize = CGSize(width: ScreenWidth - 16 * 2, height: CGFloat.greatestFiniteMagnitude)
let font = GWFont.size15
let attributes = [ NSAttributedString.Key.font: font]
let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin]
let bounds = (text as NSString).boundingRect(with: constrainedSize, options: options, attributes: attributes, context: nil)
let contentLabelHeight = ceil(bounds.height)
return CGSize(width: ScreenWidth, height: 16 + 20 + 8 + contentLabelHeight + 8)
}
// MARK: - response methods
@objc func avatarImageViewClick(_ recognizer: UIGestureRecognizer) {
self.delegate?.statusCellDidClickAvatarImageView?(self)
}
@objc func userNameLabelClick(_ sender: UITapGestureRecognizer) {
guard let userName = self.status?.user?.screenName else {
return
}
delegate?.statusCell?(self, didTapUserName: userName)
}
}
| mit | 516dfc8e4221cbf01c395b6aa8b1ce8a | 36.596154 | 131 | 0.64757 | 4.970339 | false | false | false | false |
ParsifalC/CPCollectionViewKit | Demos/CPCollectionViewCircleLayoutDemo/CPCollectionViewCircleLayoutDemo/CPColletionViewCell.swift | 1 | 1308 | //
// CPColletionViewCell.swift
// CPCollectionViewWheelLayout-Swift
//
// Created by Parsifal on 2016/12/29.
// Copyright © 2016年 Parsifal. All rights reserved.
//
import UIKit
class CPCollectionViewCell: UICollectionViewCell {
// MARK:- Public Properties
public var textLabel:UILabel!;
override init(frame: CGRect) {
super.init(frame: frame)
setupViews(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- Private Methods
fileprivate func setupViews(frame:CGRect) {
contentView.layer.masksToBounds = true
contentView.layer.borderColor = UIColor.red.cgColor
contentView.layer.borderWidth = 1
let labelFrame = CGRect(x:0, y:0, width:frame.width, height:frame.height)
textLabel = UILabel.init(frame: labelFrame)
textLabel.font = .systemFont(ofSize: 20)
textLabel.textColor = .black
textLabel.textAlignment = .center
contentView.addSubview(textLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.layer.cornerRadius = bounds.width/2
textLabel.frame = CGRect(x:0, y:0, width:bounds.width, height:bounds.height)
}
}
| mit | 72e0c0f167b1df3514cde42e63ec4b8c | 28.659091 | 84 | 0.65977 | 4.408784 | false | false | false | false |
AdilVirani/IntroiOS | Alamofire-swift-2.0/Source/ParameterEncoding.swift | 1 | 9075 | // ParameterEncoding.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Foundation
/**
HTTP method definitions.
See https://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
- URL: A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE`
requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header
field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since
there is no published specification for how to encode collection types, the convention of appending
`[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square
brackets for nested dictionary values (`foo[bar]=baz`).
- JSON: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as
the body of the request. The `Content-Type` HTTP header field of an encoded request is set to
`application/json`.
- PropertyList: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
according to the associated format and write options values, which is set as the body of the
request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
- Custom: Uses the associated closure value to construct a new request given an existing request and
parameters.
*/
public enum ParameterEncoding {
case URL
case JSON
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
- parameter URLRequest: The request to have parameters applied
- parameter parameters: The parameters to apply
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
if any.
*/
public func encode(
URLRequest: URLRequestConvertible,
parameters: [String: AnyObject]?)
-> (NSMutableURLRequest, NSError?)
{
var mutableURLRequest = URLRequest.URLRequest
guard let parameters = parameters else {
return (mutableURLRequest, nil)
}
var encodingError: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in Array(parameters.keys).sort(<) {
let value = parameters[key]!
components += queryComponents(key, value)
}
return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
URLComponents.percentEncodedQuery = percentEncodedQuery
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue(
"application/x-www-form-urlencoded; charset=utf-8",
forHTTPHeaderField: "Content-Type"
)
}
mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding(
NSUTF8StringEncoding,
allowLossyConversion: false
)
}
case .JSON:
do {
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
} catch {
encodingError = error as NSError
}
case .PropertyList(let format, let options):
do {
let data = try NSPropertyListSerialization.dataWithPropertyList(
parameters,
format: format,
options: options
)
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
} catch {
encodingError = error as NSError
}
case .Custom(let closure):
(mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, encodingError)
}
/**
Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
- parameter key: The key of the query component.
- parameter value: The value of the query component.
- returns: The percent-escaped, URL encoded query string components.
*/
public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
- parameter string: The string to be percent-escaped.
- returns: The percent-escaped string.
*/
public func escape(string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode)
return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? ""
}
}
| apache-2.0 | 9004dc25657f454015d0e333b50745dc | 44.139303 | 124 | 0.618208 | 5.515502 | false | false | false | false |
box/box-ios-sdk | Sources/Sessions/OAuth2/OAuth2Session.swift | 1 | 5837 | //
// OAuth2Session.swift
// BoxSDK
//
// Created by Daniel Cech on 28/03/2019.
// Copyright © 2019 Box. All rights reserved.
//
import Foundation
/// OAuth 2 Session
public class OAuth2Session: SessionProtocol, ExpiredTokenHandling {
var authModule: AuthModule
var configuration: BoxSDKConfiguration
var tokenStore: TokenStore
var tokenInfo: TokenInfo
let authDispatcher = AuthModuleDispatcher()
init(authModule: AuthModule, tokenInfo: TokenInfo, tokenStore: TokenStore, configuration: BoxSDKConfiguration) {
self.authModule = authModule
self.tokenInfo = tokenInfo
self.configuration = configuration
self.tokenStore = tokenStore
}
public func getAccessToken(completion: @escaping AccessTokenClosure) {
// Check if the cached token info is valid, if so just return that access token
if isValidToken() {
completion(.success(tokenInfo.accessToken))
return
}
authDispatcher.start { [weak self] done in
guard let self = self else {
return
}
if self.isValidToken() {
completion(.success(self.tokenInfo.accessToken))
done()
return
}
// If the cached token info is expired, attempt refresh
self.refreshToken { result in
completion(result)
done()
}
}
}
/// Handles token expiration.
///
/// - Parameter completion: Returns either empty result representing success or error.
public func handleExpiredToken(completion: @escaping Callback<Void>) {
tokenStore.clear { result in
switch result {
case .success:
completion(.success(()))
case let .failure(error):
completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error)))
}
}
}
/// Gets refreshed access token if necessary
///
/// - Parameter completion: Completion for obtaining access token.
/// - Returns: AccessTokenClosure containing either token string or error.
public func refreshToken(completion: @escaping AccessTokenClosure) {
guard let refreshToken = tokenInfo.refreshToken else {
completion(.failure(BoxAPIAuthError(message: .refreshTokenNotFound)))
return
}
authModule.refresh(refreshToken: refreshToken) { result in
switch result {
case let .success(tokenInfo):
self.tokenInfo = tokenInfo
// If refresh succeeds, cache the new token info (and write to the store if present) and return the new access token
self.tokenStore.write(tokenInfo: tokenInfo) { result in
switch result {
case .success:
DispatchQueue.main.async { completion(.success(tokenInfo.accessToken)) }
case let .failure(error):
DispatchQueue.main.async { completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error))) }
}
}
case .failure:
// If refresh fails, try reading from the store
self.tokenStore.read { [weak self] result in
guard let self = self else {
return
}
switch result {
case let .success(storedTokenInfo):
// If reading from store succeeds, check if the tokens in the store were the same as the cached tokens; if so, fail
guard storedTokenInfo != self.tokenInfo else {
DispatchQueue.main.async { completion(.failure(BoxAPIAuthError(message: .expiredToken))) }
return
}
self.tokenInfo = storedTokenInfo
DispatchQueue.main.async { completion(.success(self.tokenInfo.accessToken)) }
case let .failure(error):
// If reading from store fails, fail
DispatchQueue.main.async { completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error))) }
}
}
}
}
}
public func revokeTokens(completion: @escaping Callback<Void>) {
authModule.revokeToken(token: tokenInfo.accessToken) { [weak self] result in
guard let self = self else {
return
}
switch result {
case .success:
self.tokenStore.clear { _ in }
completion(.success(()))
case let .failure(error):
completion(.failure(error))
}
}
}
/// Downscope the token.
///
/// - Parameters:
/// - scope: Scope or scopes that you want to apply to the resulting token.
/// - resource: Full url path to the file that the token should be generated for, eg: https://api.box.com/2.0/files/{file_id}
/// - sharedLink: Shared link to get a token for.
/// - completion: Returns the success or an error.
public func downscopeToken(
scope: Set<TokenScope>,
resource: String? = nil,
sharedLink: String? = nil,
completion: @escaping TokenInfoClosure
) {
authModule.downscopeToken(parentToken: tokenInfo.accessToken, scope: scope, resource: resource, sharedLink: sharedLink, completion: completion)
}
}
// MARK: - Private Helpers
private extension OAuth2Session {
func isValidToken() -> Bool {
return tokenInfo.expiresAt.timeIntervalSinceNow > configuration.tokenRefreshThreshold
}
}
| apache-2.0 | 7eeaee63dcec9b0fb2fdcfdbe39d7ab2 | 36.651613 | 151 | 0.578992 | 5.418756 | false | false | false | false |
Keanyuan/SwiftContact | SwiftContent/SwiftContent/Classes/ContentView/shaixuan/FiltrateView.swift | 1 | 2188 | //
// FiltrateView.swift
// SwiftContent
//
// Created by Kean on 2017/6/25.
// Copyright © 2017年 祁志远. All rights reserved.
//
import UIKit
/// 动画时长
private let kAnimationDuration = 0.25
class FiltrateView: UIView {
class func show(){
let filtrateView = FiltrateView()
filtrateView.frame = UIScreen.main.bounds
filtrateView.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.6)
let window = UIApplication.shared.keyWindow
window?.addSubview(filtrateView)
}
func randomFloat(min: Float, max: Float) -> Float {
return (Float(arc4random()) / 0xFFFFFFFF) * (max - min) + min
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
UIView.animate(withDuration: kAnimationDuration) {
self.bgView.x = SCREENW - self.bgView.width
}
}
fileprivate func setupUI(){
addSubview(bgView)
bgView.addSubview(filtrateView)
filtrateView.snp.makeConstraints { (make) in
make.top.right.bottom.equalTo(bgView)
make.width.equalTo(bgView).multipliedBy(0.8)
}
}
private lazy var bgView:UIView = {
let bgView = UIView()
bgView.frame = CGRect(x: SCREENW, y: 0, width: SCREENW, height: SCREENH)
return bgView
}()
private lazy var filtrateView:UIView = {
let filtrateView = UIView()
filtrateView.backgroundColor = UIColor.white
filtrateView.isUserInteractionEnabled = true
return filtrateView
}()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
cancleBtnClick()
}
func cancleBtnClick(){
UIView.animate(withDuration: kAnimationDuration, animations: {
self.bgView.x = SCREENW
}) { (_) in
self.removeFromSuperview()
}
}
}
| mit | 6c354cd50da7e8a4b580177e1ce5df54 | 24.845238 | 103 | 0.593736 | 4.541841 | false | false | false | false |
diversario/bitfountain-ios-foundations | Swift/UISwitch/UISwitch/ViewController.swift | 1 | 1436 | //
// ViewController.swift
// UISwitch
//
// Created by Ilya Shaisultanov on 1/2/16.
// Copyright © 2016 Ilya Shaisultanov. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var demoSwitch: UISwitch!
@IBOutlet weak var switchStateLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(patternImage: UIImage(named: "UISwitchBackground")!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func changeSwitchTapped(sender: UIButton) {
let yellow = UIColor(red: 255/255, green: 209/255, blue: 77/255, alpha: 1)
let brown = UIColor(red: 108/255, green: 76/255, blue: 73/255, alpha: 1)
if demoSwitch.on {
demoSwitch.onTintColor = yellow
demoSwitch.thumbTintColor = UIColor(red: 87/255, green: 175/255, blue: 63/255, alpha: 1)
} else {
demoSwitch.tintColor = brown
demoSwitch.thumbTintColor = brown
}
}
@IBAction func demoSwitchTapped(sender: UISwitch) {
switchStateLabel.text = "Switch is \(demoSwitch.on)"
let purple = UIColor(red: 189.255, green: 81/255, blue: 222/255, alpha: 1)
demoSwitch.thumbTintColor = purple
}
}
| mit | e2f1fe9c24d9f0186954e0f5af142bb8 | 27.7 | 100 | 0.627178 | 4.375 | false | false | false | false |
quadro5/swift3_L | swift_question.playground/Pages/Let88 Merge Sorted Array.xcplaygroundpage/Contents.swift | 1 | 1928 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
class Solution {
func merge2(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
var index = m + n - 1
var indexNum1 = m - 1
var indexNum2 = n - 1
while index >= 0 {
//nums1[index] = nums1[indexNum1] > nums2[indexNum2] ? nums1[indexNum1] : nums2[indexNum2]
if indexNum1 >= 0, indexNum2 >= 0 {
if nums1[indexNum1] > nums2[indexNum2] {
nums1[index] = nums1[indexNum1]
indexNum1 -= 1
} else {
nums1[index] = nums2[indexNum2]
indexNum2 -= 1
}
} else if indexNum1 >= 0 {
nums1[index] = nums1[indexNum1]
indexNum1 -= 1
} else {
nums1[index] = nums2[indexNum2]
indexNum2 -= 1
}
index -= 1
}
}
func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
var index = m + n - 1
var indexNum1 = m - 1
var indexNum2 = n - 1
// replace x > y ? ... : ...;
func calculate(index1: inout Int, index2: inout Int) -> Int {
var res = 0
if nums1[indexNum1] > nums2[indexNum2] {
res = nums1[indexNum1]
indexNum1 -= 1
return res
}
res = nums2[indexNum2]
indexNum2 -= 1
return res
}
while index >= 0 {
if indexNum1 >= 0, indexNum2 >= 0 {
nums1[index] = calculate(index1: &indexNum1, index2: &indexNum2)
} else if indexNum2 >= 0 {
nums1[index] = nums2[indexNum2]
indexNum2 -= 1
}
index -= 1
}
}
} | unlicense | a459de760c1e46578048765d5840ec3d | 28.227273 | 102 | 0.427386 | 4.016667 | false | false | false | false |
typarker/LotLizard | KitchenSink/ExampleFiles/ViewControllers/SellSpotViewController.swift | 1 | 10519 | //
// SellSpotViewController.swift
// DrawerControllerKitchenSink
//
// Created by Ty Parker on 1/16/15.
// Copyright (c) 2015 evolved.io. All rights reserved.
//
import UIKit
import MapKit
class SellSpotViewController: UIViewController, MKMapViewDelegate, PFLogInViewControllerDelegate {
var mapView: MKMapView!
//long press
var coordToPass = CLLocationCoordinate2D(
latitude: 0,
longitude: 0
)
var currentUser = PFUser.currentUser()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Sell Your Spot"
self.mapView = MKMapView()
if currentUser != nil { // is user already signed in
// Do stuff with the user
// populateMap()
} else {
// Show the signup or login screen
var logInController = PFLogInViewController()
logInController.delegate = self
logInController.fields = PFLogInFields.UsernameAndPassword | PFLogInFields.SignUpButton | PFLogInFields.LogInButton | PFLogInFields.PasswordForgotten | PFLogInFields.DismissButton
self.presentViewController(logInController, animated:true, completion: nil)
}
var lpgr = UILongPressGestureRecognizer(target: self, action: "action:")
lpgr.minimumPressDuration = 0.5;
mapView.addGestureRecognizer(lpgr)
// 1
let location = CLLocationCoordinate2D(
latitude: 29.6520,
longitude: -82.35
)
// 2
let span = MKCoordinateSpanMake(0.025, 0.025)
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
self.mapView.mapType = .Standard
self.mapView.frame = view.frame
self.mapView.delegate = self
self.view.addSubview(self.mapView)
let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTap:")
doubleTap.numberOfTapsRequired = 2
self.view.addGestureRecognizer(doubleTap)
let twoFingerDoubleTap = UITapGestureRecognizer(target: self, action: "twoFingerDoubleTap:")
twoFingerDoubleTap.numberOfTapsRequired = 2
twoFingerDoubleTap.numberOfTouchesRequired = 2
self.view.addGestureRecognizer(twoFingerDoubleTap)
self.setupLeftMenuButton()
//self.setupRightMenuButton()
let barColor = UIColor(red: 247/255, green: 249/255, blue: 250/255, alpha: 1.0)
self.navigationController?.navigationBar.barTintColor = barColor
self.navigationController?.view.layer.cornerRadius = 10.0
let backView = UIView()
backView.backgroundColor = UIColor(red: 208/255, green: 208/255, blue: 208/255, alpha: 1.0)
//self.tableView.backgroundView = backView
// populateMap()
}
//Dismiss Login View Controller after Login
func logInViewController(controller: PFLogInViewController, didLogInUser user: PFUser) -> Void {
self.dismissViewControllerAnimated(true, completion: nil)
// populateMap()
//matching user to device
let currentInstallation: PFInstallation = PFInstallation.currentInstallation()
var user = PFUser.currentUser()
currentInstallation.setObject(user, forKey: "user")
currentInstallation.saveInBackground()
}
func logInViewControllerDidCancelLogIn(controller: PFLogInViewController) -> Void {
self.dismissViewControllerAnimated(true, completion: nil)
//performSegueWithIdentifier("startAgainID", sender: self)
}
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// if segue.identifier == "goToAddLot"{
// var newProjectVC:AddLotViewController = AddLotViewController()
// newProjectVC = segue.destinationViewController as AddLotViewController
// newProjectVC.latitude = self.coordToPass.latitude
// newProjectVC.longitude = self.coordToPass.longitude
// }
// }
class MapPin : NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String
var subtitle: String
init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
func mapView(_mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
//if !(annotation is MKPointAnnotation) {
//if annotation is not an MKPointAnnotation (eg. MKUserLocation),
//return nil so map draws default view for it (eg. blue dot)...
// return nil
// }
//let textbox : UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200.00, height: 40.00));
//textbox.text = "blah"
let reuseId = "test"
let button : UIButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as UIButton
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.image = UIImage(named:"redPin.png")
anView.canShowCallout = true
//anView.leftCalloutAccessoryView = textbox
//price = self.textbox.text
anView.rightCalloutAccessoryView = button
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
}
else {
//we are re-using a view, update its annotation reference...
anView.annotation = annotation
}
return anView
}
//long press annotation add
func action(gestureRecognizer:UIGestureRecognizer) {
//Remove any annotations
if mapView.annotations.count != 0 {
mapView.removeAnnotations(mapView.annotations)
}
//Add new annotation
var touchPoint = gestureRecognizer.locationInView(self.mapView)
var newCoord:CLLocationCoordinate2D = mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
var info2 = MapPin(coordinate: newCoord,title: "Your Yard",subtitle: "")
//var anView:MKAnnotationView! = mapView(self.mapView, viewForAnnotation: info2)
self.mapView.addAnnotation(info2)
coordToPass=newCoord
}
// Do any additional setup after loading the view.
func buttonClicked(sender: UIButton!) {
//let ann = self.mapView.selectedAnnotations[0] as LotAnnotation
let secondViewController: AddLotWithXIBViewController = AddLotWithXIBViewController(nibName:"AddLotWithXIBViewController", bundle: nil)
//secondViewController.ann = ann
// if ann.coordinate.latitude == 0 {
secondViewController.latitude = coordToPass.latitude
secondViewController.longitude = coordToPass.longitude
// }
// else{
// secondViewController.latitude = ann.coordinate.latitude
// secondViewController.longitude = ann.coordinate.longitude
// }
//let secondViewController: BuySpotViewController = BuySpotViewController()
self.presentViewController(secondViewController, animated: true, completion: nil)
//performSegueWithIdentifier("goToAddLot", sender: sender)
}
//add annotations to map
func populateMap(){
mapView.removeAnnotations(mapView.annotations) // 1
var user = PFUser.currentUser()
var query = PFQuery(className:"MyLotParse")
query.whereKey("owner", equalTo: user)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
// The find succeeded.
NSLog("Successfully retrieved \(objects.count) spots.")
// Do something with the found objects
for object in objects {
NSLog("%@", object.objectId)
let location = object ["location"] as PFGeoPoint
let latitude = location.latitude as Double
let longitude = location.longitude as Double
let price = object["price"] as String
let coord = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let id = object.objectId
let spots = object["spots"] as Int
let notes = object["notes"] as String?
let lotAnnotation = LotAnnotation(coordinate: coord, title: price, subtitle: "Dollars", id: id, owner: user, notes: notes, spots: spots) // 3
self.mapView.addAnnotation(lotAnnotation) // 4
}
} else {
// Log details of the failure
NSLog("Error: %@ %@", error, error.userInfo!)
}
}
}
func setupLeftMenuButton() {
let leftDrawerButton = DrawerBarButtonItem(target: self, action: "leftDrawerButtonPress:")
self.navigationItem.setLeftBarButtonItem(leftDrawerButton, animated: true)
}
func setupRightMenuButton() {
let rightDrawerButton = DrawerBarButtonItem(target: self, action: "rightDrawerButtonPress:")
self.navigationItem.setRightBarButtonItem(rightDrawerButton, animated: true)
}
func leftDrawerButtonPress(sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.Left, animated: true, completion: nil)
}
func rightDrawerButtonPress(sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.Right, animated: true, completion: nil)
}
func doubleTap(gesture: UITapGestureRecognizer) {
self.evo_drawerController?.bouncePreviewForDrawerSide(.Left, completion: nil)
}
func twoFingerDoubleTap(gesture: UITapGestureRecognizer) {
self.evo_drawerController?.bouncePreviewForDrawerSide(.Right, completion: nil)
}
}
| mit | 817b9b47ff775f966eaaf111bc4be815 | 36.038732 | 191 | 0.622398 | 5.504448 | false | false | false | false |
slavapestov/swift | stdlib/public/core/Builtin.swift | 2 | 18845 | //===----------------------------------------------------------------------===//
//
// 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
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
/// An initialized raw pointer to use as a NULL value.
@_transparent
internal var _nilRawPointer: Builtin.RawPointer {
let zero: Int8 = 0
return Builtin.inttoptr_Int8(zero._value)
}
/// Returns the contiguous memory footprint of `T`.
///
/// Does not include any dynamically-allocated or "remote" storage.
/// In particular, `sizeof(X.self)`, when `X` is a class type, is the
/// same regardless of how many stored properties `X` has.
@_transparent
@warn_unused_result
public func sizeof<T>(_:T.Type) -> Int {
return Int(Builtin.sizeof(T.self))
}
/// Returns the contiguous memory footprint of `T`.
///
/// Does not include any dynamically-allocated or "remote" storage.
/// In particular, `sizeof(a)`, when `a` is a class instance, is the
/// same regardless of how many stored properties `a` has.
@_transparent
@warn_unused_result
public func sizeofValue<T>(_:T) -> Int {
return sizeof(T.self)
}
/// Returns the minimum memory alignment of `T`.
@_transparent
@warn_unused_result
public func alignof<T>(_:T.Type) -> Int {
return Int(Builtin.alignof(T.self))
}
/// Returns the minimum memory alignment of `T`.
@_transparent
@warn_unused_result
public func alignofValue<T>(_:T) -> Int {
return alignof(T.self)
}
/// Returns the least possible interval between distinct instances of
/// `T` in memory. The result is always positive.
@_transparent
@warn_unused_result
public func strideof<T>(_:T.Type) -> Int {
return Int(Builtin.strideof_nonzero(T.self))
}
/// Returns the least possible interval between distinct instances of
/// `T` in memory. The result is always positive.
@_transparent
@warn_unused_result
public func strideofValue<T>(_:T) -> Int {
return strideof(T.self)
}
@warn_unused_result
func _roundUpToAlignment(offset: Int, _ alignment: Int) -> Int {
_sanityCheck(offset >= 0)
_sanityCheck(alignment > 0)
_sanityCheck(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = (offset + alignment &- 1)
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(alignment &- 1)
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@_transparent
@warn_unused_result
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of `x`, interpreted as having type `U`.
///
/// - Warning: Breaks the guarantees of Swift's type system; use
/// with extreme care. There's almost always a better way to do
/// anything.
///
@_transparent
@warn_unused_result
public func unsafeBitCast<T, U>(x: T, _: U.Type) -> U {
_precondition(sizeof(T.self) == sizeof(U.self),
"can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@_transparent
@warn_unused_result
public func _reinterpretCastToAnyObject<T>(x: T) -> AnyObject {
return unsafeBitCast(x, AnyObject.self)
}
@_transparent
@warn_unused_result
func ==(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return unsafeBitCast(lhs, Int.self) == unsafeBitCast(rhs, Int.self)
}
@_transparent
@warn_unused_result
func !=(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return !(lhs == rhs)
}
@_transparent
@warn_unused_result
func ==(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return unsafeBitCast(lhs, Int.self) == unsafeBitCast(rhs, Int.self)
}
@_transparent
@warn_unused_result
func !=(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Return `true` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
@warn_unused_result
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
return unsafeBitCast(t0, Int.self) == unsafeBitCast(t1, Int.self)
}
/// Return `false` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
@warn_unused_result
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@_transparent
internal func _unreachable(condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@_transparent @noreturn internal
func _conditionallyUnreachable() {
Builtin.conditionallyUnreachable()
}
@warn_unused_result
@_silgen_name("swift_isClassOrObjCExistentialType")
func _swift_isClassOrObjCExistentialType<T>(x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@inline(__always)
@warn_unused_result
internal func _isClassOrObjCExistential<T>(x: T.Type) -> Bool {
let tmp = _canBeClass(x)
// Is not a class.
if tmp == 0 {
return false
// Is a class.
} else if tmp == 1 {
return true
}
// Maybe a class.
return _swift_isClassOrObjCExistentialType(x)
}
/// Returns an `UnsafePointer` to the storage used for `object`. There's
/// not much you can do with this other than use it to identify the
/// object.
@_transparent
@warn_unused_result
public func unsafeAddressOf(object: AnyObject) -> UnsafePointer<Void> {
return UnsafePointer(Builtin.bridgeToRawPointer(object))
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@_transparent
@warn_unused_result
public func _unsafeReferenceCast<T, U>(x: T, _: U.Type) -> U {
return Builtin.castReference(x)
}
/// - returns: `x as T`.
///
/// - Requires: `x is T`. In particular, in -O builds, no test is
/// performed to ensure that `x` actually has dynamic type `T`.
///
/// - Warning: Trades safety for performance. Use `unsafeDowncast`
/// only when `x as T` has proven to be a performance problem and you
/// are confident that, always, `x is T`. It is better than an
/// `unsafeBitCast` because it's more restrictive, and because
/// checking is still performed in debug builds.
@_transparent
@warn_unused_result
public func unsafeDowncast<T : AnyObject>(x: AnyObject) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
/// - Returns: `nonEmpty!`.
///
/// - Requires: `nonEmpty != nil`. In particular, in -O builds, no test
/// is performed to ensure that `nonEmpty` actually is non-nil.
///
/// - Warning: Trades safety for performance. Use `unsafeUnwrap`
/// only when `nonEmpty!` has proven to be a performance problem and
/// you are confident that, always, `nonEmpty != nil`. It is better
/// than an `unsafeBitCast` because it's more restrictive, and
/// because checking is still performed in debug builds.
@inline(__always)
@warn_unused_result
public func unsafeUnwrap<T>(nonEmpty: T?) -> T {
if let x = nonEmpty {
return x
}
_debugPreconditionFailure("unsafeUnwrap of nil optional")
}
/// - Returns: `unsafeUnwrap(nonEmpty)`.
///
/// This version is for internal stdlib use; it avoids any checking
/// overhead for users, even in Debug builds.
@inline(__always)
@warn_unused_result
public // SPI(SwiftExperimental)
func _unsafeUnwrap<T>(nonEmpty: T?) -> T {
if let x = nonEmpty {
return x
}
_sanityCheckFailure("_unsafeUnwrap of nil optional")
}
@inline(__always)
@warn_unused_result
public func _getUnsafePointerToStoredProperties(x: AnyObject)
-> UnsafeMutablePointer<UInt8> {
let storedPropertyOffset = _roundUpToAlignment(
sizeof(_HeapObject.self), alignof(Optional<AnyObject>.self))
return UnsafeMutablePointer<UInt8>(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
@_transparent
@_semantics("branchhint")
@warn_unused_result
internal func _branchHint<C : BooleanType>(actual: C, _ expected: Bool)
-> Bool {
return Bool(Builtin.int_expect_Int1(actual.boolValue._value, expected._value))
}
/// Optimizer hint that `x` is expected to be `true`.
@_transparent
@_semantics("fastpath")
@warn_unused_result
public func _fastPath<C: BooleanType>(x: C) -> Bool {
return _branchHint(x.boolValue, true)
}
/// Optimizer hint that `x` is expected to be `false`.
@_transparent
@_semantics("slowpath")
@warn_unused_result
public func _slowPath<C : BooleanType>(x: C) -> Bool {
return _branchHint(x.boolValue, false)
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
@inline(__always)
@warn_unused_result
internal func _usesNativeSwiftReferenceCounting(theClass: AnyClass) -> Bool {
#if _runtime(_ObjC)
return swift_objc_class_usesNativeSwiftReferenceCounting(
unsafeAddressOf(theClass)
)
#else
return true
#endif
}
@warn_unused_result
@_silgen_name("swift_class_getInstanceExtents")
func swift_class_getInstanceExtents(theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@warn_unused_result
@_silgen_name("swift_objc_class_unknownGetInstanceExtents")
func swift_objc_class_unknownGetInstanceExtents(theClass: AnyClass)
-> (negative: UInt, positive: UInt)
/// - Returns:
@inline(__always)
@warn_unused_result
internal func _class_getInstancePositiveExtentSize(theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive)
#else
return Int(swift_class_getInstanceExtents(theClass).positive)
#endif
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
#if arch(i386) || arch(arm)
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0003 }
}
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(x86_64)
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0006 }
}
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 1 }
}
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0001 }
}
#elseif arch(arm64)
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0007 }
}
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0000 }
}
#elseif arch(powerpc64) || arch(powerpc64le)
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#endif
/// Extract the raw bits of `x`.
@inline(__always)
@warn_unused_result
internal func _bitPattern(x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@inline(__always)
@warn_unused_result
internal func _nonPointerBits(x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@inline(__always)
@warn_unused_result
internal func _isObjCTaggedPointer(x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Requires: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@inline(__always)
@warn_unused_result
internal func _makeNativeBridgeObject(
nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inline(__always)
@warn_unused_result
public // @testable
func _makeObjCBridgeObject(
objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Requires:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@inline(__always)
@warn_unused_result
internal func _makeBridgeObject(
object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_sanityCheck(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(object.dynamicType)
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_sanityCheck(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
/// Return the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
@inline(__always)
@warn_unused_result
public // @testable
func _getSuperclass(t: AnyClass) -> AnyClass? {
return unsafeBitCast(
swift_class_getSuperclass(unsafeBitCast(t, COpaquePointer.self)),
AnyClass.self)
}
/// Return the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inline(__always)
@warn_unused_result
public // @testable
func _getSuperclass(t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique and _isUniquePinned cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Return true if `object` is uniquely referenced.
@_transparent
@warn_unused_result
internal func _isUnique<T>(inout object: T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Return true if `object` is uniquely referenced or pinned.
@_transparent
@warn_unused_result
internal func _isUniqueOrPinned<T>(inout object: T) -> Bool {
return Bool(Builtin.isUniqueOrPinned(&object))
}
/// Return true if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@_transparent
@warn_unused_result
public // @testable
func _isUnique_native<T>(inout object: T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
(Builtin.reinterpretCast(object) as AnyObject).dynamicType))
return Bool(Builtin.isUnique_native(&object))
}
/// Return true if `object` is uniquely referenced or pinned.
/// This provides sanity checks on top of the Builtin.
@_transparent
@warn_unused_result
public // @testable
func _isUniqueOrPinned_native<T>(inout object: T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
(Builtin.reinterpretCast(object) as AnyObject).dynamicType))
return Bool(Builtin.isUniqueOrPinned_native(&object))
}
/// Return true if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@_transparent
@warn_unused_result
public // @testable
func _isPOD<T>(type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Return true if type is nominally an Optional type.
@_transparent
@warn_unused_result
public // @testable
func _isOptional<T>(type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
| apache-2.0 | cda6b900338172e063a733d766acafaa | 30.83277 | 80 | 0.696153 | 3.899234 | false | false | false | false |
Brezeler/MusicCenter | MusicCenter-master/Music/MusicViewControler.swift | 2 | 2410 | //
// MusicViewControler.swift
// Music
//
// Created by Jordan Sejean on 28/11/2016.
// Copyright © 2016 Brezeler. All rights reserved.
//
import Foundation
import UIKit
class MusicViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var MusicList: UITableView!
var music :[Music] = []
override func viewDidLoad() {
super.viewDidLoad()
self.MusicList.dataSource = self
self.MusicList.delegate = self
self.MusicList.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.getMusic()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.music.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.MusicList.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
let music = self.music[indexPath.row];
cell.textLabel?.text = music.singer + "-" + music.song
cell.textLabel?.textColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)
cell.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let playMusicViewController : PlayMusicViewController = PlayMusicViewController()
playMusicViewController.music = self.music[indexPath.row];
navigationController?.pushViewController(playMusicViewController, animated: true)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCellEditingStyle.delete) {
}
}
func getMusic()->Void{
let musicWebServices : MusicWB = MusicWB()
musicWebServices.getAllMusics(){
(result: [Music]) in
self.music = result
self.refreshTableView()
} }
func refreshTableView(){
DispatchQueue.main.async(execute: {
self.MusicList.reloadData()
})
}
}
| bsd-3-clause | 00602a5f666aaab37acece378a0666ba | 31.12 | 127 | 0.654628 | 5.082278 | false | false | false | false |
lzpfmh/actor-platform | actor-apps/app-ios/ActorApp/View/Cells/CommonCell.swift | 1 | 5327 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
enum CommonCellStyle {
case Normal
case DestructiveCentered
case Destructive
case Switch
case Action
case ActionCentered
case Navigation
case Hint
}
class CommonCell: UATableViewCell {
private var switcher: UISwitch?
private var titleLabel = UILabel()
private var hintLabel = UILabel()
var style: CommonCellStyle = .Normal { didSet { updateCellStyle() } }
var switchBlock: ((Bool) -> ())?
var contentInset: CGFloat = 15
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel.font = UIFont.systemFontOfSize(17.0)
contentView.addSubview(titleLabel)
hintLabel.font = UIFont.systemFontOfSize(17.0)
hintLabel.textColor = MainAppTheme.list.hintColor
contentView.addSubview(hintLabel)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Setting text content
func setContent(content: String?) {
titleLabel.text = content
}
func setHint(hint: String?) {
if hint == nil {
hintLabel.hidden = true
} else {
hintLabel.text = hint
hintLabel.hidden = false
}
}
// Setting switcher content
func setSwitcherOn(on: Bool) {
setSwitcherOn(on, animated: false)
}
func setSwitcherOn(on: Bool, animated: Bool) {
switcher?.setOn(on, animated: animated)
}
func setSwitcherEnabled(enabled: Bool) {
switcher?.enabled = enabled
}
// Private methods
private func updateCellStyle() {
switch (style) {
case .Normal:
titleLabel.textColor = MainAppTheme.list.textColor
titleLabel.textAlignment = NSTextAlignment.Left
switcher?.hidden = true
accessoryType = UITableViewCellAccessoryType.None
break
case .Hint:
titleLabel.textColor = MainAppTheme.list.hintColor
titleLabel.textAlignment = NSTextAlignment.Left
switcher?.hidden = true
accessoryType = UITableViewCellAccessoryType.None
break
case .DestructiveCentered:
titleLabel.textColor = UIColor.redColor()
titleLabel.textAlignment = NSTextAlignment.Center
switcher?.hidden = true
accessoryType = UITableViewCellAccessoryType.None
break
case .Destructive:
titleLabel.textColor = UIColor.redColor()
titleLabel.textAlignment = NSTextAlignment.Left
switcher?.hidden = true
accessoryType = UITableViewCellAccessoryType.None
break
case .Switch:
titleLabel.textColor = MainAppTheme.list.textColor
titleLabel.textAlignment = NSTextAlignment.Left
setupSwitchIfNeeded()
switcher?.hidden = false
accessoryType = UITableViewCellAccessoryType.None
break
case .Action:
titleLabel.textColor = MainAppTheme.list.actionColor
titleLabel.textAlignment = NSTextAlignment.Left
switcher?.hidden = true
accessoryType = UITableViewCellAccessoryType.None
break
case .ActionCentered:
titleLabel.textColor = MainAppTheme.list.actionColor
titleLabel.textAlignment = NSTextAlignment.Center
switcher?.hidden = true
accessoryType = UITableViewCellAccessoryType.None
break
case .Navigation:
titleLabel.textColor = MainAppTheme.list.textColor
titleLabel.textAlignment = NSTextAlignment.Left
switcher?.hidden = true
accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
}
private func setupSwitchIfNeeded() {
if switcher == nil {
switcher = UISwitch()
switcher!.addTarget(self, action: Selector("switcherSwitched"), forControlEvents: UIControlEvents.ValueChanged)
contentView.addSubview(switcher!)
}
}
func switcherSwitched() {
if switchBlock != nil {
switchBlock!(switcher!.on)
}
}
override func layoutSubviews() {
super.layoutSubviews()
if hintLabel.text != nil {
hintLabel.frame = CGRectMake(0, 0, 100, 44)
hintLabel.sizeToFit()
hintLabel.frame = CGRectMake(contentView.bounds.width - hintLabel.width, 0, hintLabel.width, 44)
titleLabel.frame = CGRectMake(contentInset, 0, contentView.bounds.width - hintLabel.width - contentInset - 5, 44)
} else {
titleLabel.frame = CGRectMake(contentInset, 0, contentView.bounds.width - contentInset - 5, 44)
}
if switcher != nil {
let switcherSize = switcher!.bounds.size
switcher!.frame = CGRect(x: contentView.bounds.width - switcherSize.width - 15, y: (contentView.bounds.height - switcherSize.height) / 2, width: switcherSize.width, height: switcherSize.height)
}
}
} | mit | 11ebfd12c759fd3610cdeb41c196300f | 32.509434 | 205 | 0.617233 | 5.601472 | false | false | false | false |
bigL055/SPKit | Sources/NSLayoutConstraint/NSLayoutConstraint.swift | 2 | 2136 | //
// SPKit
//
// Copyright (c) 2017 linhay - https:// github.com/linhay
//
// 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
import UIKit
public extension NSLayoutConstraint {
/// 改变Constant 增加或者减少
/// - Parameter offSet: 变化量
public func change(offest: CGFloat) {
let nowConstant = self.constant
self.constant = nowConstant + offest
}
/// 修改倍率
///
/// - Parameter multiplier: 新倍率
/// - Returns: Constraint
public func change(multiplier: CGFloat) -> NSLayoutConstraint {
NSLayoutConstraint.deactivate([self])
let newConstraint = NSLayoutConstraint(
item: self.firstItem as Any,
attribute: self.firstAttribute,
relatedBy: self.relation,
toItem: self.secondItem,
attribute: self.secondAttribute,
multiplier: multiplier,
constant: self.constant)
newConstraint.priority = self.priority
newConstraint.shouldBeArchived = self.shouldBeArchived
newConstraint.identifier = self.identifier
NSLayoutConstraint.activate([newConstraint])
return newConstraint
}
}
| apache-2.0 | d8c2743c9a7571ed63e2d702d45d4998 | 35.206897 | 82 | 0.72381 | 4.535637 | false | false | false | false |
gaurav1981/Nuke | Sources/Manager.swift | 3 | 8028 | // The MIT License (MIT)
//
// Copyright (c) 2017 Alexander Grebenyuk (github.com/kean).
import Foundation
/// Loads images into the given targets.
public final class Manager: Loading {
public let loader: Loading
public let cache: Caching?
private let queue = DispatchQueue(label: "com.github.kean.Nuke.Manager")
/// Shared `Manager` instance.
///
/// Shared manager is created with `Loader.shared` and `Cache.shared`.
public static let shared = Manager(loader: Loader.shared, cache: Cache.shared)
/// Initializes the `Manager` with the image loader and the memory cache.
/// - parameter cache: `nil` by default.
public init(loader: Loading, cache: Caching? = nil) {
self.loader = loader
self.cache = cache
}
// MARK: Loading Images into Targets
/// Loads an image into the given target. Cancels previous outstanding request
/// associated with the target.
///
/// If the image is stored in the memory cache, the image is displayed
/// immediately. The image is loaded using the `loader` object otherwise.
///
/// `Manager` keeps a weak reference to the target. If the target deallocates
/// the associated request automatically gets cancelled.
public func loadImage(with request: Request, into target: Target) {
loadImage(with: request, into: target) { [weak target] in
target?.handle(response: $0, isFromMemoryCache: $1)
}
}
public typealias Handler = (Result<Image>, _ isFromMemoryCache: Bool) -> Void
/// Loads an image and calls the given `handler`. The method itself
/// **doesn't do** anything when the image is loaded - you have full
/// control over how to display it, etc.
///
/// The handler only gets called if the request is still associated with the
/// `target` by the time it's completed. The handler gets called immediately
/// if the image was stored in the memory cache.
///
/// See `loadImage(with:into:)` method for more info.
public func loadImage(with request: Request, into target: AnyObject, handler: @escaping Handler) {
assert(Thread.isMainThread)
// Cancel outstanding request if any
cancelRequest(for: target)
// Quick synchronous memory cache lookup
if let image = cachedImage(for: request) {
handler(.success(image), true)
return
}
// Create context and associate it with a target
let cts = CancellationTokenSource(lock: CancellationTokenSource.lock)
let context = Context(cts)
Manager.setContext(context, for: target)
// Start the request
loadImage(with: request, token: cts.token) { [weak context, weak target] in
guard let context = context, let target = target else { return }
guard Manager.getContext(for: target) === context else { return }
handler($0, false)
context.cts = nil // Avoid redundant cancellations on deinit
}
}
/// Cancels an outstanding request associated with the target.
public func cancelRequest(for target: AnyObject) {
assert(Thread.isMainThread)
if let context = Manager.getContext(for: target) {
context.cts?.cancel()
Manager.setContext(nil, for: target)
}
}
// MARK: Loading Images w/o Targets
/// Loads an image with a given request by using manager's cache and loader.
///
/// - parameter completion: Gets called asynchronously on the main thread.
public func loadImage(with request: Request, token: CancellationToken?, completion: @escaping (Result<Image>) -> Void) {
queue.async {
if token?.isCancelling == true { return } // Fast preflight check
self._loadImage(with: request, token: token) { result in
DispatchQueue.main.async { completion(result) }
}
}
}
private func _loadImage(with request: Request, token: CancellationToken? = nil, completion: @escaping (Result<Image>) -> Void) {
// Check if image is in memory cache
if let image = cachedImage(for: request) {
completion(.success(image))
} else {
// Use underlying loader to load an image and then store it in cache
loader.loadImage(with: request, token: token) { [weak self] in
if let image = $0.value {
self?.store(image: image, for: request)
}
completion($0)
}
}
}
// MARK: Memory Cache Helpers
private func cachedImage(for request: Request) -> Image? {
guard request.memoryCacheOptions.readAllowed else { return nil }
return cache?[request]
}
private func store(image: Image, for request: Request) {
guard request.memoryCacheOptions.writeAllowed else { return }
cache?[request] = image
}
// MARK: Managing Context
private static var contextAK = "Manager.Context.AssociatedKey"
// Associated objects is a simplest way to bind Context and Target lifetimes
// The implementation might change in the future.
private static func getContext(for target: AnyObject) -> Context? {
return objc_getAssociatedObject(target, &contextAK) as? Context
}
private static func setContext(_ context: Context?, for target: AnyObject) {
objc_setAssociatedObject(target, &contextAK, context, .OBJC_ASSOCIATION_RETAIN)
}
private final class Context {
var cts: CancellationTokenSource?
init(_ cts: CancellationTokenSource) { self.cts = cts }
// Automatically cancel the request when target deallocates.
deinit { cts?.cancel() }
}
}
public extension Manager {
/// Loads an image into the given target. See the corresponding
/// `loadImage(with:into)` method that takes `Request` for more info.
public func loadImage(with url: URL, into target: Target) {
loadImage(with: Request(url: url), into: target)
}
/// Loads an image and calls the given `handler`. The method itself
/// **doesn't do** anything when the image is loaded - you have full
/// control over how to display it, etc.
///
/// The handler only gets called if the request is still associated with the
/// `target` by the time it's completed. The handler gets called immediately
/// if the image was stored in the memory cache.
///
/// See `loadImage(with:into:)` method for more info.
public func loadImage(with url: URL, into target: AnyObject, handler: @escaping Handler) {
loadImage(with: Request(url: url), into: target, handler: handler)
}
}
/// Represents an arbitrary target for image loading.
public protocol Target: class {
/// Callback that gets called when the request gets completed.
func handle(response: Result<Image>, isFromMemoryCache: Bool)
}
#if os(macOS)
import Cocoa
/// Alias for `NSImageView`
public typealias ImageView = NSImageView
#elseif os(iOS) || os(tvOS)
import UIKit
/// Alias for `UIImageView`
public typealias ImageView = UIImageView
#endif
#if os(macOS) || os(iOS) || os(tvOS)
/// Default implementation of `Target` protocol for `ImageView`.
extension ImageView: Target {
/// Displays an image on success. Runs `opacity` transition if
/// the response was not from the memory cache.
public func handle(response: Result<Image>, isFromMemoryCache: Bool) {
guard let image = response.value else { return }
self.image = image
if !isFromMemoryCache {
let animation = CABasicAnimation(keyPath: "opacity")
animation.duration = 0.25
animation.fromValue = 0
animation.toValue = 1
let layer: CALayer? = self.layer // Make compiler happy on macOS
layer?.add(animation, forKey: "imageTransition")
}
}
}
#endif
| mit | 30b7c12a10f823c165cedbebbdc0e99a | 37.228571 | 132 | 0.641256 | 4.686515 | false | false | false | false |
obozhdi/handy_extensions | HandyExtensions/HandyExtensions/Extensions/UIImage+TintLinearGradient.swift | 1 | 975 | import UIKit
extension UIImage {
func tintWithLinearGradientColors(colorsArr: [CGColor?]) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
let context = UIGraphicsGetCurrentContext()
context!.translateBy(x: 0, y: self.size.height)
context!.scaleBy(x: 1.0, y: -1.0)
context!.setBlendMode(.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
let colors = colorsArr as CFArray
let space = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorsSpace: space, colors: colors, locations: nil)
context?.clip(to: rect, mask: self.cgImage!)
context!.drawLinearGradient(gradient!, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: self.size.height), options: CGGradientDrawingOptions(rawValue: 0))
let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return gradientImage!
}
}
| unlicense | 1ee1a45284ac3f9e2615271ed1103bc9 | 35.111111 | 159 | 0.70359 | 4.352679 | false | false | false | false |
barteljan/VISPER | VISPER-Swift/Classes/VISPERApp.swift | 1 | 5128 | //
// Application.swift
// SwiftyVISPER
//
// Created by bartel on 15.11.17.
//
import Foundation
import VISPER_Redux
import VISPER_Core
import VISPER_Wireframe
import VISPER_UIViewController
import VISPER_Reactive
@available(*, unavailable, message: "replace this class with VISPERApp",renamed: "VISPERApp")
public typealias Application<AppState> = VISPERApp<AppState>
/// A SwiftyVisper application, containing all dependencies which should be configured by features
open class VISPERApp<AppState>: VISPERAppType, ReduxApp, WireframeApp {
public typealias ApplicationObservableProperty = ObservableProperty<AppState>
internal let reduxApp: AnyReduxApp<AppState>
internal let wireframeApp: WireframeApp
public init(reduxApp: AnyReduxApp<AppState>,
wireframeApp: WireframeApp) {
self.reduxApp = reduxApp
self.wireframeApp = wireframeApp
}
public convenience init(reduxApp: AnyReduxApp<AppState>,
wireframe: Wireframe,
controllerContainer: ControllerContainer) {
let wireframeApp = DefaultWireframeApp(wireframe: wireframe)
self.init(reduxApp: reduxApp, wireframeApp: wireframeApp)
}
public convenience init(redux: Redux<AppState>,
wireframe: Wireframe,
controllerContainer: ControllerContainer){
let reduxApp = DefaultReduxApp(redux: redux)
let anyReduxApp = AnyReduxApp(reduxApp)
self.init(reduxApp: anyReduxApp,
wireframe: wireframe,
controllerContainer: controllerContainer)
}
/// observable app state property
open var state: ObservableProperty<AppState> {
get {
return self.reduxApp.redux.store.observableState
}
}
/// the wireframe responsible for routing between your view controllers
public var wireframe: Wireframe {
get {
return self.wireframeApp.wireframe
}
}
//redux architecture of your project
public var redux: Redux<AppState> {
get {
return self.reduxApp.redux
}
}
/// Add a feature to your application
///
/// - Parameter feature: your feature
/// - Throws: throws errors thrown by your feature observers
///
/// - note: A Feature is an empty protocol representing a distinct funtionality of your application.
/// It will be provided to all FeatureObservers after addition to configure and connect it to
/// your application and your remaining features. Have look at LogicFeature and LogicFeatureObserver for an example.
open func add(feature: Feature) throws {
try self.reduxApp.add(feature: feature)
try self.wireframeApp.add(feature: feature)
}
/// Add an observer to configure your application after adding a feature.
/// Have look at LogicFeature and LogicFeatureObserver for an example.
///
/// - Parameter featureObserver: an object observing feature addition
open func add<T : StatefulFeatureObserver>(featureObserver: T) where T.AppState == AppState{
self.reduxApp.add(featureObserver: featureObserver)
}
/// Add an observer to configure your application after adding a feature.
/// Have look at LogicFeature and LogicFeatureObserver for an example.
///
/// - Parameter featureObserver: an object observing feature addition
open func add(featureObserver: FeatureObserver) {
self.reduxApp.add(featureObserver: featureObserver)
}
/// Add an observer to configure your application after adding a feature.
/// Have look at LogicFeature and LogicFeatureObserver for an example.
///
/// - Parameter featureObserver: an object observing feature addition
public func add(featureObserver: WireframeFeatureObserver) {
self.wireframeApp.add(featureObserver: featureObserver)
}
/// Add a controller that can be used to navigate in your app.
/// Typically this will be a UINavigationController, but it could also be a UITabbarController if
/// you have a routing presenter that can handle it.
/// Be careful you can add more than one viewControllers if your RoutingPresenters can handle different
/// controller types or when the active 'rootController' changes.
/// The last added controller will be used first.
/// The controller will not be retained by the application (it is weakly stored), you need to store a
/// link to them elsewhere (if you don't want them to be removed from memory).
/// - Parameter controller: a controller that can be used to navigte in your app
open func navigateOn(_ controller: UIViewController) {
self.wireframeApp.navigateOn(controller)
}
/// return the first navigatableController that matches in a block
public func controllerToNavigate(matches: (UIViewController?) -> Bool) -> UIViewController? {
return self.wireframeApp.controllerToNavigate(matches: matches)
}
}
| mit | cb47d00ba3a8e0473d4210acb2ff5ad3 | 35.892086 | 128 | 0.684867 | 5.270298 | false | false | false | false |
natecook1000/Geomsaek | GeomsaekTests/GeomsaekTests.swift | 1 | 1527 | //
// GeomsaekTests.swift
// GeomsaekTests
//
// Copyright © 2015 Nate Cook. All rights reserved.
//
import XCTest
@testable import Geomsaek
class GeomsaekTests: XCTestCase {
lazy var index = Index()
lazy var searcher: Searcher = {
Searcher(inIndex: self.index)
}()
func fillIndex(index: Index) {
// Thank you, Project Gutenberg
let path = NSBundle(forClass: GeomsaekTests.self).resourcePath!
for i in 10...39 {
let filePath = "\(path)/\(i).txt"
let contents = try! String(contentsOfFile: filePath)
index.add(Document(url: NSURL(fileURLWithPath: filePath)), withText: contents)
}
index.flushIndex()
}
func testFillCount() {
XCTAssertEqual(index.documentCount, 0)
fillIndex(index)
XCTAssertGreaterThanOrEqual(index.documentCount, 30)
}
func testSearch() {
fillIndex(index)
let terms = ["hackers": 1, "first": 28, "elephant*": 2, "zcxjvnalskjdnf": 0]
let expectation = expectationWithDescription("Searching")
var searches = 0
terms.forEach { (term, expectedCount) in
++searches
searcher.startSearch(term) { results in
XCTAssertEqual(results.documents.count, expectedCount)
if --searches == 0 {
expectation.fulfill()
}
}
}
waitForExpectationsWithTimeout(500, handler: nil)
}
}
| mit | f107eae1b085c0883242bf3972e5739a | 27.259259 | 90 | 0.577326 | 4.610272 | false | true | false | false |
josherick/DailySpend | DailySpend/ReviewViewExpensesController.swift | 1 | 6306 | //
// ReviewViewExpenseController.swift
// DailySpend
//
// Created by Josh Sherick on 11/2/18.
// Copyright © 2018 Josh Sherick. All rights reserved.
//
import Foundation
class ReviewViewExpensesController: AddExpenseDelegate {
var delegate: ReviewEntityControllerDelegate?
struct ExpenseCellDatum {
var shortDescription: String?
var amountDescription: String
init(_ shortDescription: String?, _ amountDescription: String) {
self.shortDescription = shortDescription
self.amountDescription = amountDescription
}
}
private var goal: Goal?
private var interval: CalendarIntervalProvider?
private var expenses: [Expense]
private var expenseCellData: [ExpenseCellDatum]
private var section: Int
private var cellCreator: TableViewCellHelper
private var present: (UIViewController, Bool, (() -> Void)?) -> ()
init(
section: Int,
cellCreator: TableViewCellHelper,
present: @escaping (UIViewController, Bool, (() -> Void)?) -> ()
) {
self.goal = nil
self.expenses = []
self.expenseCellData = []
self.section = section
self.cellCreator = cellCreator
self.present = present
}
private func makeExpenseCellDatum(_ expense: Expense) -> ExpenseCellDatum {
return ExpenseCellDatum(
expense.shortDescription,
String.formatAsCurrency(amount: expense.amount ?? 0) ?? ""
)
}
func presentCreateExpenseModal() {
guard let goal = goal else {
return
}
let addExpenseVC = AddExpenseViewController()
addExpenseVC.setupExpenseWithGoal(goal: goal)
addExpenseVC.delegate = self
let navCtrl = UINavigationController(rootViewController: addExpenseVC)
self.present(navCtrl, true, nil)
}
private func remakeExpenses() {
expenseCellData = []
expenses = []
guard let goal = self.goal,
let interval = self.interval else {
return
}
expenses = goal.getExpenses(interval: interval)
for expense in expenses {
expenseCellData.append(makeExpenseCellDatum(expense))
}
}
func setGoal(_ newGoal: Goal?, interval: CalendarIntervalProvider) {
self.goal = newGoal
self.interval = interval
remakeExpenses()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return max(expenseCellData.count, 1)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if expenseCellData.isEmpty {
return cellCreator.centeredLabelCell(labelText: "No Expenses", disabled: true)
}
let row = indexPath.row
let description = expenseCellData[row].shortDescription ?? "No Description"
let value = expenseCellData[row].amountDescription
return cellCreator.optionalDescriptorValueCell(
description: description,
undescribed: expenseCellData[row].shortDescription == nil,
value: value,
detailButton: true
)
}
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
self.tableView(tableView, didSelectRowAt: indexPath)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if expenseCellData.count == 0 {
return
}
let addExpenseVC = AddExpenseViewController()
addExpenseVC.delegate = self
addExpenseVC.expense = expenses[indexPath.row]
let navCtrl = UINavigationController(rootViewController: addExpenseVC)
self.present(navCtrl, true, nil)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return expenseCellData.count > 0
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle != .delete {
return
}
let row = indexPath.row
let expense = expenses[row]
context.delete(expense)
appDelegate.saveContext()
expenses.remove(at: row)
expenseCellData.remove(at: row)
delegate?.deletedEntity(at: indexPath, use: .automatic, isLast: expenses.count == 0)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
func createdExpenseFromModal(_ expense: Expense) {
remakeExpenses()
let row = expenses.firstIndex(of: expense)
let path = IndexPath(row: row ?? 0, section: section)
let day = expense.transactionDay!.start
delegate?.addedEntity(
on: day,
with: expense.goal!,
at: path,
use: .automatic,
isFirst: expenseCellData.count == 1
)
}
func editedExpenseFromModal(_ expense: Expense) {
guard let day = expense.transactionDay?.start,
let origRow = expenses.firstIndex(of: expense) else {
return
}
remakeExpenses()
if let newRow = expenses.firstIndex(of: expense) {
// This expense is still in this view, but did not necesarily
// switch rows.
expenseCellData[newRow] = makeExpenseCellDatum(expense)
delegate?.editedEntity(
on: day,
with: expense.goal!,
at: IndexPath(row: origRow, section: section),
movedTo: origRow != newRow ? IndexPath(row: newRow, section: section) : nil,
use: .automatic
)
} else {
// This expense switched goals or intervals and is no longer in
// this view.
delegate?.editedEntity(
on: day,
with: expense.goal!,
at: IndexPath(row: origRow, section: section),
movedTo: nil,
use: .automatic
)
}
}
}
| mit | be3326cee697b5b0ec83598a4f38ba16 | 32.897849 | 127 | 0.607296 | 5.262938 | false | false | false | false |
austinzheng/swift | validation-test/compiler_crashers_fixed/01677-swift-dependentmembertype-get.swift | 65 | 1857 | // 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
// RUN: not %target-swift-frontend %s -typecheck
] == 1)
func a<A? {
func a(object1, V, (T] {
init(() -> Any] == 1]()
assert(T> Any, U>(.<c<f = compose<T.c where Optional<D>Bool)] as String):
A"
func a)
let n1: Collection where f: b: l.endIndex - range..b(b(i> {
protocol a {
}
}
struct c, U, let start = {
let foo as a: T: [0
func b> String
func compose<T>(self, x in a {
}
})?
()
extension String = Swift.B
}
}
(c
}
var b> T : (b: T) {
func f)
enum B == Int>: () -> e() -> T : A<T where H.startIndex)
return p: String)!.startIndex)
}
}
class a: Int {
class A) -> String {
print()
}
f: a {
d
}
}
func c(c: ())
init()()
import Foundation
typealias F>](.c : b(b[c
return p
return [Any) {
i()
protocol a {
typealias e {
class d() -> {
var b: A, A : d : d = {
typealias f = { self.h : T, () { c
struct A.dynamicType)
import Foundation
class func i(T>(a)
let end = B
}
private class A, B
protocol b {
func e: (""")) -> String = b<T
class b: d = [Int>? = T>] {
}
struct A {
protocol b {
f)
}
print(T>
func f.h : d = true {
}
}
}
}
func a: String
func f<c]
struct c, i : b() -> Any) -> {
map("foo"foobar"
self[1)
}
typealias f == g<U) {
struct B, d>()
convenience init() -> U, k : a {
typealias C {
}
protocol A {
var a""
return { _, g = Int
}(c) -> : T>(f() -> (z: Boolean>(m(v: Int>()] = { c
}
typealias e : NSObject {
let n1: 1], let g == Swift.join(h, Bool) -> (g.endIndex - range.lowerBound))
func f())
class A? {
}
typealias F>(g..substringWithRange(")
}
func i<Q<T, e: S() -> String {
}
var f = b.init(t: H
| apache-2.0 | 0163844e3ef80eb04fcb64f2f6b85da0 | 17.029126 | 79 | 0.598277 | 2.622881 | false | false | false | false |
austinzheng/swift | test/SILGen/init_ref_delegation.swift | 6 | 7919 | // RUN: %target-swift-emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s
struct X { }
// Initializer delegation within a struct.
struct S {
// CHECK-LABEL: sil hidden [ossa] @$s19init_ref_delegation1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> S {
init() {
// CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin S.Type):
// CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var S }
// CHECK-NEXT: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK-NEXT: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK-NEXT: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X_CTOR:%[0-9]+]] = function_ref @$s19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X
// CHECK-NEXT: [[X:%[0-9]+]] = apply [[X_CTOR]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[S_DELEG_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, @thin S.Type) -> S
// CHECK-NEXT: [[REPLACEMENT_SELF:%[0-9]+]] = apply [[S_DELEG_INIT]]([[X]], [[SELF_META]]) : $@convention(method) (X, @thin S.Type) -> S
self.init(x: X())
// CHECK-NEXT: assign [[REPLACEMENT_SELF]] to [[PB]] : $*S
// CHECK-NEXT: [[SELF_BOX1:%[0-9]+]] = load [trivial] [[PB]] : $*S
// CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] : ${ var S }
// CHECK-NEXT: return [[SELF_BOX1]] : $S
}
init(x: X) { }
}
// Initializer delegation within an enum
enum E {
// We don't want the enum to be uninhabited
case Foo
// CHECK-LABEL: sil hidden [ossa] @$s19init_ref_delegation1EO{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin E.Type) -> E
init() {
// CHECK: bb0([[E_META:%[0-9]+]] : $@thin E.Type):
// CHECK: [[E_BOX:%[0-9]+]] = alloc_box ${ var E }
// CHECK: [[MARKED_E_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[E_BOX]]
// CHECK: [[PB:%.*]] = project_box [[MARKED_E_BOX]]
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[E_DELEG_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X:%[0-9]+]] = apply [[E_DELEG_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation1EO{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, @thin E.Type) -> E
// CHECK: [[S:%[0-9]+]] = apply [[X_INIT]]([[X]], [[E_META]]) : $@convention(method) (X, @thin E.Type) -> E
// CHECK: assign [[S:%[0-9]+]] to [[PB]] : $*E
// CHECK: [[E_BOX1:%[0-9]+]] = load [trivial] [[PB]] : $*E
self.init(x: X())
// CHECK: destroy_value [[MARKED_E_BOX]] : ${ var E }
// CHECK: return [[E_BOX1:%[0-9]+]] : $E
}
init(x: X) { }
}
// Initializer delegation to a generic initializer
struct S2 {
// CHECK-LABEL: sil hidden [ossa] @$s19init_ref_delegation2S2V{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S2.Type) -> S2
init() {
// CHECK: bb0([[S2_META:%[0-9]+]] : $@thin S2.Type):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var S2 }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_BOX:%[0-9]+]] = alloc_stack $X
// CHECK: store [[X]] to [trivial] [[X_BOX]] : $*X
// CHECK: [[S2_DELEG_INIT:%[0-9]+]] = function_ref @$s19init_ref_delegation2S2V{{[_0-9a-zA-Z]*}}fC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2
// CHECK: [[SELF_BOX1:%[0-9]+]] = apply [[S2_DELEG_INIT]]<X>([[X_BOX]], [[S2_META]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2
// CHECK: dealloc_stack [[X_BOX]] : $*X
// CHECK: assign [[SELF_BOX1]] to [[PB]] : $*S2
// CHECK: [[SELF_BOX4:%[0-9]+]] = load [trivial] [[PB]] : $*S2
self.init(t: X())
// CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var S2 }
// CHECK: return [[SELF_BOX4]] : $S2
}
init<T>(t: T) { }
}
class C1 {
var ivar: X
// CHECK-LABEL: sil hidden [ossa] @$s19init_ref_delegation2C1C{{[_0-9a-zA-Z]*}}fC
convenience init(x: X) {
// CHECK: bb0([[X:%[0-9]+]] : $X, [[SELF_META:%[0-9]+]] : $@thick C1.Type):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var C1 }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_META]] : $@thick C1.Type, #C1.init!allocator.1
// CHECK: [[SELFP:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_META]])
// CHECK: assign [[SELFP]] to [[PB]]
// CHECK: [[SELFP:%[0-9]+]] = load [copy] [[PB]] : $*C1
// CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var C1 }
// CHECK: return [[SELFP]] : $C1
self.init(x1: x, x2: x)
}
init(x1: X, x2: X) { ivar = x1 }
}
@objc class C2 {
var ivar: X
// CHECK-LABEL: sil hidden [ossa] @$s19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fC
convenience init(x: X) {
// CHECK: bb0([[X:%[0-9]+]] : $X, [[SELF_META:%[0-9]+]] : $@thick C2.Type):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var C2 }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB_SELF:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_META]] : $@thick C2.Type, #C2.init!allocator.1
// CHECK: [[REPLACE_SELF:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_META]])
// CHECK: assign [[REPLACE_SELF]] to [[PB_SELF]] : $*C2
// CHECK: [[VAR_15:%[0-9]+]] = load [copy] [[PB_SELF]] : $*C2
// CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var C2 }
// CHECK: return [[VAR_15]] : $C2
self.init(x1: x, x2: x)
// CHECK-NOT: sil hidden [ossa] @$s19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (X, @owned C2) -> @owned C2 {
}
// CHECK-LABEL: sil hidden [ossa] @$s19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, X, @thick C2.Type) -> @owned C2 {
// CHECK-NOT: sil [ossa] @$s19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (X, X, @owned C2) -> @owned C2 {
init(x1: X, x2: X) { ivar = x1 }
}
var x: X = X()
class C3 {
var i: Int = 5
// CHECK-LABEL: sil hidden [ossa] @$s19init_ref_delegation2C3C{{[_0-9a-zA-Z]*}}fC
convenience init() {
// CHECK: mark_uninitialized [delegatingself]
// CHECK-NOT: integer_literal
// CHECK: class_method [[SELF:%[0-9]+]] : $@thick C3.Type, #C3.init!allocator.1
// CHECK-NOT: integer_literal
// CHECK: return
self.init(x: x)
}
init(x: X) { }
}
// Initializer delegation from a constructor defined in an extension.
class C4 { }
extension C4 {
convenience init(x1: X) {
self.init()
}
// CHECK: sil hidden [ossa] @$s19init_ref_delegation2C4C{{[_0-9a-zA-Z]*}}fC
// CHECK: [[PEER:%[0-9]+]] = function_ref @$s19init_ref_delegation2C4C{{[_0-9a-zA-Z]*}}fC
// CHECK: apply [[PEER]]([[X:%[0-9]+]], [[META:%[0-9]+]])
convenience init(x2: X) {
self.init(x1: x2)
}
}
// Initializer delegation to a constructor defined in a protocol extension.
protocol Pb {
init()
}
extension Pb {
init(d: Int) { }
}
class Sn : Pb {
required init() { }
convenience init(d3: Int) {
self.init(d: d3)
}
}
// Same as above but for a value type.
struct Cs : Pb {
init() { }
init(d3: Int) {
self.init(d: d3)
}
}
| apache-2.0 | 3174ce717ffb89ef88b6065f5d589254 | 40.439791 | 168 | 0.541503 | 2.730252 | false | false | false | false |
kissshot13/kissshot-weibo | weibodemo/weibodemo/Classes/comm/Controller/KISBaseTableViewController.swift | 1 | 2133 | //
// KISBaseTableViewController.swift
// weibodemo
//
// Created by 李威 on 16/8/14.
// Copyright © 2016年 李威. All rights reserved.
//
import UIKit
class KISBaseTableViewController: UITableViewController,KISVisitorViewDelegate {
//查看用户是否登入
var userlogin = true
var visitorView : KISVisitorView?
override func loadView()
{
userlogin ? super.loadView() : setUpVisitorView()
}
///创建游客登入界面
private func setUpVisitorView() {
visitorView = KISVisitorView.init()
visitorView?.delegate = self
view = visitorView
}
func setControllerTpey(type:KISControllTpye){
switch type {
case KISControllTpye.home:
setupNavgationItem()
visitorView?.setupVisitorInfo(KISControllTpye.home)
case KISControllTpye.message:
visitorView?.setupVisitorInfo(KISControllTpye.message)
case KISControllTpye.discovery:
setupNavgationItem()
visitorView?.setupVisitorInfo(KISControllTpye.discovery)
case KISControllTpye.profile:
visitorView?.setupVisitorInfo(KISControllTpye.profile)
}
}
private func setupNavgationItem() {
navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(registerBtnClick))
navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "登入", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(loginBtnClick))
}
// MARK:- 点击事件
//注册点击
@objc private func registerBtnClick()
{
print(#function)
}
//登入
@objc private func loginBtnClick()
{
print(#function)
}
///MARK: -KISVisitorViewDelegate
func registerBtnWillClick() {
registerBtnClick()
}
func loginBtnWillClick() {
loginBtnClick()
}
}
| apache-2.0 | 61dab4d7b533a51c6e8cdafe06f51829 | 21.637363 | 162 | 0.607767 | 5.228426 | false | false | false | false |
GlebRadchenko/AdvertServer | Sources/App/Models/Beacon.swift | 1 | 1608 | //
// Beacon.swift
// AdvertServer
//
// Created by Gleb Radchenko on 13.11.16.
//
//
import Foundation
import Vapor
import Fluent
final class Beacon: Model {
var id: Node?
var udid: String
var major: String
var minor: String
var parentId: Node?
var exists: Bool = false
init(udid: String, major: String, minor: String) {
self.udid = udid
self.major = major
self.minor = minor
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
udid = try node.extract("udid")
major = try node.extract("major")
minor = try node.extract("minor")
parentId = try node.extract("parentId")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"_id": id,
"udid": udid,
"major": major,
"minor": minor,
"parentId": parentId
])
}
static func prepare(_ database: Database) throws {
try database.create("beacons") { beacons in
beacons.id()
beacons.string("udid")
beacons.string("major")
beacons.string("minor")
beacons.id("parentId", optional: false)
}
}
static func revert(_ database: Database) throws {
try database.delete("beacons")
}
}
extension Beacon {
func owner() throws -> Parent<User> {
return try parent(parentId)
}
func advertisments() throws -> Children<Advertisment> {
return children("parentId", Advertisment.self)
}
}
| mit | 9753eff9f80e7c5038f0dbbe416cfb2d | 23.363636 | 59 | 0.556592 | 4.231579 | false | false | false | false |
brentdax/swift | test/Constraints/diagnostics_swift4.swift | 7 | 1915 | // RUN: %target-typecheck-verify-swift -swift-version 4
// SR-2505: "Call arguments did not match up" assertion
func sr_2505(_ a: Any) {} // expected-note {{}}
sr_2505() // expected-error {{missing argument for parameter #1 in call}}
sr_2505(a: 1) // expected-error {{extraneous argument label 'a:' in call}}
sr_2505(1, 2) // expected-error {{extra argument in call}}
sr_2505(a: 1, 2) // expected-error {{extra argument in call}}
struct C_2505 {
init(_ arg: Any) {
}
}
protocol P_2505 {
}
extension C_2505 {
init<T>(from: [T]) where T: P_2505 {
}
}
class C2_2505: P_2505 {
}
let c_2505 = C_2505(arg: [C2_2505()]) // expected-error {{incorrect argument label in call (have 'arg:', expected 'from:')}}
// rdar://problem/31898542 - Swift 4: 'type of expression is ambiguous without more context' errors, without a fixit
enum R31898542<T> {
case success(T) // expected-note {{'success' declared here}}
case failure
}
func foo() -> R31898542<()> {
return .success() // expected-error {{missing argument for parameter #1 in call}} {{19-19=<#T#>}}
}
// rdar://problem/31973368 - Cannot convert value of type '(K, V) -> ()' to expected argument type '((key: _, value: _)) -> Void'
// SE-0110: We reverted to allowing this for the time being, but this
// test is valuable in case we end up disallowing it again in the
// future.
class R<K: Hashable, V> {
func forEach(_ body: (K, V) -> ()) {
let dict: [K:V] = [:]
dict.forEach(body)
}
}
// Make sure that solver doesn't try to form solutions with available overloads when better generic choices are present.
infix operator +=+ : AdditionPrecedence
func +=+(_ lhs: Int, _ rhs: Int) -> Bool { return lhs == rhs }
func +=+<T: BinaryInteger>(_ lhs: T, _ rhs: Int) -> Bool { return lhs == rhs }
// FIXME: DoubleWidth is no longer part of the standard library
// let _ = DoubleWidth<Int>(Int.min) - 1 +=+ Int.min // Ok
| apache-2.0 | 0324772c0eb46f3f3823f6f9e69f8fc3 | 32.017241 | 129 | 0.642298 | 3.267918 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.