repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nixzhu/MonkeyKing | China/WeiboViewController.swift | 1 | 3486 |
import MonkeyKing
import UIKit
class WeiboViewController: UIViewController {
var accessToken: String?
override func viewDidLoad() {
super.viewDidLoad()
let account = MonkeyKing.Account.weibo(appID: Configs.Weibo.appID, appKey: Configs.Weibo.appKey, redirectURL: Configs.Weibo.redirectURL, universalLink: Configs.Weibo.universalLink)
MonkeyKing.registerAccount(account)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// not installed weibo app, must need accessToken
if !MonkeyKing.SupportedPlatform.weibo.isAppInstalled {
MonkeyKing.oauth(for: .weibo) { [weak self] result in
switch result {
case .success(let info):
if let accessToken = info?["access_token"] as? String {
self?.accessToken = accessToken
}
case .failure(let error):
print("error: \(String(describing: error))")
}
}
}
}
@IBAction func shareImage(_ sender: UIButton) {
let message = MonkeyKing.Message.weibo(.default(info: (
title: "Image",
description: "Rabbit",
thumbnail: nil,
media: .image(UIImage(named: "rabbit")!)
), accessToken: accessToken))
MonkeyKing.deliver(message) { result in
print("result: \(result)")
}
}
@IBAction func shareText(_ sender: UIButton) {
let message = MonkeyKing.Message.weibo(.default(info: (
title: nil,
description: "Text",
thumbnail: nil,
media: nil
), accessToken: accessToken))
MonkeyKing.deliver(message) { result in
print("result: \(result)")
}
}
@IBAction func shareURL(_ sender: UIButton) {
let message = MonkeyKing.Message.weibo(.default(info: (
title: "News",
description: "Hello Yep",
thumbnail: UIImage(named: "rabbit"),
media: .url(URL(string: "http://soyep.com")!)
), accessToken: accessToken))
MonkeyKing.deliver(message) { result in
print("result: \(result)")
}
}
// MARK: OAuth
@IBAction func OAuth(_ sender: UIButton) {
MonkeyKing.oauth(for: .weibo) { result in
switch result {
case .success(let info):
// App or Web: token & userID
guard
let unwrappedInfo = info,
let token = (unwrappedInfo["access_token"] as? String) ?? (unwrappedInfo["accessToken"] as? String),
let userID = (unwrappedInfo["uid"] as? String) ?? (unwrappedInfo["userID"] as? String) else {
return
}
let userInfoAPI = "https://api.weibo.com/2/users/show.json"
let parameters = [
"uid": userID,
"access_token": token,
]
// fetch UserInfo by userInfoAPI
SimpleNetworking.sharedInstance.request(userInfoAPI, method: .get, parameters: parameters) { userInfo, _, _ in
print("userInfo \(String(describing: userInfo))")
}
case .failure:
break
}
// More API
// http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI
}
}
}
| mit | 5841a04dd8a32b7251a52992c62eaaf0 | 34.212121 | 188 | 0.533563 | 4.896067 | false | false | false | false |
hq7781/MoneyBook | Pods/CVCalendar/CVCalendar/CVDate.swift | 5 | 2322 | //
// CVDate.swift
// CVCalendar
//
// Created by Мак-ПК on 12/31/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
public final class CVDate: NSObject {
fileprivate let date: Foundation.Date
public let year: Int
public let month: Int
public let week: Int
public let day: Int
public init(date: Foundation.Date, calendar: Calendar = Calendar.current) {
let dateRange = Manager.dateRange(date, calendar: calendar)
self.date = date
self.year = dateRange.year
self.month = dateRange.month
self.week = dateRange.weekOfMonth
self.day = dateRange.day
super.init()
}
public init(day: Int, month: Int, week: Int, year: Int, calendar: Calendar = Calendar.current) {
if let date = Manager.dateFromYear(year, month: month, week: week, day: day, calendar: calendar) {
self.date = date
} else {
self.date = Foundation.Date()
}
self.year = year
self.month = month
self.week = week
self.day = day
super.init()
}
}
extension CVDate {
public func weekDay(calendar: Calendar = Calendar.current) -> Weekday? {
let components = (calendar as NSCalendar).components(NSCalendar.Unit.weekday, from: self.date)
return Weekday(rawValue: components.weekday!)
}
public func convertedDate(calendar: Calendar = Calendar.current) -> Foundation.Date? {
var comps = Manager.componentsForDate(Foundation.Date(), calendar: calendar)
comps.year = year
comps.month = month
comps.weekOfMonth = week
comps.day = day
return calendar.date(from: comps)
}
}
extension CVDate {
public var globalDescription: String {
let month = dateFormattedStringWithFormat("MMMM", fromDate: date)
return "\(month) \(year)"
}
public var commonDescription: String {
let month = dateFormattedStringWithFormat("MMMM", fromDate: date)
return "\(day) \(month), \(year)"
}
}
private extension CVDate {
func dateFormattedStringWithFormat(_ format: String, fromDate date: Foundation.Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: date)
}
}
| mit | dcb86425f6705532d7c07a03a6fa93a8 | 26.915663 | 106 | 0.634009 | 4.330841 | false | false | false | false |
dietcoke27/SwiftLibXML | SwiftLibXML/AppDelegate.swift | 1 | 3066 | //
// AppDelegate.swift
// SwiftLibXML
//
// Created by Cole Kurkowski on 12/15/15.
// Copyright © 2015 Cole Kurkowski. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
func mergeArraysOrdered<T>(var source: [T], var toMerge: [T], isOrderedBefore: (T, T) -> Bool) -> ([T], [Bool])
{
var merged = [T]()
var isNew = [Bool]()
var i = 0
var j = 0
source.sortInPlace(isOrderedBefore)
toMerge.sortInPlace(isOrderedBefore)
while true
{
if j < toMerge.count && i < source.count && isOrderedBefore(toMerge[j], source[i])
{
merged.append(toMerge[j])
isNew.append(true)
j++
}
else if i < source.count
{
merged.append(source[i])
isNew.append(false)
i++
}
else if i == source.count
{
merged.append(toMerge[j])
isNew.append(true)
j++
}
if j == toMerge.count && i == source.count
{
break
}
}
return (merged, isNew)
}
| mit | 88ea31f63eba1aab0fcbb8f9f4bfe99c | 35.058824 | 285 | 0.668842 | 4.951535 | false | false | false | false |
fawkes32/swiftCourse | Calculadora/Calculadora/ViewController.swift | 1 | 1857 | //
// ViewController.swift
// Calculadora
//
// Created by Daniel Marquez on 6/23/15.
// Copyright (c) 2015 Tec de Monterrey. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var operandA: UITextField!
@IBOutlet weak var operandB: UITextField!
@IBOutlet weak var lblResult: UILabel!
var resultado:Int = 1
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnOperation(sender: UIButton) {
if !operandA.text.isEmpty && !operandB.text.isEmpty{
println("\(sender.tag)")
switch sender.tag{
case 0:
lblResult.text = String(operandA.text.toInt()! + operandB.text.toInt()!)
case 1:
lblResult.text = String(operandA.text.toInt()! - operandB.text.toInt()!)
case 2:
lblResult.text = String(operandA.text.toInt()! * operandB.text.toInt()!)
case 3:
lblResult.text = String(operandA.text.toInt()! / operandB.text.toInt()!)
case 4:
for var i:Int = operandA.text.toInt()!; i > 0 ; i-- {
resultado *= i
}
lblResult.text = String(resultado)
resultado = 1
default:
println("Go baby Go")
}
}else{
let alert = UIAlertView()
alert.title = "Error"
alert.message = "please put numbers on both textfields"
alert.addButtonWithTitle("Acknowledge")
alert.show()
}
}
}
| mit | e96c6acc5c9826102ed935edb6a4b1fd | 25.528571 | 84 | 0.556274 | 4.496368 | false | false | false | false |
jwfriese/FrequentFlyer | FrequentFlyerTests/Authentication/AuthMethodDataDeserializerSpec.swift | 1 | 13803 | import XCTest
import Quick
import Nimble
import RxSwift
import ObjectMapper
@testable import FrequentFlyer
class AuthMethodDataDeserializerSpec: QuickSpec {
override func spec() {
describe("AuthMethodDataDeserializer") {
var subject: AuthMethodDataDeserializer!
let publishSubject = PublishSubject<AuthMethod>()
var result: StreamResult<AuthMethod>!
var authMethods: [AuthMethod] {
get {
return result.elements
}
}
beforeEach {
subject = AuthMethodDataDeserializer()
}
describe("Deserializing auth methods data that is all valid") {
beforeEach {
let validDataJSONArray = [
[
"type" : "basic",
"display_name" : AuthMethod.DisplayNames.basic,
"auth_url": "basic_turtle.com"
],
[
"type" : "oauth",
"display_name": AuthMethod.DisplayNames.gitHub,
"auth_url": "oauth_turtle.com"
]
]
let validData = try! JSONSerialization.data(withJSONObject: validDataJSONArray, options: .prettyPrinted)
result = StreamResult(subject.deserialize(validData))
}
it("returns an auth method for each JSON auth method entry") {
if authMethods.count != 2 {
fail("Expected to return 2 auth methods, returned \(authMethods.count)")
return
}
expect(authMethods[0]).to(equal(AuthMethod(type: .basic, displayName: AuthMethod.DisplayNames.basic, url: "basic_turtle.com")))
expect(authMethods[1]).to(equal(AuthMethod(type: .gitHub, displayName: AuthMethod.DisplayNames.gitHub, url: "oauth_turtle.com")))
}
it("returns no error") {
expect(result.error).to(beNil())
}
}
describe("Deserializing auth method data where some of the data is invalid") {
context("Missing required 'type' field") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"type" : "basic",
"display_name" : AuthMethod.DisplayNames.basic,
"auth_url": "basic_turtle.com"
],
[
"somethingelse" : "value",
"display_name" : AuthMethod.DisplayNames.basic,
"auth_url": "basic_crab.com"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
result = StreamResult(subject.deserialize(partiallyValidData))
}
it("emits an auth method for each valid JSON auth method entry") {
expect(authMethods).to(equal([AuthMethod(type: .basic, displayName: AuthMethod.DisplayNames.basic, url: "basic_turtle.com")]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("'type' field is not a string") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"type" : "basic",
"display_name" : AuthMethod.DisplayNames.basic,
"auth_url": "basic_turtle.com"
],
[
"type" : 1,
"display_name" : AuthMethod.DisplayNames.basic,
"auth_url": "basic_turtle.com"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
result = StreamResult(subject.deserialize(partiallyValidData))
}
it("emits an auth method for each valid JSON auth method entry") {
expect(authMethods).to(equal([AuthMethod(type: .basic, displayName: AuthMethod.DisplayNames.basic, url: "basic_turtle.com")]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("Missing required 'display_name' field") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"type" : "basic",
"display_name" : AuthMethod.DisplayNames.basic
],
[
"type" : "oauth",
"display_name" : AuthMethod.DisplayNames.gitHub,
"auth_url": "basic_crab.com"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
result = StreamResult(subject.deserialize(partiallyValidData))
}
it("emits an auth method for each valid JSON auth method entry") {
expect(authMethods).to(equal([AuthMethod(type: .gitHub, displayName: AuthMethod.DisplayNames.gitHub, url: "basic_crab.com")]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("'display_name' field is not a string") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"type" : "basic",
"display_name" : AuthMethod.DisplayNames.basic,
"auth_url": "basic_turtle.com"
],
[
"type" : "oauth",
"display_name" : 1,
"auth_url": "oauth_turtle.com"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
result = StreamResult(subject.deserialize(partiallyValidData))
}
it("emits an auth method for each valid JSON auth method entry") {
expect(authMethods).to(equal([AuthMethod(type: .basic, displayName: AuthMethod.DisplayNames.basic, url: "basic_turtle.com")]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("Unrecognized combination of 'type' and 'display_name'") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"type" : "basic",
"display_name" : AuthMethod.DisplayNames.basic,
"auth_url": "basic_turtle.com"
],
[
"type" : "basic",
"display_name" : "something else",
"auth_url": "basic_crab.com"
],
[
"type" : "oauth",
"display_name": AuthMethod.DisplayNames.gitHub,
"auth_url": "oauth_turtle.com"
],
[
"type" : "oauth",
"display_name": "something else",
"auth_url": "oauth_crab.com"
],
[
"type" : "oauth",
"display_name": AuthMethod.DisplayNames.uaa,
"auth_url": "uaa_oauth_turtle.com"
],
[
"type" : "oauth",
"display_name": "something else",
"auth_url": "oauth_crab.com"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
result = StreamResult(subject.deserialize(partiallyValidData))
}
it("emits an auth method for each valid JSON auth method entry") {
let expectedAuthMethods = [
AuthMethod(type: .basic, displayName: AuthMethod.DisplayNames.basic, url: "basic_turtle.com"),
AuthMethod(type: .gitHub, displayName: AuthMethod.DisplayNames.gitHub, url: "oauth_turtle.com"),
AuthMethod(type: .uaa, displayName: AuthMethod.DisplayNames.uaa, url: "uaa_oauth_turtle.com"),
]
expect(authMethods).to(equal(expectedAuthMethods))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("Missing required 'auth_url' field") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"type" : "basic",
"display_name" : AuthMethod.DisplayNames.basic
],
[
"type" : "oauth",
"display_name" : AuthMethod.DisplayNames.gitHub,
"auth_url": "basic_crab.com"
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
result = StreamResult(subject.deserialize(partiallyValidData))
}
it("emits an auth method for each valid JSON auth method entry") {
expect(authMethods).to(equal([AuthMethod(type: .gitHub, displayName: AuthMethod.DisplayNames.gitHub, url: "basic_crab.com")]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("'auth_url' field is not a string") {
beforeEach {
let partiallyValidDataJSONArray = [
[
"type" : "basic",
"display_name" : AuthMethod.DisplayNames.basic,
"auth_url": "basic_turtle.com"
],
[
"type" : "basic",
"display_name" : AuthMethod.DisplayNames.basic,
"auth_url": 1
]
]
let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted)
result = StreamResult(subject.deserialize(partiallyValidData))
}
it("emits an auth method for each valid JSON auth method entry") {
expect(authMethods).to(equal([AuthMethod(type: .basic, displayName: AuthMethod.DisplayNames.basic, url: "basic_turtle.com")]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
}
describe("Given data cannot be interpreted as JSON") {
beforeEach {
let authMethodsDataString = "some string"
let invalidAuthMethodsData = authMethodsDataString.data(using: String.Encoding.utf8)
result = StreamResult(subject.deserialize(invalidAuthMethodsData!))
}
it("emits no methods") {
expect(authMethods).to(haveCount(0))
}
it("emits an error") {
let error = result.error as? MapError
expect(error).toNot(beNil())
expect(error?.reason).to(equal("Could not interpret response from auth methods endpoint as JSON"))
}
}
}
}
}
| apache-2.0 | 360d399e4effdef77aa0adde52664bb1 | 44.857143 | 150 | 0.424256 | 6.352048 | false | false | false | false |
nghialv/Hakuba | Hakuba/Source/Core/Hakuba.swift | 1 | 16242 | //
// Hakuba.swift
// Example
//
// Created by Le VanNghia on 3/4/16.
//
//
import UIKit
final public class Hakuba: NSObject {
weak var tableView: UITableView?
public weak var delegate: HakubaDelegate?
public private(set) var sections: [Section] = []
public var loadmoreHandler: (() -> ())?
public var loadmoreEnabled = false
public var loadmoreThreshold: CGFloat = 25
private let bumpTracker = BumpTracker()
private var offscreenCells: [String: Cell] = [:]
public var selectedRows: [IndexPath] {
return tableView?.indexPathsForSelectedRows ?? []
}
public var visibleRows: [IndexPath] {
return tableView?.indexPathsForVisibleRows ?? []
}
public var visibleCells: [Cell] {
return (tableView?.visibleCells as? [Cell]) ?? []
}
var currentTopSection = NSNotFound
var willFloatingSection = NSNotFound
public var sectionsCount: Int {
return sections.count
}
public var cellEditable = false
public var commitEditingHandler: ((UITableViewCellEditingStyle, IndexPath) -> ())?
public subscript<T: RawRepresentable & SectionIndexType>(index: T) -> Section {
get {
return self[index.rawValue]
}
set {
self[index.rawValue] = newValue
}
}
public subscript(index: Int) -> Section {
get {
return sections[index]
}
set {
setupSections([newValue], from: index)
sections[index] = newValue
}
}
subscript(indexPath: IndexPath) -> CellModel? {
return self[indexPath.section][indexPath.row]
}
public func getCellmodel(at indexPath: IndexPath) -> CellModel? {
return sections.get(at: indexPath.section)?[indexPath.row]
}
public func getSection(at index: Int) -> Section? {
return sections.get(at: index)
}
public func getSection<T: RawRepresentable & SectionIndexType>(at index: T) -> Section? {
return getSection(at: index.rawValue)
}
public init(tableView: UITableView) {
super.init()
self.tableView = tableView
tableView.delegate = self
tableView.dataSource = self
}
deinit {
tableView?.delegate = nil
tableView?.dataSource = nil
}
@discardableResult
public func bump(_ animation: UITableViewRowAnimation = .none) -> Self {
let changedCount = sections.reduce(0) { $0 + ($1.isChanged ? 1 : 0) }
if changedCount == 0 {
switch bumpTracker.getHakubaBumpType() {
case .reload:
tableView?.reloadData()
case let .insert(indexSet):
tableView?.insertSections(indexSet, with: animation)
case let .delete(indexSet):
tableView?.deleteSections(indexSet, with: animation)
case let .move(from, to):
tableView?.moveSection(from, toSection: to)
}
} else {
tableView?.reloadData()
sections.forEach { $0.didReloadTableView() }
}
bumpTracker.didBump()
return self
}
}
// MARK - UITableView methods
public extension Hakuba {
func setEditing(_ editing: Bool, animated: Bool) {
tableView?.setEditing(editing, animated: animated)
}
func selectCell(at indexPath: IndexPath, animated: Bool, scrollPosition: UITableViewScrollPosition) {
tableView?.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
func deselectCell(at indexPath: IndexPath, animated: Bool) {
tableView?.deselectRow(at: indexPath, animated: animated)
}
func deselectAllCells(animated: Bool) {
selectedRows.forEach {
tableView?.deselectRow(at: $0, animated: animated)
}
}
func cellForRow(at indexPath: IndexPath) -> Cell? {
return tableView?.cellForRow(at: indexPath) as? Cell
}
}
// MARK - Sections
public extension Hakuba {
// MARK - Reset
@discardableResult
func reset<T: RawRepresentable & SectionIndexType>(_ listType: T.Type) -> Self {
let sections = (0..<listType.count).map { _ in Section() }
return reset(sections)
}
@discardableResult
func reset() -> Self {
return reset([])
}
@discardableResult
func reset(_ section: Section) -> Self {
return reset([section])
}
@discardableResult
func reset(_ sections: [Section]) -> Self {
setupSections(sections, from: 0)
self.sections = sections
bumpTracker.didReset()
return self
}
// MARK - Append
@discardableResult
func append(_ section: Section) -> Self {
return append([section])
}
@discardableResult
func append(_ sections: [Section]) -> Self {
return insert(sections, at: sectionsCount)
}
// MARK - Insert
@discardableResult
func insert(_ section: Section, at index: Int) -> Self {
return insert([section], at: index)
}
@discardableResult
func insert(_ sections: [Section], at index: Int) -> Self {
guard sections.isNotEmpty else { return self }
let sIndex = min(max(index, 0), sectionsCount)
setupSections(sections, from: sIndex)
let r = self.sections.insert(sections, at: sIndex)
bumpTracker.didInsert(indexes: Array(r.lowerBound...r.upperBound))
return self
}
@discardableResult
func insertBeforeLast(_ section: Section) -> Self {
return insertBeforeLast([section])
}
@discardableResult
func insertBeforeLast(_ sections: [Section]) -> Self {
let index = max(sections.count - 1, 0)
return insert(sections, at: index)
}
// MARK - Remove
@discardableResult
func remove(at index: Int) -> Self {
return remove(at: [index])
}
@discardableResult
func remove(range: CountableRange<Int>) -> Self {
return remove(at: range.map { $0 })
}
@discardableResult
func remove(range: CountableClosedRange<Int>) -> Self {
return remove(at: range.map { $0 })
}
@discardableResult
func remove(at indexes: [Int]) -> Self {
guard indexes.isNotEmpty else { return self }
let sortedIndexes = indexes
.sorted(by: <)
.filter { $0 >= 0 && $0 < self.sectionsCount }
var remainSections: [Section] = []
var i = 0
for j in 0..<sectionsCount {
if let k = sortedIndexes.get(at: i), k == j {
i += 1
} else {
remainSections.append(sections[j])
}
}
sections = remainSections
setupSections(sections, from: 0)
bumpTracker.didRemove(indexes: sortedIndexes)
return self
}
@discardableResult
func removeLast() -> Self {
let index = sectionsCount - 1
guard index >= 0 else { return self }
return remove(at: index)
}
@discardableResult
func remove(_ section: Section) -> Self {
let index = section.index
guard index >= 0 && index < sectionsCount else { return self }
return remove(at: index)
}
@discardableResult
func removeAll() -> Self {
return reset()
}
// MAKR - Move
@discardableResult
func move(from fromIndex: Int, to toIndex: Int) -> Self {
sections.move(from: fromIndex, to: toIndex)
setupSections([sections[fromIndex]], from: fromIndex)
setupSections([sections[toIndex]], from: toIndex)
bumpTracker.didMove(from: fromIndex, to: toIndex)
return self
}
}
// MARK - SectionDelegate, CellModelDelegate
extension Hakuba: SectionDelegate, CellModelDelegate {
func bumpMe(with type: SectionBumpType, animation: UITableViewRowAnimation) {
switch type {
case .reload(let indexSet):
tableView?.reloadSections(indexSet, with: animation)
case .insert(let indexPaths):
tableView?.insertRows(at: indexPaths, with: animation)
case .move(let ori, let des):
tableView?.moveRow(at: ori, to: des)
case .delete(let indexPaths):
tableView?.deleteRows(at: indexPaths, with: animation)
}
}
func bumpMe(with type: ItemBumpType, animation: UITableViewRowAnimation) {
switch type {
case .reload(let indexPath):
tableView?.reloadRows(at: [indexPath], with: animation)
case .reloadHeader:
break
case .reloadFooter:
break
}
}
func getOffscreenCell(by identifier: String) -> Cell {
if let cell = offscreenCells[identifier] {
return cell
}
guard let cell = tableView?.dequeueReusableCell(withIdentifier: identifier) as? Cell else { return .init() }
offscreenCells[identifier] = cell
return cell
}
func tableViewWidth() -> CGFloat {
return tableView?.bounds.width ?? 0
}
}
// MARK - UITableViewDelegate cell
extension Hakuba: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return getCellmodel(at: indexPath)?.height ?? 0
}
public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return self.tableView(tableView, heightForRowAt: indexPath)
}
public func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return cellForRow(at: indexPath)?.willSelect(tableView, at: indexPath)
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cellmodel = getCellmodel(at: indexPath), let cell = cellForRow(at: indexPath) else { return }
cellmodel.didSelect(cell: cell)
cell.didSelect(tableView)
}
public func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
return cellForRow(at: indexPath)?.willDeselect(tableView, at: indexPath)
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
cellForRow(at: indexPath)?.didDeselect(tableView)
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? Cell else { return }
cell.willDisplay(tableView)
}
public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? Cell else { return }
cell.didEndDisplay(tableView)
}
public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return getCellmodel(at: indexPath)?.editingStyle ?? .none
}
public func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return getCellmodel(at: indexPath)?.shouldHighlight ?? true
}
public func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
cellForRow(at: indexPath)?.didHighlight(tableView)
}
public func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
cellForRow(at: indexPath)?.didUnhighlight(tableView)
}
}
// MARK - UITableViewDelegate header-footer
extension Hakuba {
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return sections.get(at: section)?.header?.height ?? 0
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let header = sections.get(at: section)?.header,
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: header.reuseIdentifier) as? HeaderFooterView else {
return nil
}
headerView.configureView(header)
return headerView
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return sections.get(at: section)?.footer?.height ?? 0
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let footer = sections.get(at: section)?.footer,
let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: footer.reuseIdentifier) as? HeaderFooterView else {
return nil
}
footerView.configureView(footer)
return footerView
}
public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let view = view as? HeaderFooterView, section == willFloatingSection else { return }
view.willDisplay(tableView, section: section)
view.didChangeFloatingState(true, section: section)
willFloatingSection = NSNotFound
}
public func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
guard let view = view as? HeaderFooterView else { return }
view.willDisplay(tableView, section: section)
}
public func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
guard let view = view as? HeaderFooterView else { return }
view.didEndDisplaying(tableView, section: section)
}
public func tableView(_ tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) {
guard let view = view as? HeaderFooterView else { return }
view.didEndDisplaying(tableView, section: section)
}
}
// MARK - UITableViewDataSource
extension Hakuba: UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return sectionsCount
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections.get(at: section)?.count ?? 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cellmodel = getCellmodel(at: indexPath),
let cell = tableView.dequeueReusableCell(withIdentifier: cellmodel.reuseIdentifier, for: indexPath) as? Cell else {
return .init()
}
cell.configureCell(cellmodel)
return cell
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
commitEditingHandler?(editingStyle, indexPath)
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
guard let cellmodel = getCellmodel(at: indexPath) else { return false }
return cellmodel.editable || cellEditable
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections.get(at: section)?.header?.title
}
public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return sections.get(at: section)?.footer?.title
}
}
// MARK - Private methods
private extension Hakuba {
func setupSections(_ sections: [Section], from index: Int) {
var index = index
sections.forEach {
$0.setup(at: index, delegate: self)
index += 1
}
}
}
| mit | 028e65465e7efd2c2b8302ac4a2c95af | 30.415861 | 138 | 0.617104 | 5.096329 | false | false | false | false |
Ramotion/circle-menu | CircleMenu/ViewController.swift | 1 | 2528 | //
// ViewController.swift
// CircleMenu
//
// Created by Alex K. on 27/01/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
extension UIColor {
static func color(_ red: Int, green: Int, blue: Int, alpha: Float) -> UIColor {
return UIColor(
red: 1.0 / 255.0 * CGFloat(red),
green: 1.0 / 255.0 * CGFloat(green),
blue: 1.0 / 255.0 * CGFloat(blue),
alpha: CGFloat(alpha))
}
}
class ViewController: UIViewController, CircleMenuDelegate {
// let colors = [UIColor.redColor(), UIColor.grayColor(), UIColor.greenColor(), UIColor.purpleColor()]
let items: [(icon: String, color: UIColor)] = [
("icon_home", UIColor(red: 0.19, green: 0.57, blue: 1, alpha: 1)),
("icon_search", UIColor(red: 0.22, green: 0.74, blue: 0, alpha: 1)),
("notifications-btn", UIColor(red: 0.96, green: 0.23, blue: 0.21, alpha: 1)),
("settings-btn", UIColor(red: 0.51, green: 0.15, blue: 1, alpha: 1)),
("nearby-btn", UIColor(red: 1, green: 0.39, blue: 0, alpha: 1))
]
override func viewDidLoad() {
super.viewDidLoad()
// add button
// let button = CircleMenu(
// frame: CGRect(x: 200, y: 200, width: 50, height: 50),
// normalIcon:"icon_menu",
// selectedIcon:"icon_close",
// buttonsCount: 4,
// duration: 4,
// distance: 120)
// button.backgroundColor = UIColor.lightGrayColor()
// button.delegate = self
// button.layer.cornerRadius = button.frame.size.width / 2.0
// view.addSubview(button)
}
// MARK: <CircleMenuDelegate>
func circleMenu(_: CircleMenu, willDisplay button: UIButton, atIndex: Int) {
button.backgroundColor = items[atIndex].color
button.setImage(UIImage(named: items[atIndex].icon), for: .normal)
// set highlited image
let highlightedImage = UIImage(named: items[atIndex].icon)?.withRenderingMode(.alwaysTemplate)
button.setImage(highlightedImage, for: .highlighted)
button.tintColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
}
func circleMenu(_: CircleMenu, buttonWillSelected _: UIButton, atIndex: Int) {
print("button will selected: \(atIndex)")
}
func circleMenu(_: CircleMenu, buttonDidSelected _: UIButton, atIndex: Int) {
print("button did selected: \(atIndex)")
}
}
| mit | bb6405a2039183cae9b0f574e8c38152 | 36.161765 | 109 | 0.57776 | 3.942278 | false | false | false | false |
hilen/TSWeChat | TSWeChat/Classes/Chat/Views/TSChatVoiceIndicatorView.swift | 1 | 3740 | //
// TSRecordIndicatorView.swift
// TSWeChat
//
// Created by Hilen on 12/22/15.
// Copyright © 2015 Hilen. All rights reserved.
//
import UIKit
import Dollar
class TSChatVoiceIndicatorView: UIView {
@IBOutlet weak var centerView: UIView!{didSet { //中央的灰色背景 view
centerView.layer.cornerRadius = 4.0
centerView.layer.masksToBounds = true
}}
@IBOutlet weak var noteLabel: UILabel! {didSet { //提示的 label
noteLabel.layer.cornerRadius = 2.0
noteLabel.layer.masksToBounds = true
}}
@IBOutlet weak var cancelImageView: UIImageView! //取消提示
@IBOutlet weak var signalValueImageView: UIImageView! //音量的图片
@IBOutlet weak var recordingView: UIView! //录音整体的 view,控制是否隐藏
@IBOutlet weak var tooShotPromptImageView: UIImageView! //录音时间太短的提示
override init (frame : CGRect) {
super.init(frame : frame)
self.initContent()
}
convenience init () {
self.init(frame:CGRect.zero)
self.initContent()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initContent() {
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
//对外交互的 view 控制
// MARK: - @extension TSChatVoiceIndicatorView
extension TSChatVoiceIndicatorView {
//正在录音
func recording() {
self.isHidden = false
self.cancelImageView.isHidden = true
self.tooShotPromptImageView.isHidden = true
self.recordingView.isHidden = false
self.noteLabel.backgroundColor = UIColor.clear
self.noteLabel.text = "手指上滑,取消发送"
}
//录音过程中音量的变化
func signalValueChanged(_ value: CGFloat) {
}
//滑动取消
func slideToCancelRecord() {
self.isHidden = false
self.cancelImageView.isHidden = false
self.tooShotPromptImageView.isHidden = true
self.recordingView.isHidden = true
self.noteLabel.backgroundColor = UIColor.init(ts_hexString: "#9C3638")
self.noteLabel.text = "松开手指,取消发送"
}
//录音时间太短的提示
func messageTooShort() {
self.isHidden = false
self.cancelImageView.isHidden = true
self.tooShotPromptImageView.isHidden = false
self.recordingView.isHidden = true
self.noteLabel.backgroundColor = UIColor.clear
self.noteLabel.text = "说话时间太短"
//0.5秒后消失
let delayTime = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.endRecord()
}
}
//录音结束
func endRecord() {
self.isHidden = true
}
//更新麦克风的音量大小
func updateMetersValue(_ value: Float) {
var index = Int(round(value))
index = index > 7 ? 7 : index
index = index < 0 ? 0 : index
let array = [
TSAsset.RecordingSignal001.image,
TSAsset.RecordingSignal002.image,
TSAsset.RecordingSignal003.image,
TSAsset.RecordingSignal004.image,
TSAsset.RecordingSignal005.image,
TSAsset.RecordingSignal006.image,
TSAsset.RecordingSignal007.image,
TSAsset.RecordingSignal008.image,
]
self.signalValueImageView.image = Dollar.fetch(array, index)
}
}
| mit | 260159af1cca4b8647e7c08c26f30d67 | 27.512195 | 109 | 0.629598 | 4.130742 | false | false | false | false |
jkolb/ModestProposal | ModestProposal/HTTPResponseField.swift | 2 | 2412 | // Copyright (c) 2016 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public enum HTTPResponseField : String {
case AccessControlAllowOrigin = "Access-Control-Allow-Origin"
case AcceptRanges = "Accept-Ranges"
case Age = "Age"
case Allow = "Allow"
case CacheControl = "Cache-Control"
case Connection = "Connection"
case ContentEncoding = "Content-Encoding"
case ContentLanguage = "Content-Language"
case ContentLength = "Content-Length"
case ContentLocation = "Content-Location"
case ContentMD5 = "Content-MD5"
case ContentDisposition = "Content-Disposition"
case ContentRange = "Content-Range"
case ContentType = "Content-Type"
case Date = "Date"
case ETag = "ETag"
case Expires = "Expires"
case LastModified = "Last-Modified"
case Link = "Link"
case Pragma = "Pragma"
case ProxyAuthenticate = "Proxy-Authenticate"
case Refresh = "Refresh"
case RetryAfter = "Retry-After"
case Server = "Server"
case SetCookie = "Set-Cookie"
case Status = "Status"
case StrictTransportSecurity = "Strict-Transport-Security"
case Trailer = "Trailer"
case TransferEncoding = "Transfer-Encoding"
case Upgrade = "Upgrade"
case Vary = "Vary"
case Via = "Via"
case Warning = "Warning"
case WWWAuthenticate = "WWW-Authenticate"
}
| mit | 1e2caac53bdeb67368ea07f3e96a994c | 42.071429 | 80 | 0.721393 | 4.299465 | false | false | false | false |
JGiola/swift | test/ClangImporter/objc_async.swift | 1 | 12804 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -I %S/Inputs/custom-modules %s -verify -verify-additional-file %swift_src_root/test/Inputs/clang-importer-sdk/usr/include/ObjCConcurrency.h -strict-concurrency=targeted -parse-as-library -enable-experimental-feature SendableCompletionHandlers
// REQUIRES: objc_interop
// REQUIRES: concurrency
// REQUIRES: asserts
import Foundation
import ObjCConcurrency
// expected-remark@-1{{add '@preconcurrency' to suppress 'Sendable'-related warnings from module 'ObjCConcurrency'}}
@available(SwiftStdlib 5.5, *)
@MainActor func onlyOnMainActor() { }
@available(SwiftStdlib 5.5, *)
func testSlowServer(slowServer: SlowServer) async throws {
let _: Int = await slowServer.doSomethingSlow("mail")
let _: Bool = await slowServer.checkAvailability()
let _: String = try await slowServer.findAnswer()
let _: String = try await slowServer.findAnswerFailingly()
let (aOpt, b) = try await slowServer.findQAndA()
if let a = aOpt { // make sure aOpt is optional
print(a)
}
let _: String = b // make sure b is non-optional
let _: String = try await slowServer.findAnswer()
let _: Void = await slowServer.doSomethingFun("jump")
let _: (Int) -> Void = slowServer.completionHandler
// async version
let _: Int = await slowServer.doSomethingConflicted("thinking")
// still async version...
let _: Int = slowServer.doSomethingConflicted("thinking")
// expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{16-16=await }}
// expected-note@-2{{call is 'async'}}
let _: String? = try await slowServer.fortune()
let _: Int = try await slowServer.magicNumber(withSeed: 42)
await slowServer.serverRestart("localhost")
await slowServer.serverRestart("localhost", atPriority: 0.8)
_ = await slowServer.allOperations()
let _: Int = await slowServer.bestName("hello")
let _: Int = await slowServer.customize("hello")
slowServer.unavailableMethod() // expected-warning{{instance method 'unavailableMethod' is unavailable from asynchronous contexts}}
slowServer.unavailableMethodWithMessage() // expected-warning{{instance method 'unavailableMethodWithMessage' is unavailable from asynchronous contexts; Blarpy!}}
let _: String = await slowServer.dance("slide")
let _: String = await slowServer.__leap(17)
slowServer.repeatTrick("jump") // expected-error{{missing argument for parameter 'completionHandler' in call}}
_ = try await slowServer.someAsyncMethod()
_ = await slowServer.operations()
_ = await slowServer.runOnMainThread()
}
@available(SwiftStdlib 5.5, *)
func testSlowServerSynchronous(slowServer: SlowServer) {
// synchronous version
let _: Int = slowServer.doSomethingConflicted("thinking")
slowServer.poorlyNamed("hello") { (i: Int) in print(i) }
slowServer.customize(with: "hello") { (i: Int) in print(i) }
slowServer.dance("jig") { s in print(s + "") }
slowServer.leap(17) { s in print(s + "") }
slowServer.repeatTrick("jump") { i in print(i + 1) }
let s = slowServer.operations
_ = s + []
slowServer.runOnMainThread { s in
print(s)
onlyOnMainActor() // okay because runOnMainThread has a @MainActor closure
}
slowServer.overridableButRunsOnMainThread { s in
print(s)
onlyOnMainActor() // okay because parameter is @MainActor
}
let _: Int = slowServer.overridableButRunsOnMainThread // expected-error{{cannot convert value of type '(((String) -> Void)?) -> Void' to specified type 'Int'}}
}
@available(SwiftStdlib 5.5, *)
func testSlowServerOldSchool(slowServer: SlowServer) {
slowServer.doSomethingSlow("mail") { i in
_ = i
}
_ = slowServer.allOperations
}
@available(SwiftStdlib 5.5, *)
func testSendable(fn: () -> Void) {
doSomethingConcurrently(fn) // okay, due to implicit @preconcurrency
doSomethingConcurrentlyButUnsafe(fn) // okay, @Sendable not part of the type
var x = 17
doSomethingConcurrently {
print(x)
x = x + 1
}
}
@available(SwiftStdlib 5.5, *)
func testSendableInAsync() async {
var x = 17
doSomethingConcurrentlyButUnsafe {
x = 42 // expected-warning{{mutation of captured var 'x' in concurrently-executing code}}
}
print(x)
}
@available(SwiftStdlib 5.5, *)
func testSendableAttrs(
sendableClass: SendableClass, nonSendableClass: NonSendableClass,
sendableEnum: SendableEnum, nonSendableEnum: NonSendableEnum,
sendableOptions: SendableOptions, nonSendableOptions: NonSendableOptions,
sendableError: SendableError, nonSendableError: NonSendableError,
sendableStringEnum: SendableStringEnum, nonSendableStringEnum: NonSendableStringEnum,
sendableStringStruct: SendableStringStruct, nonSendableStringStruct: NonSendableStringStruct
) async {
func takesSendable<T: Sendable>(_: T) {}
takesSendable(sendableClass) // no-error
takesSendable(nonSendableClass) // expected-warning{{conformance of 'NonSendableClass' to 'Sendable' is unavailable}}
doSomethingConcurrently {
print(sendableClass) // no-error
print(nonSendableClass) // expected-warning{{capture of 'nonSendableClass' with non-sendable type 'NonSendableClass' in a `@Sendable` closure}}
print(sendableEnum) // no-error
print(nonSendableEnum) // expected-warning{{capture of 'nonSendableEnum' with non-sendable type 'NonSendableEnum' in a `@Sendable` closure}}
print(sendableOptions) // no-error
print(nonSendableOptions) // expected-warning{{capture of 'nonSendableOptions' with non-sendable type 'NonSendableOptions' in a `@Sendable` closure}}
print(sendableError) // no-error
print(nonSendableError) // no-error--we don't respect `@_nonSendable` on `ns_error_domain` types because all errors are Sendable
print(sendableStringEnum) // no-error
print(nonSendableStringEnum) // expected-warning{{capture of 'nonSendableStringEnum' with non-sendable type 'NonSendableStringEnum' in a `@Sendable` closure}}
print(sendableStringStruct) // no-error
print(nonSendableStringStruct) // expected-warning{{capture of 'nonSendableStringStruct' with non-sendable type 'NonSendableStringStruct' in a `@Sendable` closure}}
}
}
// Check import of attributes
@available(SwiftStdlib 5.5, *)
func globalAsync() async { }
@available(SwiftStdlib 5.5, *)
actor MySubclassCheckingSwiftAttributes : ProtocolWithSwiftAttributes {
func syncMethod() { } // expected-note 2{{calls to instance method 'syncMethod()' from outside of its actor context are implicitly asynchronous}}
nonisolated func independentMethod() {
syncMethod() // expected-error{{ctor-isolated instance method 'syncMethod()' can not be referenced from a non-isolated context}}
}
nonisolated func nonisolatedMethod() {
}
@MainActor func mainActorMethod() {
syncMethod() // expected-error{{actor-isolated instance method 'syncMethod()' can not be referenced from the main actor}}
}
@MainActor func uiActorMethod() { }
}
// Sendable conformance inference for imported types.
func acceptCV<T: Sendable>(_: T) { }
struct MyStruct: Sendable {
var range: NSRange
var inner: SendableStructWithNonSendable
}
@available(SwiftStdlib 5.5, *)
func testCV(r: NSRange, someStruct: SendableStructWithNonSendable) async {
acceptCV(r)
acceptCV(someStruct)
}
// Global actor (unsafe) isolation.
@available(SwiftStdlib 5.5, *)
actor SomeActor { }
@available(SwiftStdlib 5.5, *)
@globalActor
struct SomeGlobalActor {
static let shared = SomeActor()
}
@available(SwiftStdlib 5.5, *)
class MyButton : NXButton {
@MainActor func testMain() {
onButtonPress() // okay
}
@SomeGlobalActor func testOther() {
onButtonPress() // expected-error{{call to main actor-isolated instance method 'onButtonPress()' in a synchronous global actor 'SomeGlobalActor'-isolated context}}
}
func test() {
onButtonPress() // okay
}
}
@available(SwiftStdlib 5.5, *)
func testButtons(mb: MyButton) {
mb.onButtonPress()
}
@available(SwiftStdlib 5.5, *)
func testMirrored(instance: ClassWithAsync) async {
await instance.instanceAsync()
await instance.protocolMethod()
await instance.customAsyncName()
}
@available(SwiftStdlib 5.5, *)
@MainActor class MyToolbarButton : NXButton {
var count = 5
func f() {
Task {
let c = count
print(c)
}
}
}
@available(SwiftStdlib 5.5, *)
@MainActor class MyView: NXView {
func f() {
Task {
await self.g()
}
}
func g() async { }
}
@available(SwiftStdlib 5.5, *)
@MainActor func mainActorFn() {}
@available(SwiftStdlib 5.5, *)
@SomeGlobalActor func sgActorFn() {}
// Check inferred isolation for overridden decls from ObjC.
// Note that even if the override is not present, it
// can have an affect. -- rdar://87217618 / SR-15694
@MainActor
@available(SwiftStdlib 5.5, *)
class FooFrame: PictureFrame {
init() {
super.init(size: 0)
}
override init(size n: Int) {
super.init(size: n)
}
override func rotate() {
mainActorFn()
}
}
@available(SwiftStdlib 5.5, *)
class BarFrame: PictureFrame {
init() {
super.init(size: 0)
}
override init(size n: Int) {
super.init(size: n)
}
override func rotate() {
mainActorFn()
}
}
@available(SwiftStdlib 5.5, *)
@SomeGlobalActor
class BazFrame: NotIsolatedPictureFrame {
init() {
super.init(size: 0)
}
override init(size n: Int) {
super.init(size: n)
}
override func rotate() {
sgActorFn()
}
}
@SomeGlobalActor
class BazFrameIso: PictureFrame { // expected-error {{global actor 'SomeGlobalActor'-isolated class 'BazFrameIso' has different actor isolation from main actor-isolated superclass 'PictureFrame'}}
}
@available(SwiftStdlib 5.5, *)
func check() async {
_ = await BarFrame()
_ = await FooFrame()
_ = await BazFrame()
_ = await BarFrame(size: 0)
_ = await FooFrame(size: 0)
_ = await BazFrame(size: 0)
}
@available(SwiftStdlib 5.5, *)
func testSender(
sender: NXSender,
sendableObject: SendableClass,
nonSendableObject: NonSendableClass,
sendableSubclassOfNonSendableObject: NonSendableClass & Sendable,
sendableProtos: LabellyProtocol & ObjCClub & Sendable,
nonSendableProtos: LabellyProtocol & ObjCClub,
sendableGeneric: GenericObject<SendableClass> & Sendable,
nonSendableGeneric: GenericObject<SendableClass>,
ptr: UnsafeMutableRawPointer,
stringArray: [String]
) async {
sender.sendAny(sendableObject)
sender.sendAny(nonSendableObject)
// expected-warning@-1 {{conformance of 'NonSendableClass' to 'Sendable' is unavailable}}
sender.sendOptionalAny(sendableObject)
sender.sendOptionalAny(nonSendableObject)
// expected-warning@-1 {{conformance of 'NonSendableClass' to 'Sendable' is unavailable}}
sender.sendSendable(sendableObject)
sender.sendSendableSubclasses(nonSendableObject)
// expected-warning@-1 {{conformance of 'NonSendableClass' to 'Sendable' is unavailable}}
sender.sendSendableSubclasses(sendableSubclassOfNonSendableObject)
// expected-warning@-1 {{conformance of 'NonSendableClass' to 'Sendable' is unavailable}}
// FIXME(rdar://89992569): Should allow for the possibility that NonSendableClass will have a Sendable subclass
sender.sendProto(sendableProtos)
sender.sendProto(nonSendableProtos)
// expected-warning@-1 {{type 'any LabellyProtocol & ObjCClub' does not conform to the 'Sendable' protocol}}
sender.sendProtos(sendableProtos)
sender.sendProtos(nonSendableProtos)
// expected-warning@-1 {{type 'any LabellyProtocol & ObjCClub' does not conform to the 'Sendable' protocol}}
sender.sendAnyArray([sendableObject])
sender.sendAnyArray([nonSendableObject])
// expected-warning@-1 {{conformance of 'NonSendableClass' to 'Sendable' is unavailable; this is an error in Swift 6}}
sender.sendGeneric(sendableGeneric)
// expected-warning@-1{{type 'GenericObject<SendableClass>' does not conform to the 'Sendable' protocol}}
// FIXME: Shouldn't warn
sender.sendGeneric(nonSendableGeneric)
// expected-warning@-1 {{type 'GenericObject<SendableClass>' does not conform to the 'Sendable' protocol}}
sender.sendPtr(ptr)
sender.sendStringArray(stringArray)
}
// Sendable checking
public struct SomeWrapper<T: AuditedNonSendable> {
public let unit: T
}
extension SomeWrapper: Sendable where T: Sendable {}
// rdar://96830159
@MainActor class SendableCompletionHandler {
var isolatedThing: [String] = []
// expected-note@-1 {{property declared here}}
func makeCall(slowServer: SlowServer) {
slowServer.doSomethingSlow("churn butter") { (_ : Int) in
let _ = self.isolatedThing
// expected-warning@-1 {{main actor-isolated property 'isolatedThing' can not be referenced from a Sendable closure; this is an error in Swift 6}}
}
}
}
| apache-2.0 | 240caf089009c7b4d8c13cbdc9267ad2 | 31.090226 | 315 | 0.722196 | 3.953072 | false | false | false | false |
kosicki123/eidolon | Kiosk/Sale Artwork Details/SaleArtworkDetailsViewController.swift | 1 | 13653 | import UIKit
import ORStackView
import Artsy_UILabels
import Artsy_UIFonts
class SaleArtworkDetailsViewController: UIViewController {
var allowAnimations = true
var auctionID = AppSetup.sharedState.auctionID
var saleArtwork: SaleArtwork!
@IBOutlet weak var metadataStackView: ORTagBasedAutoStackView!
@IBOutlet weak var additionalDetailScrollView: ORStackScrollView!
override func viewDidLoad() {
super.viewDidLoad()
setupMetadataView()
setupAdditionalDetailStackView()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == .ZoomIntoArtwork {
let nextViewController = segue.destinationViewController as SaleArtworkZoomViewController
nextViewController.saleArtwork = saleArtwork
}
}
}
enum MetadataStackViewTag: Int {
case ArtistNameLabel = 1
case ArtworkNameLabel
case ArtworkMediumLabel
case ArtworkDimensionsLabel
case ImageRightsLabel
case EstimateTopBorder
case EstimateLabel
case EstimateBottomBorder
case CurrentBidLabel
case CurrentBidValueLabel
case NumberOfBidsPlacedLabel
case BidButton
case Gobbler
}
extension SaleArtworkDetailsViewController {
@IBAction func backWasPressed(sender: AnyObject) {
navigationController?.popViewControllerAnimated(true)
}
private func setupMetadataView() {
enum LabelType {
case Serif
case SansSerif
case ItalicsSerif
case Bold
}
func label(type: LabelType, tag: MetadataStackViewTag, fontSize: CGFloat = 16.0) -> UILabel {
let label: UILabel = { () -> UILabel in
switch type {
case .Serif:
return ARSerifLabel()
case .SansSerif:
return ARSansSerifLabel()
case .ItalicsSerif:
return ARItalicsSerifLabel()
case .Bold:
let label = ARSerifLabel()
label.font = UIFont.sansSerifFontWithSize(label.font.pointSize)
return label
}
}()
label.lineBreakMode = .ByWordWrapping
label.font = label.font.fontWithSize(fontSize)
label.tag = tag.rawValue
label.preferredMaxLayoutWidth = 276
return label
}
if let artist = artist() {
let artistNameLabel = label(.SansSerif, .ArtistNameLabel)
artistNameLabel.text = artist.name
metadataStackView.addSubview(artistNameLabel, withTopMargin: "0", sideMargin: "0")
}
let artworkNameLabel = label(.ItalicsSerif, .ArtworkNameLabel)
artworkNameLabel.text = "\(saleArtwork.artwork.title), \(saleArtwork.artwork.date)"
metadataStackView.addSubview(artworkNameLabel, withTopMargin: "10", sideMargin: "0")
if let medium = saleArtwork.artwork.medium {
if countElements(medium) > 0 {
let mediumLabel = label(.Serif, .ArtworkMediumLabel)
mediumLabel.text = medium
metadataStackView.addSubview(mediumLabel, withTopMargin: "22", sideMargin: "0")
}
}
if countElements(saleArtwork.artwork.dimensions) > 0 {
let dimensionsLabel = label(.Serif, .ArtworkDimensionsLabel)
dimensionsLabel.text = (saleArtwork.artwork.dimensions as NSArray).componentsJoinedByString("\n")
metadataStackView.addSubview(dimensionsLabel, withTopMargin: "5", sideMargin: "0")
}
retrieveImageRights().filter { (imageRights) -> Bool in
return (countElements(imageRights as? String ?? "") > 0)
}.subscribeNext { [weak self] (imageRights) -> Void in
if countElements(imageRights as String) > 0 {
let rightsLabel = label(.Serif, .ImageRightsLabel)
rightsLabel.text = imageRights as? String
self?.metadataStackView.addSubview(rightsLabel, withTopMargin: "22", sideMargin: "0")
}
}
let estimateTopBorder = UIView()
estimateTopBorder.constrainHeight("1")
estimateTopBorder.tag = MetadataStackViewTag.EstimateTopBorder.rawValue
metadataStackView.addSubview(estimateTopBorder, withTopMargin: "22", sideMargin: "0")
let estimateLabel = label(.Serif, .EstimateLabel)
estimateLabel.text = saleArtwork.estimateString
metadataStackView.addSubview(estimateLabel, withTopMargin: "15", sideMargin: "0")
let estimateBottomBorder = UIView()
estimateBottomBorder.constrainHeight("1")
estimateBottomBorder.tag = MetadataStackViewTag.EstimateBottomBorder.rawValue
metadataStackView.addSubview(estimateBottomBorder, withTopMargin: "10", sideMargin: "0")
rac_signalForSelector("viewDidLayoutSubviews").subscribeNext { [weak estimateTopBorder, weak estimateBottomBorder] (_) -> Void in
estimateTopBorder?.drawDottedBorders()
estimateBottomBorder?.drawDottedBorders()
}
let hasBidsSignal = RACObserve(saleArtwork, "highestBidCents").map{ (cents) -> AnyObject! in
return (cents != nil) && ((cents as? NSNumber ?? 0) > 0)
}
let currentBidLabel = label(.Serif, .CurrentBidLabel)
RAC(currentBidLabel, "text") <~ RACSignal.`if`(hasBidsSignal, then: RACSignal.`return`("Current Bid:"), `else`: RACSignal.`return`("Starting Bid:"))
metadataStackView.addSubview(currentBidLabel, withTopMargin: "22", sideMargin: "0")
let currentBidValueLabel = label(.Bold, .CurrentBidValueLabel, fontSize: 27)
RAC(currentBidValueLabel, "text") <~ saleArtwork.currentBidSignal()
metadataStackView.addSubview(currentBidValueLabel, withTopMargin: "10", sideMargin: "0")
let numberOfBidsPlacedLabel = label(.Serif, .NumberOfBidsPlacedLabel)
RAC(numberOfBidsPlacedLabel, "text") <~ saleArtwork.numberOfBidsSignal
metadataStackView.addSubview(numberOfBidsPlacedLabel, withTopMargin: "10", sideMargin: "0")
let bidButton = ActionButton()
bidButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self] (_) -> Void in
if let strongSelf = self {
strongSelf.bid(strongSelf.auctionID, saleArtwork: strongSelf.saleArtwork, allowAnimations: strongSelf.allowAnimations)
}
}
bidButton.setTitle("Bid", forState: .Normal)
bidButton.tag = MetadataStackViewTag.BidButton.rawValue
metadataStackView.addSubview(bidButton, withTopMargin: "40", sideMargin: "0")
metadataStackView.bottomMarginHeight = CGFloat(NSNotFound)
}
private func setupImageView(imageView: UIImageView) {
if let image = saleArtwork.artwork.images?.first? {
if let url = image.fullsizeURL() {
imageView.sd_setImageWithURL(url, completed: { [weak self] image, error, type, url -> () in
imageView.backgroundColor = UIColor.clearColor()
return
})
}
let heightConstraintNumber = min(400, CGFloat(538) / image.aspectRatio)
imageView.constrainHeight( "\(heightConstraintNumber)" )
imageView.contentMode = .ScaleAspectFit
imageView.userInteractionEnabled = true
let recognizer = UITapGestureRecognizer()
imageView.addGestureRecognizer(recognizer)
recognizer.rac_gestureSignal().subscribeNext() { [weak self] (_) in
self?.performSegue(.ZoomIntoArtwork)
return
}
}
}
private func setupAdditionalDetailStackView() {
enum LabelType {
case Header
case Body
}
func label(type: LabelType, layoutSignal: RACSignal? = nil) -> UILabel {
let (label, fontSize) = { () -> (UILabel, CGFloat) in
switch type {
case .Header:
return (ARSansSerifLabel(), 14)
case .Body:
return (ARSerifLabel(), 16)
}
}()
label.font = label.font.fontWithSize(fontSize)
label.lineBreakMode = .ByWordWrapping
layoutSignal?.take(1).subscribeNext { [weak label] (_) -> Void in
if let label = label {
label.preferredMaxLayoutWidth = CGRectGetWidth(label.frame)
}
}
return label
}
additionalDetailScrollView.stackView.bottomMarginHeight = 40
let imageView = UIImageView()
additionalDetailScrollView.stackView.addSubview(imageView, withTopMargin: "0", sideMargin: "40")
setupImageView(imageView)
let additionalInfoHeaderLabel = label(.Header)
additionalInfoHeaderLabel.text = "Additional Information"
additionalDetailScrollView.stackView.addSubview(additionalInfoHeaderLabel, withTopMargin: "20", sideMargin: "40")
if let blurb = saleArtwork.artwork.blurb {
let blurbLabel = label(.Body, layoutSignal: additionalDetailScrollView.stackView.rac_signalForSelector("layoutSubviews"))
blurbLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( blurb )
additionalDetailScrollView.stackView.addSubview(blurbLabel, withTopMargin: "22", sideMargin: "40")
}
let additionalInfoLabel = label(.Body, layoutSignal: additionalDetailScrollView.stackView.rac_signalForSelector("layoutSubviews"))
additionalInfoLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( saleArtwork.artwork.additionalInfo )
additionalDetailScrollView.stackView.addSubview(additionalInfoLabel, withTopMargin: "22", sideMargin: "40")
retrieveAdditionalInfo().filter { (info) -> Bool in
return (countElements(info as? String ?? "") > 0)
}.subscribeNext { [weak self] (info) -> Void in
additionalInfoLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( info as String )
}
if let artist = artist() {
retrieveArtistBlurb().filter { (blurb) -> Bool in
return (countElements(blurb as? String ?? "") > 0)
}.subscribeNext { [weak self] (blurb) -> Void in
if self == nil {
return
}
let aboutArtistHeaderLabel = label(.Header)
aboutArtistHeaderLabel.text = "About \(artist.name)"
self?.additionalDetailScrollView.stackView.addSubview(aboutArtistHeaderLabel, withTopMargin: "22", sideMargin: "40")
let aboutAristLabel = label(.Body, layoutSignal: self?.additionalDetailScrollView.stackView.rac_signalForSelector("layoutSubviews"))
aboutAristLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( blurb as? String )
self?.additionalDetailScrollView.stackView.addSubview(aboutAristLabel, withTopMargin: "22", sideMargin: "40")
}
}
}
private func artist() -> Artist? {
return saleArtwork.artwork.artists?.first
}
private func retrieveImageRights() -> RACSignal {
let artwork = saleArtwork.artwork
if let imageRights = artwork.imageRights {
return RACSignal.`return`(imageRights)
} else {
let endpoint: ArtsyAPI = ArtsyAPI.Artwork(id: artwork.id)
return XAppRequest(endpoint, parameters: endpoint.defaultParameters).filterSuccessfulStatusCodes().mapJSON().map{ (json) -> AnyObject! in
return json["image_rights"]
}.filter({ (imageRights) -> Bool in
imageRights != nil
}).doNext{ (imageRights) -> Void in
artwork.imageRights = imageRights as? String
return
}
}
}
// Duped code with ^ could be better?
private func retrieveAdditionalInfo() -> RACSignal {
let artwork = saleArtwork.artwork
if let additionalInfo = artwork.additionalInfo {
return RACSignal.`return`(additionalInfo)
} else {
let endpoint: ArtsyAPI = ArtsyAPI.Artwork(id: artwork.id)
return XAppRequest(endpoint, parameters: endpoint.defaultParameters).filterSuccessfulStatusCodes().mapJSON().map{ (json) -> AnyObject! in
return json["additional_information"]
}.filter({ (info) -> Bool in
info != nil
}).doNext{ (info) -> Void in
artwork.additionalInfo = info as? String
return
}
}
}
private func retrieveArtistBlurb() -> RACSignal {
if let artist = artist() {
if let blurb = artist.blurb {
return RACSignal.`return`(blurb)
} else {
let endpoint: ArtsyAPI = ArtsyAPI.Artist(id: artist.id)
return XAppRequest(endpoint, parameters: endpoint.defaultParameters).filterSuccessfulStatusCodes().mapJSON().map{ (json) -> AnyObject! in
return json["blurb"]
}.filter({ (blurb) -> Bool in
blurb != nil
}).doNext{ (blurb) -> Void in
artist.blurb = blurb as? String
return
}
}
} else {
return RACSignal.empty()
}
}
}
| mit | f1e882852e2d13bbc7f73e559826c746 | 41.138889 | 156 | 0.622794 | 5.775381 | false | false | false | false |
nsagora/validation-kit | ValidationToolkit.playground/Pages/Predicate Constraint.xcplaygroundpage/Contents.swift | 1 | 578 | //: [Previous](@previous)
import Foundation
import ValidationToolkit
/*:
## Simple Constraint
In the following example we use a `BlockPredicate` based `Constraint` to evaluate if an username has at least 5 characters.
*/
let username = "Hel!O"
let predicate = BlockPredicate<String> { $0.count >= 5 }
let constraint = PredicateConstraint(predicate: predicate, error:Form.Username.invalid)
let result = constraint.evaluate(with: username)
switch result {
case .success:
print("Nice 🎬!")
case .failure(let summary):
print(summary.errors)
}
//: [Next](@next)
| apache-2.0 | ff583b8176391ce6830c2f373fbacf5f | 22 | 124 | 0.723478 | 3.833333 | false | false | false | false |
LockLight/Weibo_Demo | SinaWeibo/SinaWeibo/Tools/Bundle+JudgeVersion.swift | 1 | 768 | //
// Bundle+JudgeVersion.swift
// SinaWeibo
//
// Created by locklight on 17/4/5.
// Copyright © 2017年 LockLight. All rights reserved.
//
import UIKit
let versionKey:String = "versionKey"
extension Bundle {
var isNewFeatrue:Bool{
//获取当前版本
let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
as! String
//获取老版本
let oldVersion = UserDefaults.standard.value(forKey: versionKey) as? String
if(oldVersion == nil || currentVersion != oldVersion){
//保持当前版本号
UserDefaults.standard.set(currentVersion, forKey: versionKey)
return true
}
return false
}
}
| mit | 032c9b9a8015b318cd042a1269ed7068 | 24.137931 | 86 | 0.600823 | 4.445122 | false | false | false | false |
ben-ng/swift | benchmark/single-source/XorLoop.swift | 1 | 933 | //===--- XorLoop.swift ----------------------------------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
public func run_XorLoop(_ N: Int) {
for _ in 1...5*N {
let size = 100000
let ref_result = 47813324
var x = [Int](repeating: 0xA05FD, count: size)
for i in 0..<size {
x[i] = x[i] ^ 12345678
}
let res = x[10]+x[100]+x[1000]+x[10000]
CheckResults(res == ref_result,
"Incorrect results in XorLoop: \(res) != \(ref_result)")
}
}
| apache-2.0 | ce175e1b6d5e9fcb9e3079c4d5939ae1 | 32.321429 | 80 | 0.546624 | 3.970213 | false | false | false | false |
PhillipEnglish/TIY-Assignments | Jackpot/TicketPickerTableViewController.swift | 1 | 3263 | //
// TicketPickerTableViewController.swift
// Jackpot
//
// Created by Phillip English on 10/14/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class TicketPickerTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| cc0-1.0 | 3da6c9ee64e3e0c05901d897ea486ef5 | 33.336842 | 157 | 0.689148 | 5.604811 | false | false | false | false |
1aurabrown/eidolon | Kiosk/App/Views/SwitchView.swift | 1 | 6153 | import Foundation
let SwitchViewBorderWidth: CGFloat = 2
public class SwitchView: UIView {
public var shouldAnimate = true
public var animationDuration: NSTimeInterval = AnimationDuration.Short
private var _selectedIndexSubject = RACSubject()
lazy public var selectedIndexSignal: RACSignal = {
self._selectedIndexSubject.startWith(0)
}()
private let buttons: Array<UIButton>
private let selectionIndicator: UIView
private let topSelectionIndicator: UIView
private let bottomSelectionIndicator: UIView
private let topBar = CALayer()
private let bottomBar = CALayer()
var selectionConstraint: NSLayoutConstraint!
public init(buttonTitles: Array<String>) {
buttons = buttonTitles.map { (buttonTitle: String) -> UIButton in
var button = UIButton.buttonWithType(.Custom) as UIButton
button.setTitle(buttonTitle, forState: .Normal)
button.setTitle(buttonTitle, forState: .Disabled)
if let titleLabel = button.titleLabel {
titleLabel.font = UIFont.sansSerifFontWithSize(13)
titleLabel.backgroundColor = UIColor.whiteColor()
titleLabel.opaque = true
}
button.backgroundColor = UIColor.whiteColor()
button.setTitleColor(UIColor.blackColor(), forState: .Disabled)
button.setTitleColor(UIColor.blackColor(), forState: .Selected)
button.setTitleColor(UIColor.artsyMediumGrey(), forState: .Normal)
return button
}
selectionIndicator = UIView()
topSelectionIndicator = UIView()
bottomSelectionIndicator = UIView()
super.init(frame: CGRectZero)
setup()
}
public override func layoutSubviews() {
super.layoutSubviews()
var rect = CGRectMake(0, 0, CGRectGetWidth(layer.bounds), SwitchViewBorderWidth)
topBar.frame = rect
rect.origin.y = CGRectGetHeight(layer.bounds) - SwitchViewBorderWidth
bottomBar.frame = rect
}
required convenience public init(coder aDecoder: NSCoder) {
self.init(buttonTitles: [])
}
override public func intrinsicContentSize() -> CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: 46)
}
public func selectedButton(button: UIButton!) {
let index = find(buttons, button)!
setSelectedIndex(index, animated: shouldAnimate)
}
public subscript(index: Int) -> UIButton? {
get {
if index >= 0 && index < countElements(buttons) {
return buttons[index]
}
return nil
}
}
}
private extension SwitchView {
func setup() {
if let firstButton = buttons.first {
firstButton.enabled = false
}
let widthPredicateMultiplier = "*\(widthMultiplier())"
for var i = 0; i < buttons.count; i++ {
var button = buttons[i]
self.addSubview(button)
button.addTarget(self, action: "selectedButton:", forControlEvents: .TouchUpInside)
button.constrainWidthToView(self, predicate: widthPredicateMultiplier)
if (i == 0) {
button.alignLeadingEdgeWithView(self, predicate: nil)
} else {
button.constrainLeadingSpaceToView(buttons[i-1], predicate: nil)
}
button.alignTop("\(SwitchViewBorderWidth)", bottom: "\(-SwitchViewBorderWidth)", toView: self)
}
topBar.backgroundColor = UIColor.artsyMediumGrey().CGColor
bottomBar.backgroundColor = UIColor.artsyMediumGrey().CGColor
layer.addSublayer(topBar)
layer.addSublayer(bottomBar)
selectionIndicator.addSubview(topSelectionIndicator)
selectionIndicator.addSubview(bottomSelectionIndicator)
topSelectionIndicator.backgroundColor = UIColor.blackColor()
bottomSelectionIndicator.backgroundColor = UIColor.blackColor()
topSelectionIndicator.alignTop("0", leading: "0", bottom: nil, trailing: "0", toView: selectionIndicator)
bottomSelectionIndicator.alignTop(nil, leading: "0", bottom: "0", trailing: "0", toView: selectionIndicator)
topSelectionIndicator.constrainHeight("\(SwitchViewBorderWidth)")
bottomSelectionIndicator.constrainHeight("\(SwitchViewBorderWidth)")
addSubview(selectionIndicator)
selectionIndicator.constrainWidthToView(self, predicate: widthPredicateMultiplier)
selectionIndicator.alignTop("0", bottom: "0", toView: self)
selectionConstraint = selectionIndicator.alignLeadingEdgeWithView(self, predicate: nil).last! as NSLayoutConstraint
}
func widthMultiplier() -> Float {
return 1.0 / Float(buttons.count)
}
func setSelectedIndex(index: Int) {
setSelectedIndex(index, animated: false)
}
func setSelectedIndex(index: Int, animated: Bool) {
UIView.animateIf(shouldAnimate && animated, withDuration: animationDuration, options: .CurveEaseOut) { () -> Void in
let button = self.buttons[index]
self.buttons.map { (button: UIButton) -> Void in
button.enabled = true
}
button.enabled = false
// Set the x-position of the selection indicator as a fraction of the total width of the switch view according to which button was pressed.
let multiplier = CGFloat(index) / CGFloat(countElements(self.buttons))
self.removeConstraint(self.selectionConstraint)
self.selectionConstraint = NSLayoutConstraint(item: self.selectionIndicator, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: multiplier, constant: 0)
self.addConstraint(self.selectionConstraint)
self.layoutIfNeeded()
}
self._selectedIndexSubject.sendNext(index)
}
}
| mit | 7119d456229206d6b7b2c5f83b9adf70 | 37.217391 | 195 | 0.635787 | 5.548242 | false | false | false | false |
deepestblue/Lipika_IME | HostingApp/LipikaIME/InputSourceUtil.swift | 1 | 3787 | /*
* LipikaIME is a user-configurable phonetic Input Method Engine for Mac OS X.
* Copyright (C) 2017 Ranganath Atreya
*
* 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.
*/
import Carbon
enum InstallType {
case new, replace, upgrade, downgrade
}
class InputSourceUtil {
let bundleId = "com.daivajnanam.inputmethod.LipikaIME.InputSource"
let inputSourcePath = "/Library/Input Methods/LipikaIME.app"
func getType() -> InstallType {
var type = InstallType.new
let inputSources = getInputSources()
if inputSources.count > 0 {
// Get existing bundle version
if let currentBundle = Bundle(path: inputSourcePath),
let currentInfo = currentBundle.infoDictionary,
let currentVersion = currentInfo["CFBundleShortVersionString"] as? String {
// Get payload version
if let newBundlePath = Bundle.main.path(forResource: "LipikaInputSource", ofType: "app"),
let newBundle = Bundle(path: newBundlePath),
let newInfo = newBundle.infoDictionary,
let newVersion = newInfo["CFBundleShortVersionString"] as? String {
// Check if there is an older version installed
switch newVersion.compare(currentVersion, options: NSString.CompareOptions.numeric) {
case ComparisonResult.orderedDescending:
type = InstallType.upgrade
case ComparisonResult.orderedSame:
type = InstallType.replace
case ComparisonResult.orderedAscending:
type = InstallType.downgrade
}
}
else {
NSLog("Unable to get new bundle version")
}
}
else {
NSLog("Unable to get current bundle version")
}
}
return type;
}
func getInputSources() -> Array<TISInputSource> {
let options: CFDictionary = [kTISPropertyBundleID as String: bundleId] as CFDictionary
if let rawList = TISCreateInputSourceList(options, true) {
let inputSourceNSArray = rawList.takeRetainedValue() as NSArray
let inputSourceList = inputSourceNSArray as! [TISInputSource]
return inputSourceList
}
else {
NSLog("Unable to get a list of Input Sources")
return []
}
}
func register() -> Bool {
let path = NSURL(fileURLWithPath: inputSourcePath)
let status = TISRegisterInputSource(path)
if (Int(status) == paramErr) {
NSLog("Failed to register: %@ due to: %d", inputSourcePath, status)
return false;
}
return true;
}
func remove(inputSource: TISInputSource) -> Bool {
let status = TISDisableInputSource(inputSource)
if (Int(status) == paramErr) {
NSLog("Failed to remove due to: %d", status)
return false;
}
return true;
}
func enable(inputSource: TISInputSource) -> Bool {
let status = TISEnableInputSource(inputSource)
if (Int(status) == paramErr) {
NSLog("Failed to enable due to: %d", status)
return false;
}
return true;
}
func select(inputSource: TISInputSource) -> Bool {
let status = TISSelectInputSource(inputSource)
if (Int(status) == paramErr) {
NSLog("Failed to select due to: %d", status)
return false;
}
return true;
}
}
| gpl-3.0 | f68bcb867f9c84434435fea593754bd4 | 35.413462 | 105 | 0.58648 | 5.076408 | false | false | false | false |
ChinaHackers/QQMusic | QQMusic/QQMusic/Classes/Other/Tool/QQTimeTool.swift | 1 | 1291 | //
// QQTimeTool.swift
// QQMusic
//
// Created by Liu Chuan on 2017/6/24.
// Copyright © 2017年 LC. All rights reserved.
//
import UIKit
/// 时间工具类
class QQTimeTool: NSObject {
/// 目的: 根据 秒数 转换为格式化后的 字符串
///
/// - Parameter timeInterval: 秒数
/// - Returns: 格式化后的字符串
class func getFormatTime(timeInterval: TimeInterval) -> String {
// timeInterval 21.123
let min = Int(timeInterval) / 60
let sec = Int(timeInterval) % 60
return String(format: "%02d: %02d", min, sec)
}
/// 根据 字符串 转换成 秒数
///
/// - Parameter formatTime: 格式化字符串
/// - Returns: 秒数
class func getTimeInterval(formatTime: String) -> TimeInterval {
// 00:00.91
//components(separatedBy:): 方法是将字符串根据指定的字符串参数进行分割,并将分别的内容转换为一个数组
let minSec = formatTime.components(separatedBy: ":")
if minSec.count != 2 {
return 0
}
let min = TimeInterval(minSec[0]) ?? 0.0
let sec = TimeInterval(minSec[1]) ?? 0.0
return min * 60.0 + sec
}
}
| mit | 85cb47aa1146d75e9604d786ef404f5c | 22.25 | 72 | 0.544803 | 3.808874 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | 04-App Architecture/Swift 2/4-3 Playgrounds/Closures.playground/Pages/Capturing and Currying.xcplaygroundpage/Contents.swift | 1 | 4649 | //: [Previous](@previous)
import UIKit
import XCPlayground
//: 
//: ## Capturing and Currying
//: The same rule apply for capturing as with nested functions.
//: ### Capturing from enclosing scope - parameters and locals
typealias DoubleTransform = Double -> Double
//: This closure encasulates the captured variable `sum`
let acc = { (var sum : Double) -> DoubleTransform in
// Return the single-parameter closure - The `return` could be dropped of course
return {
sum += $0 // Closure captures variable sum
return sum
}
}(5.0)
acc(2.0)
acc(5.0)
let y = acc(8.0)
//: As you can infer by observation, the captured `sum` persists because accumulator persists
//: ### Currying
//:
//: Any closure with `N` parameters can be broken down into `N` closures with 1 parameter.
//: This follows a process of "capture and return", just as we did with functions.
typealias IntTx = Int -> Int //Function type that takes an Int parameter, and returns an Int
//: Outer closure provides the first argument - this is captured by the next level of nesting
let curried = {( num1 : Int) -> IntTx in
{$0 + num1} // Captures num1, implicit return
}
//: Invoke with first parameter, then pass second parameter to the returned function
curried(10)(20)
//: Again, useful when you need a closure of a particular type
//: Here is the same example used in the Functions playground and lecture podcast
let tx = curried(100)
//: `tx` is a Function that has captured `num1=100`, and accepts a single parameter. For example:
tx(10)
//: Now consider the higher-order function `map`.
//: Applied to an array of type `[Int]`, it accepts a function of type `Int->U`, where 'U' is a generic type and represents the type of data in the result.
//: A key point here is that `tx` is now a function with **one** `Int` parameter as a result of currying. Therefore it can be passed as a parameter to `map`.
let arrayOfInt = [1, 5, 10]
let res = arrayOfInt.map(tx)
//: Looking at the result, each element has 100 added to it. The return
//:
//: Another example - calculating times-tables using a single for-loop.
//:
//: First, without simplification
let symbols = Array<Int>(1...12)
for x in symbols {
let mul = { (a : Int) -> Int in
return a*x //Capture x
}
let row = symbols.map(mul)
//: uncomment the line below to see the results in the timeline (can be slow)
//XCPlaygroundPage.currentPage.captureValue(row, withIdentifier: "x " + String(x))
}
//: Here is a compact way
let tables = symbols.map(){ (row : Int) -> [Int] in
symbols.map(){$0 * row}
}
//: Of course, we can do the same with two for-loops, but this is much more concise. You may prefer two for-loops of course.
//: #### Example used in the Functions lecture
typealias T1 = Double -> Double
typealias T2 = Double -> T1
//: The original function used
func f1(m : Double) -> T2 {
func f2(x : Double) -> T1 {
let prod = m*x
func f3(c : Double) -> Double {
return prod+c
}
return f3
}
return f2
}
//: Example for 10*2 + 5
f1(10)
f1(10)(2)
f1(10)(2)(5)
//: Now convert directly to closure syntax
let c1 = { (m : Double)-> T2 in
let c2 = { (x : Double) -> T1 in
let prod = m*x
let c3 = { (c : Double) -> Double in
return prod+c
}
return c3
}
return c2
}
//: Confirm the results and types are the same
c1(10)
c1(10)(2)
c1(10)(2)(5)
//: We can simplify of course
//:
//: Starting with inferred returns
//let c1 = { (m : Double)-> T2 in
// { (x : Double) -> T1 in
// { (c : Double) -> Double in m*x+c }
// }
//}
//:
//: Now the return types - these can be inferred
//let c1 = { (m : Double) in
// { (x : Double) in
// { (c : Double) in m*x+c }
// }
//}
//:
//: Shorthand notation can be used on the most inner function
//let c1 = { (m : Double) in
// { (x : Double) in
// { m*x+$0 }
// }
//}
//:
//: Parameter types can be inferred.
//: Remember - because this is a type-strict language, only a Double can be multiplied with a Double, so the type of x is implied given the type of m is known
//let c2 = { (m : Double) in
// { x in
// { m*x+$0 }
// }
//}
//: We can now write on one line.
let c2 = { (m : Double) in { x in { m*x+$0 } } }
c2(10)
c2(10)(2)
c2(10)(2)(5)
//: I will leave you with the following thought to discuss with your peers. Consider the simplified closure expressions given above. *If this was not your code*, is it clear what these closures do?
//: (If you only use your own source code, you may assume that your own code might as well be someone elses after 6 months :o)
//: [Next](@next)
| mit | 93339a8cfd01d32f69298b9726a600e4 | 28.993548 | 198 | 0.64487 | 3.400878 | false | false | false | false |
dleonard00/firebase-user-signup | Pods/Material/Sources/Menu.swift | 1 | 19765 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* 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 Material 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
public enum MenuDirection {
case Up
case Down
case Left
case Right
}
public class Menu {
/// A Boolean that indicates if the menu is open or not.
public private(set) var opened: Bool = false
/// The rectangular bounds that the menu animates.
public var origin: CGPoint {
didSet {
reloadLayout()
}
}
/// A preset wrapper around spacing.
public var spacingPreset: MaterialSpacing = .None {
didSet {
spacing = MaterialSpacingToValue(spacingPreset)
}
}
/// The space between views.
public var spacing: CGFloat {
didSet {
reloadLayout()
}
}
/// Enables the animations for the Menu.
public var enabled: Bool = true
/// The direction in which the animation opens the menu.
public var direction: MenuDirection = .Up {
didSet {
reloadLayout()
}
}
/// An Array of UIViews.
public var views: Array<UIView>? {
didSet {
reloadLayout()
}
}
/// Size of views, not including the first view.
public var itemViewSize: CGSize = CGSizeMake(48, 48)
/// An Optional base view size.
public var baseViewSize: CGSize?
/**
Initializer.
- Parameter origin: The origin position of the Menu.
- Parameter spacing: The spacing size between views.
*/
public init(origin: CGPoint, spacing: CGFloat = 16) {
self.origin = origin
self.spacing = spacing
}
/// Reload the view layout.
public func reloadLayout() {
opened = false
layoutButtons()
}
/**
Open the Menu component with animation options.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func open(duration duration: NSTimeInterval = 0.15, delay: NSTimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
if enabled {
disable()
switch direction {
case .Up:
openUpAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Down:
openDownAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Left:
openLeftAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Right:
openRightAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
}
}
}
/**
Close the Menu component with animation options.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func close(duration duration: NSTimeInterval = 0.15, delay: NSTimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
if enabled {
disable()
switch direction {
case .Up:
closeUpAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Down:
closeDownAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Left:
closeLeftAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Right:
closeRightAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
}
}
}
/**
Open the Menu component with animation options in the Up direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
private func openUpAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
var base: UIView?
for var i: Int = 1, l: Int = v.count; i < l; ++i {
if nil == base {
base = v[0]
}
let view: UIView = v[i]
view.hidden = false
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 1
view.frame.origin.y = base!.frame.origin.y - CGFloat(i) * self.itemViewSize.height - CGFloat(i) * self.spacing
animations?(view)
}) { [unowned self] _ in
completion?(view)
self.enable(view)
}
}
opened = true
}
}
/**
Close the Menu component with animation options in the Up direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func closeUpAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
for var i: Int = 1, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 0
view.frame.origin.y = self.origin.y
animations?(view)
}) { [unowned self] _ in
view.hidden = true
completion?(view)
self.enable(view)
}
}
opened = false
}
}
/**
Open the Menu component with animation options in the Down direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
private func openDownAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
var base: UIView?
for var i: Int = 1, l: Int = v.count; i < l; ++i {
if nil == base {
base = v[0]
}
let view: UIView = v[i]
view.hidden = false
let h: CGFloat = nil == baseViewSize ? itemViewSize.height : baseViewSize!.height
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 1
view.frame.origin.y = base!.frame.origin.y + h + CGFloat(i - 1) * self.itemViewSize.height + CGFloat(i) * self.spacing
animations?(view)
}) { [unowned self] _ in
completion?(view)
self.enable(view)
}
}
opened = true
}
}
/**
Close the Menu component with animation options in the Down direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func closeDownAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
for var i: Int = 1, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
let h: CGFloat = nil == baseViewSize ? itemViewSize.height : baseViewSize!.height
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 0
view.frame.origin.y = self.origin.y + h
animations?(view)
}) { [unowned self] _ in
view.hidden = true
completion?(view)
self.enable(view)
}
}
opened = false
}
}
/**
Open the Menu component with animation options in the Left direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
private func openLeftAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
var base: UIView?
for var i: Int = 1, l: Int = v.count; i < l; ++i {
if nil == base {
base = v[0]
}
let view: UIView = v[i]
view.hidden = false
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 1
view.frame.origin.x = base!.frame.origin.x - CGFloat(i) * self.itemViewSize.width - CGFloat(i) * self.spacing
animations?(view)
}) { [unowned self] _ in
completion?(view)
self.enable(view)
}
}
opened = true
}
}
/**
Close the Menu component with animation options in the Left direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func closeLeftAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
for var i: Int = 1, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 0
view.frame.origin.x = self.origin.x
animations?(view)
}) { [unowned self] _ in
view.hidden = true
completion?(view)
self.enable(view)
}
}
opened = false
}
}
/**
Open the Menu component with animation options in the Right direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
private func openRightAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
var base: UIView?
for var i: Int = 1, l: Int = v.count; i < l; ++i {
if nil == base {
base = v[0]
}
let view: UIView = v[i]
view.hidden = false
let h: CGFloat = nil == baseViewSize ? itemViewSize.height : baseViewSize!.height
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 1
view.frame.origin.x = base!.frame.origin.x + h + CGFloat(i - 1) * self.itemViewSize.width + CGFloat(i) * self.spacing
animations?(view)
}) { [unowned self] _ in
completion?(view)
self.enable(view)
}
}
opened = true
}
}
/**
Close the Menu component with animation options in the Right direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func closeRightAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
for var i: Int = 1, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
let w: CGFloat = nil == baseViewSize ? itemViewSize.width : baseViewSize!.width
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 0
view.frame.origin.x = self.origin.x + w
animations?(view)
}) { [unowned self] _ in
view.hidden = true
completion?(view)
self.enable(view)
}
}
opened = false
}
}
/// Layout the views.
private func layoutButtons() {
if let v: Array<UIView> = views {
let size: CGSize = nil == baseViewSize ? itemViewSize : baseViewSize!
for var i: Int = 0, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
if 0 == i {
view.frame.size = size
view.frame.origin = origin
view.layer.zPosition = 10000
} else {
view.alpha = 0
view.hidden = true
view.frame.size = itemViewSize
view.frame.origin.x = origin.x + (size.width - itemViewSize.width) / 2
view.frame.origin.y = origin.y + (size.height - itemViewSize.height) / 2
view.layer.zPosition = CGFloat(10000 - v.count - i)
}
}
}
}
/// Disable the Menu if views exist.
private func disable() {
if let v: Array<UIView> = views {
if 0 < v.count {
enabled = false
}
}
}
/**
Enable the Menu if the last view is equal to the passed in view.
- Parameter view: UIView that is passed in to compare.
*/
private func enable(view: UIView) {
if let v: Array<UIView> = views {
if view == v.last {
enabled = true
}
}
}
} | mit | ac05c3d92792379a440955dcd7af4d28 | 39.256619 | 280 | 0.714394 | 4.094676 | false | false | false | false |
sunfei/RxSwift | RxSwift/RxSwift/Observables/Implementations/Throttle.swift | 11 | 4167 | //
// Throttle.swift
// Rx
//
// Created by Krunoslav Zaher on 3/22/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Throttle_<O: ObserverType, SchedulerType: Scheduler> : Sink<O>, ObserverType {
typealias Element = O.Element
typealias ParentType = Throttle<Element, SchedulerType>
typealias ThrottleState = (
value: RxMutableBox<Element?>,
cancellable: SerialDisposable,
id: UInt64
)
let parent: ParentType
var lock = NSRecursiveLock()
var throttleState: ThrottleState = (
value: RxMutableBox(nil),
cancellable: SerialDisposable(),
id: 0
)
init(parent: ParentType, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let cancellable = self.throttleState.cancellable
let subscription = parent.source.subscribeSafe(self)
return CompositeDisposable(subscription, cancellable)
}
func on(event: Event<Element>) {
switch event {
case .Next:
break
case .Error: fallthrough
case .Completed:
throttleState.cancellable.dispose()
break
}
var latestId = self.lock.calculateLocked { () -> UInt64 in
let observer = self.observer
var oldValue = self.throttleState.value.value
self.throttleState.id = self.throttleState.id &+ 1
switch event {
case .Next(let boxedValue):
self.throttleState.value.value = boxedValue.value
case .Error(let error):
self.throttleState.value.value = nil
trySend(observer, event)
self.dispose()
case .Completed:
self.throttleState.value.value = nil
if let value = oldValue {
trySendNext(observer, value)
}
trySendCompleted(observer)
self.dispose()
}
return self.throttleState.id
}
switch event {
case .Next(let boxedValue):
let d = SingleAssignmentDisposable()
self.throttleState.cancellable.disposable = d
let scheduler = self.parent.scheduler
let dueTime = self.parent.dueTime
let _ = scheduler.scheduleRelative(latestId, dueTime: dueTime) { (id) in
self.propagate()
return NopDisposableResult
}.map { disposeTimer -> Disposable in
d.disposable = disposeTimer
return disposeTimer
}.recoverWith { e -> RxResult<Disposable> in
self.lock.performLocked {
trySendError(observer, e)
self.dispose()
}
return NopDisposableResult
}
default: break
}
}
func propagate() {
var originalValue: Element? = self.lock.calculateLocked {
var originalValue = self.throttleState.value.value
self.throttleState.value.value = nil
return originalValue
}
if let value = originalValue {
trySendNext(observer, value)
}
}
}
class Throttle<Element, SchedulerType: Scheduler> : Producer<Element> {
let source: Observable<Element>
let dueTime: SchedulerType.TimeInterval
let scheduler: SchedulerType
init(source: Observable<Element>, dueTime: SchedulerType.TimeInterval, scheduler: SchedulerType) {
self.source = source
self.dueTime = dueTime
self.scheduler = scheduler
}
override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = Throttle_(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
} | mit | 20af5ced8f178804c040389a62e80fd2 | 29.647059 | 145 | 0.563235 | 5.288071 | false | false | false | false |
IsaScience/ListerAProductivityAppObj-CandSwift | original-src/ListerAProductivityAppObj-CandSwift/Swift/ListerKitOSX/CheckBox.swift | 1 | 1573 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A layer-backed custom check box that is IBDesignable and IBInspectable.
*/
import Cocoa
@IBDesignable public class CheckBox: NSButton {
// MARK: Properties
@IBInspectable public var tintColor: NSColor {
get {
return NSColor(CGColor: checkBoxLayer.tintColor)
}
set {
checkBoxLayer.tintColor = newValue.CGColor
}
}
@IBInspectable public var isChecked: Bool {
get {
return checkBoxLayer.isChecked
}
set {
checkBoxLayer.isChecked = newValue
}
}
private var checkBoxLayer: CheckBoxLayer {
return layer as CheckBoxLayer
}
override public var intrinsicContentSize: NSSize {
return NSSize(width: 40, height: 40)
}
// MARK: View Life Cycle
override public func awakeFromNib() {
super.awakeFromNib()
wantsLayer = true
layer = CheckBoxLayer()
layer!.setNeedsDisplay()
}
// MARK: Events
override public func mouseDown(event: NSEvent) {
isChecked = !isChecked
cell().performClick(self)
}
override public func viewDidChangeBackingProperties() {
super.viewDidChangeBackingProperties()
if let window = window {
layer?.contentsScale = window.backingScaleFactor
}
}
} | apache-2.0 | 362477fc3559e6afa1dde3904aafa081 | 22.117647 | 87 | 0.583705 | 5.692029 | false | false | false | false |
asus4/signagetool | signagetool/main.swift | 1 | 1487 | //
// main.swift
// signagetool
//
// Created by Koki Ibukuro on 11/28/15.
// Copyright © 2015 asus4. All rights reserved.
//
import Foundation
func MouseCommand() -> CommandType {
let cmd = LightweightCommand(commandName: "mouse")
cmd.commandShortDescription = "Control mouse"
cmd.commandSignature = "<x> <y>"
var isLeftClick = false
var isRightClick = false
cmd.optionsSetupBlock = {(options) in
options.onFlags(["--click"], usage: "Execute left click") {(flag) in
isLeftClick = true
}
options.onFlags(["--rclick"], usage: "Execute right click") {(flag) in
isRightClick = true
}
}
cmd.executionBlock = {(arguments) in
guard let x = arguments.requiredArgument("x").toDouble() else {
printError("Expected x is double")
exit(EX_USAGE)
}
guard let y = arguments.requiredArgument("y").toDouble() else {
printError("Expected y is double")
exit(EX_USAGE)
}
if isLeftClick {
MouseControl.click(CGPoint(x: x, y: y))
} else if isRightClick {
MouseControl.clickRight(CGPoint(x: x, y: y))
} else {
MouseControl.move(CGPoint(x: x, y: y))
}
}
return cmd
}
// MARK: - main
CLI.setup(name: "signage-tool", version: "0.1", description: "Command line tools for OSX Signage")
CLI.registerCommand(MouseCommand())
let result = CLI.go()
exit(result)
| mit | 1fa0ea5ff34392c6b6a0ebfb5dcca961 | 26.518519 | 98 | 0.59354 | 3.849741 | false | false | false | false |
pinterest/tulsi | src/TulsiGenerator/RuleEntryMap.swift | 1 | 4375 | // Copyright 2017 The Tulsi Authors. 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
/// This class acts as a data store for all of the RuleEntries that are read by our Aspects. It
/// effectively maps from BuildLabel to RuleEntry, with the caveat that a single BuildLabel may
/// actually have multiple RuleEntries depending on Bazel configuration splits. For example, if an
/// objc_library is depended on by an ios_application with a minimum_os_version of 9 and depended on
/// by an ios_unit_test with a minimum_os_version of 10, then we will actually discover two versions
/// of the same objc_library, one for iOS 10 and the other for iOS 9.
public class RuleEntryMap {
private var labelToEntries = [BuildLabel: [RuleEntry]]()
private var allEntries = [RuleEntry]()
private let localizedMessageLogger: LocalizedMessageLogger?
init(localizedMessageLogger: LocalizedMessageLogger? = nil) {
self.localizedMessageLogger = localizedMessageLogger
}
init(_ ruleEntryMap: RuleEntryMap) {
localizedMessageLogger = ruleEntryMap.localizedMessageLogger
allEntries = ruleEntryMap.allEntries
labelToEntries = ruleEntryMap.labelToEntries
}
public var allRuleEntries: [RuleEntry] {
return allEntries
}
public func insert(ruleEntry: RuleEntry) {
allEntries.append(ruleEntry)
labelToEntries[ruleEntry.label, default: []].append(ruleEntry)
}
public func hasAnyRuleEntry(withBuildLabel buildLabel: BuildLabel) -> Bool {
return anyRuleEntry(withBuildLabel: buildLabel) != nil
}
/// Returns a RuleEntry from the list of RuleEntries with the specified BuildLabel.
public func anyRuleEntry(withBuildLabel buildLabel: BuildLabel) -> RuleEntry? {
guard let ruleEntries = labelToEntries[buildLabel] else {
return nil
}
return ruleEntries.last
}
/// Returns a list of RuleEntry with the specified BuildLabel.
public func ruleEntries(buildLabel: BuildLabel) -> [RuleEntry] {
guard let ruleEntries = labelToEntries[buildLabel] else {
return [RuleEntry]()
}
return ruleEntries
}
/// Returns a RuleEntry which is a dep of the given RuleEntry, matched by configuration.
public func ruleEntry(buildLabel: BuildLabel, depender: RuleEntry) -> RuleEntry? {
guard let deploymentTarget = depender.deploymentTarget else {
localizedMessageLogger?.warning("DependentRuleEntryHasNoDeploymentTarget",
comment: "Error when a RuleEntry with deps does not have a DeploymentTarget. RuleEntry's label is in %1$@, dep's label is in %2$@.",
values: depender.label.description,
buildLabel.description)
return anyRuleEntry(withBuildLabel: buildLabel)
}
return ruleEntry(buildLabel: buildLabel, deploymentTarget: deploymentTarget)
}
/// Returns a RuleEntry with the given buildLabel and deploymentTarget.
public func ruleEntry(buildLabel: BuildLabel, deploymentTarget: DeploymentTarget) -> RuleEntry? {
guard let ruleEntries = labelToEntries[buildLabel] else {
return nil
}
guard !ruleEntries.isEmpty else {
return nil
}
// If there's only one, we just assume that it's right.
if ruleEntries.count == 1 {
return ruleEntries.first
}
for ruleEntry in ruleEntries {
if deploymentTarget == ruleEntry.deploymentTarget {
return ruleEntry
}
}
// Must be multiple. Shoot out a warning and return the last.
localizedMessageLogger?.warning("AmbiguousRuleEntryReference",
comment: "Warning when unable to resolve a RuleEntry for a given DeploymentTarget. RuleEntry's label is in %1$@.",
values: buildLabel.description)
return ruleEntries.last
}
}
| apache-2.0 | a817bb235559261e704312bad5fc03d5 | 40.273585 | 170 | 0.710171 | 4.839602 | false | false | false | false |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/connect/ConnectAuthenticationResult.swift | 1 | 664 | //
// ConnectAuthenticationResult.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 07/10/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
public struct ConnectAuthenticationResult: Codable
{
public let user: ConnectUser
public let accessToken: String
public init?(jSON: JSON_Object) {
if let accessToken = jSON["AccessToken"] as? String,
let userJSON = jSON["User"] as? JSON_Object,
let user = ConnectUser(jSON: userJSON)
{
self.user = user
self.accessToken = accessToken
}
else {
return nil
}
}
}
| mit | 30946d297f272d08264d6fbd2e6f59e3 | 22.678571 | 61 | 0.60181 | 4.277419 | false | false | false | false |
freakdragon/CallbackURLKitSenderSample | CallbackURLKitSenderSample/Manager.swift | 1 | 10140 | //
// Manager.swift
// CallbackURLKitSenderSample
/*
The MIT License (MIT)
Copyright © 2017 Eugene Babich (freakdragon).
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
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
open class Manager {
// singletong shared instance
open static let shared = Manager()
// List of action/action closure
var actions: [Action: ActionHandler] = [:]
// keep request for callback
var requests: [RequestID: Request] = [:]
// Specify an URL scheme for callback
open var callbackURLScheme: String?
init() {
}
// Add an action handler ie. url path and block
open subscript(action: Action) -> ActionHandler? {
get {
return actions[action]
}
set {
if newValue == nil {
actions.removeValue(forKey: action)
} else {
actions[action] = newValue
}
}
}
// Handle url from app delegate
open func handleOpen(url: URL) -> Bool {
if url.scheme != self.callbackURLScheme || url.host != kXCUHost {
return false
}
let path = url.path
let action = String(path.characters.dropFirst()) // remove /
let parameters = url.query?.toQueryDictionary ?? [:]
let actionParameters = Manager.action(parameters: parameters)
// is a reponse?
if action == kResponse {
if let requestID = parameters[kRequestID] /*as? RequestID*/, let request = requests[requestID] {
if let rawType = parameters[kResponseType], let responseType = ResponseType(rawValue: rawType) {
switch responseType {
case .success:
request.successCallback?(actionParameters)
case .error:
request.failureCallback?(request.client.error(code: parameters[kXCUErrorCode], message: parameters[kXCUErrorMessage]))
case .cancel:
request.cancelCallback?()
}
requests.removeValue(forKey: requestID)
}
return true
}
return false
}
else if let actionHandler = actions[action] { // handle the action
let successCallback: SuccessCallback = { [weak self] returnParams in
self?.openCallback(parameters, type: .success) { comp in
if let query = returnParams?.queryString {
comp &= query
}
}
}
let failureCallback: FailureCallback = { [weak self] error in
self?.openCallback(parameters, type: .error) { comp in
comp &= error.XCUErrorQuery
}
}
let cancelCallback: CancelCallback = { [weak self] in
self?.openCallback(parameters, type: .cancel)
}
actionHandler(actionParameters, successCallback, failureCallback, cancelCallback)
return true
}
else {
// unknown action, notifiy it
if let errorURLString = parameters[kXCUError], let url = URL(string: errorURLString) {
let error = NSError.error(code: .notSupportedAction, failureReason: "\(action) not supported by \(Manager.appName)")
var comp = URLComponents(url: url, resolvingAgainstBaseURL: false)!
comp &= error.XCUErrorQuery
if let newURL = comp.url {
Manager.open(url: newURL)
}
return true
}
}
return false
}
public func openCallback(_ parameters: [String : String], type: ResponseType, handler: ((inout URLComponents) -> Void)? = nil ) {
if let urlString = parameters[type.key], let url = URL(string: urlString),
var comp = URLComponents(url: url, resolvingAgainstBaseURL: false) {
handler?(&comp)
if let newURL = comp.url {
Manager.open(url: newURL)
}
}
}
// Handle url with manager shared instance
open static func handleOpen(url: URL) -> Bool {
return self.shared.handleOpen(url: url)
}
// MARK: - perform action with temporary client
// Perform an action on client application
// - Parameter action: The action to perform.
// - Parameter urlScheme: The application scheme to apply action.
// - Parameter parameters: Optional parameters for the action.
// - Parameter onSuccess: callback for success.
// - Parameter onFailure: callback for failure.
// - Parameter onCancel: callback for cancel.
//
// Throws: CallbackURLKitError
open func perform(action: Action, urlScheme: String, parameters: Parameters = [:],
onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws {
let client = Client(urlScheme: urlScheme)
client.manager = self
try client.perform(action: action, parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel)
}
open static func perform(action: Action, urlScheme: String, parameters: Parameters = [:],
onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws {
try Manager.shared.perform(action: action, urlScheme: urlScheme, parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel)
}
// Utility function to get URL schemes from Info.plist
open static var urlSchemes: [String]? {
guard let urlTypes = Bundle.main.infoDictionary?["CFBundleURLTypes"] as? [[String: AnyObject]] else {
return nil
}
var result = [String]()
for urlType in urlTypes {
if let schemes = urlType["CFBundleURLSchemes"] as? [String] {
result += schemes
}
}
return result.isEmpty ? nil : result
}
// MARK: internal
func send(request: Request) throws {
if !request.client.appInstalled {
throw CallbackURLKitError.appWithSchemeNotInstalled(scheme: request.client.urlScheme)
}
var query: Parameters = [:]
query[kXCUSource] = Manager.appName
if let scheme = self.callbackURLScheme {
var xcuComponents = URLComponents()
xcuComponents.scheme = scheme
xcuComponents.host = kXCUHost
xcuComponents.path = "/" + kResponse
let xcuParams: Parameters = [kRequestID: request.ID]
for reponseType in request.responseTypes {
xcuComponents.queryDictionary = xcuParams + [kResponseType: reponseType.rawValue]
if let urlString = xcuComponents.url?.absoluteString {
query[reponseType.key] = urlString
}
}
if request.hasCallback {
requests[request.ID] = request
}
}
else if request.hasCallback {
throw CallbackURLKitError.callbackURLSchemeNotDefined
}
let components = request.URLComponents(query)
guard let URL = components.url else {
throw CallbackURLKitError.failedToCreateRequestURL(components: components)
}
Manager.open(url: URL)
}
static func action(parameters: [String : String]) -> [String : String] {
let resultArray: [(String, String)] = parameters.filter { tuple in
return !(tuple.0.hasPrefix(kXCUPrefix) || protocolKeys.contains(tuple.0))
}
var result = [String: String](resultArray)
if let source = parameters[kXCUSource] {
result[kXCUSource] = source
}
return result
}
static func open(url: Foundation.URL) {
#if os(iOS) || os(tvOS)
UIApplication.shared.openURL(url)
#elseif os(OSX)
NSWorkspace.shared().open(url)
#endif
}
static var appName: String {
if let appName = Bundle.main.localizedInfoDictionary?["CFBundleDisplayName"] as? String {
return appName
}
return Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String ?? "CallbackURLKit"
}
}
#if os(OSX)
extension Manager {
public func registerToURLEvent() {
NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(Manager.handleURLEvent(_:withReply:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
@objc public func handleURLEvent(_ event: NSAppleEventDescriptor, withReply replyEvent: NSAppleEventDescriptor) {
if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue, let url = URL(string: urlString) {
let _ = handleOpen(url: url)
}
}
}
#endif
| mit | 79ab5d13b041aa450dbeec82e295a806 | 36.973783 | 204 | 0.610711 | 4.960372 | false | false | false | false |
gewill/GWCollectionViewFloatCellLayout | Demo/ViewController.swift | 1 | 5049 | //
// ViewController.swift
// GWCollectionViewFloatCellLayout
//
// Created by Will on 2/10/17.
// Copyright © 2017 Will. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var layout: UICollectionViewFlowLayout!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "scrollDirection", style: .plain, target: self, action: #selector(self.scrollDirectionButtonClick(_:)))
collectionView.delegate = self
collectionView.dataSource = self
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
self.collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
self.collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footer")
if #available(iOS 9.0, *) {
self.layout.sectionHeadersPinToVisibleBounds = true
} else {
// Fallback on earlier versions
}
}
// MARK: - UICollectionViewDelegate
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 0
} else {
return 500
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = .gray
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath)
if indexPath.section % 2 != 0 {
view.backgroundColor = .red
} else {
view.backgroundColor = .green
}
return view
} else {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footer", for: indexPath)
if indexPath.section % 2 != 0 {
view.backgroundColor = .blue
} else {
view.backgroundColor = .black
}
return view
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 30, height: 30)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
if section == 0 {
return .zero
} else {
return UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 2
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: 0, height: 0)
} else {
return CGSize(width: 100, height: 40)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: 0, height: 300)
} else {
return CGSize(width: 200, height: 22)
}
}
// MARK: - response methods
func scrollDirectionButtonClick(_ sender: UIBarButtonItem) {
if self.layout.scrollDirection == .horizontal {
self.layout.scrollDirection = .vertical
} else {
self.layout.scrollDirection = .horizontal
}
}
}
| mit | c17fc8330411c30ffa689544dbd15273 | 35.57971 | 175 | 0.683241 | 6.163614 | false | false | false | false |
WestlakeAPC/gpa-calculator | GPACalculator/Information.swift | 1 | 4544 | /**
* Copyright (c) 2017 Westlake APC
*
* 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
class Information: NSObject, NSCoding {
override public var description: String { return "\(name): \(grade) *\(multiplier) credit: \(credits)\n" }
static var classesAndGrades = [Information]()
static let keyValueStore = NSUbiquitousKeyValueStore()
static var selectedRow: Int = 0
var name: String
var grade: Int
var multiplier: Double
var credits: Double
// Initialize
public init(_ name: String, grade: Int, multiplier: Double, credits: Double) {
self.name = name
self.grade = grade
self.multiplier = multiplier
self.credits = credits
}
public required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObject(forKey: "name") as? String ?? "Classy McClassFace"
let grade = aDecoder.decodeInteger(forKey: "grade")
let multiplier = aDecoder.decodeDouble(forKey: "multiplier")
let credits = aDecoder.decodeDouble(forKey: "credits")
self.init(name, grade: grade, multiplier: multiplier, credits: credits)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(grade, forKey: "grade")
aCoder.encode(multiplier, forKey: "multiplier")
aCoder.encode(credits, forKey: "credits")
}
public static func initializeArray() {
// Add time stamp if there is data on iclouds
if Information.keyValueStore.data(forKey: "savedList") != nil && Information.keyValueStore.data(forKey: "timeStamp") == nil {
let i = NSKeyedUnarchiver.unarchiveObject(with: Information.keyValueStore.data(forKey: "savedList")!)! as? [Information]
ArchiveDataSystem.archiveGradeData(infoList: i!, key: "savedList")
print("Using array from iclouds and creating time stamp")
initializeArray()
return
}
// If there is no data stored
if UserDefaults.standard.object(forKey: "savedList") == nil && Information.keyValueStore.data(forKey: "savedList") == nil{
Information.classesAndGrades = [Information]()
print("Using new array")
return
// If there is data in userdefaults and iclouds, compare time stamps
} else if UserDefaults.standard.object(forKey: "timeStamp") != nil && Information.keyValueStore.data(forKey: "timeStamp") != nil {
let cloudDate = NSKeyedUnarchiver.unarchiveObject(with: Information.keyValueStore.data(forKey: "timeStamp")!) as? Date
let udDate = UserDefaults.standard.object(forKey: "timeStamp") as? Date
if(udDate?.compare(cloudDate!) == .orderedDescending) {
print("Using data from userdefaults")
Information.classesAndGrades = (NSKeyedUnarchiver.unarchiveObject(with: (UserDefaults.standard.object(forKey: "savedList") as! Data)) as? [Information])!
return
}
}
print("Using data from iclouds")
// Use data from iclouds if no conditions are met
guard let data = Information.keyValueStore.data(forKey: "savedList"),
let classesAndGrades = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Information] else {
return
}
Information.classesAndGrades = classesAndGrades
}
}
| apache-2.0 | f90cb95f3030de0da3496fcbf8027030 | 44.44 | 169 | 0.665933 | 4.748171 | false | false | false | false |
Yalantis/PixPic | PixPic/Classes/DTO/User.swift | 1 | 1355 | //
// User.swift
// PixPic
//
// Created by Jack Lapin on 15.01.16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import ParseFacebookUtilsV4
class User: PFUser {
@NSManaged var avatar: PFFile?
@NSManaged var facebookId: String?
@NSManaged var appUsername: String?
@NSManaged var passwordSet: Bool
private static var onceToken: dispatch_once_t = 0
static var sortedQuery: PFQuery {
let query = PFQuery(className: User.parseClassName())
query.cachePolicy = .NetworkElseCache
query.orderByDescending("updatedAt")
return query
}
override class func initialize() {
dispatch_once(&onceToken) {
self.registerSubclass()
}
}
override class func currentUser() -> User? {
return PFUser.currentUser() as? User
}
}
extension User {
var isCurrentUser: Bool {
get {
if let currentUser = User.currentUser() where currentUser.facebookId == self.facebookId {
return true
}
return false
}
}
static var isAbsent: Bool {
get {
return User.currentUser() == nil
}
}
static var notAuthorized: Bool {
get {
return PFAnonymousUtils.isLinkedWithUser(User.currentUser()) || User.isAbsent
}
}
}
| mit | c5d852a5aa0c287f5e7cab5775b89d38 | 20.15625 | 101 | 0.597489 | 4.483444 | false | false | false | false |
ylovesy/CodeFun | wuzhentao/convertToTitle.swift | 1 | 575 | class Solution {
func convertToTitle(_ n: Int) -> String {
var s = n
var str:String = ""
while s > 0 {
let r = s % 26
s = s / 26
if r == 0 {
str = str + "Z"
s -= 1
} else {
str = str + String(Character(UnicodeScalar(Int((UnicodeScalar("A")?.value)!) + r - 1)!))
}
}
let sddd = str.characters.reversed()
return String(sddd)
}
}
let s = Solution()
print(s.convertToTitle(37))
| apache-2.0 | 892879f8a250f51c0d4b674c43c0d4b4 | 22.958333 | 105 | 0.398261 | 4.19708 | false | false | false | false |
iamyuiwong/swift-common | util/Log.swift | 1 | 5978 | import Foundation
public class Log {
public static func trace (
let name: String = __FILE__,
let line: Int = __LINE__,
let funcName: String = __FUNCTION__) {
#if ENABLE_LOG
if (Log.T >= Log.logLevel) {
let t: String = name + " +\(line) " + funcName
Log.log(tag: Log.TAG_T, items: t)
}
#endif
}
public static func v (
tag t: String?, items: Any ...,
let name: String = __FILE__,
let line: Int = __LINE__,
let funcName: String = __FUNCTION__) {
#if ENABLE_LOG
if (Log.V >= Log.logLevel) {
let trace: String = name + " +\(line) " + funcName
var msg: String = Log.TAG_V
if let tt = t {
msg += " " + tt
}
for i in items {
msg += " \(i)"
}
msg += " ." + trace
Log.log(msg)
}
#endif
}
public static func t (
tag t: String?, items: Any ...,
let name: String = __FILE__,
let line: Int = __LINE__,
let funcName: String = __FUNCTION__) {
#if ENABLE_LOG
if (Log.T >= Log.logLevel) {
let trace: String = name + " +\(line) " + funcName
var msg: String = Log.TAG_T
if let tt = t {
msg += " " + tt
}
for i in items {
msg += " \(i)"
}
msg += " ." + trace
Log.log(msg)
}
#endif
}
public static func i (
tag t: String?, items: Any ...,
let name: String = __FILE__,
let line: Int = __LINE__,
let funcName: String = __FUNCTION__) {
#if ENABLE_LOG
if (Log.I >= Log.logLevel) {
let trace: String = name + " +\(line) " + funcName
var msg: String = Log.TAG_I
if let tt = t {
msg += " " + tt
}
for i in items {
msg += " \(i)"
}
msg += " ." + trace
Log.log(msg)
}
#endif
}
public static func w (
tag t: String?, items: Any ...,
let name: String = __FILE__,
let line: Int = __LINE__,
let funcName: String = __FUNCTION__) {
#if ENABLE_LOG
if (Log.I >= Log.logLevel) {
let trace: String = name + " +\(line) " + funcName
var msg: String = Log.TAG_W
if let tt = t {
msg += " " + tt
}
for i in items {
msg += " \(i)"
}
msg += " ." + trace
Log.log(msg)
}
#endif
}
public static func e (
tag t: String?, items: Any ...,
let name: String = __FILE__,
let line: Int = __LINE__,
let funcName: String = __FUNCTION__) {
#if ENABLE_LOG
if (Log.I >= Log.logLevel) {
let trace: String = name + " +\(line) " + funcName
var msg: String = Log.TAG_E
if let tt = t {
msg += " " + tt
}
for i in items {
msg += " \(i)"
}
msg += " ." + trace
Log.log(msg)
}
#endif
}
public static func lmax (
tag t: String?, items: Any ...,
let name: String = __FILE__,
let line: Int = __LINE__,
let funcName: String = __FUNCTION__) {
/* #if ENABLE_LOG */
/* if (Log.LMAX >= Log.logLevel) { */
let trace: String = name + " +\(line) " + funcName
var msg: String = Log.TAG_LMAX
if let tt = t {
msg += " " + tt
}
for i in items {
msg += " \(i)"
}
msg += " ." + trace
Log.log(msg)
/* } */
/* #endif */
}
public static func log (level l: Int, tag: String?, items: Any ...) {
#if ENABLE_LOG
if (l >= Log.logLevel) {
let ts = TimeUtil.timestampstring()
var msg = ts
if let t = tag {
msg += " " + t
}
for i in items {
msg += " \(i)"
}
print(msg)
Log.readyFile()
let ap = StringUtil.tocstringArray(fromString: msg,
encoding: NSUTF8StringEncoding)
ap!.data!.append(10)
FileIO.append(int8_data: ap!, toFile: Log.logFile!)
}
#endif
}
public static func log (tag t: String?, items: Any ...) {
#if ENABLE_LOG
let ts = TimeUtil.timestampstring()
var msg = ts
if let tt = t {
msg += " " + tt
}
for i in items {
msg += " \(i)"
}
print(msg)
Log.readyFile()
let ap = StringUtil.tocstringArray(fromString: msg,
encoding: NSUTF8StringEncoding)
ap!.data!.append(10)
FileIO.append(int8_data: ap!, toFile: Log.logFile!)
#endif
}
public static func log (items: Any ...) {
#if ENABLE_LOG
let ts = TimeUtil.timestampstring()
var msg = ts
for i in items {
msg += " \(i)"
}
print(msg)
Log.readyFile()
let ap = StringUtil.tocstringArray(fromString: msg,
encoding: NSUTF8StringEncoding)
ap!.data!.append(10)
FileIO.append(int8_data: ap!, toFile: Log.logFile!)
#endif
}
public static func purePrint (items: Any ...) {
#if ENABLE_LOG
print(items)
#endif
}
public static func readyFile () {
#if ENABLE_LOG
let td = TimeUtil.todayName()
if ( ((nil != Log.fileLogDate) && (td > Log.fileLogDate!))
|| (nil == Log.fileLogDate)) {
Log.fileLogDate = td
#if os (iOS)
let dp = AppUtil.appDocPath
#endif
#if os (OSX)
let dp = FileUtil.userDocPath
#endif
Log.fileLog = dp! + "/log/" + td + ".log"
FileUtil.Mkdir(dir: dp! + "/log", parent: false)
if (nil == Log.logFile) {
Log.logFile = FileAppend(withToPath: Log.fileLog!,
oflag: O_WRONLY | O_APPEND | O_CREAT,
createMode:
mode_t(StringUtil.toInt(fromOctString: "664")))
if (nil == Log.logFile) {
print("ERROR")
}
} else {
Log.logFile!.reinit(withToPath: Log.fileLog!,
oflag: O_WRONLY | O_APPEND | O_CREAT,
createMode:
mode_t(StringUtil.toInt(fromOctString: "664")))
}
}
#endif
}
public static let V: Int = 8
public static let D: Int = 9
public static let T: Int = 16
public static let I: Int = 24
public static let W: Int = 32
public static let E: Int = 40
public static let F: Int = 48
public static let LMAX: Int = Int.max
public static let TAG_V: String = "lvVERBOSE"
public static let TAG_D: String = "lvDEBUG"
public static let TAG_T: String = "lvTRACE"
public static let TAG_I: String = "lvINFO"
public static let TAG_W: String = "lvWARN"
public static let TAG_E: String = "lvERROR"
public static let TAG_F: String = "lvFATAL"
public static let TAG_LMAX: String = "!!!!!MAX"
public static var logLevel: Int = Log.V
private static var logFile: FileAppend?
private static var fileLog: String?
private static var fileLogDate: String?
}
| lgpl-3.0 | 567608c10b9641a08726977c86db92c3 | 17.337423 | 70 | 0.57009 | 2.779172 | false | false | false | false |
redlock/SwiftyDeepstream | SwiftyDeepstream/Classes/deepstream/rpc/RpcHandler.swift | 1 | 10431 | //
// RpcHandler.swift
// deepstreamSwiftTest
//
// Created by Redlock on 4/7/17.
// Copyright © 2017 JiblaTech. All rights reserved.
//
import Foundation
enum RpcHandlerError: Error {
case alreadyRegisteredError(message: String)
}
/**
* Listener for any rpc requests recieved from the server
*/
protocol RpcRequestedListener: class {
/**
* This listener will be invoked whenever the client recieves an rpc request from the server, and will be able
* to respond via [RpcResponse.send] or [RpcResponse.reject]
* @param rpcName The name of the rpc being requested
* *
* @param data The data the request was made with
* *
* @param response The [RpcResponse] to respond to the request with
*/
func onRPCRequested(rpcName: String, data: Any, response: RpcResponse)
}
/**
* The callback for an rpc that has been requested by the client
*/
class RpcResponseCallbackObj: RpcResponseCallback {
init(){}
/**
* Called when the rpc was completed successfully by another client that has provided the rpc via
* [RpcHandler.provide]
* @param rpcName The rpc name
* *
* @param data The result data from the rpc
*/
var onRpcSuccess: ((_ rpcName: String, _ data: Any) -> ())!
var onRpcError: ((_ rpcName: String, _ error: Any) -> ())!
}
protocol RpcResponseCallback: class {
/**
* Called when the rpc was completed successfully by another client that has provided the rpc via
* [RpcHandler.provide]
* @param rpcName The rpc name
* *
* @param data The result data from the rpc
*/
var onRpcSuccess: ((_ rpcName: String, _ data: Any) -> ())! { get set }
/**
* Called when the rpc was completed unsuccessfully by another client that has provided the rpc via
* [RpcHandler.provide]
* @param rpcName The rpc name
*/
var onRpcError: ((_ rpcName: String, _ error: Any) -> ())! { get set }
}
/**
* The entry point for rpcs, both requesting them via [RpcHandler.make] and
* providing them via [RpcHandler.provide]
*/
/**
* The main class for remote procedure calls
* Provides the rpc interface and handles incoming messages
* on the rpc topic
* @param deepstreamConfig The deepstreamConfig the client was created with
* *
* @param connection The connection to deepstream
* *
* @param client The deepstream client
*/
class RpcHandler {
let deepstreamConfig: DeepstreamConfig
private let connection: IConnection
private let client: DeepstreamClientAbstract
private var providers: [String: RpcRequestedListener] = [:]
private let ackTimeoutRegistry: UtilAckTimeoutRegistry
private var rpcs: [String: Rpc] = [:]
init(deepstreamConfig: DeepstreamConfig, connection: IConnection, client: DeepstreamClientAbstract) {
self.connection = connection
self.deepstreamConfig = deepstreamConfig
self.client = client
self.ackTimeoutRegistry = client.ackTimeoutRegistry
let listner = UtilResubscribeListenerObj()
listner.resubscribe = {
for rpcName in self.providers.keys {
self.sendRPCSubscribe(rpcName: rpcName)
}
}
UtilResubscribeNotifier(client: self.client, resubscribe: listner)
}
/**
* Registers a [RpcRequestedListener] as a RPC provider. If another connected client calls
* [RpcHandler.make] the request will be routed to the supplied listener.
* <br></br>
* Only one listener can be registered for a RPC at a time.
* <br></br>
* Please note: Deepstream tries to deliver data in its original format. Data passed to
* [RpcHandler.make] as a String will arrive as a String, numbers or
* implicitly JSON serialized objects will arrive in their respective format as well.
* @param rpcName The rpcName of the RPC to provide
* *
* @param rpcRequestedListener The listener to invoke when requests are received
*/
func provide(rpcName: String, rpcRequestedListener: RpcRequestedListener) throws {
if self.providers[rpcName] != nil {
throw RpcHandlerError.alreadyRegisteredError(message: "RPC $rpcName already registered")
}
// synchronized(self) {
self.providers[rpcName] = rpcRequestedListener
self.sendRPCSubscribe(rpcName: rpcName)
// }
}
/**
* Unregister a [RpcRequestedListener] registered via Rpc[.provide]
* @param rpcName The rpcName of the RPC to stop providing
*/
func unprovide(rpcName: String) {
if self.providers[rpcName] != nil {
self.providers.removeValue(forKey: rpcName)
self.ackTimeoutRegistry.add(topic: Topic.RPC, action: Actions.UNSUBSCRIBE, name: rpcName, timeout: deepstreamConfig.subscriptionTimeout)
self.connection.sendMsg(topic: Topic.RPC, action: Actions.UNSUBSCRIBE, data: [rpcName])
}
}
/**
* Create a remote procedure call. self requires a rpc name for routing, a JSON serializable object for any associated
* arguments and a callback to notify you with the rpc result or potential error.
* @param rpcName The name of the rpc
* *
* @param data Serializable data that will be passed to the provider
* *
* @return Find out if the rpc succeeded via [RpcResult.success] and associated data via [RpcResult.getData]
*/
func make(rpcName: String, data: Any, callback: @escaping (RpcResult? , DeepstreamError?) -> Void ) {
let uid = self.client.uid
let listener = RpcResponseCallbackObj()
listener.onRpcSuccess = { (rpcName: String, data: Any) in
callback(RpcResult(success: true, data: data), nil)
return
}
listener.onRpcError = { (rpcName: String, error: Any) in
callback(RpcResult(success: false, data: error), DeepstreamError(message: "Rpc Error"))
return
}
self.rpcs[uid] = Rpc(deepstreamConfig: self.deepstreamConfig, client: self.client, rpcName: rpcName, uid: uid, callback : listener)
let typedData = MessageBuilder.typed(value: data)
self.connection.sendMsg(topic: Topic.RPC, action: Actions.REQUEST, data: [rpcName, uid, typedData])
}
/**
* Main interface. Handles incoming messages
* from the message distributor
* @param message The message recieved from the server
*/
func handle(message: Message) throws {
let rpcName: String
let correlationId: String
let rpc: Rpc?
// RPC Requests
if message.action == Actions.REQUEST {
try self.respondToRpc(message: message)
return
}
// RPC subscription Acks
if message.action == Actions.ACK && (message.data[0] == Actions.SUBSCRIBE.rawValue || message.data[0] == Actions.UNSUBSCRIBE.rawValue) {
self.ackTimeoutRegistry.clear(message: message)
return
}
/*
* Error messages always have the error as first parameter. So the
* order is different to ack and response messages
*/
if message.action == Actions.ERROR || message.action == Actions.ACK {
rpcName = message.data[1]
correlationId = message.data[2]
} else {
rpcName = message.data[0]
correlationId = message.data[1]
}
/*
* Retrieve the rpc object
*/
rpc = self.getRpc(correlationId: correlationId, raw: message.raw)
if (rpc == nil) {
return
}
// RPC Responses
if message.action == Actions.ACK {
rpc?.ack()
} else if message.action == Actions.RESPONSE {
try rpc?.respond(rpcName: rpcName, data: message.data[2])
self.rpcs.removeValue(forKey: correlationId)
} else if message.action == Actions.ERROR
{
rpc?.error(rpcName: rpcName, err: message.data[0])
self.rpcs.removeValue(forKey: correlationId)
}
}
/**
* Retrieves a RPC instance for a correlationId or throws an error
* if it can't be found (which should never happen)
*/
private func getRpc(correlationId: String, raw: String) -> Rpc {
let rpc = self.rpcs[correlationId]
if (rpc == nil) {
self.client.onError( Topic.RPC, Event.UNSOLICITED_MESSAGE, raw)
}
return rpc!
}
/**
* Handles incoming rpc REQUEST messages. Instantiates a new response object
* and invokes the provider callback or rejects the request if no rpc provider
* is present (which shouldn't really happen, but might be the result of a race condition
* if self client sends a unprovide message whilst an incoming request is already in flight)
*/
private func respondToRpc(message: Message) throws {
let rpcName = message.data[0]
let correlationId = message.data[1]
let response: RpcResponse
var data: Any? = nil
if message.data[2] != nil {
data = try MessageParser.convertTyped(value: message.data[2], onError: self.client.onError)
}
let callback = self.providers[rpcName]
if (callback != nil) {
response = RpcResponse(connection: self.connection, name: rpcName, correlationId: correlationId)
callback!.onRPCRequested(rpcName: rpcName, data: data, response: response)
} else {
self.connection.sendMsg(topic: Topic.RPC,action: Actions.REJECTION,data: [rpcName, correlationId])
}
}
/**
* Send an unsubscribe or subscribe event if the connection is open
*/
private func sendRPCSubscribe(rpcName: String) {
if self.client.connectionState == ConnectionState.OPEN {
self.ackTimeoutRegistry.add(topic: Topic.RPC, action: Actions.SUBSCRIBE, name: rpcName, timeout: deepstreamConfig.subscriptionTimeout)
self.connection.sendMsg(topic: Topic.RPC, action: Actions.SUBSCRIBE, data: [rpcName])
}
}
}
| mit | 875726d2f2739f6a42fedd1d1d47f7c5 | 32.429487 | 148 | 0.624736 | 4.41762 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Nodes/Generators/Physical Models/Plucked String/AKPluckedString.swift | 1 | 4507 | //
// AKPluckedString.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// Karplus-Strong plucked string instrument.
///
open class AKPluckedString: AKNode, AKToggleable, AKComponent {
public typealias AKAudioUnitType = AKPluckedStringAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(generator: "pluk")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var frequencyParameter: AUParameter?
fileprivate var amplitudeParameter: AUParameter?
fileprivate var lowestFrequency: Double
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
@objc open dynamic var frequency: Double = 110 {
willSet {
if frequency != newValue {
if let existingToken = token {
frequencyParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Amplitude
@objc open dynamic var amplitude: Double = 0.5 {
willSet {
if amplitude != newValue {
if let existingToken = token {
amplitudeParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize the pluck with defaults
override convenience init() {
self.init(frequency: 110)
}
/// Initialize this pluck node
///
/// - Parameters:
/// - frequency: Variable frequency. Values less than the initial frequency will be
/// doubled until it is greater than that.
/// - amplitude: Amplitude
/// - lowestFrequency: This frequency is used to allocate all the buffers needed for the delay.
/// This should be the lowest frequency you plan on using.
///
@objc public init(
frequency: Double = 440,
amplitude: Double = 0.5,
lowestFrequency: Double = 110) {
self.frequency = frequency
self.amplitude = amplitude
self.lowestFrequency = lowestFrequency
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
frequencyParameter = tree["frequency"]
amplitudeParameter = tree["amplitude"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
}
/// Trigger the sound with an optional set of parameters
/// - frequency: Frequency in Hz
/// - amplitude amplitude: Volume
///
open func trigger(frequency: Double, amplitude: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
internalAU?.start()
internalAU?.triggerFrequency(Float(frequency), amplitude: Float(amplitude))
}
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| mit | b7e22ee86c0ee7cf3e175505b1ccffa4 | 32.132353 | 113 | 0.617843 | 5.282532 | false | false | false | false |
goldenplan/Pattern-on-Swift | Builder/Builder/ConcreteBuilder.swift | 1 | 974 | //
// ConcreteBuilder.swift
// Builder
//
// Created by Snake on 16.07.17.
// Copyright © 2017 Stanislav Belsky. All rights reserved.
//
import UIKit
class ConcreteBuilder: NSObject, Builder {
var material: Material!
var collect: Collect!
var fry: Fry!
var pack: Pack!
var count: Int!
init(material: Material) {
super.init()
self.material = material
if material is Seeds {
self.count = 1000
}else{
self.count = 100
}
self.collect = Collect(material:material, countForCollect:count)
self.fry = Fry(material: material)
self.pack = Pack(material: material)
}
func stageA(){
collect.make()
}
func stageB(){
fry.make()
}
func stageC(){
pack.make()
}
func getResult() -> Material{
return material
}
}
| mit | 3c4b36d1eb9e65ddb60d208085894428 | 16.070175 | 72 | 0.514902 | 4.267544 | false | false | false | false |
SettlePad/client-iOS | SettlePad/UserIdentifier.swift | 1 | 1720 | //
// UserIdentifier.swift
// SettlePad
//
// Created by Rob Everhardt on 24/03/15.
// Copyright (c) 2015 SettlePad. All rights reserved.
//
import Foundation
class UserIdentifier : NSObject, NSCoding {
var identifier: String
var source: String
var verified: Bool
var pending: Bool
var primary: Bool
init(identifier: String, source: String, verified: Bool, pending: Bool, primary: Bool) {
self.identifier = identifier
self.source = source
self.verified = verified
self.pending = pending
self.primary = primary
}
//All below required for saving to and loading from NSUserDefaults
required init?(coder decoder: NSCoder) {
if let identifier = decoder.decodeObjectForKey("identifier") as? String {
self.identifier = identifier
} else {
self.identifier = "unknown"
}
if let source = decoder.decodeObjectForKey("source") as? String {
self.source = source
} else {
self.source = "email"
}
if let verified = decoder.decodeObjectForKey("verified") as? Bool {
self.verified = verified
} else {
self.verified = false
}
if let pending = decoder.decodeObjectForKey("pending") as? Bool {
self.pending = pending
} else {
self.pending = false
}
if let primary = decoder.decodeObjectForKey("primary") as? Bool {
self.primary = primary
} else {
self.primary = false
}
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(identifier, forKey: "identifier")
coder.encodeObject(source, forKey: "source")
coder.encodeObject(verified, forKey: "verified")
coder.encodeObject(pending, forKey: "pending")
coder.encodeObject(primary, forKey: "primary")
}
} | mit | 05f20343c66569697564586e9bfe93d4 | 25.890625 | 89 | 0.672093 | 3.954023 | false | false | false | false |
rumana1411/Giphying | SwappingCollectionView/LvlViewController.swift | 1 | 3190 | //
// LvlViewController.swift
// SwappingCollectionView
//
// Created by Rumana Nazmul on 24/6/17.
// Copyright © 2017 Paweł Łopusiński. All rights reserved.
//
import UIKit
class LvlViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// Set the button type as Custom in storyborad MUST
@IBOutlet weak var backButton: UIButton!
var lvlArray = ["Beginner","Intermediate","Advanced"]
override func viewDidLoad() {
super.viewDidLoad()
// let button = UIButton.init(type: .custom)
// button.setImage(UIImage.init(named: "Back.png"), for: UIControlState.normal)
// button.addTarget(revealViewController(), action:#selector(SWRevealViewController.revealToggle(_:)), for: UIControlEvents.touchUpInside)
// button.addTarget(self, action:#selector(back), for: UIControlEvents.touchUpInside)
// button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) //CGRectMake(0, 0, 30, 30)
// let backButton = UIBarButtonItem.init(customView: button)
// self.navigationItem.leftBarButtonItem = backButton
// leftBackButton.addTarget(self, action:#selector(back), for: UIControlEvents.touchUpInside)
// leftBackButton.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) //CGRectMake(0, 0, 30, 30)
self.navigationController?.isNavigationBarHidden = true
backButton.frame = CGRect.init(x: 10, y: 20, width: 30, height: 30) //CGRectMake(0, 0, 30, 30)
backButton.setImage(UIImage.init(named: "Back.png"), for: UIControlState.normal)
backButton.addTarget(self, action:#selector(back), for: UIControlEvents.touchUpInside)
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return lvlArray.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "LvlCell", for: indexPath)
cell.textLabel?.text = lvlArray[indexPath.row]
return cell
}
func back() {
print("BAckBack")
let nc = revealViewController().rearViewController as? UINavigationController
let frontNVC = (nc?.topViewController as? RearViewController)?.frontNVC
_ = frontNVC?.popViewController(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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 | 11cdfed19f10e3287d266cf3ffbf05e8 | 29.932039 | 150 | 0.643754 | 4.762332 | false | false | false | false |
TomHarte/CLK | OSBindings/Mac/Clock SignalTests/PatrikRakTests.swift | 1 | 3285 | //
// PatrikRakTests.swift
// Clock Signal
//
// Created by Thomas Harte on 22/02/2020.
// Copyright 2017 Thomas Harte. All rights reserved.
//
import XCTest
import Foundation
class PatrikRakTests: XCTestCase, CSTestMachineTrapHandler {
private var done = false
private var output = ""
private func runTest(_ name: String) {
if let filename = Bundle(for: type(of: self)).path(forResource: name, ofType: "tap") {
if let testData = try? Data(contentsOf: URL(fileURLWithPath: filename)) {
// Do a minor parsing of the TAP file to find the final file.
var dataPointer = 0
var finalBlock = 0
while dataPointer < testData.count {
let blockSize = Int(testData[dataPointer]) + Int(testData[dataPointer+1]) << 8
finalBlock = dataPointer + 2
dataPointer += 2 + blockSize
}
assert(dataPointer == testData.count)
// Create a machine.
let machine = CSTestMachineZ80()
machine.portLogic = .return191
// Copy everything from finalBlock+1 to the end of the file to $8000.
let fileContents = testData.subdata(in: finalBlock+1 ..< testData.count)
machine.setData(fileContents, atAddress: 0x8000)
// Add a RET and a trap at 10h, this is the Spectrum's system call for outputting text.
machine.setValue(0xc9, atAddress: 0x0010)
machine.addTrapAddress(0x0010);
machine.trapHandler = self
// Also add a RET at $1601, which is where the Spectrum puts 'channel open'.
machine.setValue(0xc9, atAddress: 0x1601)
// Add a call to $8000 and then an infinite loop; these tests load at $8000 and RET when done.
machine.setValue(0xcd, atAddress: 0x7000)
machine.setValue(0x00, atAddress: 0x7001)
machine.setValue(0x80, atAddress: 0x7002)
machine.setValue(0xc3, atAddress: 0x7003)
machine.setValue(0x03, atAddress: 0x7004)
machine.setValue(0x70, atAddress: 0x7005)
machine.addTrapAddress(0x7003);
// seed execution at 0x7000
machine.setValue(0x7000, for: .programCounter)
// run!
let cyclesPerIteration: Int32 = 400_000_000
while !done {
machine.runForNumber(ofCycles: cyclesPerIteration)
}
let successRange = output.range(of: "Result: all tests passed.")
XCTAssertNotEqual(successRange, nil)
if successRange == nil {
print("Output was: \(output)")
}
}
}
}
func testCCF() {
runTest("z80ccf")
}
func testDoc() {
runTest("z80doc")
}
func testDocFlags() {
runTest("z80docflags")
}
func testFlags() {
runTest("z80flags")
}
func testFull() {
runTest("z80full")
}
func testMemptr() {
runTest("z80memptr")
}
func testMachine(_ testMachine: CSTestMachine, didTrapAtAddress address: UInt16) {
let testMachineZ80 = testMachine as! CSTestMachineZ80
switch address {
case 0x0010:
var characterCode = testMachineZ80.value(for: .A)
// Of the control codes, retain only new line. Map the rest to space.
if characterCode < 32 && characterCode != 13 {
characterCode = 32
}
// Similarly, map down unprintables.
if characterCode >= 127 {
characterCode = 32
}
let textToAppend = UnicodeScalar(characterCode)!
output += String(textToAppend)
// print(textToAppend, terminator:"")
case 0x7003:
done = true
default:
break
}
}
}
| mit | 9f4012656981a1ffe596c2f120d0e491 | 24.664063 | 98 | 0.680974 | 3.345214 | false | true | false | false |
qzephyrmor/antavo-sdk-swift | AntavoLoyaltySDK/Classes/ANTReward.swift | 1 | 1548 | //
// Reward.swift
// AntavoSDK
//
// Copyright © 2017 Antavo Ltd. All rights reserved.
//
// MARK: Base Antavo Reward object.
open class ANTReward {
/**
Reward's unique identifier specified as string.
*/
open var id: String?
/**
Reward's name specified as string or array of strings.
*/
open var name: Any?
/**
Reward's description specified as string or array of strings.
*/
open var description: Any?
/**
Reward's category specified as string.
*/
open var category: String?
/**
Reward's price specified as integer or array of integers.
*/
open var price: Any?
/**
Creates a new instance of Reward, and assigns the given properties to it.
- Parameter data: Properties to assign as NSDictionary object.
*/
open func assign(data: NSDictionary) -> ANTReward {
let reward = ANTReward()
if let id = data.object(forKey: "id") {
reward.id = id as? String
}
if let name = data.object(forKey: "name") {
reward.name = name
}
if let description = data.object(forKey: "description") {
reward.description = description
}
if let category = data.object(forKey: "category") {
reward.category = category as? String
}
if let price = data.object(forKey: "price") {
reward.price = price
}
return reward
}
}
| mit | 64f96f78e46edfe08b42b8949df7ebf0 | 22.8 | 78 | 0.55139 | 4.55 | false | false | false | false |
february29/Learning | swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift | 127 | 4152 | //
// TailRecursiveSink.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
enum TailRecursiveSinkCommand {
case moveNext
case dispose
}
#if DEBUG || TRACE_RESOURCES
public var maxTailRecursiveSinkStackSize = 0
#endif
/// This class is usually used with `Generator` version of the operators.
class TailRecursiveSink<S: Sequence, O: ObserverType>
: Sink<O>
, InvocableWithValueType where S.Iterator.Element: ObservableConvertibleType, S.Iterator.Element.E == O.E {
typealias Value = TailRecursiveSinkCommand
typealias E = O.E
typealias SequenceGenerator = (generator: S.Iterator, remaining: IntMax?)
var _generators: [SequenceGenerator] = []
var _isDisposed = false
var _subscription = SerialDisposable()
// this is thread safe object
var _gate = AsyncLock<InvocableScheduledItem<TailRecursiveSink<S, O>>>()
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func run(_ sources: SequenceGenerator) -> Disposable {
_generators.append(sources)
schedule(.moveNext)
return _subscription
}
func invoke(_ command: TailRecursiveSinkCommand) {
switch command {
case .dispose:
disposeCommand()
case .moveNext:
moveNextCommand()
}
}
// simple implementation for now
func schedule(_ command: TailRecursiveSinkCommand) {
_gate.invoke(InvocableScheduledItem(invocable: self, state: command))
}
func done() {
forwardOn(.completed)
dispose()
}
func extract(_ observable: Observable<E>) -> SequenceGenerator? {
rxAbstractMethod()
}
// should be done on gate locked
private func moveNextCommand() {
var next: Observable<E>? = nil
repeat {
guard let (g, left) = _generators.last else {
break
}
if _isDisposed {
return
}
_generators.removeLast()
var e = g
guard let nextCandidate = e.next()?.asObservable() else {
continue
}
// `left` is a hint of how many elements are left in generator.
// In case this is the last element, then there is no need to push
// that generator on stack.
//
// This is an optimization used to make sure in tail recursive case
// there is no memory leak in case this operator is used to generate non terminating
// sequence.
if let knownOriginalLeft = left {
// `- 1` because generator.next() has just been called
if knownOriginalLeft - 1 >= 1 {
_generators.append((e, knownOriginalLeft - 1))
}
}
else {
_generators.append((e, nil))
}
let nextGenerator = extract(nextCandidate)
if let nextGenerator = nextGenerator {
_generators.append(nextGenerator)
#if DEBUG || TRACE_RESOURCES
if maxTailRecursiveSinkStackSize < _generators.count {
maxTailRecursiveSinkStackSize = _generators.count
}
#endif
}
else {
next = nextCandidate
}
} while next == nil
guard let existingNext = next else {
done()
return
}
let disposable = SingleAssignmentDisposable()
_subscription.disposable = disposable
disposable.setDisposable(subscribeToNext(existingNext))
}
func subscribeToNext(_ source: Observable<E>) -> Disposable {
rxAbstractMethod()
}
func disposeCommand() {
_isDisposed = true
_generators.removeAll(keepingCapacity: false)
}
override func dispose() {
super.dispose()
_subscription.dispose()
schedule(.dispose)
}
}
| mit | 8cde3dbf569317c5a9e90ae0d5e2a3bc | 26.673333 | 111 | 0.572151 | 5.131026 | false | false | false | false |
mumbler/PReVo-iOS | DatumbazKonstruilo/DatumbazKonstruilo/Konstruado/TekstFarilo.swift | 1 | 3171 | //
// TekstFarilo.swift
// DatumbazKonstruilo
//
// Created by Robin Hill on 8/24/19.
// Copyright © 2019 Robin Hill. All rights reserved.
//
import Foundation
import ReVoDatumbazoOSX
final class TekstFarilo {
public static func fariTekstoDosieron(_ alirilo: DatumbazAlirilo, produktajhoURL: URL) {
let teksto = verkiTekstojn(alirilo)
let fileURL = produktajhoURL.appendingPathComponent("Generataj.strings")
//writing
do {
try teksto.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {
print("Eraro: Ne sukcesis fari generatajn tekstojn.")
}
}
private static func verkiTekstojn(_ alirilo: DatumbazAlirilo) -> String {
print("Verkas tekstojn")
var teksto = ""
teksto += verkiKapanTekston()
teksto += "\n"
teksto += verkiVortaroMallongiganTekston(alirilo)
teksto += verkiFakoMallongiganTekston(alirilo)
return teksto
}
private static func verkiKapanTekston() -> String {
var teksto = ""
teksto += "// Komputile generataj tekstoj\n"
teksto += "// Ne ŝanĝu mane. Vidu 'TekstFarilo.swift' en DatumbazKonstruilo.\n"
return teksto
}
private static func verkiVortaroMallongiganTekston(_ alirilo: DatumbazAlirilo) -> String {
let mallongigoj = alirilo.chiujMallongigoj().sorted(by: { (unua, dua) -> Bool in
let unuaKodo = (unua.value(forKey: "kodo") as? String) ?? ""
let duaKodo = (dua.value(forKey: "kodo") as? String) ?? ""
return unuaKodo.compare(duaKodo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending
})
var teksto = ""
for mallongigo in mallongigoj {
let kodo = mallongigo.value(forKey: "kodo") as? String
let nomo = mallongigo.value(forKey: "nomo") as? String
if let kodo = kodo,
let nomo = nomo {
teksto += "<b>" + kodo + "</b>\\\n " + nomo + "\\\n\n"
}
}
return "\"informoj vortaraj-mallongigoj teksto\"\t\t\t= \"" + teksto + "\";\n"
}
private static func verkiFakoMallongiganTekston(_ alirilo: DatumbazAlirilo) -> String {
let fakoj = alirilo.chiujFakoj().sorted(by: { (unua, dua) -> Bool in
let unuaKodo = (unua.value(forKey: "kodo") as? String) ?? ""
let duaKodo = (dua.value(forKey: "kodo") as? String) ?? ""
return unuaKodo.compare(duaKodo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending
})
var teksto = ""
for fako in fakoj {
let kodo = fako.value(forKey: "kodo") as? String
let nomo = fako.value(forKey: "nomo") as? String
if let kodo = kodo,
let nomo = nomo {
teksto += "<b>" + kodo + "</b>\\\n " + nomo + "\\\n\n"
}
}
return "\"informoj fakaj-mallongigoj teksto\"\t\t\t\t= \"" + teksto + "\";\n"
}
}
| mit | f9f951db9fa811d1cbbe9533de0dc440 | 35 | 138 | 0.559343 | 3.399142 | false | false | false | false |
nathawes/swift | test/Constraints/mutating_members_compat.swift | 12 | 1388 | // RUN: %target-swift-frontend -typecheck -verify -swift-version 4 %s
protocol P {}
struct Foo {
mutating func boom() {}
}
let x = Foo.boom // expected-warning{{partial application of 'mutating' method}}
var y = Foo()
let z0 = y.boom // expected-error{{partial application of 'mutating' method}}
let z1 = Foo.boom(&y) // expected-error{{partial application of 'mutating' method}}
func fromLocalContext() -> (inout Foo) -> () -> () {
return Foo.boom // expected-warning{{partial application of 'mutating' method}}
}
func fromLocalContext2(x: inout Foo, y: Bool) -> () -> () {
if y {
return x.boom // expected-error{{partial application of 'mutating' method}}
} else {
return Foo.boom(&x) // expected-error{{partial application of 'mutating' method}}
}
}
func bar() -> P.Type { fatalError() }
func bar() -> Foo.Type { fatalError() }
_ = bar().boom // expected-warning{{partial application of 'mutating' method}}
_ = bar().boom(&y) // expected-error{{partial application of 'mutating' method}}
_ = bar().boom(&y)() // expected-error{{partial application of 'mutating' method}}
func foo(_ foo: Foo.Type) {
_ = foo.boom // expected-warning{{partial application of 'mutating' method}}
_ = foo.boom(&y) // expected-error{{partial application of 'mutating' method}}
_ = foo.boom(&y)() // expected-error{{partial application of 'mutating' method}}
}
| apache-2.0 | 339aa5415d49904061af7a10a6c268d5 | 37.555556 | 85 | 0.659222 | 3.57732 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Tokens/Types/CollectibleTokenObject.swift | 1 | 2991 | // Copyright DApps Platform Inc. All rights reserved.
import RealmSwift
import Realm
import BigInt
import TrustCore
final class CollectibleTokenObject: Object, Decodable {
@objc dynamic var id: String = ""
@objc dynamic var uniqueID: String = ""
@objc dynamic var contract: String = ""
@objc dynamic var name: String = ""
@objc dynamic var category: String = ""
@objc dynamic var annotation: String = ""
@objc dynamic var imagePath: String = ""
@objc dynamic var externalPath: String = ""
convenience init(
id: String,
contract: String,
name: String,
category: String,
annotation: String,
imagePath: String,
externalPath: String
) {
self.init()
self.id = id
self.contract = contract
self.name = name
self.category = category
self.annotation = annotation
self.imagePath = imagePath
self.externalPath = externalPath
self.uniqueID = id + contract
}
override static func primaryKey() -> String? {
return "uniqueID"
}
private enum NonFungibleTokenCodingKeys: String, CodingKey {
case id = "token_id"
case contract = "contract_address"
case name = "name"
case category = "category"
case annotation = "description"
case imagePath = "image_url"
case externalPath = "external_link"
}
convenience required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: NonFungibleTokenCodingKeys.self)
let id = try container.decodeIfPresent(String.self, forKey: .id) ?? ""
let contract = try container.decodeIfPresent(String.self, forKey: .contract) ?? ""
let name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
let category = try container.decodeIfPresent(String.self, forKey: .category) ?? ""
let annotation = try container.decodeIfPresent(String.self, forKey: .annotation) ?? ""
let imagePath = try container.decodeIfPresent(String.self, forKey: .imagePath) ?? ""
let externalPath = try container.decodeIfPresent(String.self, forKey: .externalPath) ?? ""
self.init(
id: id,
contract: contract,
name: name,
category: category,
annotation: annotation,
imagePath: imagePath,
externalPath: externalPath
)
}
required init() {
super.init()
}
required init(value: Any, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
required init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
var imageURL: URL? {
return URL(string: imagePath)
}
var extentalURL: URL? {
return URL(string: externalPath)
}
var contractAddress: EthereumAddress {
return EthereumAddress(string: contract)!
}
}
| gpl-3.0 | bf960b6a69d71f467efe8edf0b034153 | 30.484211 | 98 | 0.620194 | 4.601538 | false | false | false | false |
timgrohmann/vertretungsplan_ios | Vertretungsplan/WatchDataExtension.swift | 1 | 4238 | //
// WatchDataExtension.swift
// Vertretungsplan
//
// Created by Tim Grohmann on 17.08.17.
// Copyright © 2017 Tim Grohmann. All rights reserved.
//
import Foundation
import UIKit
import WatchConnectivity
class WatchDataExtension: NSObject, WCSessionDelegate{
let session = WCSession.default
override init() {
super.init()
if WCSession.isSupported() {
session.delegate = self
session.activate()
}else{
print("WCSession not supported!")
}
}
func sendWatchData(){
if let rawData: [String:Any] = getEncodedData() {
if session.activationState == .activated{
session.transferCurrentComplicationUserInfo(rawData)
}
}
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print(activationState)
if let error = error {print(error)}
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
if message["intent"] as? String == "reload" {
print("watch wants new data")
DispatchQueue.main.async {
if let rawData = self.getEncodedData(){
print("Data message sent")
replyHandler(["data":rawData])
}else{
replyHandler(["error":"Data object construction failed"])
print("Data object construction failed")
}
}
}
}
func session(_ session: WCSession, didFinish userInfoTransfer: WCSessionUserInfoTransfer, error: Error?) {
if let error = error {print("_:didFinish",error)}
}
func sessionDidDeactivate(_ session: WCSession) {
print(":sessionDidDeactivate")
}
func sessionDidBecomeInactive(_ session: WCSession) {
print(":sessionDidBecomeInactive")
}
func getEncodedData() -> [String:Any]? {
if let vc = (delegate.window?.rootViewController as? UINavigationController)?.viewControllers.first as? ViewController {
let timetable = vc.timetable
let changedTimeTable = vc.changedTimetable
changedTimeTable.refreshChanged()
let timescheme = Array(vc.user?.school?.timeschemes ?? [])
var rawData: [String:Any] = [:]
let days = timetable.days
for day in days {
var dayLessons: [String:Any] = [:]
for lesson in day.lessons{
var lessonRawified: [String:Any] = [:]
lessonRawified["subj"] = lesson.subject.capitalized
lessonRawified["room"] = lesson.room.capitalized
if let change = changedTimeTable.getChange(lesson){
lessonRawified["subj"] = change.subject.capitalized
lessonRawified["room"] = change.room.capitalized
lessonRawified["change"] = true
}
if lesson.subject != "" {
dayLessons[String(lesson.hour)] = lessonRawified
}
}
rawData[String(day.number)] = dayLessons
}
var timeRaw: [String:Any] = [:]
for time in timescheme {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
if let from = time.startTime, let to = time.endTime{
timeRaw[String(time.lessonNumber)] = ["from": formatter.string(from: from), "to": formatter.string(from: to)]
}
}
rawData["timescheme"] = timeRaw
return rawData
}
return nil
}
}
| apache-2.0 | 2279218f962d77d0f63840f9b9cc285f | 32.362205 | 133 | 0.518999 | 5.446015 | false | false | false | false |
longsirhero/DinDinShop | DinDinShopDemo/DinDinShopDemo/首页/Views/WCProductDetailHeadView.swift | 1 | 1724 | //
// WCProductDetailHeadView.swift
// DinDinShopDemo
//
// Created by longsirHERO on 2017/9/5.
// Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved.
//
import UIKit
import FSPagerView
class WCProductDetailHeadView: UITableViewHeaderFooterView {
let pagerView = FSPagerView()
var dataSource:NSArray = NSArray() {
didSet {
self.pagerView.reloadData()
}
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
pagerView.backgroundColor = UIColor.white
pagerView.automaticSlidingInterval = 3.0
pagerView.isInfinite = true
pagerView.dataSource = self
pagerView.delegate = self
pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
self.addSubview(pagerView)
pagerView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WCProductDetailHeadView:FSPagerViewDataSource,FSPagerViewDelegate {
func numberOfItems(in pagerView: FSPagerView) -> Int {
return dataSource.count
}
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
let pic:String = dataSource[index] as! String
cell.imageView?.kf.setImage(with: URL(string: pic))
cell.imageView?.contentMode = .scaleAspectFit
return cell
}
}
| mit | 039fa2da1fdf42bfd8476726b6771f3f | 26.758065 | 91 | 0.650203 | 4.945402 | false | false | false | false |
umairhassanbaig/UHBDataFetcher | UHBDataFetcher/Classes/UHBDataCache.swift | 1 | 4322 | //
// UHBDataCache.swift
// DataCacheSample
//
// Created by Umair Hassan Baig on 7/8/17.
// Copyright © 2017 Umair Hassan Baig. All rights reserved.
//
import UIKit
/// UHBDataCache is self memory managing cache that caches any kind of objects. It manages objects w.r.t given capacity and clears object w.r.t date Hard cache will be supported soon
class UHBDataCache: NSObject {
/// Maximum capacity of cahce
public var capacity = 0;
private var cache : [AnyHashable : Any]
private var clearance_factor : Int = 4;
//=================================
// MARK: - Public interface
//=================================
public override init() {
self.capacity = 300
self.cache = [AnyHashable : Any]();
super.init();
NotificationCenter.default.addObserver(self, selector: #selector(recievedMemoryWarning), name: .UIApplicationDidReceiveMemoryWarning, object: nil);
}
/// Convienience initializer with cahce maximum capicity
///
/// - Parameter capacity: Maximum capacity of cahce.
convenience init(capacity : Int) {
self.init();
self.capacity = capacity
}
/// Set Any Object in cahce with key
///
/// - Parameters:
/// - obj: Object to be set in cache
/// - key: key for the object to store
open func setObject(_ obj: Any, forKey key: AnyHashable){
(self.cache as NSObject).sync(closure: {
self.cache[key] = UHBCacheObject(object: obj);
if self.cache.count > self.capacity {
//Clearing 25%(Based on clearance factor) cache of older objects of older use
var keys = self.cache.sortedKeysByValue(isOrderedBefore: { return (($0 as! UHBCacheObject).date.compare(($1 as! UHBCacheObject).date)) == .orderedAscending})
for n in 0...Int(self.cache.count/self.clearance_factor) {
self.cache.removeValue(forKey: keys[n]);
}
}
})
}
/// Returns stored object for the given key
///
/// - Parameter key: Key for the object to be retrieved
/// - Returns: Object if present else it returns nil
open func object(forKey key: AnyHashable) -> Any? {
let cached_obj = (self.cache[key] as? UHBCacheObject);
cached_obj?.date = Date();
return cached_obj?.object;
}
/// Clears cache. Removes all objects in the cache
open func removeAllObjects() {
self.cache.removeAll();
}
/// Removes object for the key from cache if present
///
/// - Parameter key: key for the object to be removed
open func removeObject(forKey key: AnyHashable){
self.cache.removeValue(forKey: key);
}
//=================================
// MARK: - Memory management
//=================================
/// Clears objects if app memory is low
@objc private func recievedMemoryWarning() {
self.cache.removeAll();
}
deinit {
NotificationCenter.default.removeObserver(self);
}
//=================================
// MARK: - Cache Object
//=================================
/// Wrapper object with date to manage order by usage
private class UHBCacheObject : NSObject {
var date : Date
var object : Any
init(object : Any) {
self.date = Date();
self.object = object;
super.init();
}
}
}
// MARK: - Mutex safety
fileprivate extension NSObject {
/// Thread safe block execution on any NSObject that is protected with mutex lock
///
/// - Parameters:
/// - closure: Execution block to be executed with thread lock
fileprivate func sync(closure: () -> Void) {
objc_sync_enter(self)
closure()
objc_sync_exit(self)
}
}
// MARK: - Sort helpers
fileprivate extension Dictionary {
func sortedKeys(isOrderedBefore:(Key,Key) -> Bool) -> [Key] {
return Array(self.keys).sorted(by: isOrderedBefore)
}
func sortedKeysByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {
return sortedKeys {
isOrderedBefore(self[$0]!, self[$1]!)
}
}
}
| mit | 1f514ab8af923f4e497b80ac2ce14062 | 28.59589 | 182 | 0.563758 | 4.601704 | false | false | false | false |
Shannon-Yang/SYNetworking | Pods/Alamofire/Source/Request.swift | 2 | 74197 | //
// Request.swift
//
// Copyright (c) 2014-2020 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
/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
/// handling.
public class Request {
/// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
/// `cancel()` on the `Request`.
public enum State {
/// Initial state of the `Request`.
case initialized
/// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
/// them in this state.
case resumed
/// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
/// them in this state.
case suspended
/// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
/// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition
/// to any other state.
case cancelled
/// `State` set when all response serialization completion closures have been cleared on the `Request` and
/// enqueued on their respective queues.
case finished
/// Determines whether `self` can be transitioned to the provided `State`.
func canTransitionTo(_ state: State) -> Bool {
switch (self, state) {
case (.initialized, _):
return true
case (_, .initialized), (.cancelled, _), (.finished, _):
return false
case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
return true
case (.suspended, .suspended), (.resumed, .resumed):
return false
case (_, .finished):
return true
}
}
}
// MARK: - Initial State
/// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
public let id: UUID
/// The serial queue for all internal async actions.
public let underlyingQueue: DispatchQueue
/// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
public let serializationQueue: DispatchQueue
/// `EventMonitor` used for event callbacks.
public let eventMonitor: EventMonitor?
/// The `Request`'s interceptor.
public let interceptor: RequestInterceptor?
/// The `Request`'s delegate.
public private(set) weak var delegate: RequestDelegate?
// MARK: - Mutable State
/// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
struct MutableState {
/// State of the `Request`.
var state: State = .initialized
/// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
/// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
/// `RedirectHandler` provided for to handle request redirection.
var redirectHandler: RedirectHandler?
/// `CachedResponseHandler` provided to handle response caching.
var cachedResponseHandler: CachedResponseHandler?
/// Closure called when the `Request` is able to create a cURL description of itself.
var cURLHandler: ((String) -> Void)?
/// Response serialization closures that handle response parsing.
var responseSerializers: [() -> Void] = []
/// Response serialization completion closures executed once all response serializers are complete.
var responseSerializerCompletions: [() -> Void] = []
/// Whether response serializer processing is finished.
var responseSerializerProcessingFinished = false
/// `URLCredential` used for authentication challenges.
var credential: URLCredential?
/// All `URLRequest`s created by Alamofire on behalf of the `Request`.
var requests: [URLRequest] = []
/// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
var tasks: [URLSessionTask] = []
/// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
/// exactly the the `tasks` created.
var metrics: [URLSessionTaskMetrics] = []
/// Number of times any retriers provided retried the `Request`.
var retryCount = 0
/// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
var error: AFError?
/// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a
/// representation in the state machine in the future.
var isFinishing = false
}
/// Protected `MutableState` value that provides thread-safe access to state values.
@Protected
fileprivate var mutableState = MutableState()
/// `State` of the `Request`.
public var state: State { mutableState.state }
/// Returns whether `state` is `.initialized`.
public var isInitialized: Bool { state == .initialized }
/// Returns whether `state is `.resumed`.
public var isResumed: Bool { state == .resumed }
/// Returns whether `state` is `.suspended`.
public var isSuspended: Bool { state == .suspended }
/// Returns whether `state` is `.cancelled`.
public var isCancelled: Bool { state == .cancelled }
/// Returns whether `state` is `.finished`.
public var isFinished: Bool { state == .finished }
// MARK: Progress
/// Closure type executed when monitoring the upload or download progress of a request.
public typealias ProgressHandler = (Progress) -> Void
/// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
public let uploadProgress = Progress(totalUnitCount: 0)
/// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
public let downloadProgress = Progress(totalUnitCount: 0)
/// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
fileprivate var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
get { mutableState.uploadProgressHandler }
set { mutableState.uploadProgressHandler = newValue }
}
/// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
get { mutableState.downloadProgressHandler }
set { mutableState.downloadProgressHandler = newValue }
}
// MARK: Redirect Handling
/// `RedirectHandler` set on the instance.
public private(set) var redirectHandler: RedirectHandler? {
get { mutableState.redirectHandler }
set { mutableState.redirectHandler = newValue }
}
// MARK: Cached Response Handling
/// `CachedResponseHandler` set on the instance.
public private(set) var cachedResponseHandler: CachedResponseHandler? {
get { mutableState.cachedResponseHandler }
set { mutableState.cachedResponseHandler = newValue }
}
// MARK: URLCredential
/// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
public private(set) var credential: URLCredential? {
get { mutableState.credential }
set { mutableState.credential = newValue }
}
// MARK: Validators
/// `Validator` callback closures that store the validation calls enqueued.
@Protected
fileprivate var validators: [() -> Void] = []
// MARK: URLRequests
/// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
public var requests: [URLRequest] { mutableState.requests }
/// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
public var firstRequest: URLRequest? { requests.first }
/// Last `URLRequest` created on behalf of the `Request`.
public var lastRequest: URLRequest? { requests.last }
/// Current `URLRequest` created on behalf of the `Request`.
public var request: URLRequest? { lastRequest }
/// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
/// `requests` due to `URLSession` manipulation.
public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap { $0.currentRequest } } }
// MARK: HTTPURLResponse
/// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
/// last `URLSessionTask`.
public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse }
// MARK: Tasks
/// All `URLSessionTask`s created on behalf of the `Request`.
public var tasks: [URLSessionTask] { mutableState.tasks }
/// First `URLSessionTask` created on behalf of the `Request`.
public var firstTask: URLSessionTask? { tasks.first }
/// Last `URLSessionTask` crated on behalf of the `Request`.
public var lastTask: URLSessionTask? { tasks.last }
/// Current `URLSessionTask` created on behalf of the `Request`.
public var task: URLSessionTask? { lastTask }
// MARK: Metrics
/// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
public var allMetrics: [URLSessionTaskMetrics] { mutableState.metrics }
/// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first }
/// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last }
/// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
public var metrics: URLSessionTaskMetrics? { lastMetrics }
// MARK: Retry Count
/// Number of times the `Request` has been retried.
public var retryCount: Int { mutableState.retryCount }
// MARK: Error
/// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
public fileprivate(set) var error: AFError? {
get { mutableState.error }
set { mutableState.error = newValue }
}
/// Default initializer for the `Request` superclass.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
init(id: UUID = UUID(),
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate) {
self.id = id
self.underlyingQueue = underlyingQueue
self.serializationQueue = serializationQueue
self.eventMonitor = eventMonitor
self.interceptor = interceptor
self.delegate = delegate
}
// MARK: - Internal Event API
// All API must be called from underlyingQueue.
/// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
/// the `URLRequest` will be adapted before being issued.
///
/// - Parameter request: The `URLRequest` created.
func didCreateInitialURLRequest(_ request: URLRequest) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.requests.append(request) }
eventMonitor?.request(self, didCreateInitialURLRequest: request)
}
/// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
///
/// - Note: Triggers retry.
///
/// - Parameter error: `AFError` thrown from the failed creation.
func didFailToCreateURLRequest(with error: AFError) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = error
eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
callCURLHandlerIfNecessary()
retryOrFinish(error: error)
}
/// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
///
/// - Parameters:
/// - initialRequest: The `URLRequest` that was adapted.
/// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.requests.append(adaptedRequest) }
eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
}
/// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
///
/// - Note: Triggers retry.
///
/// - Parameters:
/// - request: The `URLRequest` the adapter was called with.
/// - error: The `AFError` returned by the `RequestAdapter`.
func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = error
eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
callCURLHandlerIfNecessary()
retryOrFinish(error: error)
}
/// Final `URLRequest` has been created for the instance.
///
/// - Parameter request: The `URLRequest` created.
func didCreateURLRequest(_ request: URLRequest) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didCreateURLRequest: request)
callCURLHandlerIfNecessary()
}
/// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
private func callCURLHandlerIfNecessary() {
$mutableState.write { mutableState in
guard let cURLHandler = mutableState.cURLHandler else { return }
self.underlyingQueue.async { cURLHandler(self.cURLDescription()) }
mutableState.cURLHandler = nil
}
}
/// Called when a `URLSessionTask` is created on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` created.
func didCreateTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.tasks.append(task) }
eventMonitor?.request(self, didCreateTask: task)
}
/// Called when resumption is completed.
func didResume() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.requestDidResume(self)
}
/// Called when a `URLSessionTask` is resumed on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` resumed.
func didResumeTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didResumeTask: task)
}
/// Called when suspension is completed.
func didSuspend() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.requestDidSuspend(self)
}
/// Called when a `URLSessionTask` is suspended on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` suspended.
func didSuspendTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didSuspendTask: task)
}
/// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
func didCancel() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
error = error ?? AFError.explicitlyCancelled
eventMonitor?.requestDidCancel(self)
}
/// Called when a `URLSessionTask` is cancelled on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` cancelled.
func didCancelTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didCancelTask: task)
}
/// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
///
/// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.metrics.append(metrics) }
eventMonitor?.request(self, didGatherMetrics: metrics)
}
/// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
///
/// - Parameters:
/// - task: The `URLSessionTask` which failed.
/// - error: The early failure `AFError`.
func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = error
// Task will still complete, so didCompleteTask(_:with:) will handle retry.
eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
}
/// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
///
/// - Note: Response validation is synchronously triggered in this step.
///
/// - Parameters:
/// - task: The `URLSessionTask` which completed.
/// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this
/// value is ignored.
func didCompleteTask(_ task: URLSessionTask, with error: AFError?) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = self.error ?? error
validators.forEach { $0() }
eventMonitor?.request(self, didCompleteTask: task, with: error)
retryOrFinish(error: self.error)
}
/// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
func prepareForRetry() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.retryCount += 1 }
reset()
eventMonitor?.requestIsRetrying(self)
}
/// Called to determine whether retry will be triggered for the particular error, or whether the instance should
/// call `finish()`.
///
/// - Parameter error: The possible `AFError` which may trigger retry.
func retryOrFinish(error: AFError?) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
guard let error = error, let delegate = delegate else { finish(); return }
delegate.retryResult(for: self, dueTo: error) { retryResult in
switch retryResult {
case .doNotRetry:
self.finish()
case let .doNotRetryWithError(retryError):
self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
case .retry, .retryWithDelay:
delegate.retryRequest(self, withDelay: retryResult.delay)
}
}
}
/// Finishes this `Request` and starts the response serializers.
///
/// - Parameter error: The possible `Error` with which the instance will finish.
func finish(error: AFError? = nil) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
guard !mutableState.isFinishing else { return }
mutableState.isFinishing = true
if let error = error { self.error = error }
// Start response handlers
processNextResponseSerializer()
eventMonitor?.requestDidFinish(self)
}
/// Appends the response serialization closure to the instance.
///
/// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
///
/// - Parameter closure: The closure containing the response serialization call.
func appendResponseSerializer(_ closure: @escaping () -> Void) {
$mutableState.write { mutableState in
mutableState.responseSerializers.append(closure)
if mutableState.state == .finished {
mutableState.state = .resumed
}
if mutableState.responseSerializerProcessingFinished {
underlyingQueue.async { self.processNextResponseSerializer() }
}
if mutableState.state.canTransitionTo(.resumed) {
underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
}
}
}
/// Returns the next response serializer closure to execute if there's one left.
///
/// - Returns: The next response serialization closure, if there is one.
func nextResponseSerializer() -> (() -> Void)? {
var responseSerializer: (() -> Void)?
$mutableState.write { mutableState in
let responseSerializerIndex = mutableState.responseSerializerCompletions.count
if responseSerializerIndex < mutableState.responseSerializers.count {
responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
}
}
return responseSerializer
}
/// Processes the next response serializer and calls all completions if response serialization is complete.
func processNextResponseSerializer() {
guard let responseSerializer = nextResponseSerializer() else {
// Execute all response serializer completions and clear them
var completions: [() -> Void] = []
$mutableState.write { mutableState in
completions = mutableState.responseSerializerCompletions
// Clear out all response serializers and response serializer completions in mutable state since the
// request is complete. It's important to do this prior to calling the completion closures in case
// the completions call back into the request triggering a re-processing of the response serializers.
// An example of how this can happen is by calling cancel inside a response completion closure.
mutableState.responseSerializers.removeAll()
mutableState.responseSerializerCompletions.removeAll()
if mutableState.state.canTransitionTo(.finished) {
mutableState.state = .finished
}
mutableState.responseSerializerProcessingFinished = true
mutableState.isFinishing = false
}
completions.forEach { $0() }
// Cleanup the request
cleanup()
return
}
serializationQueue.async { responseSerializer() }
}
/// Notifies the `Request` that the response serializer is complete.
///
/// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
/// are complete.
func responseSerializerDidComplete(completion: @escaping () -> Void) {
$mutableState.write { $0.responseSerializerCompletions.append(completion) }
processNextResponseSerializer()
}
/// Resets all task and response serializer related state for retry.
func reset() {
error = nil
uploadProgress.totalUnitCount = 0
uploadProgress.completedUnitCount = 0
downloadProgress.totalUnitCount = 0
downloadProgress.completedUnitCount = 0
$mutableState.write { state in
state.isFinishing = false
state.responseSerializerCompletions = []
}
}
/// Called when updating the upload progress.
///
/// - Parameters:
/// - totalBytesSent: Total bytes sent so far.
/// - totalBytesExpectedToSend: Total bytes expected to send.
func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
}
/// Perform a closure on the current `state` while locked.
///
/// - Parameter perform: The closure to perform.
func withState(perform: (State) -> Void) {
$mutableState.withState(perform: perform)
}
// MARK: Task Creation
/// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
///
/// - Parameters:
/// - request: `URLRequest` to use to create the `URLSessionTask`.
/// - session: `URLSession` which creates the `URLSessionTask`.
///
/// - Returns: The `URLSessionTask` created.
func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
fatalError("Subclasses must override.")
}
// MARK: - Public API
// These APIs are callable from any queue.
// MARK: State
/// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
///
/// - Returns: The instance.
@discardableResult
public func cancel() -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.cancelled) else { return }
mutableState.state = .cancelled
underlyingQueue.async { self.didCancel() }
guard let task = mutableState.tasks.last, task.state != .completed else {
underlyingQueue.async { self.finish() }
return
}
// Resume to ensure metrics are gathered.
task.resume()
task.cancel()
underlyingQueue.async { self.didCancelTask(task) }
}
return self
}
/// Suspends the instance.
///
/// - Returns: The instance.
@discardableResult
public func suspend() -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.suspended) else { return }
mutableState.state = .suspended
underlyingQueue.async { self.didSuspend() }
guard let task = mutableState.tasks.last, task.state != .completed else { return }
task.suspend()
underlyingQueue.async { self.didSuspendTask(task) }
}
return self
}
/// Resumes the instance.
///
/// - Returns: The instance.
@discardableResult
public func resume() -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.resumed) else { return }
mutableState.state = .resumed
underlyingQueue.async { self.didResume() }
guard let task = mutableState.tasks.last, task.state != .completed else { return }
task.resume()
underlyingQueue.async { self.didResumeTask(task) }
}
return self
}
// MARK: - Closure API
/// Associates a credential using the provided values with the instance.
///
/// - Parameters:
/// - username: The username.
/// - password: The password.
/// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
///
/// - Returns: The instance.
@discardableResult
public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
let credential = URLCredential(user: username, password: password, persistence: persistence)
return authenticate(with: credential)
}
/// Associates the provided credential with the instance.
///
/// - Parameter credential: The `URLCredential`.
///
/// - Returns: The instance.
@discardableResult
public func authenticate(with credential: URLCredential) -> Self {
mutableState.credential = credential
return self
}
/// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
///
/// - Note: Only the last closure provided is used.
///
/// - Parameters:
/// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
/// - closure: The closure to be executed periodically as data is read from the server.
///
/// - Returns: The instance.
@discardableResult
public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
mutableState.downloadProgressHandler = (handler: closure, queue: queue)
return self
}
/// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
///
/// - Note: Only the last closure provided is used.
///
/// - Parameters:
/// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
/// - closure: The closure to be executed periodically as data is sent to the server.
///
/// - Returns: The instance.
@discardableResult
public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
mutableState.uploadProgressHandler = (handler: closure, queue: queue)
return self
}
// MARK: Redirects
/// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
///
/// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
///
/// - Parameter handler: The `RedirectHandler`.
///
/// - Returns: The instance.
@discardableResult
public func redirect(using handler: RedirectHandler) -> Self {
$mutableState.write { mutableState in
precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
mutableState.redirectHandler = handler
}
return self
}
// MARK: Cached Responses
/// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
///
/// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
///
/// - Parameter handler: The `CachedResponseHandler`.
///
/// - Returns: The instance.
@discardableResult
public func cacheResponse(using handler: CachedResponseHandler) -> Self {
$mutableState.write { mutableState in
precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
mutableState.cachedResponseHandler = handler
}
return self
}
/// Sets a handler to be called when the cURL description of the request is available.
///
/// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
///
/// - Parameter handler: Closure to be called when the cURL description is available.
///
/// - Returns: The instance.
@discardableResult
public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
$mutableState.write { mutableState in
if mutableState.requests.last != nil {
underlyingQueue.async { handler(self.cURLDescription()) }
} else {
mutableState.cURLHandler = handler
}
}
return self
}
// MARK: Cleanup
/// Final cleanup step executed when the instance finishes response serialization.
func cleanup() {
delegate?.cleanup(after: self)
// No-op: override in subclass
}
}
// MARK: - Protocol Conformances
extension Request: Equatable {
public static func ==(lhs: Request, rhs: Request) -> Bool {
lhs.id == rhs.id
}
}
extension Request: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
extension Request: CustomStringConvertible {
/// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
/// created, as well as the response status code, if a response has been received.
public var description: String {
guard let request = performedRequests.last ?? lastRequest,
let url = request.url,
let method = request.httpMethod else { return "No request created yet." }
let requestDescription = "\(method) \(url.absoluteString)"
return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
}
}
extension Request {
/// cURL representation of the instance.
///
/// - Returns: The cURL equivalent of the instance.
public func cURLDescription() -> String {
guard
let request = lastRequest,
let url = request.url,
let host = url.host,
let method = request.httpMethod else { return "$ curl command could not be created" }
var components = ["$ curl -v"]
components.append("-X \(method)")
if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
let protectionSpace = URLProtectionSpace(host: host,
port: url.port ?? 0,
protocol: url.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
guard let user = credential.user, let password = credential.password else { continue }
components.append("-u \(user):\(password)")
}
} else {
if let credential = credential, let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
}
if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
if
let cookieStorage = configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
components.append("-b \"\(allCookies)\"")
}
}
var headers = HTTPHeaders()
if let sessionHeaders = delegate?.sessionConfiguration.headers {
for header in sessionHeaders where header.name != "Cookie" {
headers[header.name] = header.value
}
}
for header in request.headers where header.name != "Cookie" {
headers[header.name] = header.value
}
for header in headers {
let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-H \"\(header.name): \(escapedValue)\"")
}
if let httpBodyData = request.httpBody {
let httpBody = String(decoding: httpBodyData, as: UTF8.self)
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
}
/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
public protocol RequestDelegate: AnyObject {
/// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
var sessionConfiguration: URLSessionConfiguration { get }
/// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
var startImmediately: Bool { get }
/// Notifies the delegate the `Request` has reached a point where it needs cleanup.
///
/// - Parameter request: The `Request` to cleanup after.
func cleanup(after request: Request)
/// Asynchronously ask the delegate whether a `Request` will be retried.
///
/// - Parameters:
/// - request: `Request` which failed.
/// - error: `Error` which produced the failure.
/// - completion: Closure taking the `RetryResult` for evaluation.
func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
/// Asynchronously retry the `Request`.
///
/// - Parameters:
/// - request: `Request` which will be retried.
/// - timeDelay: `TimeInterval` after which the retry will be triggered.
func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
}
// MARK: - Subclasses
// MARK: - DataRequest
/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
public class DataRequest: Request {
/// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
public let convertible: URLRequestConvertible
/// `Data` read from the server so far.
public var data: Data? { mutableData }
/// Protected storage for the `Data` read by the instance.
@Protected
private var mutableData: Data? = nil
/// Creates a `DataRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
init(id: UUID = UUID(),
convertible: URLRequestConvertible,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate) {
self.convertible = convertible
super.init(id: id,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
override func reset() {
super.reset()
mutableData = nil
}
/// Called when `Data` is received by this instance.
///
/// - Note: Also calls `updateDownloadProgress`.
///
/// - Parameter data: The `Data` received.
func didReceive(data: Data) {
if self.data == nil {
mutableData = data
} else {
$mutableData.write { $0?.append(data) }
}
updateDownloadProgress()
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
let copiedRequest = request
return session.dataTask(with: copiedRequest)
}
/// Called to updated the `downloadProgress` of the instance.
func updateDownloadProgress() {
let totalBytesReceived = Int64(data?.count ?? 0)
let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
downloadProgress.totalUnitCount = totalBytesExpected
downloadProgress.completedUnitCount = totalBytesReceived
downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
}
/// Validates the request, using the specified closure.
///
/// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Parameter validation: `Validation` closure used to validate the response.
///
/// - Returns: The instance.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validator: () -> Void = { [unowned self] in
guard self.error == nil, let response = self.response else { return }
let result = validation(self.request, response, self.data)
if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
self.eventMonitor?.request(self,
didValidateRequest: self.request,
response: response,
data: self.data,
withResult: result)
}
$validators.write { $0.append(validator) }
return self
}
}
// MARK: - DataStreamRequest
/// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
public final class DataStreamRequest: Request {
/// Closure type handling `DataStreamRequest.Stream` values.
public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void
/// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
/// to stop the stream at any time.
public struct Stream<Success, Failure: Error> {
/// Latest `Event` from the stream.
public let event: Event<Success, Failure>
/// Token used to cancel the stream.
public let token: CancellationToken
/// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
public func cancel() {
token.cancel()
}
}
/// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
/// `Data` or the completion of the stream.
public enum Event<Success, Failure: Error> {
/// Output produced every time the instance receives additional `Data`. The associated value contains the
/// `Result` of processing the incoming `Data`.
case stream(Result<Success, Failure>)
/// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
/// Associated `Completion` value contains the final state.
case complete(Completion)
}
/// Value containing the state of a `DataStreamRequest` when the stream was completed.
public struct Completion {
/// Last `URLRequest` issued by the instance.
public let request: URLRequest?
/// Last `HTTPURLResponse` received by the instance.
public let response: HTTPURLResponse?
/// Last `URLSessionTaskMetrics` produced for the instance.
public let metrics: URLSessionTaskMetrics?
/// `AFError` produced for the instance, if any.
public let error: AFError?
}
/// Type used to cancel an ongoing stream.
public struct CancellationToken {
weak var request: DataStreamRequest?
init(_ request: DataStreamRequest) {
self.request = request
}
/// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
public func cancel() {
request?.cancel()
}
}
/// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
public let convertible: URLRequestConvertible
/// Whether or not the instance will be cancelled if stream parsing encounters an error.
public let automaticallyCancelOnStreamError: Bool
/// Internal mutable state specific to this type.
struct StreamMutableState {
/// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
var outputStream: OutputStream?
/// Stream closures called as `Data` is received.
var streams: [(_ data: Data) -> Void] = []
/// Number of currently executing streams. Used to ensure completions are only fired after all streams are
/// enqueued.
var numberOfExecutingStreams = 0
/// Completion calls enqueued while streams are still executing.
var enqueuedCompletionEvents: [() -> Void] = []
}
@Protected
var streamMutableState = StreamMutableState()
/// Creates a `DataStreamRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
/// by default.
/// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
/// instance.
/// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
/// is thrown while serializing stream `Data`.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
/// targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by
/// the `Request`.
init(id: UUID = UUID(),
convertible: URLRequestConvertible,
automaticallyCancelOnStreamError: Bool,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate) {
self.convertible = convertible
self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
super.init(id: id,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
let copiedRequest = request
return session.dataTask(with: copiedRequest)
}
override func finish(error: AFError? = nil) {
$streamMutableState.write { state in
state.outputStream?.close()
}
super.finish(error: error)
}
func didReceive(data: Data) {
$streamMutableState.write { state in
if let stream = state.outputStream {
underlyingQueue.async {
var bytes = Array(data)
stream.write(&bytes, maxLength: bytes.count)
}
}
state.numberOfExecutingStreams += state.streams.count
let localState = state
underlyingQueue.async { localState.streams.forEach { $0(data) } }
}
}
/// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
///
/// - Parameter validation: `Validation` closure used to validate the request and response.
///
/// - Returns: The `DataStreamRequest`.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validator: () -> Void = { [unowned self] in
guard self.error == nil, let response = self.response else { return }
let result = validation(self.request, response)
if case let .failure(error) = result {
self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
}
self.eventMonitor?.request(self,
didValidateRequest: self.request,
response: response,
withResult: result)
}
$validators.write { $0.append(validator) }
return self
}
/// Produces an `InputStream` that receives the `Data` received by the instance.
///
/// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
/// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
/// not the creating session has `startRequestsImmediately` set to `true`.
///
/// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
///
/// - Returns: The `InputStream` bound to the internal `OutboundStream`.
public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
defer { resume() }
var inputStream: InputStream?
$streamMutableState.write { state in
Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
inputStream: &inputStream,
outputStream: &state.outputStream)
state.outputStream?.open()
}
return inputStream
}
func capturingError(from closure: () throws -> Void) {
do {
try closure()
} catch {
self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
cancel()
}
}
func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
stream: @escaping Handler<Success, Failure>) {
appendResponseSerializer {
self.underlyingQueue.async {
self.responseSerializerDidComplete {
self.$streamMutableState.write { state in
guard state.numberOfExecutingStreams == 0 else {
state.enqueuedCompletionEvents.append {
self.enqueueCompletion(on: queue, stream: stream)
}
return
}
self.enqueueCompletion(on: queue, stream: stream)
}
}
}
}
}
func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
stream: @escaping Handler<Success, Failure>) {
queue.async {
do {
let completion = Completion(request: self.request,
response: self.response,
metrics: self.metrics,
error: self.error)
try stream(.init(event: .complete(completion), token: .init(self)))
} catch {
// Ignore error, as errors on Completion can't be handled anyway.
}
}
}
}
extension DataStreamRequest.Stream {
/// Incoming `Result` values from `Event.stream`.
public var result: Result<Success, Failure>? {
guard case let .stream(result) = event else { return nil }
return result
}
/// `Success` value of the instance, if any.
public var value: Success? {
guard case let .success(value) = result else { return nil }
return value
}
/// `Failure` value of the instance, if any.
public var error: Failure? {
guard case let .failure(error) = result else { return nil }
return error
}
/// `Completion` value of the instance, if any.
public var completion: DataStreamRequest.Completion? {
guard case let .complete(completion) = event else { return nil }
return completion
}
}
// MARK: - DownloadRequest
/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
public class DownloadRequest: Request {
/// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
/// `URL`.
public struct Options: OptionSet {
/// Specifies that intermediate directories for the destination URL should be created.
public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
/// Specifies that any previous file at the destination `URL` should be removed.
public static let removePreviousFile = Options(rawValue: 1 << 1)
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
// MARK: Destination
/// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
/// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
/// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
public typealias Destination = (_ temporaryURL: URL,
_ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
/// Creates a download file destination closure which uses the default file manager to move the temporary file to a
/// file URL in the first available directory with the specified search path directory and search path domain mask.
///
/// - Parameters:
/// - directory: The search path directory. `.documentDirectory` by default.
/// - domain: The search path domain mask. `.userDomainMask` by default.
/// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
/// default.
/// - Returns: The `Destination` closure.
public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask,
options: Options = []) -> Destination {
{ temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
return (url, options)
}
}
/// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
/// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
/// with this destination must be additionally moved if they should survive the system reclamation of temporary
/// space.
static let defaultDestination: Destination = { url, _ in
let filename = "Alamofire_\(url.lastPathComponent)"
let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
return (destination, [])
}
// MARK: Downloadable
/// Type describing the source used to create the underlying `URLSessionDownloadTask`.
public enum Downloadable {
/// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
case request(URLRequestConvertible)
/// Download should be started from the associated resume `Data` value.
case resumeData(Data)
}
// MARK: Mutable State
/// Type containing all mutable state for `DownloadRequest` instances.
private struct DownloadRequestMutableState {
/// Possible resume `Data` produced when cancelling the instance.
var resumeData: Data?
/// `URL` to which `Data` is being downloaded.
var fileURL: URL?
}
/// Protected mutable state specific to `DownloadRequest`.
@Protected
private var mutableDownloadState = DownloadRequestMutableState()
/// If the download is resumable and eventually cancelled, this value may be used to resume the download using the
/// `download(resumingWith data:)` API.
///
/// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
public var resumeData: Data? { mutableDownloadState.resumeData }
/// If the download is successful, the `URL` where the file was downloaded.
public var fileURL: URL? { mutableDownloadState.fileURL }
// MARK: Initial State
/// `Downloadable` value used for this instance.
public let downloadable: Downloadable
/// The `Destination` to which the downloaded file is moved.
let destination: Destination
/// Creates a `DownloadRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
/// - destination: `Destination` closure used to move the downloaded file to its final location.
init(id: UUID = UUID(),
downloadable: Downloadable,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate,
destination: @escaping Destination) {
self.downloadable = downloadable
self.destination = destination
super.init(id: id,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
override func reset() {
super.reset()
$mutableDownloadState.write {
$0.resumeData = nil
$0.fileURL = nil
}
}
/// Called when a download has finished.
///
/// - Parameters:
/// - task: `URLSessionTask` that finished the download.
/// - result: `Result` of the automatic move to `destination`.
func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
switch result {
case let .success(url): mutableDownloadState.fileURL = url
case let .failure(error): self.error = error
}
}
/// Updates the `downloadProgress` using the provided values.
///
/// - Parameters:
/// - bytesWritten: Total bytes written so far.
/// - totalBytesExpectedToWrite: Total bytes expected to write.
func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
downloadProgress.totalUnitCount = totalBytesExpectedToWrite
downloadProgress.completedUnitCount += bytesWritten
downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
session.downloadTask(with: request)
}
/// Creates a `URLSessionTask` from the provided resume data.
///
/// - Parameters:
/// - data: `Data` used to resume the download.
/// - session: `URLSession` used to create the `URLSessionTask`.
///
/// - Returns: The `URLSessionTask` created.
public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
session.downloadTask(withResumeData: data)
}
/// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
///
/// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
/// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
///
/// - Returns: The instance.
@discardableResult
override public func cancel() -> Self {
cancel(producingResumeData: false)
}
/// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
/// resumed or suspended.
///
/// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
/// available.
///
/// - Returns: The instance.
@discardableResult
public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
}
/// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
/// or suspended.
///
/// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
/// property.
///
/// - Parameter completionHandler: The completion handler that is called when the download has been successfully
/// cancelled. It is not guaranteed to be called on a particular queue, so you may
/// want use an appropriate queue to perform your work.
///
/// - Returns: The instance.
@discardableResult
public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
cancel(optionallyProducingResumeData: completionHandler)
}
/// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
/// cancellation is performed without producing resume data.
///
/// - Parameter completionHandler: Optional resume data handler.
///
/// - Returns: The instance.
private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.cancelled) else { return }
mutableState.state = .cancelled
underlyingQueue.async { self.didCancel() }
guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
underlyingQueue.async { self.finish() }
return
}
if let completionHandler = completionHandler {
// Resume to ensure metrics are gathered.
task.resume()
task.cancel { resumeData in
self.mutableDownloadState.resumeData = resumeData
self.underlyingQueue.async { self.didCancelTask(task) }
completionHandler(resumeData)
}
} else {
// Resume to ensure metrics are gathered.
task.resume()
task.cancel(byProducingResumeData: { _ in })
self.underlyingQueue.async { self.didCancelTask(task) }
}
}
return self
}
/// Validates the request, using the specified closure.
///
/// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Parameter validation: `Validation` closure to validate the response.
///
/// - Returns: The instance.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validator: () -> Void = { [unowned self] in
guard self.error == nil, let response = self.response else { return }
let result = validation(self.request, response, self.fileURL)
if case let .failure(error) = result {
self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
}
self.eventMonitor?.request(self,
didValidateRequest: self.request,
response: response,
fileURL: self.fileURL,
withResult: result)
}
$validators.write { $0.append(validator) }
return self
}
}
// MARK: - UploadRequest
/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
public class UploadRequest: DataRequest {
/// Type describing the origin of the upload, whether `Data`, file, or stream.
public enum Uploadable {
/// Upload from the provided `Data` value.
case data(Data)
/// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
/// automatically removed once uploaded.
case file(URL, shouldRemove: Bool)
/// Upload from the provided `InputStream`.
case stream(InputStream)
}
// MARK: Initial State
/// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
public let upload: UploadableConvertible
/// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
/// to disk.
public let fileManager: FileManager
// MARK: Mutable State
/// `Uploadable` value used by the instance.
public var uploadable: Uploadable?
/// Creates an `UploadRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
init(id: UUID = UUID(),
convertible: UploadConvertible,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
fileManager: FileManager,
delegate: RequestDelegate) {
upload = convertible
self.fileManager = fileManager
super.init(id: id,
convertible: convertible,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
/// Called when the `Uploadable` value has been created from the `UploadConvertible`.
///
/// - Parameter uploadable: The `Uploadable` that was created.
func didCreateUploadable(_ uploadable: Uploadable) {
self.uploadable = uploadable
eventMonitor?.request(self, didCreateUploadable: uploadable)
}
/// Called when the `Uploadable` value could not be created.
///
/// - Parameter error: `AFError` produced by the failure.
func didFailToCreateUploadable(with error: AFError) {
self.error = error
eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
retryOrFinish(error: error)
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
guard let uploadable = uploadable else {
fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
}
switch uploadable {
case let .data(data): return session.uploadTask(with: request, from: data)
case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
case .stream: return session.uploadTask(withStreamedRequest: request)
}
}
override func reset() {
// Uploadable must be recreated on every retry.
uploadable = nil
super.reset()
}
/// Produces the `InputStream` from `uploadable`, if it can.
///
/// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
///
/// - Returns: The `InputStream`.
func inputStream() -> InputStream {
guard let uploadable = uploadable else {
fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
}
guard case let .stream(stream) = uploadable else {
fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
}
eventMonitor?.request(self, didProvideInputStream: stream)
return stream
}
override public func cleanup() {
defer { super.cleanup() }
guard
let uploadable = self.uploadable,
case let .file(url, shouldRemove) = uploadable,
shouldRemove
else { return }
try? fileManager.removeItem(at: url)
}
}
/// A type that can produce an `UploadRequest.Uploadable` value.
public protocol UploadableConvertible {
/// Produces an `UploadRequest.Uploadable` value from the instance.
///
/// - Returns: The `UploadRequest.Uploadable`.
/// - Throws: Any `Error` produced during creation.
func createUploadable() throws -> UploadRequest.Uploadable
}
extension UploadRequest.Uploadable: UploadableConvertible {
public func createUploadable() throws -> UploadRequest.Uploadable {
self
}
}
/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}
| mit | fd134c8a3722f360491fbb36c1778506 | 40.520425 | 177 | 0.637546 | 5.310407 | false | false | false | false |
legendecas/Rocket.Chat.iOS | Rocket.Chat.Shared/Managers/PushManager.swift | 1 | 2645 | //
// PushManager.swift
// Rocket.Chat
//
// Created by Gradler Kim on 2017. 1. 23..
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
/// A manager that manages all push notifications related actions
public class PushManager: SocketManagerInjected, AuthManagerInjected {
let kDeviceTokenKey = "deviceToken"
let kPushIdentifierKey = "pushIdentifier"
func updatePushToken() {
guard let deviceToken = getDeviceToken() else { return }
updatePushToken(with: deviceToken, pushId: getOrCreatePushId())
}
/// Update server's memories of current user's device token
///
/// - Parameters:
/// - deviceToken: new device token
/// - pushId: push id
public func updatePushToken(with deviceToken: String, pushId: String) {
guard let userIdentifier = authManager.isAuthenticated()?.userId else { return }
let request = [
"msg": "method",
"method": "raix:push-update",
"params": [[
"id": pushId,
"userId": userIdentifier,
"token": ["apn": deviceToken],
"appName": Bundle.main.bundleIdentifier ?? "main",
"metadata": [:]
]]
] as [String : Any]
socketManager.send(request)
}
/// Update server's memories of current user's push id
public func updateUser() {
guard let userIdentifier = authManager.isAuthenticated()?.userId else { return }
updateUser(userIdentifier, pushId: getOrCreatePushId())
}
/// Update server's memories of given user's push id with given push id
///
/// - Parameters:
/// - userIdentifier: user's id
/// - pushId: push id
public func updateUser(_ userIdentifier: String, pushId: String) {
let request = [
"msg": "method",
"method": "raix:push-setuser",
"userId": userIdentifier,
"params": [pushId]
] as [String : Any]
socketManager.send(request)
}
fileprivate func getOrCreatePushId() -> String {
guard let pushId = UserDefaults.standard.string(forKey: kPushIdentifierKey) else {
let randomId = UUID().uuidString.replacingOccurrences(of: "-", with: "")
UserDefaults.standard.set(randomId, forKey: kPushIdentifierKey)
return randomId
}
return pushId
}
fileprivate func getDeviceToken() -> String? {
guard let deviceToken = UserDefaults.standard.string(forKey: kDeviceTokenKey) else {
return nil
}
return deviceToken
}
}
| mit | 471f2ed02960d49d27db17393a8c63a3 | 30.105882 | 92 | 0.600605 | 4.704626 | false | false | false | false |
jovito-royeca/ManaKit | Example/ManaKit/Maintainer/Maintainer+RulingsPostgres.swift | 1 | 1149 | //
// Maintainer+RulingsPostgres.swift
// ManaKit_Example
//
// Created by Vito Royeca on 11/5/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import ManaKit
import PostgresClientKit
import PromiseKit
extension Maintainer {
func createRulingPromise(dict: [String: Any], connection: Connection) -> Promise<Void> {
let oracleId = dict["oracle_id"] as? String ?? "NULL"
let text = dict["comment"] as? String ?? "NULL"
let datePublished = dict["published_at"] as? String ?? "NULL"
let query = "SELECT createOrUpdateRuling($1,$2,$3)"
let parameters = [oracleId,
text,
datePublished]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createDeleteRulingsPromise(connection: Connection) -> Promise<Void> {
let query = "DELETE FROM cmruling"
return createPromise(with: query,
parameters: nil,
connection: connection)
}
}
| mit | b62342ce03cba45a2f5cbcd6c2dada45 | 31.8 | 92 | 0.576655 | 4.415385 | false | false | false | false |
orta/gradient | Gradients/Classes/ORKeyWindow.swift | 1 | 3357 | import Cocoa
class ORKeyWindow: NSWindow {
@IBOutlet weak var desktopGradientWindow: NSWindow!
@IBOutlet weak var gradientController: GradientController!
@IBOutlet weak var gradientScroll: NSScrollView!
override func keyDown(theEvent: NSEvent) {
println(theEvent.keyCode);
let enter = 36
let space = 49
let up = 126
let down = 125
let left = 123
let right = 124
let r = 15
let keycode = Int(theEvent.keyCode)
if (keycode == space){
if (self.alphaValue == 1) {
self.animator().alphaValue = 0.1
NSWorkspace.sharedWorkspace().hideOtherApplications();
if let screen = desktopGradientWindow.screen {
let level:Int = Int(CGWindowLevelForKey(CGWindowLevel(kCGDesktopIconWindowLevelKey)));
desktopGradientWindow.level = level - 1;
desktopGradientWindow.setFrame(screen.frame, display: true, animate: false);
desktopGradientWindow.animator().alphaValue = 1
desktopGradientWindow.makeKeyAndOrderFront(self)
gradientController.switchViews()
}
}
return;
}
if (keycode == enter){
let gradient = gradientController.view
let rep = gradient.bitmapImageRepForCachingDisplayInRect(gradient.bounds);
gradient.cacheDisplayInRect(gradient.bounds, toBitmapImageRep: rep!);
let data = rep?.representationUsingType( .NSJPEGFileType, properties: ["":""])
let path = "/tmp/wallpaper.jpg"
data?.writeToFile(path, atomically: true)
let localURL = NSURL.fileURLWithPath(path)
NSWorkspace.sharedWorkspace().setDesktopImageURL(localURL!, forScreen: NSScreen.mainScreen()!, options: ["":""], error: nil);
return;
}
if (keycode == r){
gradientController.createNewGradient()
return;
}
if (keycode == up || keycode == right || keycode == left || keycode == down ){
let d = 50
let t = (keycode == up) ? d : 0
let l = (keycode == left) ? d : 0
let r = (keycode == right) ? d : 0
let b = (keycode == down) ? d : 0
scrollBy( NSEdgeInsets(top: CGFloat(t), left: CGFloat(l), bottom: CGFloat(b), right: CGFloat(r)));
return
}
super.keyDown(theEvent);
}
override func keyUp(theEvent: NSEvent) {
let enter = 36
let space = 49
if(Int(theEvent.keyCode) == space){
desktopGradientWindow.animator().alphaValue = 0;
animator().alphaValue = 1;
gradientController.switchViews()
}
super.keyUp(theEvent);
}
func scrollBy(insets:NSEdgeInsets) {
NSAnimationContext.beginGrouping()
NSAnimationContext.currentContext().duration = 0.15
let clipView = self.gradientScroll.contentView
var newOrigin = clipView.bounds.origin
newOrigin.y += insets.top
newOrigin.y -= insets.bottom;
newOrigin.x += insets.right;
newOrigin.x -= insets.left;
clipView.animator().setBoundsOrigin(newOrigin)
NSAnimationContext.endGrouping()
}
}
| mit | 4b1cc6591576a514a0d03ff93ee77c6c | 31.592233 | 137 | 0.578493 | 4.907895 | false | false | false | false |
361425281/swift-snia | Swift-Sina/Classs/Main/Controller/DQBaseTableViewController.swift | 1 | 2588 |
//
// DQBaseTableViewController.swift
// Swift - sina
//
// Created by 熊德庆 on 15/10/26.
// Copyright © 2015年 熊德庆. All rights reserved.
//
import UIKit
class DQBaseTableViewController: UITableViewController
{
let userLogin = false
override func loadView()
{
userLogin ? super.loadView():setupVistorView()
}
func setupVistorView()
{
let vistorView = DQVistorView()
view = vistorView
//设置代理
vistorView.vistorViewDelegate = self
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "vistorViewRegistClick")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style:UIBarButtonItemStyle.Plain, target: self, action: "vistorViewLoginClick")
if self is DQHomeTabBarController
{
vistorView.startRotationAnimation()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil)
}
else if self is DQMessageTableViewController
{
vistorView.setupVistorView("visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
else if self is DQDiscoverTabBarController
{
vistorView.setupVistorView("visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
else if self is DQMeTableViewController
{
vistorView.setupVistorView("visitordiscover_image_profile", message: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
}
}
func didEnterBackgroud()
{
(view as? DQVistorView)?.pauseAnimation()
}
func didBecomeActive()
{
(view as? DQVistorView)?.resumeAnimation()
}
}
extension DQBaseTableViewController : DQVistorViewDelegate
{
func vistorViewRegistClick()
{
print(__FUNCTION__)
}
func vistorViewLoginClick()
{
let controller = DQOauthViewController()
presentViewController(UINavigationController(rootViewController: controller), animated: false, completion: nil)
}
}
| apache-2.0 | fe320dbf93125fcc688b05426869f801 | 35.136364 | 162 | 0.672956 | 5.162338 | false | false | false | false |
ujell/IceAndFireLoader | IceAndFireLoader/IceAndFire.swift | 1 | 14755 | //
// IceAndFire.swift
// AnApiOfIceAndFireSwiftWrapper
//
// Created by Yücel Uzun on 13/02/16.
// Copyright © 2016 Yücel Uzun. All rights reserved.
//
import Foundation
private class IceAndFireParser {
class func isDictionaryValid (dictionary: [String: AnyObject], type: IceAndFire.Resource) -> Bool{
if dictionary.count == 0 || dictionary["url"] == nil { return false }
if (type == IceAndFire.Resource.Book) {
return dictionary ["name"] != nil &&
dictionary ["isbn"] != nil &&
dictionary ["authors"] != nil &&
dictionary ["numberOfPages"] != nil &&
dictionary ["publisher"] != nil &&
dictionary ["country"] != nil &&
dictionary ["mediaType"] != nil &&
dictionary ["released"] != nil &&
dictionary ["characters"] != nil &&
dictionary ["povCharacters"] != nil
}
return true
}
class func stringFromDictionary (dictionary: [String: AnyObject], key: String) -> String? {
if let string = dictionary[key] as? String where string != "" {
return string
}
return nil
}
class func urlFromDictionary (dictionary: [String: AnyObject], key: String) -> NSURL? {
if let string = dictionary[key] as? String where string != "" {
return NSURL(string: string)
}
return nil
}
class func intFromDictionary (dictionary: [String: AnyObject], key: String) -> Int? {
if let number = dictionary[key] as? Int {
return number
}
return nil
}
class func dateFromDictionary (dictionary: [String: AnyObject], key: String) -> NSDate? {
if let dateString = dictionary[key] as? String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return formatter.dateFromString(dateString)
}
return nil
}
class func stringArrayFromDictionary (dictionary: [String: AnyObject], key: String) -> [String]? {
if let array = dictionary[key] as? [String] where array.count > 0 {
return array
}
return nil
}
class func urlArrayFromDictionary (dictionary: [String: AnyObject], key: String) -> [NSURL]? {
if let array = dictionary[key] as? [String] where array.count > 0 {
return array.map() { return NSURL(string: $0)! }
}
return nil
}
}
public protocol IceAndFireObject {
static var type : IceAndFire.Resource {get}
init? (dictionary: [String:AnyObject])
}
/**
Represents character resource.
For field details please check [api documentation](https://anapioficeandfire.com/Documentation#characters)
*/
public struct IceAndFireCharacter: IceAndFireObject {
public static let type = IceAndFire.Resource.Character
public let url: NSURL
public let name: String?
public let culture: String?
public let born: String?
public let died: String?
public let titles: [String]?
public let aliases: [String]?
public let father: NSURL?
public let mother: NSURL?
public let spouse: NSURL?
public let allegiances: [String]?
public let books: [NSURL]?
public let povBooks: [NSURL]?
public let tvSeries: [String]?
public let playedBy: [String]?
public init? (dictionary: [String: AnyObject]) {
guard IceAndFireParser.isDictionaryValid(dictionary, type: .Character) else {
url = NSURL()
name = nil
culture = nil
born = nil
died = nil
titles = nil
aliases = nil
father = nil
mother = nil
spouse = nil
allegiances = nil
books = nil
povBooks = nil
tvSeries = nil
playedBy = nil
return nil
}
url = IceAndFireParser.urlFromDictionary(dictionary, key: "url")!
name = IceAndFireParser.stringFromDictionary (dictionary, key: "name")
culture = IceAndFireParser.stringFromDictionary (dictionary, key: "culture")
born = IceAndFireParser.stringFromDictionary (dictionary, key: "born")
died = IceAndFireParser.stringFromDictionary (dictionary, key: "died")
titles = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "titles")
aliases = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "aliases")
father = IceAndFireParser.urlFromDictionary(dictionary, key: "father")
mother = IceAndFireParser.urlFromDictionary(dictionary, key: "mother")
spouse = IceAndFireParser.urlFromDictionary(dictionary, key: "spouse")
allegiances = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "allegiances")
books = IceAndFireParser.urlArrayFromDictionary(dictionary, key: "books")
povBooks = IceAndFireParser.urlArrayFromDictionary(dictionary, key: "povBooks")
tvSeries = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "tvSeries")
playedBy = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "playedBy")
}
}
/**
Represents book resource.
For field details please check [api documentation](https://anapioficeandfire.com/Documentation#books)
*/
public struct IceAndFireBook: IceAndFireObject {
public static let type = IceAndFire.Resource.Book
public let url: NSURL
public let name: String
public let isbn: String
public let authors : [String]
public let numberOfPages: Int
public let publisher: String
public let country: String
public let mediaType: String
public let released: NSDate
public let characters: [NSURL]
public let povCharacters: [NSURL]
public init? (dictionary: [String: AnyObject]) {
guard IceAndFireParser.isDictionaryValid(dictionary, type: .Book) else {
url = NSURL()
name = ""
isbn = ""
authors = [String]()
numberOfPages = 0
publisher = ""
country = ""
mediaType = ""
released = NSDate()
characters = [NSURL]()
povCharacters = [NSURL]()
return nil
}
url = IceAndFireParser.urlFromDictionary(dictionary, key: "url")!
name = IceAndFireParser.stringFromDictionary (dictionary, key: "name")!
isbn = IceAndFireParser.stringFromDictionary (dictionary, key: "isbn")!
authors = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "authors")!
numberOfPages = IceAndFireParser.intFromDictionary(dictionary, key: "numberOfPages")!
publisher = IceAndFireParser.stringFromDictionary (dictionary, key: "publisher")!
country = IceAndFireParser.stringFromDictionary (dictionary, key: "country")!
mediaType = IceAndFireParser.stringFromDictionary (dictionary, key: "mediaType")!
released = IceAndFireParser.dateFromDictionary(dictionary, key: "released")!
characters = IceAndFireParser.urlArrayFromDictionary(dictionary, key: "characters")!
povCharacters = IceAndFireParser.urlArrayFromDictionary(dictionary, key: "povCharacters")!
}
}
/**
Represents house resource.
For field details please check [api documentation](https://anapioficeandfire.com/Documentation#houses)
*/
public struct IceAndFireHouse: IceAndFireObject {
public static let type = IceAndFire.Resource.House
public let url: NSURL
public let name: String?
public let region: String?
public let coatOfArms: String?
public let words: String?
public let titles: [String]?
public let seats: [String]?
public let currentLord: NSURL?
public let heir: NSURL?
public let overlord: NSURL?
public let founded: String?
public let founder: NSURL?
public let diedOut: String?
public let ancestralWeapons: [String]?
public let cadetBranches: [String]?
public let swornMembers: [String]?
public init? (dictionary: [String: AnyObject]) {
guard IceAndFireParser.isDictionaryValid(dictionary, type: .House) else {
url = NSURL()
name = nil
region = nil
coatOfArms = nil
words = nil
titles = nil
seats = nil
currentLord = nil
heir = nil
overlord = nil
founded = nil
founder = nil
diedOut = nil
ancestralWeapons = nil
cadetBranches = nil
swornMembers = nil
return nil
}
url = IceAndFireParser.urlFromDictionary(dictionary, key: "url")!
name = IceAndFireParser.stringFromDictionary (dictionary, key: "name")
region = IceAndFireParser.stringFromDictionary (dictionary, key: "region")
coatOfArms = IceAndFireParser.stringFromDictionary (dictionary, key: "coatOfArms")
words = IceAndFireParser.stringFromDictionary (dictionary, key: "words")
titles = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "titles")
seats = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "seats")
currentLord = IceAndFireParser.urlFromDictionary(dictionary, key: "currentLord")
heir = IceAndFireParser.urlFromDictionary(dictionary, key: "heir")
overlord = IceAndFireParser.urlFromDictionary(dictionary, key: "overlord")
founded = IceAndFireParser.stringFromDictionary (dictionary, key: "founded")
founder = IceAndFireParser.urlFromDictionary(dictionary, key: "founder")
diedOut = IceAndFireParser.stringFromDictionary (dictionary, key: "diedOut")
ancestralWeapons = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "ancestralWeapons")
cadetBranches = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "cadetBranches")
swornMembers = IceAndFireParser.stringArrayFromDictionary(dictionary, key: "swornMembers")
}
}
public class IceAndFire {
static private let apiUrl = "https://anapioficeandfire.com/api/"
public enum Resource: String {
case Book = "books", Character = "characters", House = "houses"
}
public enum Error: ErrorType {
case ParseError(String), LoadError(String)
}
/**
Loads the resource with given ID and calls completion handler.
Uses type of first variable in completition handler to decide what to load.
```swift
IceAndFire.load (2) { (character: IceAndFireCharacter?, error: IceAndFire.Error?) in
if character != nil {
print (character!.name)
} else if error != nil {
print (error!)
}
}
*/
public class func load <T:IceAndFireObject> (id: Int, completionHandler: (T?, Error?) -> ()) {
let url = NSURL(string: apiUrl + T.type.rawValue + "/\(id)")!
load(url) { result, error in
guard error == nil else {
completionHandler(nil, error)
return
}
if let dictionary = result as? [String: AnyObject], let object = T(dictionary: dictionary) {
completionHandler (object, nil)
} else {
completionHandler (nil, .ParseError("An error happened while parsing the API data"))
}
}
}
/**
Loads the bulk of resource for given page with given size nad calls completition handler.
Uses type of first variable in completition handler to decide what to load.
Right now only way to understand if it's last page is checking if there's result.
```swift
IceAndFire.load(5, pageSize: 10) { (characters:[IceAndFireCharacter]?, error) in
guard error == nil else {
print (error!)
return
}
if characters != nil {
for character in characters! where character.name != nil {
print (character.name)
}
}
}
*/
public class func load <T:IceAndFireObject> (page: Int, pageSize: Int, completionHandler: ([T]?, Error?) -> ()) {
var pageSize = pageSize
if pageSize > 50 {
print ("Page size can be maximum 50, 50 is used.")
pageSize = 50
}
let url = NSURL(string: apiUrl + T.type.rawValue + "?page=\(page)&pageSize=\(pageSize)")!
load (url) { result, error in
guard error == nil else {
completionHandler(nil, error)
return
}
if let rawArray = result as? [[String:AnyObject]] {
var array = [T]()
for dictionary in rawArray {
if let object = T (dictionary: dictionary) {
array.append(object)
} else {
completionHandler (nil, .ParseError("An error happened while parsing the API data"))
}
}
completionHandler (array, nil)
}
}
}
private class func load (url: NSURL, completionHandler: (AnyObject?, Error?) -> ()) {
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(url) {data, response, error in
guard error == nil else {
completionHandler(nil, .LoadError(error!.description))
return
}
if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode != 200 {
let code = "\(httpResponse.statusCode)"
let message = NSHTTPURLResponse.localizedStringForStatusCode(httpResponse.statusCode)
completionHandler(nil, .LoadError(code + " " + message))
return
}
guard data != nil else {
completionHandler (nil, .LoadError ("API didn't return any data"))
return
}
do {
if let jsonDic = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? [String: AnyObject] {
completionHandler (jsonDic, nil)
} else if let jsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? [[String: AnyObject]] {
completionHandler (jsonArray, nil)
} else {
completionHandler (nil, .ParseError("Returned JSON from API was not valid"))
}
} catch {
completionHandler (nil, .ParseError("Returned JSON from API was not valid"))
}
}.resume()
}
}
| mit | dee011b40d305ecd7837b3274bf3fd55 | 39.416438 | 149 | 0.611104 | 4.674271 | false | false | false | false |
renyufei8023/WeiBo | Pods/BSImagePicker/Pod/Classes/Controller/PreviewViewController.swift | 2 | 2954 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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
final class PreviewViewController : UIViewController {
var imageView: UIImageView?
private var fullscreen = false
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
view.backgroundColor = UIColor.whiteColor()
imageView = UIImageView(frame: view.bounds)
imageView?.contentMode = .ScaleAspectFit
imageView?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
view.addSubview(imageView!)
let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.numberOfTapsRequired = 1
tapRecognizer.addTarget(self, action: "toggleFullscreen")
view.addGestureRecognizer(tapRecognizer)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func loadView() {
super.loadView()
}
func toggleFullscreen() {
fullscreen = !fullscreen
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.toggleNavigationBar()
self.toggleStatusBar()
self.toggleBackgroundColor()
})
}
func toggleNavigationBar() {
navigationController?.setNavigationBarHidden(fullscreen, animated: true)
}
func toggleStatusBar() {
self.setNeedsStatusBarAppearanceUpdate()
}
func toggleBackgroundColor() {
let aColor: UIColor
if self.fullscreen {
aColor = UIColor.blackColor()
} else {
aColor = UIColor.whiteColor()
}
self.view.backgroundColor = aColor
}
override func prefersStatusBarHidden() -> Bool {
return fullscreen
}
}
| mit | e73234a367de786ef94809240b78fa17 | 33.741176 | 84 | 0.676261 | 5.320721 | false | false | false | false |
carloscorreia94/AEISTMobileIOS | AEISTMobile/AppDelegate.swift | 1 | 2804 | //
// AppDelegate.swift
// AEISTMobile
//
// Created by Carlos Correia
// Copyright (c) 2015 Carlos Correia. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
var tabBarController = window?.rootViewController as! UITabBarController
var storyboard = UIStoryboard(name: "Main", bundle: nil)
var vc = storyboard.instantiateViewControllerWithIdentifier("NavController") as! UINavigationController
let firstImage = UIImage(named: "bbq_tab")
let secondImage = UIImage(named: "aeist_tab")
vc.tabBarItem = UITabBarItem(title: "BBQs", image: firstImage, tag: 1)
tabBarController.viewControllers?.append(vc)
var vcAE = storyboard.instantiateViewControllerWithIdentifier("NavController") as! UINavigationController
vcAE.tabBarItem = UITabBarItem(title: "A AEIST", image: secondImage, tag: 2)
tabBarController.viewControllers?.append(vcAE)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| gpl-2.0 | 11c9396299c602090c139651d71d61c0 | 43.507937 | 279 | 0.770328 | 5.007143 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/TooltipsAndHitTest/UsingTooltipModifierChartView.swift | 1 | 3805 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// UsingTooltipModifierChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
class UsingTooltipModifierChartView: SingleChartLayout {
override func initExample() {
let xAxis = SCINumericAxis()
xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
let yAxis = SCINumericAxis()
yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
let dataSeries1 = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries1.seriesName = "Lissajous Curve"
dataSeries1.acceptUnsortedData = true
let dataSeries2 = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries2.seriesName = "Sinewave"
let doubleSeries1 = DataManager.getLissajousCurve(withAlpha: 0.8, beta: 0.2, delta: 0.43, count: 500)
let doubleSeries2 = DataManager.getSinewaveWithAmplitude(1.5, phase: 1.0, pointCount: 500)
DataManager.scaleValues(doubleSeries1!.getXArray())
dataSeries1.appendRangeX(doubleSeries1!.xValues, y: doubleSeries1!.yValues, count: doubleSeries1!.size)
dataSeries2.appendRangeX(doubleSeries2!.xValues, y: doubleSeries2!.yValues, count: doubleSeries2!.size)
let pointMarker1 = SCIEllipsePointMarker()
pointMarker1.strokeStyle = nil
pointMarker1.fillStyle = SCISolidBrushStyle(color: UIColor(red: 70.0 / 255.0, green: 130.0 / 255.0, blue: 180.0 / 255.0, alpha: 1.0))
pointMarker1.height = 5
pointMarker1.width = 5
let line1 = SCIFastLineRenderableSeries()
line1.dataSeries = dataSeries1
line1.strokeStyle = SCISolidPenStyle(color: UIColor(red: 70.0 / 255.0, green: 130.0 / 255.0, blue: 180.0 / 255.0, alpha: 1.0), withThickness: 0.5)
line1.pointMarker = pointMarker1
let pointMarker2 = SCIEllipsePointMarker()
pointMarker2.strokeStyle = nil
pointMarker2.fillStyle = SCISolidBrushStyle(color: UIColor(red: 255.0 / 255.0, green: 51.0 / 255.0, blue: 51.0 / 255.0, alpha: 1.0))
pointMarker2.height = 5
pointMarker2.width = 5
let line2 = SCIFastLineRenderableSeries()
line2.dataSeries = dataSeries2
line2.strokeStyle = SCISolidPenStyle(color: UIColor(red: 255.0 / 255.0, green: 51.0 / 255.0, blue: 51.0 / 255.0, alpha: 1.0), withThickness: 0.5)
line2.pointMarker = pointMarker2
let toolTipModifier = SCITooltipModifier()
toolTipModifier.style.colorMode = .seriesColorToDataView
SCIUpdateSuspender.usingWithSuspendable(surface) {
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(yAxis)
self.surface.renderableSeries.add(line1)
self.surface.renderableSeries.add(line2)
self.surface.chartModifiers.add(toolTipModifier)
line1.addAnimation(SCIFadeRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut))
line1.addAnimation(SCIFadeRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut))
}
}
}
| mit | 7e30d6f371d8153e91bdc7a7b8883f99 | 49.693333 | 154 | 0.649658 | 4.141612 | false | false | false | false |
mirego/taylor-ios | Taylor/Geometry/CGSize.swift | 1 | 3447 | // Copyright (c) 2016, Mirego
// 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 the Mirego 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 Foundation
func + (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width + right.width, height: left.height + right.height)
}
func += (left: inout CGSize, right: CGSize) {
left = left + right
}
public extension CGSize
{
@available(*, deprecated, message: "This function was not performing an inset operation but had the effect of adding values to its components, you should use the + operator on two CGSize as a direct replacement. To perform a real inset operation, use insetBy provided by CoreGraphics.")
func inset(_ xOffset: CGFloat, yOffset: CGFloat) -> CGSize {
return CGSize(width: self.width + xOffset, height: self.height + yOffset)
}
@available(*, deprecated, message: "Use scaleBy instead of this function, its naming is more in line with naming conventions.")
func scale(_ xOffset: CGFloat, yOffset: CGFloat) -> CGSize {
return CGSize(width: self.width * xOffset, height: self.height * yOffset)
}
func scaleBy(sx: CGFloat, sy: CGFloat) -> CGSize {
return CGSize(width: self.width * sx, height: self.height * sy)
}
mutating func round() {
width = Darwin.round(width)
height = Darwin.round(height)
}
func rounded() -> CGSize {
return CGSize(width: Darwin.round(width), height: Darwin.round(height))
}
mutating func floor() {
width = Darwin.floor(width)
height = Darwin.floor(height)
}
func floored() -> CGSize {
return CGSize(width: Darwin.floor(width), height: Darwin.floor(height))
}
mutating func ceil() {
width = Darwin.ceil(width)
height = Darwin.ceil(height)
}
func ceiled() -> CGSize {
return CGSize(width: Darwin.ceil(width), height: Darwin.ceil(height))
}
static func minimalTapableSize() -> CGSize {
return CGSize(width: 44, height: 44)
}
}
| bsd-3-clause | 8fb35df11badf2a9eadb15928f337616 | 40.035714 | 290 | 0.705541 | 4.413572 | false | false | false | false |
stripe/stripe-ios | StripeApplePay/StripeApplePay/Source/Extensions/BillingDetails+ApplePay.swift | 1 | 3931 | //
// BillingDetails+ApplePay.swift
// StripeApplePay
//
// Created by David Estes on 8/9/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
import PassKit
@_spi(STP) import StripeCore
extension StripeContact {
/// Initializes a new Contact with data from an PassKit contact.
/// - Parameter contact: The PassKit contact you want to populate the Contact from.
/// - Returns: A new Contact with data copied from the passed in contact.
init(
pkContact contact: PKContact
) {
let nameComponents = contact.name
if let nameComponents = nameComponents {
givenName = stringIfHasContentsElseNil(nameComponents.givenName)
familyName = stringIfHasContentsElseNil(nameComponents.familyName)
name = stringIfHasContentsElseNil(
PersonNameComponentsFormatter.localizedString(from: nameComponents, style: .default)
)
}
email = stringIfHasContentsElseNil(contact.emailAddress)
if let phoneNumber = contact.phoneNumber {
phone = sanitizedPhoneString(from: phoneNumber)
} else {
phone = nil
}
setAddressFromCNPostal(contact.postalAddress)
}
private func sanitizedPhoneString(from phoneNumber: CNPhoneNumber) -> String? {
return stringIfHasContentsElseNil(
STPNumericStringValidator.sanitizedNumericString(for: phoneNumber.stringValue)
)
}
private mutating func setAddressFromCNPostal(_ address: CNPostalAddress?) {
line1 = stringIfHasContentsElseNil(address?.street)
city = stringIfHasContentsElseNil(address?.city)
state = stringIfHasContentsElseNil(address?.state)
postalCode = stringIfHasContentsElseNil(address?.postalCode)
country = stringIfHasContentsElseNil(address?.isoCountryCode.uppercased())
}
}
extension StripeAPI.BillingDetails {
init?(
from payment: PKPayment
) {
var billingDetails: StripeAPI.BillingDetails?
if payment.billingContact != nil {
billingDetails = StripeAPI.BillingDetails()
if let billingContact = payment.billingContact {
let billingAddress = StripeContact(pkContact: billingContact)
billingDetails?.name = billingAddress.name
billingDetails?.email = billingAddress.email
billingDetails?.phone = billingAddress.phone
if billingContact.postalAddress != nil {
billingDetails?.address = StripeAPI.BillingDetails.Address(
contact: billingAddress
)
}
}
}
// The phone number and email in the "Contact" panel in the Apple Pay dialog go into the shippingContact,
// not the billingContact. To work around this, we should fill the billingDetails' email and phone
// number from the shippingDetails.
if payment.shippingContact != nil {
var shippingAddress: StripeContact?
if let shippingContact = payment.shippingContact {
shippingAddress = StripeContact(pkContact: shippingContact)
}
if billingDetails?.email == nil && shippingAddress?.email != nil {
if billingDetails == nil {
billingDetails = StripeAPI.BillingDetails()
}
billingDetails?.email = shippingAddress?.email
}
if billingDetails?.phone == nil && shippingAddress?.phone != nil {
if billingDetails == nil {
billingDetails = StripeAPI.BillingDetails()
}
billingDetails?.phone = shippingAddress?.phone
}
}
if let billingDetails = billingDetails {
self = billingDetails
} else {
return nil
}
}
}
| mit | 1308dc892cbe89e4b67b6d0a794f8f24 | 37.910891 | 113 | 0.628244 | 5.504202 | false | false | false | false |
hovansuit/FoodAndFitness | FoodAndFitness/Controllers/Base/Controller/BaseViewController.swift | 1 | 1797 | //
// AppDelegate.swift
// BaseViewController
//
// Created by Mylo Ho on 2/15/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import UIKit
import SwiftUtils
class BaseViewController: ViewController {
var isVisible = false
var isNavigationBarHidden: Bool {
return false
}
override required init(nibName: String?, bundle: Bundle?) {
super.init(nibName: nibName, bundle: bundle)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func setup() {
super.setup()
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = isNavigationBarHidden
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.tintColor = Color.green64
navigationItem.backBarButtonItem = UIBarButtonItem(title: Strings.empty, style: .plain, target: self, action: #selector(back))
setupData()
setupUI()
}
func setupData() {
}
func setupUI() {
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isNavigationBarHidden = isNavigationBarHidden
isVisible = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isVisible = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
loadData()
}
func loadData() {
guard isViewFirstAppear else { return }
}
}
// MARK: - Action
extension BaseViewController {
@IBAction dynamic func back(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
}
| mit | 2cce3547dd5b4c76def8d94a436e3f8a | 23.27027 | 134 | 0.656459 | 5.102273 | false | false | false | false |
trujillo138/MyExpenses | MyExpenses/MyExpenses/Common/UI/LabelGradientBackgroundView.swift | 1 | 1231 | //
// LabelGradientBackgroundView.swift
// MyExpenses
//
// Created by Tomas Trujillo on 11/28/17.
// Copyright © 2017 TOMApps. All rights reserved.
//
import UIKit
class LabelGradientBackgroundView: UIView {
override func draw(_ rect: CGRect) {
let colors = [UIColor.clear.cgColor, UIColor.clear.cgColor, UIColor.black.withAlphaComponent(0.35).cgColor] as CFArray
let colorSpace = CGColorSpaceCreateDeviceRGB()
let start: CGFloat = 0.0
let middle: CGFloat = 0.2
let end: CGFloat = 1.0
let colorLocations = [start, middle, end]
guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: colorLocations) else { return }
UIGraphicsGetCurrentContext()?.drawLinearGradient(gradient, start: CGPoint.zero,
end: CGPoint(x: 0.0, y: self.bounds.height), options: .drawsBeforeStartLocation)
}
private func setup() {
backgroundColor = UIColor.clear
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
}
| apache-2.0 | 2eceff506f3341314fc9a3a5d3f91976 | 30.538462 | 138 | 0.627642 | 4.505495 | false | false | false | false |
JeffMv/JMMColorSelector-Swift | JMMColorSelector/JMMColorSelector/JMMColorSelectorView.swift | 1 | 19989 | //
// JMMColorSelectorView.swift
// JMMColorSelector
//
// Created by [email protected] on 26.10.15.
// Copyright (c) 2015 Jeffrey Mvutu Mabilama. All rights reserved.
//
import Foundation
import UIKit
// MARK: - Color selection delegation protocol
/**
* Protocol to adopt in order to receive a otification when the user is done chosing a color.
*/
public protocol JMMColorSelectorViewDelegate : NSObjectProtocol {
func colorSelectorView(colorSelectorView: JMMColorSelectorView, userChoseColor color: UIColor);
func colorSelectorView(colorSelectorView: JMMColorSelectorView, userDidDiscardColor lastColor: UIColor);
}
// MARK: Color selector view
/**
* The view that ...
*/
public class JMMColorSelectorView : UIView {
// MARK: - Initialisation
private func customInit() {
self.hueSlider?.minimumValue = 0.0;
self.saturationSlider?.minimumValue = 0.0;
self.brightnessSlider?.minimumValue = 0.0;
self.hueSlider?.maximumValue = 1.0;
self.saturationSlider?.maximumValue = 1.0;
self.brightnessSlider?.maximumValue = 1.0;
if let previewView = self.colorPreviewView {
let height: CGFloat = previewView.frame.size.height ; // frame is Zero
previewView.layer.cornerRadius = height/2.0; // no effect
}
self.configureGradientViews();
// [self updateUIForCurrentColor];
}
public override func layoutSubviews() {
super.layoutSubviews();
self.customInit()
// redraw layers (gradients)
// if layoutSubviewsCount > 2 { // magic number, because it seems to be alreight when
// self.colorCompositionChanged()
// }
// ++layoutSubviewsCount
}
// private var layoutSubviewsCount: Int = 0
override init(frame: CGRect) {
super.init(frame: frame)
self.customInit()
}
// required public init?(coder aDecoder: NSCoder) {
required public init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
}
public override func awakeFromNib() {
super.awakeFromNib()
self.customInit();
}
// MARK: Setups
public var colorMode: JMMColorSelectorColorMode = .HSB
private func setupCollectionView() -> Void {
// Setup item size
// UICollectionViewFlowLayout * flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
// CGFloat itemWidth = self.collectionView.bounds.size.width / 2.0 - 10;
// CGFloat itemWidth = 50;
// flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
// flowLayout.minimumInteritemSpacing = 5;
// flowLayout.lineSpacing = 10;
// flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5 , 5);
// flowLayout.sectionInset = UIEdgeInsetsMake(5,8,0,0);
}
private func configureGradientViews() -> Void {
self.hueGradientView?.layer.cornerRadius = (self.hueGradientView?.frame.size.height)! / 2.0;
self.saturationGradientView?.layer.cornerRadius = (self.saturationGradientView?.frame.size.height)! / 2.0;
self.brightnessGradientView?.layer.cornerRadius = (self.brightnessGradientView?.frame.size.height)! / 2.0;
// let bgColor = [[UIColor blueColor] colorWithAlphaComponent:0.2];
let bgColor = UIColor.clear;
self.hueGradientView?.backgroundColor = bgColor;
self.saturationGradientView?.backgroundColor = bgColor;
self.brightnessGradientView?.backgroundColor = bgColor;
}
// MARK: - Public API -
// MARK: Color selection validation - delegate
public var delegate: JMMColorSelectorViewDelegate?
// MARK: Sample colors external management
// public var selectionDelegate: ColorSelectorViewDelegate?
public var colorCollectionDataSource: UICollectionViewDataSource? {
set {
if let dataSource = colorCollectionDataSource {
self.colorCollectionView?.dataSource = dataSource
}
}
get {
return self.colorCollectionView?.dataSource
}
}
public var colorCollectionDelegate: UICollectionViewDelegate? {
set {
if let delegate = colorCollectionDelegate {
self.colorCollectionView?.delegate = delegate
}
}
get {
return self.colorCollectionView?.delegate
}
}
public var selectedColor: UIColor { /* code required */
/**
* It is up to the controller to retrieve saved settings.
* (When viewDidLoad() occurs, the controller can use the setter to restore last state for instance).
*
* Three main steps occur when one changes this property :
* 1) update UISlider's values
* 2) update color preview
* 3) update slider gradients
*/
set {
// 0) assigning the new value
// 1) Updating slider's values
self.currentColor = newValue
// 2) updating color preview
// 3) updating slider's gradients
self.colorCompositionChanged()
}
get {
let defaultColor = UIColor.black
if (currentColor==nil){
return defaultColor
}
return self.currentColor!
}
}
// MARK: HSB Color Properties
public var hueComponent: Float? {
get { return Float(self.selectedColor.getHueComponent()) }
set { self.selectedColor = self.selectedColor.colorWithHueComponent(hue: CGFloat(newValue!)) }
}
public var saturationComponent: Float? {
get { return Float(self.selectedColor.getSaturationComponent()) }
set { self.selectedColor = self.selectedColor.colorWithSaturationComponent(saturation: CGFloat(newValue!)) }
}
public var brightnessComponent: Float? {
get { return Float(self.selectedColor.getBrightnessComponent()) }
set { self.selectedColor = self.selectedColor.colorWithBrightnessComponent(brightness: CGFloat(newValue!)) }
}
// MARK: RGB Color Properties
public var redComponent: Float? {
get { return Float(self.selectedColor.getRedComponent()) }
set { self.selectedColor = self.selectedColor.colorWithRedComponent(red: CGFloat(newValue!)) }
}
public var greenComponent: Float? {
get { return Float(self.selectedColor.getGreenComponent()) }
set { self.selectedColor = self.selectedColor.colorWithGreenComponent(green: CGFloat(newValue!)) }
}
public var blueComponent: Float? {
get { return Float(self.selectedColor.getBlueComponent()) }
set { self.selectedColor = self.selectedColor.colorWithBlueComponent(blue: CGFloat(newValue!)) }
}
public var alphaComponent: Float? /* {
set { }
get { }
} */
// MARK: - UI Components (tweaking them more)
@IBOutlet weak var firstSlider: UISlider?
@IBOutlet weak var secondSlider: UISlider?
@IBOutlet weak var thirdSlider: UISlider?
@IBOutlet weak var forthSlider: UISlider?
public weak var hueSlider: UISlider? {
get { return firstSlider }
set { firstSlider = newValue }
}
public weak var saturationSlider: UISlider? {
get { return secondSlider }
set { secondSlider = newValue }
}
public weak var brightnessSlider: UISlider? {
get { return thirdSlider }
set { thirdSlider = newValue }
}
@IBOutlet public weak var colorPreviewView: UIView?
@IBOutlet weak var hueGradientView: UIView?
@IBOutlet weak var saturationGradientView: UIView?
@IBOutlet weak var brightnessGradientView: UIView?
@IBOutlet private weak var colorCollectionView: UICollectionView?
// MARK: - Private API -
/** Stockage de la couleur courante dans une variable
* Cela permet de jongler facilement entre les différents espaces de couleur.
*/
private var currentColor: UIColor? {
didSet {
// Update slider's values
if colorMode == .RGB || colorMode == .RGBA {
var r = CGFloat(0), g = CGFloat(0), b = CGFloat(0), a = CGFloat(0)
currentColor?.getRed(&r, green: &g, blue: &b, alpha: &a
)
self.sliderAtIndex(0)?.value = Float(r)
self.sliderAtIndex(1)?.value = Float(g)
self.sliderAtIndex(2)?.value = Float(b)
if colorMode == .RGBA {
self.sliderAtIndex(3)?.value = Float(a)
}
}
else if colorMode == .HSB || colorMode == .HSBA {
var h = CGFloat(0), s = CGFloat(0), b = CGFloat(0), a = CGFloat(0)
currentColor?.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
self.sliderAtIndex(0)?.value = Float(h)
self.sliderAtIndex(1)?.value = Float(s)
self.sliderAtIndex(2)?.value = Float(b)
if colorMode == .HSBA {
self.sliderAtIndex(3)?.value = Float(a)
}
}
}
}
private func sliderAtIndex(_ index: Int) -> UISlider? {
switch index {
case 0:
return self.firstSlider
case 1:
return secondSlider
case 2:
return thirdSlider
case 3:
return forthSlider
default:
return firstSlider
}
}
// MARK: View components
//
// @IBOutlet private weak var hueLabel: UILabel?
// @IBOutlet private weak var saturationLabel: UILabel?
// @IBOutlet private weak var brightnessLabel: UILabel?
// MARK: Manipulating sliders
// Schéma d'affectation des couleurs
//
// valeur affectée par le VC (depuis l'extérieur)
// -> report value in the view :: hsb,rgb,a,selectedColor properties
// -> store value properly (HSB, RGB, ..) :: dans le slider
// -> update UI (gradients) :: on colorCompositionChanged
// valeur affectée par le slider (depuis l'intérieur)
// -> store value properly (HSB, RGB, ..) :: dans le slider
// -> update UI (gradients) ::
// Other paradigm
@IBAction private func firstSliderChangedValue(slider: UISlider){
if (self.colorMode == .HSB || self.colorMode == .HSBA) {
self.hueComponent = slider.value
} else {
self.redComponent = slider.value
}
}
@IBAction private func secondSliderChangedValue(slider: UISlider){
if (self.colorMode == .HSB || self.colorMode == .HSBA) {
self.saturationComponent = slider.value
} else {
self.greenComponent = slider.value
}
}
@IBAction private func thirdSliderChangedValue(slider: UISlider){
if (self.colorMode == .HSB || self.colorMode == .HSBA) {
self.brightnessComponent = slider.value
} else {
self.blueComponent = slider.value
}
}
@IBAction private func forthSliderChangedValue(slider: UISlider){
// Only if alpha we want to handle alpha
if self.colorMode == .HSBA || self.colorMode == .RGBA {
self.alphaComponent = Float(slider.value)
}
}
private func switchToColorMode(colorMode: JMMColorSelectorColorMode){
// Changement du mode de couleur pour les sliders
self.colorMode = colorMode;
// straight-forward
self.resetSlidersValue()
// update the color effects and gradients
self.colorCompositionChanged()
}
private func resetSlidersValue() {
let color = self.selectedColor
if self.colorMode == .RGB || colorMode == .RGBA
{
self.firstSlider?.value = Float(color.getRedComponent())
self.secondSlider?.value = Float(color.getGreenComponent())
self.thirdSlider?.value = Float(color.getBlueComponent())
}
else
{
self.firstSlider?.value = Float(color.getHueComponent())
self.secondSlider?.value = Float(color.getSaturationComponent())
self.thirdSlider?.value = Float(color.getBrightnessComponent())
}
self.forthSlider?.value = Float(color.getAlphaComponent())
}
// MARK: - Processing UI Updates
@IBAction private func colorCompositionChanged() {
self.updateColorPreview();
self.updateSlidersUI();
}
private func updateColorPreview() {
let hue = self.hueComponent!
let saturation = self.saturationComponent!
let brightness = self.brightnessComponent!
var alpha = Float(1.0)
if let alphaComp = self.alphaComponent {
alpha = alphaComp
}
self.colorPreviewView?.backgroundColor = UIColor.init(hue: CGFloat(hue), saturation: CGFloat(saturation), brightness: CGFloat(brightness), alpha: CGFloat(alpha))
}
private func updateSlidersUI() {
self.hideTrackColorForSlider(self.hueSlider)
self.hideTrackColorForSlider(self.saturationSlider)
self.hideTrackColorForSlider(self.brightnessSlider)
self.setGradientWithColors(self.colorScaleForHue(), toView: self.hueGradientView)
self.setGradientWithColors(self.colorScaleForSaturation(), toView: self.saturationGradientView)
self.setGradientWithColors(self.colorScaleForBrightness(), toView: self.brightnessGradientView)
}
private func hideTrackColorForSlider(_ slider: UISlider?) {
let imageMin: UIImage? = slider?.minimumValueImage;
let imageMax: UIImage? = slider?.maximumValueImage;
slider?.minimumTrackTintColor = UIColor.clear
slider?.maximumTrackTintColor = UIColor.clear
// restore the icons
slider?.minimumValueImage = imageMin;
slider?.maximumValueImage = imageMax;
}
// MARK: - Gradients
private func colorScaleForHue() -> [UIColor] {
let nbSteps = 15
var colors = [UIColor]()
for i in 0 ... nbSteps {
let d = CGFloat( CGFloat(i) / CGFloat(nbSteps) )
colors.append(UIColor.init(hue: d, saturation: 1.0, brightness: 1.0, alpha: 1.0))
}
return colors
}
private func colorScaleForSaturation() -> [UIColor] {
let nbSteps = 15
var colors = [UIColor]()
for i in 0 ... nbSteps {
let d = CGFloat( CGFloat(i) / CGFloat(nbSteps) )
colors.append(UIColor.init(hue: CGFloat(self.hueComponent!), saturation: d, brightness: 1.0, alpha: 1.0))
}
return colors
}
private func colorScaleForBrightness() -> [UIColor] {
let nbSteps = 3
var colors = [UIColor]()
for i in 0 ... nbSteps {
let d = CGFloat( CGFloat(i) / CGFloat(nbSteps) )
colors.append(UIColor.init(hue: CGFloat(self.hueComponent!), saturation: 1.0, brightness: d, alpha: 1.0))
}
return colors
}
// MARK: Slider's Gradient Layers
private func setGradientWithColors(_ colors: [UIColor], toView view:UIView?) {
guard let view = view else {
return
}
let sublayer: CAGradientLayer = self.gradientLayerForView(view, withColors:colors);
let oldSublayer: CALayer? = view.layer.sublayers?[0];
if ( oldSublayer == nil ){
view.layer.addSublayer(sublayer);
} else {
view.layer.replaceSublayer(oldSublayer!, with:sublayer);
}
}
private func gradientLayerForView(_ view: UIView, withColors colors:[UIColor]) -> CAGradientLayer {
let layer: CAGradientLayer = CAGradientLayer.init();
self.updateGradientLayer(layer, withColors:colors, forView:view);
var locations = [NSNumber]();
for i in 0...colors.count {
let val = CGFloat(CGFloat(1.0) / CGFloat(colors.count - 1) * CGFloat(i));
let value = NSNumber(value:val)
locations.append(value)
}
layer.locations = locations;
layer.startPoint = CGPointMake(0.0, 0.5);
layer.endPoint = CGPointMake(1.0, 0.5);
layer.cornerRadius = view.frame.size.height / 2.0;
return layer;
}
private func updateGradientLayer(_ gradientLayer: CAGradientLayer, withColors colors:[UIColor], forView view:UIView) -> Void {
let rect: CGRect = view.bounds;
gradientLayer.frame = rect;
var cgColors = [CGColor]();
for color in colors {
cgColors.append(color.CGColor);
}
gradientLayer.colors = cgColors;
}
}
/*
@implementation ColorSelectorView
#pragma mark - Updates -
// API method
#pragma mark - Sliders -
+ (void)drawGradientOverContainer:(UIView *)container
{
UIColor *transBgColor = [UIColor colorWithWhite:1.0 alpha:0.0];
UIColor *black = [UIColor blackColor];
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.opacity = 0.8;
maskLayer.colors = [NSArray arrayWithObjects:(id)black.CGColor,
(id)transBgColor.CGColor, (id)transBgColor.CGColor, (id)black.CGColor, nil];
// Hoizontal - commenting these two lines will make the gradient veritcal
maskLayer.startPoint = CGPointMake(0.0, 0.5);
maskLayer.endPoint = CGPointMake(1.0, 0.5);
NSNumber *gradTopStart = [NSNumber numberWithFloat:0.0];
NSNumber *gradTopEnd = [NSNumber numberWithFloat:0.4];
NSNumber *gradBottomStart = [NSNumber numberWithFloat:0.6];
NSNumber *gradBottomEnd = [NSNumber numberWithFloat:1.0];
maskLayer.locations = @[gradTopStart, gradTopEnd, gradBottomStart, gradBottomEnd];
maskLayer.bounds = container.bounds;
maskLayer.anchorPoint = CGPointZero;
[container.layer addSublayer:maskLayer];
}
#pragma mark Slider gradients
private func setGradientLayerForHueSlider() {
let sublayer: CAGradientLayer = self.hueGradientLayer();
if(self.hueGradientView?.layer.sublayers.count == 0){
[self.hueGradientView.layer addSublayer:sublayer];
} else {
oldSublayer: CAGradientLayer = self.hueGradientView?.layer.sublayers.firstObject;
[self.hueGradientView.layer replaceSublayer:oldSublayer with:sublayer];
}
}
#pragma mark Gradients
- (CAGradientLayer *)hueGradientLayer {
NSMutableArray *colorSteps = [[NSMutableArray alloc]init];
NSMutableArray *positionSteps = [[NSMutableArray alloc]init];
int nbrOfSampling = 10;
float babyStep = 1.0 / (float)(nbrOfSampling - 1);
for (int i=0; i < nbrOfSampling ; ++i) {
CGFloat currentHue = i * babyStep;
CGFloat currentPos = currentHue;
[colorSteps addObject:(id)[UIColor colorWithHue:currentHue saturation:1.0 brightness:1.0 alpha:1.0].CGColor];
[positionSteps addObject:[NSNumber numberWithFloat:currentPos]];
}
CAGradientLayer *layer = [CAGradientLayer layer];
layer.frame = self.hueGradientView.frame;
layer.colors = colorSteps;
layer.locations = positionSteps;
layer.startPoint = CGPointMake(0.0, 0.5);
layer.endPoint = CGPointMake(1.0, 0.5);
layer.bounds = self.hueGradientView.bounds;
layer.anchorPoint = CGPointZero;
return layer;
}
#pragma mark - Setups -
- (void)awakeFromNib {
[super awakeFromNib];
// NSLog(@"%s",__PRETTY_FUNCTION__);
// [self customInit];
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
// NSLog(@"%s",__PRETTY_FUNCTION__);
if (self) {
// [self customInit];
}
return self;
}
@end
*/
| gpl-2.0 | 949286f60a8ea0326414bba0c785db2d | 30.820064 | 169 | 0.620878 | 4.521041 | false | false | false | false |
geasscode/TodoList | ToDoListApp/ToDoListApp/ExtensionClasses/ExtensionString.swift | 1 | 775 | //
// ExtensionString.swift
// ToDoListApp
//
// Created by desmond on 11/27/14.
// Copyright (c) 2014 Phoenix. All rights reserved.
//
import Foundation
extension String {
// var md5 : String{
// let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
// let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
// let digestLen = Int(CC_MD5_DIGEST_LENGTH)
// let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen);
//
// CC_MD5(str!, strLen, result);
//
// var hash = NSMutableString();
// for i in 0 ..< digestLen {
// hash.appendFormat("%02x", result[i]);
// }
// result.destroy();
//
// return String(format: hash)
// }
} | mit | cb283cdb4d441905aa7f4484c1f41680 | 26.714286 | 85 | 0.590968 | 3.725962 | false | false | false | false |
haugli/Bullitt | Sample Project/Sample Project/PostViewController.swift | 1 | 1875 | //
// PostViewController.swift
// Sample Project
//
// Copyright (c) 2015 Chris Haugli. All rights reserved.
//
import Bullitt
import UIKit
class PostViewController: UITableViewController {
var posts: [Post] = []
var thread: Thread? {
didSet {
if let thread = thread {
title = thread.title
loadPostsIfNeeded()
}
}
}
var forumService: ForumService? {
didSet {
loadPostsIfNeeded()
}
}
}
// MARK:- UITableViewDataSource
extension PostViewController: UITableViewDataSource {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PostCell", forIndexPath: indexPath) as! UITableViewCell
let post = posts[indexPath.row]
let message = post.messageBBCode
let bbCodeTagExpression = NSRegularExpression(pattern: "\\[.*?\\]", options: .allZeros, error: nil)
let strippedMessage = bbCodeTagExpression?.stringByReplacingMatchesInString(message, options: .allZeros, range: NSMakeRange(0, count(message)), withTemplate: "")
cell.textLabel!.text = strippedMessage
return cell
}
}
// MARK:- Internal
extension PostViewController {
func loadPostsIfNeeded() {
if let forumService = forumService, thread = thread {
forumService.loadPosts(thread, pageNumber: 1, success: { (posts) -> () in
self.posts = posts
self.tableView.reloadData()
}, failure: { (error) -> () in
println(error)
})
}
}
}
| mit | fae601fcddeb809b5180051f175f1cd0 | 26.985075 | 169 | 0.611733 | 5.067568 | false | false | false | false |
jjluebke/pigeon | Pigeon/PID.swift | 1 | 3365 | //
// PID.swift
// Pigeon
//
// Created by Jason Luebke on 7/30/15.
// Copyright (c) 2015 Jason Luebke. All rights reserved.
//
import Darwin
import Foundation
class PID {
var kp: Double!
var ki: Double!
var kd: Double!
var imax: Double!
var integrator: Double = 0
var lastT: NSTimeInterval = 0
var lastDerivative: Double?
var lastError: Double = 0
let fCut : Double = 20
//init (kp: Double = 0, ki: Double = 0, kd: Double = 0, imax: Double = 0) {
init (pids: Dictionary<String, Double>) {
self.kp = (pids["p"] != nil) ? pids["p"] : 0
self.ki = (pids["i"] != nil) ? pids["i"] : 0
self.kd = (pids["d"] != nil) ? pids["d"] : 0
self.imax = (pids["imax"] != nil) ? pids["imax"] : 0
}
func calculate(error: Double, scaler: Double) -> Double {
let tnow: NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
var dt: Double = tnow - lastT
var output: Double = 0
var deltaTime: Double!
if lastT == 0 || dt > 1000 {
dt = 0
// if this PID hasn't been used for a full second then zero
// the intergator term. This prevents I buildup from a
// previous fight mode from causing a massive return before
// the integrator gets a chance to correct itself
resetI()
}
lastT = tnow
deltaTime = dt / 1000.0
// Compute proportional component
output += error * kp
// Compute derivative component if time has elapsed
if abs(kd) > 0 && dt > 0 {
var derivative: Double!
if lastDerivative == nil {
// we've just done a reset, suppress the first derivative
// term as we don't want a sudden change in input to cause
// a large D output change
derivative = 0
lastDerivative = 0
} else {
derivative = (error - lastError) / deltaTime
}
// discrete low pass filter, cuts out the
// high frequency noise that can drive the controller crazy
let RC = 1 / (2 * M_PI * fCut)
derivative = lastDerivative! +
((deltaTime / (RC + deltaTime)) *
(derivative - lastDerivative!))
// update state
lastError = error
lastDerivative = derivative
// add in derivative component
output += kd * derivative
}
// scale the P and D components
output *= scaler
// Compute integral component if time has elapsed
if abs(ki) > 0 && dt > 0 {
integrator += (error * ki) * scaler * deltaTime
if integrator < -imax {
integrator = -imax
} else if integrator > imax {
integrator = imax
}
output += integrator
}
return output
}
func resetI () {
integrator = 0;
// we use nil to indicate that the last
// derivative value is not valid
lastDerivative = nil
}
}
| apache-2.0 | acc085d9d2b958144190cda4e0d4131b | 28.008621 | 79 | 0.49153 | 4.706294 | false | false | false | false |
colemancda/SwiftyGPIO | Sources/UART.swift | 1 | 7411 | /*
SwiftyGPIO
Copyright (c) 2016 Umberto Raimondi
Licensed under the MIT license, as follows:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.)
*/
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
extension SwiftyGPIO {
public static func UARTs(for board: SupportedBoard) -> [UARTInterface]? {
switch board {
case .RaspberryPiRev1:
fallthrough
case .RaspberryPiRev2:
fallthrough
case .RaspberryPiPlusZero:
fallthrough
case .RaspberryPi2:
fallthrough
case .RaspberryPi3:
return [UARTRPI[0]!]
default:
return nil
}
}
}
// MARK: - UART Presets
extension SwiftyGPIO {
// RaspberryPis SPIs
static let UARTRPI: [Int:UARTInterface] = [
0: SysFSUART("AMA0")!
]
}
// MARK: UART
public protocol UARTInterface {
func configureInterface(speed: UARTSpeed, bitsPerChar: CharSize, stopBits: StopBits, parity: ParityType)
func readString() -> String
func readLine() -> String
func readData() -> [CChar]
func writeString(_ value: String)
func writeData(_ values: [CChar])
}
public enum ParityType {
case None
case Even
case Odd
public func configure(_ cfg: inout termios){
switch self {
case .None:
cfg.c_cflag &= ~UInt32(PARENB | PARODD)
case .Even:
cfg.c_cflag &= ~UInt32(PARENB | PARODD)
cfg.c_cflag |= UInt32(PARENB)
case .Odd:
cfg.c_cflag |= UInt32(PARENB | PARODD)
}
}
}
public enum CharSize {
case Eight
case Seven
case Six
public func configure(_ cfg: inout termios){
cfg.c_cflag = (cfg.c_cflag & ~UInt32(CSIZE))
switch self {
case .Eight:
cfg.c_cflag |= UInt32(CS8)
case .Seven:
cfg.c_cflag |= UInt32(CS7)
case .Six:
cfg.c_cflag |= UInt32(CS6)
}
}
}
public enum StopBits {
case One
case Two
public func configure(_ cfg: inout termios){
switch self {
case .One:
cfg.c_cflag &= ~UInt32(CSTOPB)
case .Two:
cfg.c_cflag |= UInt32(CSTOPB)
}
}
}
public enum UARTSpeed {
case S9600
case S19200
case S38400
case S57600
case S115200
public func configure(_ cfg: inout termios) {
switch self {
case .S9600:
cfsetispeed(&cfg, speed_t(B9600))
cfsetospeed(&cfg, speed_t(B9600))
case .S19200:
cfsetispeed(&cfg, speed_t(B19200))
cfsetospeed(&cfg, speed_t(B19200))
case .S38400:
cfsetispeed(&cfg, speed_t(B38400))
cfsetospeed(&cfg, speed_t(B38400))
case .S57600:
cfsetispeed(&cfg, speed_t(B57600))
cfsetospeed(&cfg, speed_t(B57600))
case .S115200:
cfsetispeed(&cfg, speed_t(B115200))
cfsetospeed(&cfg, speed_t(B115200))
}
}
}
/// UART via SysFS
public final class SysFSUART: UARTInterface {
var device: String
var tty: termios
var fd: Int32
public init?(_ uartId: String){
device = "/dev/tty"+uartId
tty = termios()
fd = open(device, O_RDWR | O_NOCTTY | O_SYNC)
guard fd>0 else {
perror("Couldn't open UART device")
abort()
}
let ret = tcgetattr(fd, &tty)
guard ret == 0 else {
perror("Couldn't get terminal attributes")
abort()
}
}
public func configureInterface(speed: UARTSpeed, bitsPerChar: CharSize, stopBits: StopBits, parity: ParityType){
speed.configure(&tty)
bitsPerChar.configure(&tty)
tty.c_iflag &= ~UInt32(IGNBRK) // disable break processing
tty.c_lflag = 0 // no signaling chars, no echo,
// no canonical processing -> read bytes as they come without waiting for LF
tty.c_oflag = 0 // no remapping, no delays
withUnsafeMutableBytes(of: &tty.c_cc){$0[Int(VMIN)] = UInt8(1); return}
withUnsafeMutableBytes(of: &tty.c_cc){$0[Int(VTIME)] = UInt8(5); return} // 5 10th of second read timeout
tty.c_iflag &= ~UInt32(IXON | IXOFF | IXANY) // Every kind of software flow control off
tty.c_cflag &= ~UInt32(CRTSCTS) //No hw flow control
tty.c_cflag |= UInt32(CLOCAL | CREAD) // Ignore modem controls, enable read
parity.configure(&tty)
stopBits.configure(&tty)
applyConfiguration()
}
public func readLine() -> String {
var buf = [CChar](repeating:0, count: 4097) //4096 chars at max in canonical mode
var ptr = UnsafeMutablePointer<CChar>(&buf)
var pos = 0
repeat {
let n = read(fd, ptr, MemoryLayout<CChar>.stride)
if n<0 {
perror("Error while reading from UART")
abort()
}
ptr += 1
pos += 1
} while buf[pos-1] != CChar(UInt8(ascii: "\n"))
buf[pos] = 0
return String(cString: &buf)
}
public func readString() -> String {
var buf = readData()
buf.append(0) //Add terminator to convert cString correctly
return String(cString: &buf)
}
public func readData() -> [CChar] {
var buf = [CChar](repeating:0, count: 4096) //4096 chars at max in canonical mode
let n = read(fd, &buf, buf.count * MemoryLayout<CChar>.stride)
if n<0 {
perror("Error while reading from UART")
abort()
}
return Array(buf[0..<n])
}
public func writeString(_ value: String) {
let chars = Array(value.utf8CString)
writeData(chars)
}
public func writeData(_ value: [CChar]) {
var value = value
let _ = write(fd, &value, value.count)
tcdrain(fd)
}
private func applyConfiguration(){
if tcsetattr (fd, TCSANOW, &tty) != 0 {
perror("Couldn't set terminal attributes")
abort()
}
}
deinit {
close(fd)
}
}
// MARK: - Darwin / Xcode Support
#if os(OSX)
private var O_SYNC: CInt { fatalError("Linux only") }
private var CRTSCTS: CInt { fatalError("Linux only") }
// Shadowing some declarations from termios.h just to get it to compile with Xcode
// As the rest, not atually intended to be run.
public struct termios{
var c_iflag: UInt32 = 0
var c_oflag: UInt32 = 0
var c_cflag: UInt32 = 0
var c_lflag: UInt32 = 0
var c_cc = [UInt32]()
}
func tcsetattr (_ fd: Int32, _ attr: Int32, _ tty: inout termios) -> Int { fatalError("Linux only") }
func tcgetattr(_ fd: Int32, _ tty: inout termios) -> Int { fatalError("Linux only") }
func cfsetispeed(_ tty: inout termios, _ speed: UInt) { fatalError("Linux only") }
func cfsetospeed(_ tty: inout termios, _ speed: UInt) { fatalError("Linux only") }
#endif
| mit | 5757ed8c51dba7f70514e885bb643eec | 25.280142 | 113 | 0.642154 | 3.347335 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/WrappingHeaderFlowLayout.swift | 1 | 3134 | //
// WrappingHeaderFlowLayout.swift
// Slide for Reddit
//
// Created by Carlos Crane on 8/26/20.
// Copyright © 2020 Haptic Apps. All rights reserved.
//
import Foundation
protocol WrappingHeaderFlowLayoutDelegate: class {
func collectionView(_ collectionView: UICollectionView, indexPath: IndexPath) -> CGSize
}
class WrappingHeaderFlowLayout: UICollectionViewFlowLayout {
weak var delegate: WrappingHeaderFlowLayoutDelegate!
var xOffset = [CGFloat]()
private var cache = [UICollectionViewLayoutAttributes]()
private var contentHeight: CGFloat = 40.0
private var contentWidth: CGFloat = 0.0
override var collectionViewContentSize: CGSize {
return CGSize(width: contentWidth, height: contentHeight)
}
func reset() {
cache = []
contentWidth = 0
prepare()
}
override func prepare() {
if cache.isEmpty && collectionView!.numberOfItems(inSection: 0) != 0 {
xOffset = [CGFloat](repeating: 0, count: collectionView!.numberOfItems(inSection: 0))
for item in 0 ..< collectionView!.numberOfItems(inSection: 0) {
let indexPath = IndexPath.init(row: item, section: 0)
let width = delegate.collectionView(collectionView!, indexPath: indexPath).width
let height = contentHeight
var calculatedOffset = CGFloat(0)
for index in 0..<item {
calculatedOffset += xOffset[index]
}
let frame = CGRect(x: calculatedOffset, y: 0, width: width, height: height)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = frame
cache.append(attributes)
xOffset[item] = width + 24
contentWidth += width + 24
}
}
}
func offsetAt(_ index: Int) -> CGFloat {
var calculatedOffset = CGFloat(0)
if index < 0 {
return 0
}
if index < 0 || xOffset.count <= index {
return calculatedOffset
}
for ind in 0...index {
calculatedOffset += xOffset[ind]
}
return calculatedOffset
}
func widthAt(_ index: Int) -> CGFloat {
if index < 0 || xOffset.isEmpty {
return 0
}
return xOffset[index]
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if cache.isEmpty {
return nil
}
return cache[indexPath.item]
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
}
| apache-2.0 | d2f6241e5285c4a8f86028e181e41f67 | 29.417476 | 105 | 0.575168 | 5.604651 | false | false | false | false |
J-F-Liu/Neuronwork | Neuronwork/BinaryReader.swift | 1 | 851 | import Foundation
class BinaryReader{
var fileData:NSData
var location:Int
init(filePath:String){
self.fileData = NSData(contentsOfFile: filePath)!
self.location = 0
}
func readBytes(count:Int)->[Byte]{
if location >= fileData.length{
return [Byte]()
}
var bytes = [Byte](count:count, repeatedValue:0)
fileData.getBytes(&bytes, range:NSRange(location: location, length: count))
location += count
return bytes
}
func readUInt8() -> UInt8{
var bytes = readBytes(1)
return bytes[0]
}
func readInt32BE() -> Int32{
var bytes = readBytes(4)
var integer = Int32(0)
for byte in bytes{
integer <<= 8
integer |= Int32(byte)
}
return integer
}
} | bsd-2-clause | 609b1995a819e6f682b9694c5560478b | 22.666667 | 83 | 0.548766 | 4.478947 | false | false | false | false |
xmartlabs/Bender | Example/UIImage.swift | 1 | 2555 | //
// UIImage.swift
// Example
//
// Created by Mathias Claassen on 5/19/17.
//
//
import UIKit
import MetalKit
import MetalPerformanceShaders
extension UIImage {
func getPixelColor(pos: CGPoint) -> UIColor {
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4
let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
debugPrint("\(r) \(g) \(b) \(a)")
return UIColor(red: r, green: g, blue: b, alpha: a)
}
func toMPS(loader: MTKTextureLoader) -> MPSImage? {
guard let cgImage = self.cgImage,
let texture = try? loader.newTexture(cgImage: cgImage, options: [MTKTextureLoader.Option.SRGB : NSNumber(value: false)]) else {
return nil
}
return MPSImage(texture: texture, featureChannels: 4)
}
func toCVPixelBuffer(height: CGFloat = 224, width: CGFloat = 224) -> CVPixelBuffer? {
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary
var pixelBuffer : CVPixelBuffer?
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(width), Int(height), kCVPixelFormatType_32ARGB, attrs, &pixelBuffer)
guard status == kCVReturnSuccess else {
return nil
}
if let pixelBuffer = pixelBuffer {
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: pixelData, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue)
context?.translateBy(x: 0, y: height)
context?.scaleBy(x: 1.0, y: -1.0)
UIGraphicsPushContext(context!)
self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
UIGraphicsPopContext()
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
return pixelBuffer
}
return nil
}
}
| mit | 2bd6ef73a8681f7969c282f47503bebb | 36.028986 | 243 | 0.656751 | 4.538188 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/Microservices/Controller/MicroservicesTableViewController.swift | 1 | 6360 | //
// MicroservicesTableViewController.swift
// WePeiYang
//
// Created by Qin Yubo on 16/1/30.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import UIKit
import AFNetworking
import MJRefresh
import SafariServices
import SwiftyJSON
import ObjectMapper
class MicroservicesTableViewController: UITableViewController {
var dataArr: [WebAppItem] = []
override init(style: UITableViewStyle) {
super.init(style: style)
self.contentSizeInPopup = CGSizeMake(300, 400)
self.landscapeContentSizeInPopup = CGSizeMake(400, 260)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// iOS 8 FUCKING BUG
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.contentSizeInPopup = CGSizeMake(300, 400)
self.landscapeContentSizeInPopup = CGSizeMake(400, 260)
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.title = "探索"
self.tableView.tableFooterView = UIView()
self.tableView.estimatedRowHeight = 65
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.registerNib(UINib(nibName: "WebAppTableViewCell", bundle: nil), forCellReuseIdentifier: "reuseIdentifier")
self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
self.refresh()
})
self.refresh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Private methods
private func refresh() {
MsgDisplay.showLoading()
let parameters = NSUserDefaults().boolForKey(DEV_DISPLAY_DEV_WEB_APP) ? ["env": "development"] : [:]
SolaSessionManager.solaSessionWithSessionType(.GET, URL: "/microservices", token: nil, parameters: parameters, success: {(task, responseObject) in
let dic = JSON(responseObject)
if dic["error_code"].int == -1 {
self.dataArr = Mapper<WebAppItem>().mapArray(dic["data"].arrayObject)!
self.tableView.reloadData()
self.tableView.mj_header.endRefreshing()
}
MsgDisplay.dismiss()
}, failure: {(task, error) in
if let errorResponse = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? NSData {
let errorJSON = JSON(errorResponse)
MsgDisplay.showErrorMsg("获取数据失败\n\(errorJSON["message"])")
} else {
MsgDisplay.showErrorMsg("获取数据失败\n请稍后再试...")
}
})
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier") as? WebAppTableViewCell
let row = indexPath.row
cell?.setObject(dataArr[row])
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = indexPath.row
let dataItem = dataArr[row]
var webController: UIViewController
if dataItem.fullScreen {
webController = WebAppViewController(address: dataItem.sites)
} else {
if #available(iOS 9.0, *) {
webController = SFSafariViewController(URL: NSURL(string: dataItem.sites)!)
} else {
webController = wpyModalWebViewController(address: dataItem.sites)
}
}
// self.navigationController?.showViewController(webController, sender: nil)
self.presentViewController(webController, animated: true, completion: nil)
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 2581a5a8161baa24bd73f5736f4716aa | 36.838323 | 157 | 0.663871 | 5.336993 | false | false | false | false |
jeantimex/swift-photo-viewer | Swift Photo Viewer/PhotosManager.swift | 1 | 1601 | //
// PhotosManager.swift
// Swift Photo Viewer
//
// Created by Yong Su on 3/31/17.
// Copyright © 2017 jeantimex. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
extension UInt64 {
func megabytes() -> UInt64 {
return self * 1024 * 1024
}
}
class PhotosManager {
static let shared = PhotosManager()
private var dataPath: String {
return Bundle.main.path(forResource: "Photos", ofType: "plist")!
}
lazy var photos: [Photo] = {
var photos = [Photo]()
guard let data = NSArray(contentsOfFile: self.dataPath) as? [[String: Any]] else { return photos }
for info in data {
let photo = Photo(info: info)
photos.append(photo)
}
return photos
}()
let imageCache = AutoPurgingImageCache(
memoryCapacity: UInt64(100).megabytes(),
preferredMemoryUsageAfterPurge: UInt64(60).megabytes()
)
//MARK: - Image Downloading
func retrieveImage(for url: String, completion: @escaping (UIImage) -> Void) -> Request {
return Alamofire.request(url, method: .get).responseImage { response in
guard let image = response.result.value else { return }
completion(image)
self.cache(image, for: url)
}
}
//MARK: - Image Caching
func cache(_ image: Image, for url: String) {
imageCache.add(image, withIdentifier: url)
}
func cachedImage(for url: String) -> Image? {
return imageCache.image(withIdentifier: url)
}
}
| mit | 5ffa3713dc6bd91001560e7686f1ecad | 24.806452 | 106 | 0.60125 | 4.289544 | false | false | false | false |
AlexRamey/mbird-iOS | iOS Client/Models/Core Data/MBAuthor+CoreDataClass.swift | 1 | 1578 | //
// MBAuthor+CoreDataClass.swift
// iOS Client
//
// Created by Alex Ramey on 10/5/17.
// Copyright © 2017 Mockingbird. All rights reserved.
//
//
import Foundation
import CoreData
public class MBAuthor: NSManagedObject {
static let entityName: String = "Author"
class func newAuthor(fromAuthor from: Author, inContext managedContext: NSManagedObjectContext) -> MBAuthor? {
let predicate = NSPredicate(format: "authorID == %d", from.authorId)
let fetchRequest = NSFetchRequest<MBAuthor>(entityName: self.entityName)
fetchRequest.predicate = predicate
var resolvedAuthor: MBAuthor? = nil
do {
let fetchedEntities = try managedContext.fetch(fetchRequest)
resolvedAuthor = fetchedEntities.first
} catch {
print("Error fetching author \(from.authorId) from core data: \(error)")
return nil
}
if resolvedAuthor == nil {
let entity = NSEntityDescription.entity(forEntityName: self.entityName, in: managedContext)!
resolvedAuthor = NSManagedObject(entity: entity, insertInto: managedContext) as? MBAuthor
}
guard let author = resolvedAuthor else {
return nil
}
author.authorID = Int32(from.authorId)
author.info = from.info
author.name = from.name
return author
}
func toDomain() -> Author {
return Author(authorId: Int(self.authorID), name: self.name ?? "mockingbird", info: self.info ?? "")
}
}
| mit | 01181b0c9b3632d6e31bf2397f277d4e | 31.183673 | 114 | 0.627774 | 4.778788 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Extensions/Media+Sync.swift | 1 | 3874 | import Foundation
extension Media {
/// Returns a list of Media objects that should be uploaded for the given input parameters.
///
/// - Parameters:
/// - automatedRetry: whether the media to upload is the result of an automated retry.
///
/// - Returns: the Media objects that should be uploaded for the given input parameters.
///
static func failedMediaForUpload(automatedRetry: Bool, in context: NSManagedObjectContext) -> [Media] {
let request = NSFetchRequest<Media>(entityName: Media.entityName())
let failedMediaPredicate = NSPredicate(format: "\(#keyPath(Media.remoteStatusNumber)) == %d", MediaRemoteStatus.failed.rawValue)
if automatedRetry {
let autoUploadFailureCountPredicate = NSPredicate(format: "\(#keyPath(Media.autoUploadFailureCount)) < %d", Media.maxAutoUploadFailureCount)
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [failedMediaPredicate, autoUploadFailureCountPredicate])
} else {
request.predicate = failedMediaPredicate
}
let media = (try? context.fetch(request)) ?? []
return media
}
/// This method checks the status of all media objects and updates them to the correct status if needed.
/// The main cause of wrong status is the app being killed while uploads of media are happening.
///
/// - Parameters:
/// - onCompletion: block to invoke when status update is finished.
/// - onError: block to invoke if any error occurs while the update is being made.
///
static func refreshMediaStatus(using coreDataStack: CoreDataStack, onCompletion: (() -> Void)? = nil, onError: ((Error) -> Void)? = nil) {
coreDataStack.performAndSave { context in
let fetch = NSFetchRequest<Media>(entityName: Media.classNameWithoutNamespaces())
let pushingPredicate = NSPredicate(format: "remoteStatusNumber = %@", NSNumber(value: MediaRemoteStatus.pushing.rawValue))
let processingPredicate = NSPredicate(format: "remoteStatusNumber = %@", NSNumber(value: MediaRemoteStatus.processing.rawValue))
let errorPredicate = NSPredicate(format: "remoteStatusNumber = %@", NSNumber(value: MediaRemoteStatus.failed.rawValue))
fetch.predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [pushingPredicate, processingPredicate, errorPredicate])
let mediaPushing = try context.fetch(fetch)
for media in mediaPushing {
// If file were in the middle of being pushed or being processed they now are failed.
if media.remoteStatus == .pushing || media.remoteStatus == .processing {
media.remoteStatus = .failed
}
// If they failed to upload themselfs because no local copy exists then we need to delete this media object
// This scenario can happen when media objects were created based on an asset that failed to import to the WordPress App.
// For example a PHAsset that is stored on the iCloud storage and because of the network connection failed the import process.
if media.remoteStatus == .failed,
let error = media.error as NSError?, error.domain == MediaServiceErrorDomain && error.code == MediaServiceError.fileDoesNotExist.rawValue {
context.delete(media)
}
}
} completion: { result in
DispatchQueue.main.async {
switch result {
case .success:
onCompletion?()
case let .failure(error):
DDLogError("Error while attempting to clean local media: \(error.localizedDescription)")
onError?(error)
}
}
}
}
}
| gpl-2.0 | be60a5b6bbf982a2ac2405c66a960a1e | 54.342857 | 159 | 0.65049 | 5.42577 | false | true | false | false |
anthrgrnwrld/renda | Renda/KosuriGestureRecognizer.swift | 1 | 2079 | //
// KosuriGestureRecognizer.swift
// Renda
//
// Created by Masaki Horimoto on 2015/09/02.
// Copyright (c) 2015年 Masaki Horimoto. All rights reserved.
//
import UIKit
/**
2つのViewにおいて、PanにてView範囲に入った時に、closureで指定された動作を行う。
使用例:コスリ機能
:param: _targetViewA:対象となるView(1つ目)
:param: _targetViewB:対象となるView(2つ目)
:param: 対象となるView範囲に入った時に実行する動作
*/
class KosuriGestureRecognizer : NSObject {
let pan = UIPanGestureRecognizer()
var targetViewA:UIView? = nil //targetViewAとtargetViewBは同じsuperviewを持っていること
var targetViewB:UIView? = nil //targetViewAとtargetViewBは同じsuperviewを持っていること
var didPush:(()->Void)? = nil
var inFlagA = false
var inFlagB = false
init(_targetViewA:UIView, _targetViewB:UIView, didPush:()->Void) {
super.init()
self.targetViewA = _targetViewA
self.targetViewB = _targetViewB
self.didPush = didPush
pan.addTarget(self, action: Selector("didPan:"))
_targetViewA.superview?.addGestureRecognizer(self.pan)
}
func didPan(sender:AnyObject) {
if let pan = sender as? UIPanGestureRecognizer,
targetViewA = self.targetViewA,
targetViewB = self.targetViewB,
outView = targetViewA.superview,
didPush = self.didPush
{
let p = pan.locationInView(outView) //outViewはViewControllerでいうところのself.view
if !inFlagA && targetViewA.frame.contains(p) {
inFlagA = true
didPush()
} else if inFlagA && !targetViewA.frame.contains(p) {
inFlagA = false
} else if !inFlagB && targetViewB.frame.contains(p) {
inFlagB = true
didPush()
} else if inFlagB && !targetViewB.frame.contains(p) {
inFlagB = false
}
}
}
}
| mit | 7e052f11c790b86fed19a4a69fcea1a9 | 28.698413 | 88 | 0.613576 | 3.625969 | false | false | false | false |
CosynPa/TZStackView | TZStackViewDemo/ViewController.swift | 1 | 10784 | //
// ViewController.swift
// TZStackView-Example
//
// Created by Tom van Zummeren on 20/06/15.
// Copyright (c) 2015 Tom van Zummeren. All rights reserved.
//
import UIKit
import TZStackView
class ViewController: UIViewController {
//MARK: - Properties
//--------------------------------------------------------------------------
var tzStackView: TZStackView!
let resetButton = UIButton(type: .System)
let instructionLabel = UILabel()
var axisSegmentedControl: UISegmentedControl!
var alignmentSegmentedControl: UISegmentedControl!
var distributionSegmentedControl: UISegmentedControl!
//MARK: - Lifecyle
//--------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = .None;
view.backgroundColor = UIColor.blackColor()
title = "TZStackView"
tzStackView = TZStackView(arrangedSubviews: createViews())
tzStackView.translatesAutoresizingMaskIntoConstraints = false
tzStackView.axis = .Vertical
tzStackView.distribution = .Fill
tzStackView.alignment = .Fill
tzStackView.spacing = 15
view.addSubview(tzStackView)
let toIBButton = UIButton(type: .System)
toIBButton.translatesAutoresizingMaskIntoConstraints = false
toIBButton.setTitle("Storyboard Views", forState: .Normal)
toIBButton.addTarget(self, action: #selector(ViewController.toIB), forControlEvents: .TouchUpInside)
toIBButton.setContentCompressionResistancePriority(1000, forAxis: .Vertical)
toIBButton.setContentHuggingPriority(1000, forAxis: .Vertical)
view.addSubview(toIBButton)
instructionLabel.translatesAutoresizingMaskIntoConstraints = false
instructionLabel.font = UIFont.systemFontOfSize(15)
instructionLabel.text = "Tap any of the boxes to set hidden=true"
instructionLabel.textColor = UIColor.whiteColor()
instructionLabel.numberOfLines = 0
instructionLabel.setContentCompressionResistancePriority(900, forAxis: .Horizontal)
instructionLabel.setContentCompressionResistancePriority(1000, forAxis: .Vertical)
instructionLabel.setContentHuggingPriority(1000, forAxis: .Vertical)
view.addSubview(instructionLabel)
resetButton.translatesAutoresizingMaskIntoConstraints = false
resetButton.setTitle("Reset", forState: .Normal)
resetButton.addTarget(self, action: #selector(ViewController.reset), forControlEvents: .TouchUpInside)
resetButton.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
resetButton.setContentHuggingPriority(1000, forAxis: .Horizontal)
view.addSubview(resetButton)
axisSegmentedControl = UISegmentedControl(items: ["Vertical", "Horizontal"])
axisSegmentedControl.selectedSegmentIndex = 0
axisSegmentedControl.addTarget(self, action: #selector(ViewController.axisChanged(_:)), forControlEvents: .ValueChanged)
axisSegmentedControl.setContentCompressionResistancePriority(1000, forAxis: .Vertical)
axisSegmentedControl.setContentHuggingPriority(1000, forAxis: .Vertical)
axisSegmentedControl.tintColor = UIColor.lightGrayColor()
alignmentSegmentedControl = UISegmentedControl(items: ["Fill", "Center", "Leading", "Top", "Trailing", "Bottom", "FirstBaseline"])
alignmentSegmentedControl.selectedSegmentIndex = 0
alignmentSegmentedControl.addTarget(self, action: #selector(ViewController.alignmentChanged(_:)), forControlEvents: .ValueChanged)
alignmentSegmentedControl.setContentCompressionResistancePriority(1000, forAxis: .Vertical)
alignmentSegmentedControl.setContentHuggingPriority(1000, forAxis: .Vertical)
alignmentSegmentedControl.tintColor = UIColor.lightGrayColor()
distributionSegmentedControl = UISegmentedControl(items: ["Fill", "FillEqually", "FillProportionally", "EqualSpacing", "EqualCentering"])
distributionSegmentedControl.selectedSegmentIndex = 0
distributionSegmentedControl.addTarget(self, action: #selector(ViewController.distributionChanged(_:)), forControlEvents: .ValueChanged)
distributionSegmentedControl.setContentCompressionResistancePriority(1000, forAxis: .Vertical)
distributionSegmentedControl.setContentHuggingPriority(1000, forAxis: .Vertical)
distributionSegmentedControl.tintColor = UIColor.lightGrayColor()
let controlsLayoutContainer = TZStackView(arrangedSubviews: [axisSegmentedControl, alignmentSegmentedControl, distributionSegmentedControl])
controlsLayoutContainer.axis = .Vertical
controlsLayoutContainer.translatesAutoresizingMaskIntoConstraints = false
controlsLayoutContainer.spacing = 5
view.addSubview(controlsLayoutContainer)
let views: [String:AnyObject] = [
"toIBButton": toIBButton,
"instructionLabel": instructionLabel,
"resetButton": resetButton,
"tzStackView": tzStackView,
"controlsLayoutContainer": controlsLayoutContainer
]
let metrics: [String:AnyObject] = [
"gap": 10,
"topspacing": 25
]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[toIBButton]-gap-|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-gap-[instructionLabel]-[resetButton]-gap-|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[tzStackView]|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[controlsLayoutContainer]|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-topspacing-[toIBButton]-gap-[instructionLabel]-gap-[controlsLayoutContainer]-gap-[tzStackView]|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views))
view.addConstraint(NSLayoutConstraint(item: instructionLabel, attribute: .CenterY, relatedBy: .Equal, toItem: resetButton, attribute: .CenterY, multiplier: 1, constant: 0))
}
private func createViews() -> [UIView] {
let redView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 100, height: 100), name: "Red")
let greenView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 80, height: 80), name: "Green")
let blueView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 60, height: 60), name: "Blue")
let purpleView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 80, height: 80), name: "Purple")
let yellowView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 100, height: 100), name: "Yellow")
let views = [redView, greenView, blueView, purpleView, yellowView]
for (i, view) in views.enumerate() {
let j = UILayoutPriority(i)
view.setContentCompressionResistancePriority(751 + j, forAxis: .Horizontal)
view.setContentCompressionResistancePriority(751 + j, forAxis: .Vertical)
view.setContentHuggingPriority(251 + j, forAxis: .Horizontal)
view.setContentHuggingPriority(251 + j, forAxis: .Vertical)
}
redView.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.75)
greenView.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.75)
blueView.backgroundColor = UIColor.blueColor().colorWithAlphaComponent(0.75)
purpleView.backgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.75)
yellowView.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(0.75)
return [redView, greenView, blueView, purpleView, yellowView]
}
//MARK: - Button Actions
//--------------------------------------------------------------------------
func reset() {
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .AllowUserInteraction, animations: {
for view in self.tzStackView.arrangedSubviews {
view.hidden = false
}
}, completion: nil)
}
func toIB() {
let storyboard = UIStoryboard(name: "Storyboard", bundle: nil)
let viewController = storyboard.instantiateInitialViewController()!
viewController.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Cancel, target: self, action: #selector(ViewController.backFromIB))
let navController = UINavigationController(rootViewController: viewController)
presentViewController(navController, animated: true, completion: nil)
}
func backFromIB() {
dismissViewControllerAnimated(true, completion:nil)
}
//MARK: - Segmented Control Actions
//--------------------------------------------------------------------------
func axisChanged(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
tzStackView.axis = .Vertical
default:
tzStackView.axis = .Horizontal
}
}
func alignmentChanged(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
tzStackView.alignment = .Fill
case 1:
tzStackView.alignment = .Center
case 2:
tzStackView.alignment = .Leading
case 3:
tzStackView.alignment = .Top
case 4:
tzStackView.alignment = .Trailing
case 5:
tzStackView.alignment = .Bottom
default:
tzStackView.alignment = .FirstBaseline
}
}
func distributionChanged(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
tzStackView.distribution = .Fill
case 1:
tzStackView.distribution = .FillEqually
case 2:
tzStackView.distribution = .FillProportionally
case 3:
tzStackView.distribution = .EqualSpacing
default:
tzStackView.distribution = .EqualCentering
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
} | mit | 867912f1a441c74774439924ad5041cb | 47.800905 | 180 | 0.682678 | 5.832342 | false | false | false | false |
YaoJuan/YJDouYu | YJDouYu/YJDouYu/Classes/Home-首页/ViewModel/YJRecommondVM.swift | 1 | 3488 | //
// YJRecommondViewModel.swift
// YJDouYu
//
// Created by 赵思 on 2017/8/1.
// Copyright © 2017年 赵思. All rights reserved.
//
import UIKit
import SwiftyJSON
import ObjectMapper
class YJRecommondVM: YJBaseVM {
var cycleItems = [YJRecommendCycleItem]()
/// 热门: http://capi.douyucdn.cn/api/v1/getbigDataRoom 参数只用时间
/// 颜值: "http://capi.douyucdn.cn/api/v1/getVerticalRoom"
/// 其他: "http://capi.douyucdn.cn/api/v1/getHotCate" parameters = ["limit" : "4", "offset" : "0", "time" : 时间]
func loadRecommondData(finished: @escaping () -> ()) {
// 1.定义变量保存不同分组的数据
var verticalItems = [YJRecommondGroupItem]()
var bigItems = [YJRecommondGroupItem]()
// 2.请求数据的参数
let time = Int(Date().timeIntervalSince1970)
let parameters: [String : AnyObject] = ["limit" : "4" as AnyObject, "offset" : "0" as AnyObject, "time" : time as AnyObject]
// 3. 进入组队列
let disGroup = DispatchGroup()
disGroup.enter()
// 4.1 请求颜值数据
NetworkTool.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", paramaters: parameters) { (result) in
let dic = JSON(result).dictionaryValue["data"]?.arrayObject
// 5.2 将请求到的数据包装成1个组
let rooms = Mapper<YJRecommendRoomItem>().mapArray(JSONObject: dic)
let group = YJRecommondGroupItem()
group.tag_name = "颜值"
group.room_list = rooms
verticalItems.append(group)
// 4.3 离开组队列
disGroup.leave()
}
// 5.再次进入组队列
disGroup.enter()
// 6.1 请求热门数据
NetworkTool.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", paramaters: ["time" : time]) { (result) in
let dic = JSON(result).dictionaryValue["data"]?.arrayObject
// 6.2 将请求到的数据再包装成一个组
let rooms = Mapper<YJRecommendRoomItem>().mapArray(JSONObject: dic)
let group = YJRecommondGroupItem()
group.tag_name = "热门"
group.room_list = rooms
bigItems.append(group)
// 6.3 离开组队列
disGroup.leave()
}
// 6.进入组队列
disGroup.enter()
loadAnchorData(itemType: .group, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", paramaters: parameters) {
disGroup.leave()
disGroup.notify(queue: DispatchQueue.main, execute: {
_ = verticalItems.map { self.groupItems.insert($0, at: 0) }
// 7.3 插入最后需要显示的数据
_ = bigItems.map { self.groupItems.insert($0, at: 0) }
// 7.4 回调
finished()
})
}
}
func loadCycleData(finished: @escaping () -> ()) {
NetworkTool.requestData(type: .GET, URLString: "http://www.douyutv.com/api/v1/slide/6", paramaters: ["version" : "2.300" as AnyObject]) { (result) in
let dataArr = JSON(result).dictionaryValue["data"]?.object
let cycleArr = Mapper<YJRecommendCycleItem>().mapArray(JSONObject: dataArr)
self.cycleItems = cycleArr ?? [YJRecommendCycleItem]()
finished()
}
}
}
| mit | 9bf1ad7730603d1efe00e1ad602fcd6a | 36.732558 | 157 | 0.572881 | 3.831169 | false | false | false | false |
aliceatlas/hexagen | Hexagen/Swift/Feed.swift | 1 | 1166 | /*****\\\\
/ \\\\ Swift/Feed.swift
/ /\ /\ \\\\ (part of Hexagen)
\ \_X_/ ////
\ //// Copyright © 2015 Alice Atlas (see LICENSE.md)
\*****////
public class Feed<T> {
internal var head: RecurringPromise<T>? = RecurringPromise()
public init(@noescape _ fn: (T -> Void, Void -> Void) -> Void) {
fn({ self._post($0) }, { self._post(nil) })
}
private func _post(value: T?) {
synchronized(self) {
if let last = head {
last._fulfill(value)
head = last.successor
} else {
fatalError("sequence was already closed")
}
}
}
}
internal class RecurringPromise<T>: Promise<T?> {
private var _successor = ThreadSafeLazy<RecurringPromise<T>?> { RecurringPromise() }
internal var successor: RecurringPromise<T>? {
get { return _successor.value }
set { _successor.value = newValue }
}
private override init() {
super.init()
addHandler { [unowned self] value in
if value == nil {
self.successor = nil
}
}
}
}
| mit | cd8f04de87df77cd41b4ceabb59beab0 | 26.093023 | 88 | 0.496137 | 3.962585 | false | false | false | false |
movem3nt/StreamBaseKit | StreamBaseKit/StreamBase.swift | 2 | 17193 | //
// StreamBase.swift
// StreamBaseKit
//
// Created by Steve Farrell on 8/31/15.
// Copyright (c) 2015 Movem3nt, Inc. All rights reserved.
//
import Firebase
/**
Surfaces a Firebase collection as a stream suitable for presenting in a ui table or
collection.
In addition to basic functionality of keeping stream synched with Firebase backing store
and invoking a delegate with updates, it has some more advanced features:
* Inverted streams
* Paging
* Predicates
* Batching
*/
public class StreamBase : StreamBaseProtocol {
public typealias Predicate = BaseItem -> Bool
public typealias Comparator = (BaseItem, BaseItem) -> Bool
public typealias QueryPager = (start: AnyObject?, end: AnyObject?, limit: Int?) -> FQuery
public enum Ordering {
case Key
case Child(String)
// TODO Priority
}
private var handles = [UInt]()
private var arrayBeforePredicate = KeyedArray<BaseItem>()
private var array = KeyedArray<BaseItem>()
private var batchArray = KeyedArray<BaseItem>()
private let type: BaseItem.Type!
private let query: FQuery!
private let queryPager: QueryPager!
private let limit: Int?
private var isBatching = false
private var timer: NSTimer?
private var isFetchingMore = false
private var shouldTellDelegateInitialLoadIsDone: Bool? = false
/**
The comparator function used for sorting items.
*/
public let comparator: Comparator
/**
How long to wait for a batch of changes to accumulate before invoking delegate.
If nil, then there is no delay. The unit is seconds.
*/
public var batchDelay: NSTimeInterval? = 0.1
/**
A value used to decide whether elements are members of the stream or not. This
predicate is evaluated client-side, and so scalability and under-fetching must
be taken into account.
*/
public var predicate: Predicate? {
didSet {
batching { a in
if let p = self.predicate {
a.clear()
for t in self.arrayBeforePredicate {
if p(t) {
a.append(t)
}
}
} else {
a.reset(self.arrayBeforePredicate)
}
}
}
}
/**
Limit the results after predicate to this value. If the fetch limit is combined with
a predicate, then under-fetching may result.
*/
public var afterPredicateLimit: Int?
/**
The delegate to notify as the underying data changes.
*/
public weak var delegate: StreamBaseDelegate? {
didSet {
if limit == 0 {
delegate?.streamDidFinishInitialLoad(nil)
}
}
}
/**
Construct an empty stream instance, not connected to any backing Firebase store.
*/
public init() {
type = nil
limit = 0
query = nil
queryPager = nil
comparator = { $0.key < $1.key }
}
/**
Construct a stream instance containing items of the given type at the given Firebase reference.
:param: type The type of items in the stream.
:param: ref The Firebase reference where the items are stored.
:param: limit The max number to fetch.
:param: ascending Whether to materialize the underlying array in ascending or descending order.
:param: ordering The ordering to use.
*/
public convenience init(type: BaseItem.Type, ref: Firebase, limit: Int? = nil, ascending: Bool = true, ordering: Ordering = .Key) {
let queryBuilder = QueryBuilder(ref: ref)
queryBuilder.limit = limit
queryBuilder.ascending = ascending
queryBuilder.ordering = ordering
self.init(type: type, queryBuilder: queryBuilder)
}
/**
Construct a stream instance containing items of the given type using the query builder specification.
:param: type The type of items in the stream.
:param: queryBuilder The details of what firebase data to query.
*/
public init(type: BaseItem.Type, queryBuilder: QueryBuilder) {
self.type = type
limit = queryBuilder.limit
comparator = queryBuilder.buildComparator()
query = queryBuilder.buildQuery()
queryPager = queryBuilder.buildQueryPager()
handles.append(query.observeEventType(.ChildAdded, withBlock: { [weak self] snapshot in
if let s = self {
let item = s.type.init(key: snapshot.key)
item.update(snapshot.value as? [String: AnyObject])
s.didConstructItem(item)
s.arrayBeforePredicate.append(item)
if s.predicate == nil || s.predicate!(item) {
s.batching { $0.append(item) }
}
}
}))
handles.append(query.observeEventType(.ChildRemoved, withBlock: { [weak self] snapshot in
if let s = self {
if let row = s.arrayBeforePredicate.find(snapshot.key) {
s.arrayBeforePredicate.removeAtIndex(row)
}
s.batching { a in
if let row = a.find(snapshot.key) {
a.removeAtIndex(row)
}
}
}
}))
handles.append(query.observeEventType(.ChildChanged, withBlock: { [weak self] snapshot in
if let s = self {
if let row = s.arrayBeforePredicate.find(snapshot.key) {
let t = s.arrayBeforePredicate[row]
t.update(snapshot.value as? [String: AnyObject])
s.handleItemChanged(t)
}
}
}))
let inflight = Inflight()
query.observeSingleEventOfType(.Value, withBlock: { [weak self] snapshot in
if let s = self {
inflight.hold()
s.shouldTellDelegateInitialLoadIsDone = true
s.scheduleBatch()
}
}, withCancelBlock: { [weak self] error in
self?.delegate?.streamDidFinishInitialLoad(error)
})
}
deinit {
for h in handles {
query.removeObserverWithHandle(h)
}
}
/**
Hook for additional initialization after an item in the stream is created.
:param: item The item that was just constructed.
*/
public func didConstructItem(item: BaseItem) {
}
/**
Find the item for a given key.
:param: key The key to check
:returns: The item or nil if not found.
*/
public func find(key: String) -> BaseItem? {
if let row = array.find(key) {
return array[row]
}
return nil
}
/**
Find the index path for the given key.
:param: key The key to check.
:returns: The index path or nil if not found.
*/
public func findIndexPath(key: String) -> NSIndexPath? {
if let row = array.find(key) {
return pathAt(row)
}
return nil
}
/**
Find the path of the first item that would appear in the stream after the
exemplar item. The exemplar item need not be in this stream.
:param: item The exemplar item.
:returns: The index path of that first item or nil if none is found.
*/
public func findFirstIndexPathAfter(item: BaseItem) -> NSIndexPath? {
let a = array.rawArray
if a.isEmpty {
return nil
}
let predicate = { self.comparator(item, $0) }
var left = a.startIndex
var right = a.endIndex - 1
if predicate(a.first!) {
return pathAt(left)
}
var midpoint = a.count / 2
while right - left > 1 {
if predicate(a[midpoint]) {
right = midpoint
} else {
left = midpoint
}
midpoint = (left + right) / 2
}
return predicate(a[left]) ? pathAt(left) : predicate(a[right]) ? pathAt(right) : nil
}
/**
Find the path of the last item that would appear in the stream before the
exemplar item. The exemplar item need not be in this stream.
:param: item The exemplar item.
:returns: The index path of that first item or nil if none is found.
*/
public func findLastIndexPathBefore(item: BaseItem) -> NSIndexPath? {
let a = array.rawArray
if a.isEmpty {
return nil
}
let predicate = { self.comparator($0, item) }
var left = array.startIndex
var right = array.endIndex - 1
if predicate(a.last!) {
return pathAt(right)
}
var midpoint = a.count / 2
while right - left > 1 {
if predicate(a[midpoint]) {
left = midpoint
} else {
right = midpoint
}
midpoint = (left + right) / 2
}
return predicate(a[right]) ? pathAt(right) : (predicate(a[left]) ? pathAt(left) : nil)
}
/**
Request to fetch more content at a given offset.
If there is already an ongoing fetch, does not issue another fetch but does invoke done callback.
:param: count The number of items to fetch.
:param: start The offset (key) at which to start fetching (inclusive).
:param: end The offset (key) at which to end fetching (inclusive).
:param: done A callback invoked when the fetch is done.
*/
public func fetchMore(count: Int, start: String, end: String? = nil, done: (Void -> Void)? = nil) {
if arrayBeforePredicate.count == 0 || isFetchingMore {
done?()
return
}
isFetchingMore = true
let fetchMoreQuery = queryPager(start: start, end: end, limit: count + 1)
fetchMoreQuery.observeSingleEventOfType(.Value, withBlock: { snapshot in
let inflight = Inflight()
self.isFetchingMore = false
self.batching { a in
if let result = snapshot.value as? [String: [String: AnyObject]] {
for (key, dict) in result {
if self.arrayBeforePredicate.find(key) == nil {
let item = self.type.init(key: key)
item.update(dict)
self.didConstructItem(item)
self.arrayBeforePredicate.append(item)
if self.predicate == nil || self.predicate!(item) {
a.append(item)
}
}
}
inflight.hold()
}
}
done?()
})
}
/**
Called to notify the stream that an item in it has changed which may affect the predicate
or sort order. If you have local properties on items that affect streams, consider
adding a listener in your StreamBase subclass that invokes this method.
:param: item The item that changed. Ignores items that are not part of the stream.
*/
public func handleItemChanged(item: BaseItem) {
if item.key == nil || !arrayBeforePredicate.has(item.key!) {
return
}
// This change might invalidate an in-flight batch - eg, when changing the predicate.
finishOutstandingBatch()
var prevPath: NSIndexPath? = nil
if let row = array.find(item.key!) {
prevPath = pathAt(row)
}
let prev = prevPath != nil
let cur = predicate == nil || predicate!(item)
switch (prev, cur) {
case (true, true):
delegate?.streamItemsChanged([prevPath!])
case (true, false):
batching { a in
if let newRow = a.find(item.key!) {
a.removeAtIndex(newRow)
}
}
case (false, true):
batching { a in
if a.find(item.key!) == nil {
a.append(item)
}
}
default:
break
}
}
/**
Subclasses should call this function to make changes to the underlying array of items.
The callback will be invoked with the current state of the array, which the caller
can then manipulate. After some time (@batchDelay), all changes are coallesced and
delegates are notified. Note that the order of elements in the array passed to the
callback is ignored, so appending is always preferred to insertion.
:param: fn The function the client provides to manipulate the array.
*/
func batching(fn: KeyedArray<BaseItem> -> Void) {
if !isBatching {
batchArray.reset(array)
}
fn(batchArray)
scheduleBatch()
}
private func scheduleBatch() {
isBatching = true
if let delay = batchDelay {
timer?.invalidate()
timer = NSTimer.schedule(delay: delay) { [weak self] timer in
self?.finishOutstandingBatch()
}
} else {
finishOutstandingBatch()
}
}
private func finishOutstandingBatch() {
if isBatching {
timer?.invalidate()
isBatching = false
let sortedBatch = batchArray.rawArray.sort(comparator)
StreamBase.applyBatch(array, batch: sortedBatch, delegate: delegate, limit: afterPredicateLimit)
if shouldTellDelegateInitialLoadIsDone == true {
shouldTellDelegateInitialLoadIsDone = nil
delegate?.streamDidFinishInitialLoad(nil)
}
}
}
/**
Given two sorted arrays - the current and next(batch) versions - compute the changes
and invoke the delegate with any updates.
:param: current The existing array before applying the batch. Must be sorted.
:param: batch The new array after applying batch. Must be sorted.
:param: delegate The delegate to notify of differences.
:param: limit A limit that is applied to the batch. NOTE: this is after the predicate is evaluated.
*/
class func applyBatch(current: KeyedArray<BaseItem>, batch: [BaseItem], delegate: StreamBaseDelegate?, limit: Int? = nil) {
var limitedBatch = batch
if let l = limit where batch.count > l {
limitedBatch = Array(limitedBatch[0..<l])
}
let (deletes, adds) = diffFrom(current.rawArray, to: limitedBatch)
current.reset(limitedBatch)
if let d = delegate {
if !deletes.isEmpty || !adds.isEmpty {
d.streamWillChange()
if !deletes.isEmpty {
d.streamItemsDeleted(deletes.map{ NSIndexPath(forRow: $0, inSection: 0) })
}
if !adds.isEmpty {
d.streamItemsAdded(adds.map{ NSIndexPath(forRow: $0, inSection: 0) })
}
d.streamDidChange()
}
}
}
/**
Given sorted arrays <from> and <to>, produce the deletes (indexed in from)
and adds (indexed in to) that are required to transform <from> to <to>.
:param: from The source array for computing differences. Must be sorted.
:param: to The target array for computing differences. Must be sorted.
:returns: A tuple of two arrays. The first is the indices of the deletes
in the from array. The second is the indices of the adds in the to array.
*/
private class func diffFrom(from: [BaseItem], to: [BaseItem]) -> ([Int], [Int]) {
var deletes = [Int]()
var adds = [Int]()
let fromKeys = Set(from.map{ $0.key! })
let toKeys = Set(to.map{ $0.key! })
for (i, item) in from.enumerate() {
if !toKeys.contains(item.key!) {
deletes.append(i)
}
}
for (i, item) in to.enumerate() {
if !fromKeys.contains(item.key!) {
adds.append(i)
}
}
return (deletes, adds)
}
private final func pathAt(row: Int) -> NSIndexPath {
return NSIndexPath(forRow: row, inSection: 0)
}
}
// MARK: SequenceType
extension StreamBase : Indexable {
public typealias Index = Int
public subscript(i: Index) -> BaseItem {
return array[i]
}
public var startIndex: Index {
return array.startIndex
}
public var endIndex: Index {
return array.endIndex
}
}
extension StreamBase : CollectionType { } | mit | b5ae00f7975e2c3fa3a5acbc712bee9f | 33.182903 | 135 | 0.553888 | 4.754701 | false | false | false | false |
scinfu/SwiftSoup | Sources/StreamReader.swift | 1 | 2624 | //
// StreamReader.swift
// SwifSoup
//
// Created by Nabil Chatbi on 08/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
class StreamReader {
let encoding: String.Encoding
let chunkSize: Int
var fileHandle: FileHandle!
let delimData: Data
var buffer: Data
var atEof: Bool
init?(path: String, delimiter: String = "\n", encoding: String.Encoding = .utf8,
chunkSize: Int = 4096) {
guard let fileHandle = FileHandle(forReadingAtPath: path),
let delimData = delimiter.data(using: encoding) else {
return nil
}
self.encoding = encoding
self.chunkSize = chunkSize
self.fileHandle = fileHandle
self.delimData = delimData
self.buffer = Data(capacity: chunkSize)
self.atEof = false
}
deinit {
self.close()
}
/// Return next line, or nil on EOF.
func nextLine() -> String? {
precondition(fileHandle != nil, "Attempt to read from closed file")
// Read data chunks from file until a line delimiter is found:
while !atEof {
if let range = buffer.range(of: delimData) {
// Convert complete line (excluding the delimiter) to a string:
let line = String(data: buffer.subdata(in: 0..<range.lowerBound), encoding: encoding)
// Remove line (and the delimiter) from the buffer:
buffer.removeSubrange(0..<range.upperBound)
return line
}
let tmpData = fileHandle.readData(ofLength: chunkSize)
if tmpData.count > 0 {
buffer.append(tmpData)
} else {
// EOF or read error.
atEof = true
if buffer.count > 0 {
// Buffer contains last line in file (not terminated by delimiter).
let line = String(data: buffer as Data, encoding: encoding)
buffer.count = 0
return line
}
}
}
return nil
}
/// Start reading from the beginning of file.
func rewind() {
fileHandle.seek(toFileOffset: 0)
buffer.count = 0
atEof = false
}
/// Close the underlying file. No reading must be done after calling this method.
func close() {
fileHandle?.closeFile()
fileHandle = nil
}
}
extension StreamReader: Sequence {
func makeIterator() -> AnyIterator<String> {
return AnyIterator {
return self.nextLine()
}
}
}
| mit | 33b87336f90f52e1305046e73cd3bbf6 | 28.47191 | 101 | 0.561571 | 4.743219 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne | 表格拆分/表格拆分/ViewController.swift | 1 | 5349 | //
// ViewController.swift
// 表格拆分
//
// Created by bingoogol on 14/10/2.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
/**
1.在UITableViewController中,如果要实例化视图,直接实例化self.tableView即可
2.乳沟要使用默认的平板表格UITableViewStylePlain,可以不用重写loadView方法
*/
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
let CELL_ID = "MyCell"
let EMBEDVIEW_HEIGHT:CGFloat = 200
let ROW_HEIGHT:CGFloat = 92
var tableView:UITableView!
var embedView:UIView!
// 动画的表格行
var animationRows:NSMutableArray!
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame, style: UITableViewStyle.Plain)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = ROW_HEIGHT
tableView.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(tableView)
embedView = UIView(frame: CGRectMake(0, 0, tableView.bounds.width, EMBEDVIEW_HEIGHT))
embedView.backgroundColor = UIColor.orangeColor()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 15
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID) as MyCell!
if cell == nil {
cell = MyCell(style: UITableViewCellStyle.Default, reuseIdentifier: CELL_ID)
cell.contentView.backgroundColor = UIColor.whiteColor()
cell.selectionStyle = UITableViewCellSelectionStyle.None
}
cell.textLabel?.text = "cell-\(indexPath.row)"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// 选中某一个表格行后,将下方的表格行向下方移动SUBVIEW_HEIGHT的高度
// 未打开,做打开操作
if animationRows == nil {
// 新建一个数组,把所有可能有动画的表格行的indexPath全部记录下来,一遍之后还原
animationRows = NSMutableArray(array: tableView.indexPathsForVisibleRows()!)
// 表格的偏移。注意:表格是继承自UIScrollView,有偏移量
var bottomY = tableView.contentOffset.y + tableView.frame.height
// 计算准备插入子视图的y值
var selectedCell = tableView.cellForRowAtIndexPath(indexPath)!
var subViewY = selectedCell.frame.origin.y + ROW_HEIGHT
// 准备加入子视图的最大y值
var maxSubViewY = bottomY - EMBEDVIEW_HEIGHT
// 判断空间是否够大
if maxSubViewY >= subViewY {
embedView.frame.origin.y = subViewY
// 空间够大。只要挪动选中行下方的表格行即可
UIView.animateWithDuration(0.5, animations: {
for path in self.animationRows {
var cell:MyCell = tableView.cellForRowAtIndexPath(path as NSIndexPath) as MyCell!
var frame = cell.frame
// 记录初始y位置
cell.originY = frame.origin.y
if path.row > indexPath.row {
frame.origin.y += self.EMBEDVIEW_HEIGHT
cell.frame = frame
}
}
})
} else {
embedView.frame.origin.y = maxSubViewY
// 空间不够。上面的要挪,下边也要挪
UIView.animateWithDuration(0.5, animations: {
var delta = subViewY - maxSubViewY
for path in self.animationRows {
var cell:MyCell = tableView.cellForRowAtIndexPath(path as NSIndexPath) as MyCell!
var frame = cell.frame
// 记录初始y位置
cell.originY = frame.origin.y
if path.row > indexPath.row {
frame.origin.y += (self.EMBEDVIEW_HEIGHT - delta)
} else {
frame.origin.y -= delta
}
cell.frame = frame
}
})
}
tableView.insertSubview(embedView, atIndex: 0)
} else {
// 已打开,做复位操作
UIView.animateWithDuration(0.5, animations: {
for path in self.animationRows {
var cell:MyCell = tableView.cellForRowAtIndexPath(path as NSIndexPath) as MyCell!
var frame = cell.frame
frame.origin.y = cell.originY
cell.frame = frame
}
}, completion: { (finished:Bool) in
self.embedView.removeFromSuperview()
self.animationRows = nil
}
)
}
}
} | apache-2.0 | 746fe9369b69ec61703f35932c11d377 | 37.888889 | 109 | 0.550725 | 4.963526 | false | false | false | false |
thiagolioy/Notes | Sources/Note.swift | 1 | 2271 | //
// NoteName.swift
// Notes
//
// Created by Thiago Lioy on 26/08/17.
// Copyright © 2017 com.tplioy. All rights reserved.
//
import Foundation
public struct Note {
public enum Name: String {
case A,B,C,D,E,F,G
func next() -> Name {
switch self {
case .A:
return .B
case .B:
return .C
case .C:
return .D
case .D:
return .E
case .E:
return .F
case .F:
return .G
case .G:
return .A
}
}
}
public enum Intonation: String {
case doubleFlat = "♭♭"
case flat = "♭"
case natural = ""
case sharp = "♯"
case doubleSharp = "𝄪"
}
public enum Interval: Int {
case halfstep
case wholestep
}
public let name: Name
public let intonation: Intonation
public func fullname() -> String{
return name.rawValue + intonation.rawValue
}
public init(name: Name, intonation: Intonation){
self.name = name
self.intonation = intonation
}
}
extension Note: Hashable {
public var hashValue: Int {
return name.hashValue + intonation.hashValue
}
public static func ==(lhs: Note, rhs: Note) -> Bool{
return lhs.name == rhs.name &&
lhs.intonation == rhs.intonation
}
}
extension Note {
public func eharmonicEquivalent() -> EHarmonicNote? {
return EHarmonicEquivalent.equivalent(of: self)
}
public func equivalent(to note: Note) -> Bool{
return eharmonicEquivalent()?.contains(note: note) ?? false
}
}
extension Note {
public func add(interval: Note.Interval) -> Note{
return ChromaticScale.add(interval: interval, to: self)
}
public func minus(interval: Note.Interval) -> Note{
return ChromaticScale.minus(interval: interval, to: self)
}
}
extension Note {
public func next() -> Note{
return ChromaticScale.next(of: self)
}
public func previous() -> Note{
return ChromaticScale.previous(of: self)
}
}
| mit | 93a919bb0001c52ddfecf6cf58c4383b | 20.721154 | 67 | 0.529438 | 4.129799 | false | false | false | false |
anas10/Monumap | Monumap/Wireframes/NearbyWireframe.swift | 1 | 1146 | //
// NearbyWireframe.swift
// Monumap
//
// Created by Anas Ait Ali on 12/03/2017.
// Copyright © 2017 Anas Ait Ali. All rights reserved.
//
import UIKit
typealias NearbyViewModelConstructorType = (NearbyViewController) -> (NearbyViewModel)
protocol NearbyWireframeType {
var storyboard : UIStoryboard! { get }
var provider: Networking { get }
init(storyboard: UIStoryboard, provider: Networking)
func instantiateInitialViewController(dataManager: DataManager) -> NearbyViewController
}
class NearbyWireframe: NearbyWireframeType {
let storyboard: UIStoryboard!
let provider : Networking
required init(storyboard: UIStoryboard = UIStoryboard.main(), provider: Networking) {
self.storyboard = storyboard
self.provider = provider
}
func instantiateInitialViewController(dataManager: DataManager) -> NearbyViewController {
let vc = self.storyboard.viewControllerWithID(.nearbyViewControllerID) as! NearbyViewController
vc.viewModelConstructor = { _ in
NearbyViewModel(provider: self.provider, dataManager: dataManager)
}
return vc
}
}
| apache-2.0 | 3dc58bddeed8b59ef4fb41319491dfa3 | 29.131579 | 103 | 0.724017 | 4.978261 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Home/Controllers/HomeViewController + Delegates.swift | 1 | 6927 | //
// HomeViewController + Delegates.swift
// PennMobile
//
// Created by Josh Doman on 3/27/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
import WebKit
import SafariServices
import SwiftUI
extension HomeViewController: HomeViewModelDelegate {}
// MARK: - Reservation Delegate
extension HomeViewController: GSRDeletable {
func deleteReservation(_ bookingID: String) {
deleteReservation(bookingID) { (successful) in
if successful {
guard let reservationItem = self.tableViewModel.getItems(for: [HomeItemTypes.instance.reservations]).first as? HomeReservationsCellItem else { return }
reservationItem.reservations = reservationItem.reservations.filter { $0.bookingId != bookingID }
if reservationItem.reservations.isEmpty {
self.removeItem(reservationItem)
} else {
self.reloadItem(reservationItem)
}
}
}
}
func deleteReservation(_ reservation: GSRReservation) {
deleteReservation(reservation.bookingId)
}
}
// MARK: - GSR Quick Book Delegate
extension HomeViewController: GSRBookable {
func handleBookingSelected(_ booking: GSRBooking) {
confirmBookingWanted(booking)
}
private func confirmBookingWanted(_ booking: GSRBooking) {
let message = "Booking \(booking.roomName) from \(booking.getLocalTimeString())"
let alert = UIAlertController(title: "Confirm Booking",
message: message,
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancelAction)
alert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (_) in
self.handleBookingRequested(booking)
}))
present(alert, animated: true)
}
private func handleBookingRequested(_ booking: GSRBooking) {
// if GSRUser.hasSavedUser() {
// booking.user = GSRUser.getUser()
// submitBooking(for: booking) { (completion) in
// self.fetchCellData(for: [HomeItemTypes.instance.studyRoomBooking])
// }
// } else {
// let glc = GSRLoginController()
// glc.booking = booking
// let nvc = UINavigationController(rootViewController: glc)
// present(nvc, animated: true, completion: nil)
// }
}
}
// MARK: - URL Selected
extension HomeViewController {
func handleUrlPressed(urlStr: String, title: String, item: ModularTableViewItem, shouldLog: Bool) {
self.tabBarController?.title = "Home"
if let url = URL(string: urlStr) {
let vc = SFSafariViewController(url: url)
navigationController?.present(vc, animated: true)
FirebaseAnalyticsManager.shared.trackEvent(action: .viewWebsite, result: .none, content: urlStr)
}
if shouldLog {
logInteraction(item: item)
}
}
}
// MARK: - Laundry Delegate
extension HomeViewController {
var allowMachineNotifications: Bool {
return true
}
}
// MARK: - Dining Delegate
extension HomeViewController {
func handleVenueSelected(_ venue: DiningVenue) {
let hostingView = UIHostingController(rootView: DiningVenueDetailView(for: venue)
.environmentObject(DiningViewModelSwiftUI.instance))
navigationController?.pushViewController(hostingView, animated: true)
}
func handleSettingsTapped(venues: [DiningVenue]) {
let diningSettings = DiningCellSettingsController()
diningSettings.setupFromVenues(venues: venues)
diningSettings.delegate = self
let nvc = UINavigationController(rootViewController: diningSettings)
showDetailViewController(nvc, sender: nil)
}
}
extension HomeViewController: GSRLocationSelectable {
func handleSelectedLocation(_ location: GSRLocation) {
let gc = GSRController()
gc.startingLocation = location
gc.title = "Study Room Booking"
navigationController?.pushViewController(gc, animated: true)
FirebaseAnalyticsManager.shared.trackEvent(action: "Tap Home GSR Location", result: "Tap Home GSR Location", content: "View \(location.name)")
}
}
extension HomeViewController: NewsArticleSelectable {
func handleSelectedArticle(_ article: NewsArticle) {
let nvc = NativeNewsViewController()
nvc.article = article
nvc.title = "News"
navigationController?.pushViewController(nvc, animated: true)
}
}
extension HomeViewController: FeatureNavigatable {
func navigateToFeature(feature: Feature, item: ModularTableViewItem) {
let vc = ControllerModel.shared.viewController(for: feature)
vc.title = feature.rawValue
self.navigationController?.pushViewController(vc, animated: true)
logInteraction(item: item)
}
}
// MARK: - Interaction Logging
extension HomeViewController {
fileprivate func logInteraction(item: ModularTableViewItem) {
let index = self.tableViewModel.items.firstIndex { (thisItem) -> Bool in
return thisItem.equals(item: item)
}
if let index = index {
let cellType = type(of: item) as! HomeCellItem.Type
var id: String?
if let identifiableItem = item as? LoggingIdentifiable {
id = identifiableItem.id
}
FeedAnalyticsManager.shared.trackInteraction(cellType: cellType.jsonKey, index: index, id: id)
}
}
}
// MARK: - Invite delegate
extension HomeViewController: GSRInviteSelectable {
func handleInviteSelected(_ invite: GSRGroupInvite, _ accept: Bool) {
GSRGroupNetworkManager.instance.respondToInvite(invite: invite, accept: accept) { (success) in
if success {
guard let inviteItem = self.tableViewModel.getItems(for: [HomeItemTypes.instance.invites]).first as? HomeGroupInvitesCellItem else { return }
inviteItem.invites = inviteItem.invites.filter { $0.id != invite.id }
DispatchQueue.main.async {
if inviteItem.invites.isEmpty {
self.removeItem(inviteItem)
} else {
self.reloadItem(inviteItem)
}
}
} else {
let message = "An error occured when responding to this invite. Please try again later."
let alert = UIAlertController(title: invite.group, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
| mit | 16d5828b1c1ac839da63a4b1b09cd23d | 37.692737 | 167 | 0.640485 | 4.799723 | false | false | false | false |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/AlvarezCorralMiguel/prog3.swift | 1 | 875 | /*
Nombre del programa: Producto de numeros pares
Autor: Alvarez Corral Miguel Angel 13211384
Fecha de inicio: 13-02-2017
Descripción:
Introducir un N enteros. Calcular e imprimir el producto de los numeros pares.
*/
//Importación de librerías
import Foundation
//declaración de constantes
let N = 15 //Se puede modifcar el valor de N para obtener distintos resultados.
//contador
var i = 1
//variable donde se guarda el producto de los N enteros
var prod = 1
//variable donde se guardara la cadena del producto
var texto = ""
print("Producto de N valores pares")
print("N = \(N)")
//producto de los N valores
while i<=N
{ //si el residuo de i es cero se multiplica
if (i%2) == 0
{
prod = prod * i
//Concatenacion del producto
if i != N-1
{texto += "\(i)*"}
else
{texto += "\(i)"}
}
//incremento
i = i+1
}
print("\(texto)=\(prod)")
| gpl-3.0 | 2d867a82cd899742c206e634d98fbaf4 | 17.531915 | 80 | 0.677382 | 2.884106 | false | false | false | false |
exchangegroup/UnderKeyboard | UnderKeyboard/UnderKeyboardObserver.swift | 2 | 2565 | import UIKit
/**
Detects appearance of software keyboard and calls the supplied closures that can be used for changing the layout and moving view from under the keyboard.
*/
public final class UnderKeyboardObserver: NSObject {
public typealias AnimationCallback = (_ height: CGFloat) -> ()
let notificationCenter: NotificationCenter
/// Function that will be called before the keyboard is shown and before animation is started.
public var willAnimateKeyboard: AnimationCallback?
/// Function that will be called inside the animation block. This can be used to call `layoutIfNeeded` on the view.
public var animateKeyboard: AnimationCallback?
/// Current height of the keyboard. Has value `nil` if unknown.
public var currentKeyboardHeight: CGFloat?
/// Creates an instance of the class
public override init() {
notificationCenter = NotificationCenter.default
super.init()
}
deinit {
stop()
}
/// Start listening for keyboard notifications.
public func start() {
stop()
notificationCenter.addObserver(self, selector: #selector(UnderKeyboardObserver.keyboardNotification(_:)), name:UIResponder.keyboardWillShowNotification, object: nil);
notificationCenter.addObserver(self, selector: #selector(UnderKeyboardObserver.keyboardNotification(_:)), name:UIResponder.keyboardWillHideNotification, object: nil);
}
/// Stop listening for keyboard notifications.
public func stop() {
notificationCenter.removeObserver(self)
}
// MARK: - Notification
@objc func keyboardNotification(_ notification: Notification) {
let isShowing = notification.name == UIResponder.keyboardWillShowNotification
if let userInfo = (notification as NSNotification).userInfo,
let height = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height,
let duration: TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber {
let correctedHeight = isShowing ? height : 0
willAnimateKeyboard?(correctedHeight)
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: UIView.AnimationOptions(rawValue: animationCurveRawNSN.uintValue),
animations: { [weak self] in
self?.animateKeyboard?(correctedHeight)
},
completion: nil
)
currentKeyboardHeight = correctedHeight
}
}
}
| mit | 8b5f855004e74f1720551e5dfc6a88f8 | 35.642857 | 170 | 0.730214 | 5.777027 | false | false | false | false |
sumitokamoi/Runnable | Example/Tests/Tests.swift | 1 | 1158 | // https://github.com/Quick/Quick
import Quick
import Nimble
import Runnable
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | d5188f99465677a2935160dd92501a38 | 22.04 | 60 | 0.356771 | 5.538462 | false | false | false | false |
salesawagner/wascar | Sources/Core/Base/WCARTableViewController.swift | 1 | 2292 | //
// WCARTableViewController.swift
// wascar
//
// Created by Wagner Sales on 23/11/16.
// Copyright © 2016 Wagner Sales. All rights reserved.
//
import UIKit
//**************************************************************************************************
//
// MARK: - Constants -
//
//**************************************************************************************************
//**************************************************************************************************
//
// MARK: - Definitions -
//
//**************************************************************************************************
//**************************************************************************************************
//
// MARK: - Class -
//
//**************************************************************************************************
class WCARTableViewController: WCARViewController {
//**************************************************
// MARK: - Properties
//**************************************************
@IBOutlet weak var tableView: UITableView!
//**************************************************
// MARK: - Constructors
//**************************************************
//**************************************************
// MARK: - Private Methods
//**************************************************
//**************************************************
// MARK: - Internal Methods
//**************************************************
internal func setuptableView() {
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.sectionFooterHeight = 0
self.tableView.tableFooterView = UIView()
self.tableView.showsVerticalScrollIndicator = false
self.tableView.showsHorizontalScrollIndicator = false
self.tableView.backgroundColor = UIColor.clear
}
//**************************************************
// MARK: - Public Methods
//**************************************************
//**************************************************
// MARK: - Override Public Methods
//**************************************************
override func viewDidLoad() {
super.viewDidLoad()
}
override func setupUI() {
super.setupUI()
self.setuptableView()
}
}
| mit | 7f0d9c1a4576ffaac92d1cf4e6de150c | 29.546667 | 100 | 0.308599 | 7.006116 | false | false | false | false |
scoremedia/Fisticuffs | Tests/FisticuffsTests/BindingHandlersSpec.swift | 1 | 6395 | //
// BindingHandlersSpec.swift
// Fisticuffs
//
// Created by Darren Clark on 2016-02-16.
// Copyright © 2016 theScore. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import Fisticuffs
class BindingHandlersSpec: QuickSpec {
override func spec() {
var backingVariable = ""
var property: BidirectionalBindableProperty<BindingHandlersSpec, String>!
beforeEach {
property = BidirectionalBindableProperty(
control: self,
getter: { _ in backingVariable },
setter: { _, value in backingVariable = value }
)
}
describe("TransformBindingHandler") {
it("should support transforming values to the desired property type") {
let observable = Observable(0)
property.bind(observable, BindingHandlers.transform { input in "\(input)" })
observable.value = 11
expect(backingVariable) == "11"
}
it("should support transforming the property type back to the data type") {
let observable = Observable(0)
property.bind(observable, BindingHandlers.transform({ input in "\(input)" }, reverse: { str in Int(str) ?? 0 }))
backingVariable = "42"
property.pushChangeToObservable()
expect(observable.value) == 42
}
}
describe("ThrottleBindingHandler") {
it("should push changes to the observable after a delay") {
let observable = Observable("")
property.bind(observable, BindingHandlers.throttle(delayBy: .milliseconds(500)))
backingVariable = "1"
property.pushChangeToObservable()
expect(observable.value) == ""
expect(observable.value).toEventually(equal("1"), timeout: .seconds(1))
}
it("should push the most recent value to the observable after a delay") {
let observable = Observable("")
property.bind(observable, BindingHandlers.throttle(delayBy: .milliseconds(500)))
var numberOfTimesObservableIsNotified = 0
var publishedValues = [String]()
let options = SubscriptionOptions(notifyOnSubscription: false, when: .afterChange)
_ = observable.subscribe(options) { _, newValue in
numberOfTimesObservableIsNotified += 1
publishedValues.append(newValue)
}
for i in 1...10 {
backingVariable = "\(i)"
property.pushChangeToObservable()
}
expect(numberOfTimesObservableIsNotified).toEventually(equal(1), timeout: .seconds(2))
expect(publishedValues).toEventually(equal(["10"]), timeout: .seconds(2))
}
it("should push a value to the observable exactly once") {
let observable = Observable("")
var numberOfTimesObservableIsNotified = 0
let options = SubscriptionOptions(notifyOnSubscription: false, when: .afterChange)
_ = observable.subscribe(options) { _, newValue in
numberOfTimesObservableIsNotified += 1
}
property.bind(observable, BindingHandlers.throttle(delayBy: .milliseconds(100)))
backingVariable = "test"
property.pushChangeToObservable()
waitUntil(timeout: .seconds(1)) { done in
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(500), execute: done)
}
expect(numberOfTimesObservableIsNotified) == 1
}
it("should transform the value") {
let observable: Observable<Int?> = Observable(nil)
let toIntBindingHandler: BindingHandler<BindingHandlersSpec, Int?, String> = BindingHandlers.transform(
{ data in
if let data = data { return String(data) }
return ""
},
reverse: { Int($0) }
)
property.bind(observable, ThrottleBindingHandler(delayBy: .milliseconds(500), bindingHandler: toIntBindingHandler))
backingVariable = "50"
property.pushChangeToObservable()
expect(observable.value).toEventually(equal(Optional.some(50)), timeout: .seconds(1))
}
it("should update control value immediately when observable value changes") {
let observable = Observable("")
property.bind(observable, BindingHandlers.throttle(delayBy: .seconds(1)))
observable.value = "test"
expect(backingVariable) == observable.value
}
it("should support computed subscribable") {
let observable = Observable("")
let computed: Computed<String> = Computed {
observable.value.uppercased()
}
property.bind(observable, BindingHandlers.throttle(delayBy: .milliseconds(500)))
backingVariable = "hello"
property.pushChangeToObservable()
expect(computed.value).toEventually(equal(backingVariable.uppercased()), timeout: .seconds(1))
}
it("should support optionals") {
var optionalBackingVariable: String?
let optionalProperty: BidirectionalBindableProperty<BindingHandlersSpec, String?> = BidirectionalBindableProperty(
control: self,
getter: {_ in optionalBackingVariable},
setter: { (_, value) in optionalBackingVariable = value}
)
let observable = Observable("")
optionalProperty.bind(observable, BindingHandlers.throttle(delayBy: .milliseconds(500)))
optionalBackingVariable = "test"
optionalProperty.pushChangeToObservable()
expect(observable.value) == ""
expect(observable.value).toEventually(equal(optionalBackingVariable), timeout: .seconds(1))
}
}
}
}
| mit | fb84e4c427f799650361ebed9ca3f6de | 36.83432 | 131 | 0.567251 | 5.56 | false | false | false | false |
zhuhaow/SpechtLite | ProxyConfig/ProxyConfig/main.swift | 1 | 3802 | import Foundation
import SystemConfiguration
let version = "0.4.0"
func main(_ args: [String]) {
var port: Int = 0
var flag: Bool = false
if args.count > 2 {
guard let _port = Int(args[1]) else {
print("ERROR: port is invalid.")
exit(EXIT_FAILURE)
}
guard args[2] == "enable" || args[2] == "disable" else {
print("ERROR: flag is invalid.")
exit(EXIT_FAILURE)
}
port = _port
flag = args[2] == "enable"
} else if args.count == 2 {
if args[1] == "version" {
print(version)
exit(EXIT_SUCCESS)
}
} else {
print("Usage: ProxyConfig <port> <enable/disable>")
exit(EXIT_FAILURE)
}
var authRef: AuthorizationRef? = nil
let authFlags: AuthorizationFlags = [.extendRights, .interactionAllowed, .preAuthorize]
let authErr = AuthorizationCreate(nil, nil, authFlags, &authRef)
guard authErr == noErr else {
print("Error: Failed to create administration authorization due to error \(authErr).")
exit(EXIT_FAILURE)
}
guard authRef != nil else {
print("Error: No authorization has been granted to modify network configuration.")
exit(EXIT_FAILURE)
}
if let prefRef = SCPreferencesCreateWithAuthorization(nil, "SpechtLite" as CFString, nil, authRef),
let sets = SCPreferencesGetValue(prefRef, kSCPrefNetworkServices) {
for key in sets.allKeys {
let dict = sets.object(forKey: key) as? NSDictionary
let hardware = ((dict?["Interface"]) as? NSDictionary)?["Hardware"] as? String
if hardware == "AirPort" || hardware == "Ethernet" {
let ip = flag ? "127.0.0.1" : ""
let enableInt = flag ? 1 : 0
var proxySettings: [String:AnyObject] = [:]
proxySettings[kCFNetworkProxiesHTTPProxy as String] = ip as AnyObject
proxySettings[kCFNetworkProxiesHTTPEnable as String] = enableInt as AnyObject
proxySettings[kCFNetworkProxiesHTTPSProxy as String] = ip as AnyObject
proxySettings[kCFNetworkProxiesHTTPSEnable as String] = enableInt as AnyObject
proxySettings[kCFNetworkProxiesSOCKSProxy as String] = ip as AnyObject
proxySettings[kCFNetworkProxiesSOCKSEnable as String] = enableInt as AnyObject
if flag {
proxySettings[kCFNetworkProxiesHTTPPort as String] = port as AnyObject
proxySettings[kCFNetworkProxiesHTTPSPort as String] = port as AnyObject
proxySettings[kCFNetworkProxiesSOCKSPort as String] = port + 1 as AnyObject
} else {
proxySettings[kCFNetworkProxiesHTTPPort as String] = nil
proxySettings[kCFNetworkProxiesHTTPSPort as String] = nil
proxySettings[kCFNetworkProxiesSOCKSPort as String] = nil
}
proxySettings[kCFNetworkProxiesExceptionsList as String] = [
"192.168.0.0/16",
"10.0.0.0/8",
"172.16.0.0/12",
"127.0.0.1",
"localhost",
"*.local"
] as AnyObject
let path = "/\(kSCPrefNetworkServices)/\(key)/\(kSCEntNetProxies)"
SCPreferencesPathSetValue(prefRef, path as CFString, proxySettings as CFDictionary)
}
}
SCPreferencesCommitChanges(prefRef)
SCPreferencesApplyChanges(prefRef)
}
AuthorizationFree(authRef!, AuthorizationFlags())
exit(EXIT_SUCCESS)
}
main(CommandLine.arguments)
| gpl-3.0 | 04056f27b789da0f77bef5996d9806f1 | 39.021053 | 103 | 0.576802 | 4.861893 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Views/TextLabel.swift | 1 | 1353 | // Copyright (c) 2018 Token Browser, Inc
//
// 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
import SweetUIKit
class TextLabel: UILabel {
convenience init(_ text: String) {
self.init(withAutoLayout: true)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2.5
paragraphStyle.paragraphSpacing = -4
let attributes: [NSAttributedStringKey: Any] = [
.font: Theme.preferredRegular(),
.foregroundColor: Theme.darkTextColor,
.paragraphStyle: paragraphStyle
]
adjustsFontForContentSizeCategory = true
attributedText = NSMutableAttributedString(string: text, attributes: attributes)
numberOfLines = 0
}
}
| gpl-3.0 | 38d545029a2c73d8f57e72f1a6dec995 | 34.605263 | 88 | 0.705839 | 4.849462 | false | false | false | false |
edulpn/giphysearch | giphysearch/giphysearch/Classes/GifSearchViewController.swift | 1 | 3881 | //
// GifSearchViewController.swift
// giphysearch
//
// Created by Eduardo Pinto on 01/12/16.
// Copyright © 2016 Eduardo Pinto. All rights reserved.
//
import UIKit
class GifSearchViewController: UIViewController, GifView, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
var gifs : [GifDisplay] = [] {
didSet {
tableView.reloadData()
}
}
var gifPresenter : GifPresenter?
let gifCellIdentifier : String = "gifCellIdentifier"
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var searchTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(UINib(nibName: "GifTableViewCell", bundle: nil), forCellReuseIdentifier: gifCellIdentifier)
loadingView.isHidden = true
searchTextField.delegate = self
guard (gifPresenter != nil) else {
//We reached a place where the presenter dependency should be already injected, so return
return
}
gifPresenter!.searchGifs(query: self.searchTextField.text!)
}
// MARK: - Table View Delegate/Datasource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gifs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: gifCellIdentifier, for: indexPath) as! GifTableViewCell
let gifDisplay = gifs[indexPath.row]
cell.configureGifCell(gifUrl: gifDisplay.imageUrl, source: gifDisplay.source, date: gifDisplay.date)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200.0
}
// MARK: - GifView Protocol
func startLoading() {
loadingView.isHidden = false;
}
func finishLoading() {
loadingView.isHidden = true;
}
func setSearchResult(gifs: [GifDisplay]) {
self.gifs = gifs
}
func setSearchError(error: String) {
let alert = UIAlertController(title: "", message: error, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: {})
}))
present(alert, animated: true, completion: {})
}
func setSearchEmpty (message: String) {
let alert = UIAlertController(title: "", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: {})
}))
present(alert, animated: true, completion: {})
}
// MARK: - Text Field Delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
guard (gifPresenter != nil) else {
//Again, the presenter dependency should be already injected, so return
return
}
gifPresenter!.searchGifs(query: textField.text!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | c3d74a0463875cd2b3b8e133ea79142d | 28.618321 | 123 | 0.61134 | 5.271739 | false | false | false | false |
ualch9/onebusaway-iphone | OneBusAway/externals/PromiseKit/Sources/Error.swift | 3 | 5473 | import Foundation
public enum PMKError: Error {
/**
The ErrorType for a rejected `join`.
- Parameter 0: The promises passed to this `join` that did not *all* fulfill.
- Note: The array is untyped because Swift generics are fussy with enums.
*/
case join([AnyObject])
/**
The completionHandler with form (T?, ErrorType?) was called with (nil, nil)
This is invalid as per Cocoa/Apple calling conventions.
*/
case invalidCallingConvention
/**
A handler returned its own promise. 99% of the time, this is likely a
programming error. It is also invalid per Promises/A+.
*/
case returnedSelf
/** `when()` was called with a concurrency of <= 0 */
case whenConcurrentlyZero
/** AnyPromise.toPromise failed to cast as requested */
case castError(Any.Type)
}
extension PMKError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidCallingConvention:
return "A closure was called with an invalid calling convention, probably (nil, nil)"
case .returnedSelf:
return "A promise handler returned itself"
case .whenConcurrentlyZero, .join:
return "Bad input was provided to a PromiseKit function"
case .castError(let type):
return "Promise chain sequence failed to cast an object to \(type)."
}
}
}
public enum PMKURLError: Error {
/**
The URLRequest succeeded but a valid UIImage could not be decoded from
the data that was received.
*/
case invalidImageData(URLRequest, Data)
/**
The HTTP request returned a non-200 status code.
*/
case badResponse(URLRequest, Data?, URLResponse?)
/**
The data could not be decoded using the encoding specified by the HTTP
response headers.
*/
case stringEncoding(URLRequest, Data, URLResponse)
/**
Usually the `URLResponse` is actually an `HTTPURLResponse`, if so you
can access it using this property. Since it is returned as an unwrapped
optional: be sure.
*/
public var NSHTTPURLResponse: Foundation.HTTPURLResponse! {
switch self {
case .invalidImageData:
return nil
case .badResponse(_, _, let rsp):
return (rsp as! Foundation.HTTPURLResponse)
case .stringEncoding(_, _, let rsp):
return (rsp as! Foundation.HTTPURLResponse)
}
}
}
extension PMKURLError: LocalizedError {
public var errorDescription: String? {
switch self {
case let .badResponse(rq, data, rsp):
if let data = data, let str = String(data: data, encoding: .utf8), let rsp = rsp {
return "PromiseKit: badResponse: \(rq): \(rsp)\n\(str)"
} else {
fallthrough
}
default:
return "\(self)"
}
}
}
public enum JSONError: Error {
/// The JSON response was different to that requested
case unexpectedRootNode(Any)
}
//////////////////////////////////////////////////////////// Cancellation
public protocol CancellableError: Error {
var isCancelled: Bool { get }
}
#if !SWIFT_PACKAGE
private struct ErrorPair: Hashable {
let domain: String
let code: Int
init(_ d: String, _ c: Int) {
domain = d; code = c
}
func hash(into hasher: inout Hasher) {
hasher.combine(domain)
hasher.combine(code)
}
}
private func ==(lhs: ErrorPair, rhs: ErrorPair) -> Bool {
return lhs.domain == rhs.domain && lhs.code == rhs.code
}
extension NSError {
@objc public class func cancelledError() -> NSError {
let info = [NSLocalizedDescriptionKey: "The operation was cancelled"]
return NSError(domain: PMKErrorDomain, code: PMKOperationCancelled, userInfo: info)
}
/**
- Warning: You must call this method before any promises in your application are rejected. Failure to ensure this may lead to concurrency crashes.
- Warning: You must call this method on the main thread. Failure to do this may lead to concurrency crashes.
*/
@objc public class func registerCancelledErrorDomain(_ domain: String, code: Int) {
cancelledErrorIdentifiers.insert(ErrorPair(domain, code))
}
/// - Returns: true if the error represents cancellation.
@objc public var isCancelled: Bool {
return (self as Error).isCancelledError
}
}
private var cancelledErrorIdentifiers = Set([
ErrorPair(PMKErrorDomain, PMKOperationCancelled),
ErrorPair(NSCocoaErrorDomain, NSUserCancelledError),
ErrorPair(NSURLErrorDomain, NSURLErrorCancelled),
])
#endif
extension Error {
public var isCancelledError: Bool {
if let ce = self as? CancellableError {
return ce.isCancelled
} else {
#if SWIFT_PACKAGE
return false
#else
let ne = self as NSError
return cancelledErrorIdentifiers.contains(ErrorPair(ne.domain, ne.code))
#endif
}
}
}
//////////////////////////////////////////////////////// Unhandled Errors
class ErrorConsumptionToken {
var consumed = false
let error: Error
init(_ error: Error) {
self.error = error
}
deinit {
if !consumed {
#if os(Linux) || os(Android)
PMKUnhandledErrorHandler(error)
#else
PMKUnhandledErrorHandler(error as NSError)
#endif
}
}
}
| apache-2.0 | 7fbbf2debb57f2558f5cab42e32748a1 | 27.957672 | 152 | 0.624155 | 4.669795 | false | false | false | false |
hulinSun/MyRx | MyRx/MyRx/Classes/Main/View/RecommendCell.swift | 1 | 2382 | //
// RecommendCell.swift
// MyRx
//
// Created by Hony on 2017/1/5.
// Copyright © 2017年 Hony. All rights reserved.
//
import UIKit
import UIColor_Hex_Swift
class RecommendCell: UITableViewCell {
fileprivate lazy var recommendView: RecommendView = {
let i = RecommendView.loadFromNib()
return i
}()
fileprivate lazy var lay1: CALayer = {
let i = CALayer()
i.backgroundColor = UIColor("#f1f1f2").cgColor
i.anchorPoint = CGPoint.zero
i.bounds = CGRect(x: 0, y: 0, width: UIConst.screenWidth, height: 0.7)
return i
}()
fileprivate lazy var lay2: CALayer = {
let i = CALayer()
i.backgroundColor = UIColor("#e3e3e5").cgColor
i.anchorPoint = CGPoint.zero
i.bounds = CGRect(x: 0, y: 0, width: UIConst.screenWidth, height: 0.7)
return i
}()
var topic: Topic?{
didSet{
// 赋值
recommendView.topic = topic
}
}
fileprivate lazy var moreBtn: UIButton = {
let i = UIButton()
i.setTitle("更多推荐", for: .normal)
i.titleLabel?.font = UIFont.systemFont(ofSize: 15)
i.setTitleColor(.lightGray, for: .normal)
i.backgroundColor = .white
return i
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(recommendView)
contentView.addSubview(moreBtn)
contentView.backgroundColor = UIColor("#fafafa")
recommendView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(10)
make.left.right.equalToSuperview()
make.height.equalTo(222)
}
moreBtn.snp.makeConstraints { (make) in
make.left.right.equalToSuperview()
make.height.equalTo(35)
make.top.equalTo(recommendView.snp.bottom)
}
}
override func layoutSubviews() {
super.layoutSubviews()
lay1.position = CGPoint(x: 0, y: 230)
self.layer.addSublayer(lay1)
lay2.position = CGPoint(x: 0, y: 266.3)
self.layer.addSublayer(lay2)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 501beca9cfa0c2cac89fb0d2ab45973e | 27.518072 | 78 | 0.589776 | 4.264865 | false | false | false | false |
BenziAhamed/Tracery | Common/Parser.Gen2.swift | 1 | 19225 | //
// Parser.Gen2.swift
// Tracery
//
// Created by Benzi on 25/03/17.
// Copyright © 2017 Benzi Ahamed. All rights reserved.
//
import Foundation
extension Parser {
static func gen2(_ tokens: [Token]) throws -> [ParserNode] {
return try gen2(tokens[0..<tokens.count])
}
// parses rules, tags, weights and plaintext
static func gen2(_ tokens: ArraySlice<Token>) throws -> [ParserNode] {
var index = tokens.startIndex
var endIndex = tokens.endIndex
func advance() {
index += 1
}
var currentToken: Token? {
return index < endIndex ? tokens[index] : nil
}
var nextToken: Token? {
return index+1 < endIndex ? tokens[index+1] : nil
}
func parseOptionalText() -> String? {
guard let token = currentToken, case let .text(text) = token else { return nil }
advance()
return text
}
func parseText(_ error: @autoclosure () -> String? = nil) throws -> String {
guard let token = currentToken, case let .text(text) = token else {
throw ParserError.error(error() ?? "expected text")
}
advance()
return text
}
func parseModifiers(for rule: String) throws -> [Modifier] {
var modifiers = [Modifier]()
while let token = currentToken, token == .DOT {
try parse(.DOT)
let modName = try parseText("expected modifier name after . in rule '\(rule)'")
var params = [ValueCandidate]()
if currentToken == .LEFT_ROUND_BRACKET {
try parse(.LEFT_ROUND_BRACKET)
let argsList = try parseFragmentList(separator: .COMMA, context: "parameter", stopParsingFragmentBlockOnToken: Token.RIGHT_ROUND_BRACKET)
params = argsList.map {
return ValueCandidate.init(nodes: $0)
}
try parse(.RIGHT_ROUND_BRACKET, "expected ) to close modifier call")
}
modifiers.append(Modifier(name: modName, parameters: params))
}
return modifiers
}
func parseRule() throws -> [ParserNode] {
var nodes = [ParserNode]()
try parseAny([.HASH, .LEFT_CURLY_BRACKET])
// a rule may contain sub rules
// or tags
while let token = currentToken, token == .LEFT_SQUARE_BRACKET {
nodes.append(contentsOf: try parseTag())
}
// empty rules evaluate to empty strings
// ##, {}
if currentToken == .HASH || currentToken == .RIGHT_CURLY_BRACKET {
try parseAny([.HASH, .RIGHT_CURLY_BRACKET])
nodes.append(.text(""))
return nodes
}
// parses a comma separated list of value candidates
// (a,b,c) -> value candidates [a,b,c]
func parseValueCandidateList(context: String) throws -> [ValueCandidate] {
try parse(.LEFT_ROUND_BRACKET)
let candidates = try parseFragmentList(
separator: .COMMA,
context: context,
stopParsingFragmentBlockOnToken: .RIGHT_ROUND_BRACKET
)
.map {
return ValueCandidate(nodes: $0)
}
try parse(.RIGHT_ROUND_BRACKET, "expected ) after \(context) list")
return candidates
}
let name = parseOptionalText()
switch (name, currentToken) {
case (nil, .some(Token.LEFT_ROUND_BRACKET)):
// inline rules
// #(a,b,c)#
// {(a,b,c).mod1.mod2}
let candidates = try parseValueCandidateList(context: "inline rule candidate")
let mods = try parseModifiers(for: "inline rule")
nodes.append(.any(values: candidates, selector: candidates.selector(), mods: mods))
try parseAny([.HASH, .RIGHT_CURLY_BRACKET], "expected # or } after inline rule definition")
return nodes
case (let .some(name), .some(Token.LEFT_ROUND_BRACKET)):
let candidates = try parseValueCandidateList(context: "rule candidate")
nodes.append(.createRule(name: name, values: candidates))
try parseAny([.HASH, .RIGHT_CURLY_BRACKET], "expected # or } after new rule definition")
return nodes
case (_, _):
// #rule?.mod1.mod2().mod3(list)#
let name = name ?? ""
let modifiers = try parseModifiers(for: name)
nodes.append(ParserNode.rule(name: name, mods: modifiers))
try parseAny([.HASH, .RIGHT_CURLY_BRACKET], "closing # or } not found for rule '\(name)'")
return nodes
}
}
func parseTag() throws -> [ParserNode] {
var nodes = [ParserNode]()
try parse(.LEFT_SQUARE_BRACKET)
scanning: while let token = currentToken {
switch token {
case Token.HASH, Token.LEFT_CURLY_BRACKET:
nodes.append(contentsOf: try parseRule())
case Token.LEFT_SQUARE_BRACKET:
nodes.append(contentsOf: try parseTag())
case Token.RIGHT_SQUARE_BRACKET:
break scanning
default:
let name = try parseText("expected tag name")
try parse(.COLON, "expected : after tag '\(name)'")
let values = try parseFragmentList(separator: .COMMA, context: "tag value", stopParsingFragmentBlockOnToken: Token.RIGHT_SQUARE_BRACKET)
if values[0].count == 0 {
throw ParserError.error("expected a tag value")
}
let tagValues = values.map { return ValueCandidate.init(nodes: $0) }
nodes.append(ParserNode.tag(name: name, values: tagValues))
}
}
try parse(.RIGHT_SQUARE_BRACKET)
return nodes
}
func parseWeight() throws -> ParserNode {
try parse(.COLON)
// if there is a next token, and it is a number
// then we have a weight, else treat colon as raw text
guard let token = currentToken, case let .number(value) = token else {
return .text(":")
}
advance() // since we can consume the number
return .weight(value: value)
}
func parseCondition() throws -> ParserCondition {
var lhs = try parseFragmentSequence()
stripTrailingSpace(from: &lhs)
let op: ParserConditionOperator
var rhs: [ParserNode]
switch currentToken {
case let x where x == Token.EQUAL_TO:
advance()
parseOptional(.SPACE)
op = .equalTo
rhs = try parseFragmentSequence()
if rhs.count == 0 {
throw ParserError.error("expected rule or text after == in condition")
}
case let x where x == Token.NOT_EQUAL_TO:
advance()
parseOptional(.SPACE)
op = .notEqualTo
rhs = try parseFragmentSequence()
if rhs.count == 0 {
throw ParserError.error("expected rule or text after != in condition")
}
case let x where x == Token.KEYWORD_IN || x == Token.KEYWORD_NOT_IN:
advance()
parseOptional(.SPACE)
rhs = try parseFragmentSequence()
// the rhs should evaluate to a single token
// that is either a text or a rule
if rhs.count > 0 {
if case .text = rhs[0] {
op = x == Token.KEYWORD_IN ? .equalTo : .notEqualTo
}
else {
op = x == Token.KEYWORD_IN ? .valueIn : .valueNotIn
}
}
else {
throw ParserError.error("expected rule after in/not in keyword")
}
default:
rhs = [.text("")]
op = .notEqualTo
}
stripTrailingSpace(from: &rhs)
return ParserCondition.init(lhs: lhs, rhs: rhs, op: op)
}
func parseIfBlock() throws -> [ParserNode] {
try parse(.LEFT_SQUARE_BRACKET)
try parse(.KEYWORD_IF)
try parse(.SPACE, "expected space after if")
let condition = try parseCondition()
try parse(.KEYWORD_THEN, "expected 'then' after condition")
try parse(.SPACE, "expected space after 'then'")
var thenBlock = try parseFragmentSequence()
guard thenBlock.count > 0 else { throw ParserError.error("'then' must be followed by rule(s)") }
var elseBlock:[ParserNode]? = nil
if currentToken == .KEYWORD_ELSE {
stripTrailingSpace(from: &thenBlock)
try parse(.KEYWORD_ELSE)
try parse(.SPACE, "expected space after else")
let checkedElseBlock = try parseFragmentSequence()
if checkedElseBlock.count > 0 {
elseBlock = checkedElseBlock
}
else {
throw ParserError.error("'else' must be followed by rule(s)")
}
}
let block = ParserNode.ifBlock(condition: condition, thenBlock: thenBlock, elseBlock: elseBlock)
try parse(.RIGHT_SQUARE_BRACKET)
return [block]
}
func parseWhileBlock() throws -> [ParserNode] {
try parse(.LEFT_SQUARE_BRACKET)
try parse(.KEYWORD_WHILE)
try parse(.SPACE, "expected space after while")
let condition = try parseCondition()
try parse(.KEYWORD_DO, "expected `do` in while after condition")
try parse(.SPACE, "expected space after do in while")
let doBlock = try parseFragmentSequence()
guard doBlock.count > 0 else { throw ParserError.error("'do' must be followed by rule(s)") }
let whileBlock = ParserNode.whileBlock(condition: condition, doBlock: doBlock)
try parse(.RIGHT_SQUARE_BRACKET)
return [whileBlock]
}
func parseFragmentList(separator: Token, context: String, stopParsingFragmentBlockOnToken: Token) throws -> [[ParserNode]] {
let stoppers = [separator, stopParsingFragmentBlockOnToken]
var list = [[ParserNode]]()
// list -> fragment more_fragments
// more_fragments -> separator fragment more_fragments | e
func parseMoreFragments(list: inout [[ParserNode]]) throws {
if currentToken != separator { return }
try parse(separator)
let moreFragments = try parseFragmenSequenceWithContext(until: stoppers)
if moreFragments.count == 0 {
throw ParserError.error("expected \(context) after \(separator.rawText)")
}
list.append(moreFragments)
try parseMoreFragments(list: &list)
}
let block = try parseFragmenSequenceWithContext(until: stoppers)
list.append(block)
try parseMoreFragments(list: &list)
return list
}
func parse(_ token: Token, _ error: @autoclosure () -> String? = nil) throws {
guard let c = currentToken else {
throw ParserError.error(error() ?? "unexpected eof")
}
guard c == token else {
throw ParserError.error(error() ?? "token mismatch expected \(token), got: \(c)")
}
advance()
}
func parseAny(_ tokens: [Token], _ error: @autoclosure () -> String? = nil) throws {
guard let c = currentToken else {
throw ParserError.error(error() ?? "unexpected eof")
}
guard tokens.contains(c) else {
throw ParserError.error(error() ?? "token mismatch expected \(tokens), got: \(c)")
}
advance()
}
func parseOptional(_ token: Token) {
guard let c = currentToken, c == token else { return }
advance()
}
// a fragment is the most basic block in tracery
// a fragement can contain multiple parser nodes though
// #rule# is a fragment with 1 node
// #[tag:value]rule# is a fragment with 2 nodes
func parseFragment() throws -> [ParserNode]? {
var nodes = [ParserNode]()
guard let token = currentToken else { return nil }
switch token {
case Token.HASH, Token.LEFT_CURLY_BRACKET:
nodes.append(contentsOf: try parseRule())
case Token.LEFT_SQUARE_BRACKET:
guard let next = nextToken else { return nil }
switch next {
case Token.KEYWORD_IF:
nodes.append(contentsOf: try parseIfBlock())
case Token.KEYWORD_WHILE:
nodes.append(contentsOf: try parseWhileBlock())
default:
nodes.append(contentsOf: try parseTag())
}
case Token.COLON:
nodes.append(try parseWeight())
case .text, .number:
nodes.append(.text(token.rawText))
advance()
default:
return nil
}
return nodes
}
// parses a sequence of fragments
// i.e. until a 'hanging' token is found
// - #r##r# parses 2 rules
// - #r#,#r# parses 1 rule
// more context is required to decide if the hanging ','
// part of a fragment list e.g. as tag value candidates
// or just part of raw text, as in the entire input
// was '#r#,#r#' which will parse to RULE,TXT(,),RULE nodes
func parseFragmentSequence() throws -> [ParserNode] {
var block = [ParserNode]()
while let fragment = try parseFragment() {
block.append(contentsOf: fragment)
}
return block
}
// consume as many fragments as possible, until any of the stopper
// tokens are reached
// the default behaviour is to parse an valid input string entirely
// in one shot, since no stopper tokens are specified
// stopper tokens can be used to separate greedy calls,
// for example:
// parsing a comma separated list of fragments
// #r1#,#r2#,[t:1],#[t:2]# can be parsed by calling greedy 3 times
// with a stopper of 1 comma
func parseFragmenSequenceWithContext(until stoppers: [Token] = []) throws -> [ParserNode] {
var nodes = [ParserNode]()
while currentToken != nil {
nodes.append(contentsOf: try parseFragmentSequence())
guard let token = currentToken, !stoppers.contains(token) else { break }
// at this stage, we may have consumed
// all tokens, or reached a lone token that we can
// treat as text since it is not a stopper
nodes.append(.text(token.rawText))
advance()
}
return nodes.count > 1 ? flattenText(nodes) : nodes
}
do {
// we parse as much as possible, until we hit
// a lone non-text token. If we were able to
// parse out previous tokens, this lone
// token is stopping us from moving forward,
// so treat it as a text token, and move forward
// this scheme allows us to consume hanging non-text
// nodes as plain-text, and avoids unnecessarily
// escaping tokens
// "hello world."
// tokens: txt(hello world), op(.)
// nodes : TXT(hello world), TXT(.)
return try parseFragmenSequenceWithContext()
}
catch ParserError.error(let message) {
// generate a readable error message like so
//
// expected : after tag 'tag' # the underlying message
// #[tag❌]# # the full input text, with marker
// .....^ # location highlighter
let end = min(index, endIndex)
let consumed = tokens[0..<end].map { $0.rawText }.joined()
var all = tokens.map { $0.rawText }.joined()
let location = consumed.count
all.insert("❌", at: all.index(all.startIndex, offsetBy: location, limitedBy: all.endIndex)!)
let lines = [
message,
" " + all,
" " + String(repeating: ".", count: location) + "^",
""
]
throw ParserError.error(lines.joined(separator: "\n"))
}
}
// combine a stream of text nodes into a single node
// affects debug legibility and reduces interpretation time
// (by a very very miniscule amount only though)
// hence, this is mainly for sane and legible trace output
private static func flattenText(_ nodes: [ParserNode]) -> [ParserNode] {
var output = [ParserNode]()
var i = nodes.startIndex
while i < nodes.endIndex {
switch nodes[i] {
case .text(let text):
var t = text
i += 1
while i < nodes.endIndex, case let .text(text) = nodes[i] {
t.append(text)
i += 1
}
output.append(.text(t))
default:
output.append(nodes[i])
i += 1
}
}
return output
}
private static func stripTrailingSpace(from nodes: inout [ParserNode]) {
guard let last = nodes.last, case let .text(content) = last else { return }
if content == " " {
nodes.removeLast()
}
else if content.hasSuffix(" ") {
nodes[nodes.count-1] = .text(String(content[..<content.index(before: content.endIndex)]))
}
}
}
| mit | 02e4493a28722fd7e4a099231700de02 | 40.422414 | 157 | 0.508949 | 4.985733 | false | false | false | false |
AliSoftware/SwiftGen | Sources/SwiftGenKit/Parsers/Strings/PlaceholderType.swift | 1 | 4960 | //
// SwiftGenKit
// Copyright © 2020 SwiftGen
// MIT Licence
//
import Foundation
extension Strings {
public enum PlaceholderType: String {
case object = "String"
case float = "Float"
case int = "Int"
case char = "CChar"
case cString = "UnsafePointer<CChar>"
case pointer = "UnsafeRawPointer"
init?(formatChar char: Character) {
guard let lcChar = String(char).lowercased().first else {
return nil
}
switch lcChar {
case "@":
self = .object
case "a", "e", "f", "g":
self = .float
case "d", "i", "o", "u", "x":
self = .int
case "c":
self = .char
case "s":
self = .cString
case "p":
self = .pointer
default:
return nil
}
}
}
}
extension Strings.PlaceholderType {
private static let formatTypesRegEx: NSRegularExpression = {
// %d/%i/%o/%u/%x with their optional length modifiers like in "%lld"
let patternInt = "(?:h|hh|l|ll|q|z|t|j)?([dioux])"
// valid flags for float
let patternFloat = "[aefg]"
// like in "%3$" to make positional specifiers
let position = "(\\d+\\$)?"
// precision like in "%1.2f"
let precision = "[-+# 0]?\\d?(?:\\.\\d)?"
do {
return try NSRegularExpression(
pattern: "(?:^|(?<!%)(?:%%)*)%\(position)\(precision)(@|\(patternInt)|\(patternFloat)|[csp])",
options: [.caseInsensitive]
)
} catch {
fatalError("Error building the regular expression used to match string formats")
}
}()
/// Extracts the list of PlaceholderTypes from a format key
///
/// Example: "I give %d apples to %@" --> [.int, .string]
static func placeholderTypes(fromFormat formatString: String) throws -> [Strings.PlaceholderType] {
let range = NSRange(location: 0, length: (formatString as NSString).length)
// Extract the list of chars (conversion specifiers) and their optional positional specifier
let chars = formatTypesRegEx.matches(in: formatString, options: [], range: range)
.compactMap { match -> (String, Int?)? in
let range: NSRange
if match.range(at: 3).location != NSNotFound {
// [dioux] are in range #3 because in #2 there may be length modifiers (like in "lld")
range = match.range(at: 3)
} else {
// otherwise, no length modifier, the conversion specifier is in #2
range = match.range(at: 2)
}
let char = (formatString as NSString).substring(with: range)
let posRange = match.range(at: 1)
if posRange.location == NSNotFound {
// No positional specifier
return (char, nil)
} else {
// Remove the "$" at the end of the positional specifier, and convert to Int
let posRange1 = NSRange(location: posRange.location, length: posRange.length - 1)
let posString = (formatString as NSString).substring(with: posRange1)
let pos = Int(posString)
if let pos = pos, pos <= 0 {
return nil // Foundation renders "%0$@" not as a placeholder but as the "0@" literal
}
return (char, pos)
}
}
return try placeholderTypes(fromChars: chars)
}
/// Creates an array of `PlaceholderType` from an array of format chars and their optional positional specifier
///
/// - Note: Any position that doesn't have a placeholder defined will be stripped out, shifting the position of
/// the remaining placeholders. This is to match how Foundation behaves at runtime.
/// i.e. a string of `"%2$@ %3$d"` will end up with `[.object, .int]` since no placeholder
/// is defined for position 1.
/// - Parameter chars: An array of format chars and their optional positional specifier
/// - Throws: `Strings.ParserError.invalidPlaceholder` in case a `PlaceholderType` would be overwritten
/// - Returns: An array of `PlaceholderType`
private static func placeholderTypes(fromChars chars: [(String, Int?)]) throws -> [Strings.PlaceholderType] {
var list = [Int: Strings.PlaceholderType]()
var nextNonPositional = 1
for (str, pos) in chars {
guard let char = str.first, let placeholderType = Strings.PlaceholderType(formatChar: char) else { continue }
let insertionPos: Int
if let pos = pos {
insertionPos = pos
} else {
insertionPos = nextNonPositional
nextNonPositional += 1
}
guard insertionPos > 0 else { continue }
if let existingEntry = list[insertionPos], existingEntry != placeholderType {
throw Strings.ParserError.invalidPlaceholder(previous: existingEntry, new: placeholderType)
} else {
list[insertionPos] = placeholderType
}
}
// Omit any holes (i.e. position without a placeholder defined)
return list
.sorted { $0.0 < $1.0 } // Sort by key, i.e. the positional value
.map { $0.value }
}
}
| mit | 874c43479a963d1ed2ba5dbe37e56b25 | 35.19708 | 115 | 0.61343 | 4.206107 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Spaces/SpaceList/SpaceListViewController.swift | 1 | 7138 | // File created from ScreenTemplate
// $ createScreen.sh Spaces/SpaceList SpaceList
/*
Copyright 2020 New Vector Ltd
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
final class SpaceListViewController: UIViewController {
// MARK: - Constants
private enum Constants {
static let estimatedRowHeight: CGFloat = 46.0
}
// MARK: - Properties
// MARK: Outlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
// MARK: Private
private var viewModel: SpaceListViewModelType!
private var theme: Theme!
private var errorPresenter: MXKErrorPresentation!
private var sections: [SpaceListSection] = []
// MARK: - Setup
class func instantiate(with viewModel: SpaceListViewModelType) -> SpaceListViewController {
let viewController = StoryboardScene.SpaceListViewController.initialScene.instantiate()
viewController.viewModel = viewModel
viewController.theme = ThemeService.shared().theme
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupViews()
self.errorPresenter = MXKErrorAlertPresentation()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
self.viewModel.viewDelegate = self
self.viewModel.process(viewAction: .loadData)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
// MARK: - Private
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.colors.background
self.tableView.backgroundColor = theme.colors.background
self.tableView.reloadData()
self.titleLabel.textColor = theme.colors.primaryContent
self.titleLabel.font = theme.fonts.bodySB
self.activityIndicator.color = theme.colors.secondaryContent
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
private func setupViews() {
self.setupTableView()
self.titleLabel.text = VectorL10n.spacesLeftPanelTitle
}
private func setupTableView() {
self.tableView.separatorStyle = .none
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = Constants.estimatedRowHeight
self.tableView.allowsSelection = true
self.tableView.register(cellType: SpaceListViewCell.self)
self.tableView.tableFooterView = UIView()
}
private func render(viewState: SpaceListViewState) {
switch viewState {
case .loading:
self.renderLoading()
case .loaded(let sections):
self.renderLoaded(sections: sections)
case .selectionChanged(let indexPath):
self.renderSelectionChanged(at: indexPath)
case .error(let error):
self.render(error: error)
}
}
private func renderLoading() {
self.activityIndicator.startAnimating()
}
private func renderLoaded(sections: [SpaceListSection]) {
self.activityIndicator.stopAnimating()
self.sections = sections
self.tableView.reloadData()
}
private func renderSelectionChanged(at indexPath: IndexPath) {
self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
}
private func render(error: Error) {
self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil)
}
}
// MARK: - SpaceListViewModelViewDelegate
extension SpaceListViewController: SpaceListViewModelViewDelegate {
func spaceListViewModel(_ viewModel: SpaceListViewModelType, didUpdateViewState viewSate: SpaceListViewState) {
self.render(viewState: viewSate)
}
}
// MARK: - UITableViewDataSource
extension SpaceListViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return self.sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRows: Int
let spaceListSection = self.sections[section]
switch spaceListSection {
case .home:
numberOfRows = 1
case .spaces(let viewDataList):
numberOfRows = viewDataList.count
case .addSpace:
numberOfRows = 1
}
return numberOfRows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath, cellType: SpaceListViewCell.self)
let viewData: SpaceListItemViewData
let spaceListSection = self.sections[indexPath.section]
switch spaceListSection {
case .home(let spaceViewData):
viewData = spaceViewData
case .spaces(let viewDataList):
viewData = viewDataList[indexPath.row]
case .addSpace(let spaceViewData):
viewData = spaceViewData
}
cell.update(theme: self.theme)
cell.fill(with: viewData)
cell.selectionStyle = .none
cell.delegate = self
return cell
}
}
// MARK: - UITableViewDelegate
extension SpaceListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.viewModel.process(viewAction: .selectRow(at: indexPath, from: tableView.cellForRow(at: indexPath)))
}
}
// MARK: - SpaceListViewCellDelegate
extension SpaceListViewController: SpaceListViewCellDelegate {
func spaceListViewCell(_ cell: SpaceListViewCell, didPressMore button: UIButton) {
guard let indexPath = self.tableView.indexPath(for: cell) else {
MXLog.warning("[SpaceListViewController] didPressMore called from invalid cell.")
return
}
self.viewModel.process(viewAction: .moreAction(at: indexPath, from: button))
}
}
| apache-2.0 | 603e3ac273e70c084a319032c40e3dab | 31.153153 | 137 | 0.672457 | 5.370956 | false | false | false | false |
ECLabs/CareerUp | CandidateHandler.swift | 1 | 5981 | import Parse
var candidateInstance: CandidateHandler?
class CandidateHandler: NSObject {
var candidates:[Candidate] = []
var localCandidates:[Candidate] = []
var loadingCount = 0
var reloaded = false
var timer:NSTimer?
var pullDate:NSDate?
class func sharedInstance() -> CandidateHandler {
if !(candidateInstance != nil) {
candidateInstance = CandidateHandler()
}
return candidateInstance!
}
func get() {
loadingCount = -1
// need to change to compare to loaded objects
self.candidates.removeAll(keepCapacity: false)
let query = PFQuery(className: "Candidate")
query.cachePolicy = kPFCachePolicyNetworkElseCache;
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if (error == nil) {
self.pullDate = NSDate()
self.loadingCount = objects.count
for object in objects {
let resume = Candidate()
resume.objectId = object.objectId
if (object["firstName"]? != nil) {
resume.firstName = object["firstName"] as String
}
if (object["lastName"]? != nil) {
resume.lastName = object["lastName"] as String
}
if (object["email"]? != nil) {
resume.email = object["email"] as String
}
if (object["desiredJobTitle"]? != nil) {
resume.jobTitle = object["desiredJobTitle"] as String
}
if (object["linkedInUrl"]? != nil) {
resume.linkedIn = object["linkedInUrl"] as String
}
if (object["comments"]? != nil) {
resume.comments = object["comments"] as String
}
if (object["notes"]? != nil) {
resume.notes = object["notes"] as String
}
self.candidates.append(resume)
println("adding Object")
if (object["resumeImage"]? != nil) {
self.loadingCount++
let userImageFile:PFFile = object["resumeImage"] as PFFile
userImageFile.getDataInBackgroundWithBlock({(imageData, error) -> Void in
if (error == nil) {
resume.pdfData = imageData
}
self.loadingCount--
})
}
self.loadingCount--
}
}
else{
self.loadingCount = 0
}
})
}
func count() {
let query:PFQuery = PFQuery(className: "Candidate")
query.whereKey("updatedAt", greaterThan: pullDate)
query.countObjectsInBackgroundWithBlock({(objectCount, error) -> Void in
if (error == nil) {
if Int(objectCount) > 0 {
self.get()
self.reloaded = true
}
}
})
}
func save(submission:Candidate){
let object = PFObject(className: "Candidate")
if !contains(self.localCandidates, submission){
self.localCandidates.append(submission)
}
if !submission.objectId.isEmpty{
object.objectId = submission.objectId
}
if !submission.editing {
object["firstName"] = submission.firstName
object["lastName"] = submission.lastName
object["email"] = submission.email
object["desiredJobTitle"] = submission.jobTitle
object["linkedInUrl"] = submission.linkedIn
object["comments"] = submission.comments
object["notes"] = submission.notes
if (submission.resumeImages.count > 0) {
let pdfData = submission.getResumePDF()
submission.pdfData = pdfData
let imageFile = PFFile(name: "resume.pdf", data: pdfData)
object["resumeImage"] = imageFile
}
object.saveInBackgroundWithBlock({(success, error) -> Void in
if success {
submission.objectId = object.objectId
if let index = find(self.localCandidates, submission){
self.localCandidates.removeAtIndex(index)
}
if (self.timer != nil) && self.localCandidates.count == 0{
self.timer?.invalidate()
self.timer = nil
} else if (self.timer != nil) {
self.timer?.invalidate()
self.timer = nil
self.resave()
}
}
else{
self.timer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: "resave", userInfo: nil, repeats: false)
}
})
}
else {
if (self.timer != nil) {
self.timer?.invalidate()
self.timer = nil
}
self.timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "resave", userInfo: nil, repeats: false)
}
}
func resave(){
if self.localCandidates.count > 0 {
let candidate = localCandidates.last
localCandidates.removeLast()
save(candidate!)
}
}
}
| mit | 5e450581ce3d1902aed6f58d5b04e302 | 35.693252 | 140 | 0.461796 | 5.801164 | false | false | false | false |
ngageoint/mage-ios | Mage/BottomSheets/FeedItemBottomSheetView.swift | 1 | 4870 | //
// FeedItemBottomSheetView.swift
// MAGE
//
// Created by Daniel Barela on 7/14/21.
// Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
class FeedItemBottomSheetView: BottomSheetView {
private var didSetUpConstraints = false;
private var feedItem: FeedItem?;
private var actionsDelegate: FeedItemActionsDelegate?;
var scheme: MDCContainerScheming?;
private lazy var stackView: PassThroughStackView = {
let stackView = PassThroughStackView(forAutoLayout: ());
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 0
stackView.distribution = .fill;
stackView.directionalLayoutMargins = .zero;
stackView.isLayoutMarginsRelativeArrangement = false;
stackView.translatesAutoresizingMaskIntoConstraints = false;
stackView.clipsToBounds = true;
return stackView;
}()
private lazy var summaryView: FeedItemSummary = {
let view = FeedItemSummary();
return view;
}()
private lazy var actionsView: FeedItemActionsView? = {
guard let feedItem = self.feedItem else {
return nil;
}
let view = FeedItemActionsView(feedItem: feedItem, actionsDelegate: actionsDelegate, scheme: scheme);
return view;
}()
private lazy var detailsButton: MDCButton = {
let detailsButton = MDCButton(forAutoLayout: ());
detailsButton.accessibilityLabel = "More Details";
detailsButton.setTitle("More Details", for: .normal);
detailsButton.clipsToBounds = true;
detailsButton.addTarget(self, action: #selector(detailsButtonTapped), for: .touchUpInside);
return detailsButton;
}()
private lazy var detailsButtonView: UIView = {
let view = UIView();
view.addSubview(detailsButton);
detailsButton.autoAlignAxis(toSuperviewAxis: .vertical);
detailsButton.autoMatch(.width, to: .width, of: view, withMultiplier: 0.9);
detailsButton.autoPinEdge(.top, to: .top, of: view);
detailsButton.autoPinEdge(.bottom, to: .bottom, of: view);
return view;
}()
private lazy var expandView: UIView = {
let view = UIView(forAutoLayout: ());
view.setContentHuggingPriority(.defaultLow, for: .vertical);
return view;
}();
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
init(feedItem: FeedItem, actionsDelegate: FeedItemActionsDelegate? = nil, scheme: MDCContainerScheming?) {
super.init(frame: CGRect.zero);
self.translatesAutoresizingMaskIntoConstraints = false;
self.actionsDelegate = actionsDelegate;
self.feedItem = feedItem;
self.scheme = scheme;
stackView.addArrangedSubview(summaryView);
if (actionsView != nil) {
stackView.addArrangedSubview(actionsView!);
}
stackView.addArrangedSubview(detailsButtonView);
self.addSubview(stackView);
stackView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0));
populateView();
if let scheme = scheme {
applyTheme(withScheme: scheme);
}
}
func applyTheme(withScheme scheme: MDCContainerScheming? = nil) {
guard let scheme = scheme else {
return;
}
self.backgroundColor = scheme.colorScheme.surfaceColor;
summaryView.applyTheme(withScheme: scheme);
actionsView?.applyTheme(withScheme: scheme);
detailsButton.applyContainedTheme(withScheme: scheme);
}
func populateView() {
guard let feedItem = self.feedItem else {
return
}
summaryView.populate(item: feedItem, actionsDelegate: actionsDelegate);
actionsView?.populate(feedItem: feedItem, delegate: actionsDelegate)
}
override func updateConstraints() {
if (!didSetUpConstraints) {
stackView.autoPinEdgesToSuperviewEdges(with: .zero);
didSetUpConstraints = true;
}
super.updateConstraints();
}
override func refresh() {
guard let feedItem = self.feedItem else {
return
}
summaryView.populate(item: feedItem, actionsDelegate: actionsDelegate);
}
@objc func detailsButtonTapped() {
if let feedItem = feedItem {
// let the ripple dissolve before transitioning otherwise it looks weird
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
NotificationCenter.default.post(name: .ViewFeedItem, object: feedItem)
self.actionsDelegate?.viewFeedItem?(feedItem: feedItem)
}
}
}
}
| apache-2.0 | 804bc8bc65dbf6c1d5354d956a2a90a4 | 34.540146 | 110 | 0.642637 | 5.27519 | false | false | false | false |
Lasithih/LIHImageSlider | LIHImageSlider/Classes/LIHSlider.swift | 1 | 1203 | //
// LIHSlider.swift
// Pods
//
// Created by Lasith Hettiarachchi on 3/13/16.
//
//
import Foundation
open class LIHSlider: NSObject {
open var sliderImages: [UIImage] = []
open var sliderDescriptions: [String] = []
open var descriptionColor: UIColor = UIColor.white
open var descriptionBackgroundAlpha: CGFloat = 0.3
open var descriptionBackgroundColor: UIColor = UIColor.black
open var descriptionFont: UIFont = UIFont.systemFont(ofSize: 15)
open var numberOfLinesInDescription: Int = 2
open var transitionInterval: Double = 3.0
open var customImageView: UIImageView?
open var showPageIndicator: Bool = true
open var userInteractionEnabled: Bool = true
//Sliding options
open var transitionStyle: UIPageViewControllerTransitionStyle = UIPageViewControllerTransitionStyle.scroll
open var slidingOrientation: UIPageViewControllerNavigationOrientation = UIPageViewControllerNavigationOrientation.horizontal
open var sliderNavigationDirection: UIPageViewControllerNavigationDirection = UIPageViewControllerNavigationDirection.forward
public init(images: [UIImage]) {
self.sliderImages = images
}
}
| mit | 36832c27d51c55e185f19876528b0283 | 34.382353 | 129 | 0.750623 | 5.230435 | false | false | false | false |
courteouselk/Relations | Sources/WeakWrapper.swift | 1 | 662 | //
// WeakWrapper.swift
// Relations
//
// Created by Anton Bronnikov on 03/01/2017.
// Copyright © 2017 Anton Bronnikov. All rights reserved.
//
struct WeakWrapper<Object: AnyObject> : Equatable, Hashable {
private weak var _object: Object?
var hashValue: Int { return objectIdentifier.hashValue }
var object: Object { return _object! }
let objectIdentifier: ObjectIdentifier
init(_ object: Object) {
self._object = object
self.objectIdentifier = ObjectIdentifier(object)
}
static func == (lhs: WeakWrapper, rhs: WeakWrapper) -> Bool {
return lhs.objectIdentifier == rhs.objectIdentifier
}
}
| mit | 4d9dd8f070c0b9d424b5737753975ac8 | 22.607143 | 65 | 0.673222 | 4.466216 | false | false | false | false |
iOSDevLog/iOSDevLog | 2048-Xcode6/2048-Xcode6/CollectionViewCell.swift | 1 | 1184 | //
// CollectionViewCell.swift
// 2048-Xcode6
//
// Created by JiaXianhua on 15/9/14.
// Copyright (c) 2015年 jiaxianhua. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var valueLabel: UILabel!
var tileMergeStartScale: NSTimeInterval = 1.0
let tilePopMinScale: CGFloat = 0.1
let tilePopMaxScale: CGFloat = 1.1
var duration: NSTimeInterval = 0.2
func configCell(value: Int?, delegate d: AppearanceProviderProtocol) {
var number: Int = 9
if let v = value {
number = v
}
valueLabel.text = "\(number)"
valueLabel.font = d.fontForNumbers()
self.layer.cornerRadius = 5;
self.backgroundColor = d.tileColor(number)
valueLabel.textColor = d.numberColor(number)
self.valueLabel.layer.setAffineTransform(CGAffineTransformMakeScale(self.tilePopMinScale, self.tilePopMinScale))
UIView.animateWithDuration(duration, animations: { () -> Void in
self.valueLabel.layer.setAffineTransform(CGAffineTransformMakeScale(self.tilePopMaxScale, self.tilePopMaxScale))
})
}
}
| mit | 2383bacc3427d8748f00884cd68efea6 | 30.945946 | 124 | 0.666667 | 4.313869 | false | false | false | false |
ostatnicky/kancional-ios | Cancional/AppDelegate.swift | 1 | 2188 | //
// AppDelegate.swift
// Cancional
//
// Created by Jiri Ostatnicky on 22/05/2017.
// Copyright © 2017 Jiri Ostatnicky. All rights reserved.
//
import UIKit
import SwiftyBeaver
import Fabric
import Crashlytics
import Trackable
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
log.addDestination(ConsoleDestination()) // log to Xcode Console
#if !DEBUG
Fabric.with([Crashlytics.self])
setupTrackableChain(parent: analytics)
#endif
RemotePersistence.setup()
Persistence.instance.populateData()
configureStyling()
return true
}
}
private extension AppDelegate {
func configureStyling() {
window?.tintColor = UIColor.Cancional.tintColor()
window?.backgroundColor = UIColor.Cancional.tintColor()
// Text styles setup
Styles.setup()
// Navigation bar
UINavigationBar.appearance().titleTextAttributes = [
NSAttributedStringKey.foregroundColor: UIColor.white,
NSAttributedStringKey.font: UIFont.Cancional.mediumFontOfSize(20)
]
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
UINavigationBar.appearance().backgroundColor = UIColor.Cancional.tintColor()
UINavigationBar.appearance().barTintColor = UIColor.Cancional.tintColor()
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().barStyle = .blackTranslucent
// Search bar
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [
NSAttributedStringKey.foregroundColor.rawValue: UIColor.white,
NSAttributedStringKey.font.rawValue: R.font.ubuntuMedium(size: 16)!
]
}
}
extension AppDelegate : TrackableClass { }
| mit | 41292ff2dfb5218d5ebb8e5b0b3ac79f | 31.161765 | 142 | 0.684499 | 5.440299 | false | false | false | false |
russelhampton05/MenMew | App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/Models.swift | 1 | 8647 | //
// Models.swift
// App_Prototype_Alpha_001
//
// Created by Jon Calanio on 10/3/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import Foundation
import Firebase
class User{
var ID: String
var name: String?
var email: String?
var ticket: Ticket?
var image: String?
var theme: String?
var touchEnabled = false
var notifications = true
init(id: String, email: String?, name: String?, ticket: Ticket?, image: String?, theme: String?){
self.ID = id
self.email = email
self.name = name
self.ticket = ticket
self.image = image
self.theme = theme
}
convenience init(id: String, email: String?, name: String?, ticket: Ticket?, image: String?, theme: String?, touchEnabled: Bool, notifications: Bool){
self.init( id: id, email: email, name: name, ticket: ticket, image: image, theme: theme)
self.touchEnabled = touchEnabled
self.notifications = notifications
}
}
//need to look at maybe changing this
struct Details {
var sides: [String]
var cookType: [String]
}
class Menu{
var rest_id : String?
var title : String?
var cover_picture : String?
var tax: Double?
var menu_groups : [MenuGroup]? = []
init(id:String, title:String, cover_picture:String?, groups: [MenuGroup], tax: Double?){
self.rest_id = id
self.title = title
self.cover_picture = cover_picture
self.menu_groups = groups
self.tax = tax
}
init(){
}
convenience init(id: String, title: String, groups: [MenuGroup], tax: Double) {
self.init(id:id, title:title, cover_picture:nil, groups:groups, tax: tax)
}
}
class MenuGroup{
var cover_picture: String?
var desc: String?
var title: String?
var items: [MenuItem]?
init(){
}
init(desc: String,items: [MenuItem], title: String?, cover_picture:String?){
self.cover_picture = cover_picture
self.desc = desc
self.title = title
self.items = items
}
convenience init(desc: String,items: [MenuItem], title: String?){
self.init(desc:desc,items:items, title:title, cover_picture:nil)
}
convenience init(desc: String,items: [MenuItem], cover_picture:String?) {
self.init(desc:desc,items:items, title:nil, cover_picture:cover_picture)
}
convenience init(desc: String,items: [MenuItem]) {
self.init(desc:desc, items:items, title:nil, cover_picture:nil)
}
}
//menu item objects and menus are for UI purposes only.
//Menu item will have a member called "item", which will tie it in to the actaul
//details necessary for order tracking.
class MenuItem {
//will eventually point to an actual item (if we care to implement that, possibly not)
//for now just UI facing fields and those needed for ordering/pricing
var item_ID: String?
var title: String?
var price: Double?
//var sides: [String]?
var image: String?
var desc: String?
init(){
}
init(item_ID: String?, title:String, price:Double, image: String, desc: String) {
self.item_ID = item_ID
self.title = title
self.image = image
self.price = price
// self.sides = sides
self.desc = desc
}
//convenience init(title:String, price:Double, image: String, desc: String){
// self.init(title : title, price : price, image : image, desc: desc, sides:nil)
//}
}
//Ticket Class
class Ticket {
var ticket_ID: String?
var user_ID: String?
var restaurant_ID: String?
var tableNum: String?
var timestamp: String?
var paid: Bool?
var itemsOrdered: [MenuItem]?
var desc: String?
var confirmed: Bool?
var status: String?
var total: Double?
var tip: Double?
var message_ID: String?
init() {
self.message_ID = ""
self.ticket_ID = ""
self.user_ID = ""
self.restaurant_ID = ""
self.tableNum = ""
self.paid = false
self.itemsOrdered = []
self.desc = ""
self.confirmed = false
self.status = "Ordering"
self.total = 0.0
self.tip = 0.0
}
init(ticket_ID: String, user_ID: String, restaurant_ID: String, tableNum: String, timestamp: String, paid: Bool, itemsOrdered:[MenuItem]?, desc: String?, confirmed: Bool?, status: String?, total: Double?, tip: Double?, message_ID: String?) {
self.ticket_ID = ticket_ID
self.user_ID = user_ID
self.restaurant_ID = restaurant_ID
self.tableNum = tableNum
self.timestamp = timestamp
self.paid = paid
self.itemsOrdered = itemsOrdered
self.desc = desc
self.confirmed = confirmed
self.status = status
self.total = total
self.tip = tip
self.message_ID = message_ID
if self.message_ID == nil{
self.message_ID = ""
}
}
func generateMessageGUID(){
let id = UUID().uuidString.lowercased()
self.message_ID = id.replacingOccurrences(of: "-", with: "")
}
init(snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: AnyObject]
self.ticket_ID = snapshot.key
self.user_ID = snapshotValue["user"] as? String
self.restaurant_ID = snapshotValue["restaurant"] as? String
self.tableNum = snapshotValue["table"] as? String
self.timestamp = snapshotValue["timestamp"] as? String
self.paid = snapshotValue["paid"] as? Bool
self.desc = snapshotValue["desc"] as? String
self.confirmed = snapshotValue["confirmed"] as? Bool
self.status = snapshotValue["status"] as? String
self.total = snapshotValue["total"] as? Double
self.tip = snapshotValue["tip"] as? Double
if snapshotValue["message"] != nil{
self.message_ID = snapshotValue["message"] as? String
}
else{
self.message_ID = ""
}
// MenuItemManager.GetMenuItem(ids: snapshotValue["itemsOrdered"]?.allKeys as! [String]) {
// items in
// self.itemsOrdered = items;
// }
//ItemsOrdered is the array of items ordered for the table
// let menuItems = snapshotValue["itemsOrdered"] as? NSDictionary
}
}
//Message Class
class Message {
var message_ID: String?
var serverMessage: String?
var userMessage: String?
init(snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: AnyObject]
self.message_ID = snapshot.key
self.serverMessage = snapshotValue["server"] as? String
self.userMessage = snapshotValue["user"] as? String
}
}
//Theme Class
class Theme {
var name: String?
var primary: UIColor?
var secondary: UIColor?
var highlight: UIColor?
var invert: UIColor?
init(type: String) {
if type == "Salmon" {
name = "Salmon"
primary = UIColor(red: 255, green: 106, blue: 92)
secondary = UIColor(red: 255, green: 255, blue: 255)
highlight = UIColor(red: 255, green: 255, blue: 255)
invert = UIColor(red: 255, green: 106, blue: 92)
}
else if type == "Light" {
name = "Light"
primary = UIColor(red: 255, green: 255, blue: 255)
secondary = UIColor(red: 255, green: 255, blue: 255)
highlight = UIColor(red: 255, green: 141, blue: 43)
invert = UIColor(red: 255, green: 141, blue: 43)
}
else if type == "Midnight" {
name = "Midnight"
primary = UIColor(red: 55, green: 30, blue: 96)
secondary = UIColor(red: 18, green: 3, blue: 42)
highlight = UIColor(red: 255, green: 255, blue: 255)
invert = UIColor(red: 255, green: 255, blue: 255)
}
else if type == "Slate" {
name = "Slate"
primary = UIColor(red: 27, green: 27, blue: 27)
secondary = UIColor(red: 20, green: 20, blue: 20)
highlight = UIColor(red: 255, green: 255, blue: 255)
invert = UIColor(red: 255, green: 255, blue: 255)
}
}
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
let newRed = CGFloat(red)/255
let newGreen = CGFloat(green)/255
let newBlue = CGFloat(blue)/255
self.init(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
}
| mit | b8de7c460225f32a2f399ef5691d67f4 | 30.212996 | 245 | 0.586861 | 3.999075 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.