repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hellogaojun/Swift-coding
swift学习教材案例/GuidedTour-1.2.playground/section-29-original.swift
76
164
var firstForLoop = 0 for i in 0..3 { firstForLoop += i } firstForLoop var secondForLoop = 0 for var i = 0; i < 3; ++i { secondForLoop += 1 } secondForLoop
apache-2.0
e06eb9783aa9a238f0799f9b79c762a1
13.909091
27
0.634146
2.981818
false
false
false
false
justindhill/Facets
Facets/View Controllers/Issue/OZLIssueViewModel.swift
1
9150
// // OZLIssueViewModel.swift // Facets // // Created by Justin Hill on 5/6/16. // Copyright © 2016 Justin Hill. All rights reserved. // import Foundation protocol OZLIssueViewModelDelegate: AnyObject { func viewModel(_ viewModel: OZLIssueViewModel, didFinishLoadingIssueWithError error: NSError?) func viewModelDetailDisplayModeDidChange(_ viewModel: OZLIssueViewModel) func viewModelIssueContentDidChange(_ viewModel: OZLIssueViewModel) } enum OZLIssueCompleteness: Int { case none case some case all } @objc class OZLIssueViewModel: NSObject, OZLQuickAssignDelegate { fileprivate static let PinnedIdentifiersDefaultsKeypath = "facets.issue.pinned-detail-identifiers" static let SectionDetail = "OZLIssueSectionDetail" static let SectionDescription = "OZLIssueSectionDescription" static let SectionAttachments = "OZLIssueSectionAttachments" static let SectionRecentActivity = "OZLIssueSectionRecentActivity" fileprivate static let defaultPinnedDetailIdentifiers: Set<String> = ["status_id", "category_id", "priority_id", "fixed_version_id"] fileprivate var pinnedDetailIdentifiers = OZLIssueViewModel.defaultPinnedDetailIdentifiers var showAllDetails = false { didSet(oldValue) { if self.showAllDetails != oldValue { self.refreshVisibleDetails() self.delegate?.viewModelDetailDisplayModeDidChange(self) } } } // (identifier, displayName, displayValue) fileprivate var details: [(String, String, String)] = [] fileprivate var visibleDetails: [(String, String, String)] = [] weak var delegate: OZLIssueViewModelDelegate? var successfullyFetchedIssue = false var currentSectionNames: [String] = [] var issueModel: OZLModelIssue { didSet { self.updateSectionNames() self.refreshDetails() } } // MARK: - Life cycle init(issueModel: OZLModelIssue) { self.issueModel = issueModel super.init() let keyPath = self.targetedPinnedIdentifiersDefaultsKeypath() if let storedIdentifiers = UserDefaults.standard.array(forKey: keyPath) as? [String] { self.pinnedDetailIdentifiers = Set(storedIdentifiers) } self.updateSectionNames() self.refreshDetails() self.refreshVisibleDetails() } func targetedPinnedIdentifiersDefaultsKeypath() -> String { return "\(OZLIssueViewModel.PinnedIdentifiersDefaultsKeypath).\(String(describing: self.issueModel.projectId))" } // MARK: - Behavior func updateSectionNames() { var sectionNames = [ OZLIssueViewModel.SectionDetail ] if self.issueModel.issueDescription?.characters.count ?? 0 > 0 { sectionNames.append(OZLIssueViewModel.SectionDescription) } if self.issueModel.attachments?.count ?? 0 > 0 { sectionNames.append(OZLIssueViewModel.SectionAttachments) } if self.issueModel.journals?.count ?? 0 > 0 { sectionNames.append(OZLIssueViewModel.SectionRecentActivity) } self.currentSectionNames = sectionNames } func completeness() -> OZLIssueCompleteness { if self.successfullyFetchedIssue { return .all } else if self.issueModel.subject != nil { return .some } else { return .none } } func displayNameForSectionName(_ sectionName: String) -> String? { if sectionName == OZLIssueViewModel.SectionDescription { return "DESCRIPTION" } else if sectionName == OZLIssueViewModel.SectionAttachments { return "ATTACHMENTS" } else if sectionName == OZLIssueViewModel.SectionRecentActivity { return "RECENT ACTIVITY" } return nil } func sectionNumberForSectionName(_ sectionName: String) -> Int? { return self.currentSectionNames.index(of: sectionName) } func loadIssueData() { weak var weakSelf = self let params = [ "include": "attachments,journals,relations" ] OZLNetwork.sharedInstance().getDetailForIssue(self.issueModel.index, withParams: params) { (issue, error) in if let weakSelf = weakSelf { if let issue = issue { weakSelf.successfullyFetchedIssue = true weakSelf.issueModel = issue } weakSelf.delegate?.viewModel(weakSelf, didFinishLoadingIssueWithError: error as NSError?) } } } // MARK: - Details func refreshDetails() { var details = [(String, String, String)]() if let status = self.issueModel.status?.name { details.append(("status_id", OZLModelIssue.displayNameForAttributeName("status_id"), status)) } if let priority = self.issueModel.priority?.name { details.append(("priority_id", OZLModelIssue.displayNameForAttributeName("priority_id"), priority)) } if let author = self.issueModel.author?.name { details.append(("author", OZLModelIssue.displayNameForAttributeName("author"), author)) } if let startDate = self.issueModel.startDate { details.append(("start_date", OZLModelIssue.displayNameForAttributeName("start_date"), String(describing: startDate))) } if let dueDate = self.issueModel.dueDate { details.append(("due_date", OZLModelIssue.displayNameForAttributeName("due_date"), String(describing: dueDate))) } if let category = self.issueModel.category { details.append(("category_id", OZLModelIssue.displayNameForAttributeName("category_id"), category.name)) } if let targetVersion = self.issueModel.targetVersion { details.append(("fixed_version_id", OZLModelIssue.displayNameForAttributeName("fixed_version_id"), targetVersion.name)) } if let doneRatio = self.issueModel.doneRatio { details.append(("done_ratio", OZLModelIssue.displayNameForAttributeName("done_ratio"), String(doneRatio))) } if let spentHours = self.issueModel.spentHours { details.append(("spent_hours", OZLModelIssue.displayNameForAttributeName("spent_hours"), String(spentHours))) } for field in self.issueModel.customFields ?? [] where field.value != nil { let cachedField = OZLModelCustomField(forPrimaryKey: field.fieldId) details.append( ( String(field.fieldId), field.name ?? "", OZLModelCustomField.displayValue(for: cachedField?.type ?? field.type, attributeId: field.fieldId, attributeValue: field.value as? String ?? "") ) ) } self.details = details } func refreshVisibleDetails() { var visibleDetails: [(String, String, String)] = [] for (index, (identifier, _, _)) in self.details.enumerated() { if self.pinnedDetailIdentifiers.contains(identifier) || self.showAllDetails { visibleDetails.append(self.details[index]) } } self.visibleDetails = visibleDetails } func numberOfDetails() -> Int { return self.visibleDetails.count } func detailAtIndex(_ index: Int) -> (String, String, Bool) { let (identifier, name, value) = self.visibleDetails[index] return (name, value, self.pinnedDetailIdentifiers.contains(identifier)) } func togglePinningForDetailAtIndex(_ index: Int) { let (identifier, _, _) = self.details[index] if self.pinnedDetailIdentifiers.contains(identifier) { self.pinnedDetailIdentifiers.remove(identifier) } else { self.pinnedDetailIdentifiers.insert(identifier) } UserDefaults.standard.set(Array(self.pinnedDetailIdentifiers), forKey: self.targetedPinnedIdentifiersDefaultsKeypath()) } // MARK: - Recent activity func recentActivityCount() -> Int { return min(self.issueModel.journals?.count ?? 0, 3) } func recentActivityAtIndex(_ index: Int) -> OZLModelJournal { if let journals = self.issueModel.journals { return journals[journals.count - index - 1] } fatalError("Journals array doesn't exist") } // MARK: - Quick assign delegate func quickAssignController(_ quickAssign: OZLQuickAssignViewController, didChangeAssigneeInIssue issue: OZLModelIssue, from: OZLModelUser?, to: OZLModelUser?) { self.issueModel = issue let journal = OZLModelJournal() journal.creationDate = Date() let detail = OZLModelJournalDetail() detail.type = .attribute detail.oldValue = String(describing: from?.userId) detail.newValue = String(describing: to?.userId) detail.name = "assigned_to_id" journal.details = [ detail ] issue.journals?.append(journal) self.delegate?.viewModelIssueContentDidChange(self) } }
mit
e694ff8f98322f633f19d48365da39a6
34.188462
164
0.649033
5.128363
false
false
false
false
Noambaron/ScoreboardLabel
ScoreboardLabel/ScoreboardLabel.swift
1
4087
// // ScoreboardLabel.swift // Outscore // // Created by Noam on 9/9/15. // Copyright (c) 2015 ICOgroup. All rights reserved. // import Foundation import UIKit public class ScoreboardLabel: UIView, ScoreboardLabelLetterProtocol { public var firstText = "" public var secondText = "" public var textFont : UIFont! public var textColor: UIColor! public var interval = CFTimeInterval(0.3) public var isRepeating = true var firstWordLetters = Array<String>() var secondWordLetters = Array<String>() var flippingLetters = Array<ScoreboardLabelLetter>() public var completionHandler:((Bool)->Void)! private var showingFirstWord = true override init(frame:CGRect) { super.init(frame: frame) clipsToBounds = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience public init(backgroundImage:UIImage ,text:String, flipToText:String, font:UIFont, textColor:UIColor) { let maxChars = max(text.Letterize().count, flipToText.Letterize().count) let rect = CGRectMake(0, 0, CGFloat(maxChars) * CGFloat(font.pointSize), CGFloat(font.pointSize) * CGFloat(1.5)) self.init (frame:rect) textFont = font self.textColor = textColor firstWordLetters = text.Letterize() secondWordLetters = flipToText.Letterize() firstText = text secondText = flipToText var lastOriginX = CGFloat(0) let height = textFont.pointSize * 1.5 let width = textFont.pointSize //build flipping letters for index in 1...maxChars { let frameForLetter = CGRectMake(lastOriginX, 0, width, height) let flipLetter = ScoreboardLabelLetter(frame: frameForLetter) flipLetter.font = textFont flipLetter.letterIndex = index flipLetter.delegate = self var firstLetter = "" var secondLetter = "" if let letter = firstWordLetters.get(index - 1) { firstLetter = letter } if let otherLetter = secondWordLetters.get(index - 1) { secondLetter = otherLetter } flipLetter.renderScoreboardLabelLetters(backgroundImage, textColor:textColor,letter: firstLetter, nextLetter: secondLetter) flippingLetters.append(flipLetter) addSubview(flipLetter) lastOriginX += width + 5 } } public func flip(continuosly: Bool) { isRepeating = continuosly flipLetterAtIndex(0) } public func stopFlipping() { isRepeating = false } func flipLetterAtIndex(index:Int) { if (index > flippingLetters.count - 1) { showingFirstWord = !showingFirstWord return } let viewLetter = flippingLetters[index] let letter = (showingFirstWord == true) ? secondWordLetters.get(index) : firstWordLetters.get(index) if let letter = letter { viewLetter.flipToLetterAfterWait(letter, wait: interval * CFTimeInterval(index)) }else { viewLetter.flipToLetterAfterWait("", wait: interval * CFTimeInterval(index)) } flipLetterAtIndex(index + 1) } func didFinishAnimatingLetter(letter: ScoreboardLabelLetter) { if (letter.letterIndex == flippingLetters.count && isRepeating == true) { //it was the last letter and we need to repeat performThisAfter(0.8, closure: { () -> () in self.flipLetterAtIndex(0) }) }else if letter.letterIndex == flippingLetters.count { if completionHandler != nil { completionHandler(true) } } } }
mit
bc1d1643e674f66ed505a70b31219ce8
26.246667
135
0.583313
5.045679
false
false
false
false
Arcovv/CleanArchitectureRxSwift
CoreDataPlatform/Entities/CDUser+Ext.swift
2
2183
// // CDUser+Ext.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import Foundation import CoreData import Domain import QueryKit import RxSwift extension CDUser { static var website: Attribute<String> { return Attribute("website")} static var email: Attribute<String> { return Attribute("email")} static var name: Attribute<String> { return Attribute("name")} static var phone: Attribute<String> { return Attribute("phone")} static var username: Attribute<String> { return Attribute("username")} static var uid: Attribute<String> { return Attribute("uid")} static var address: Attribute<CDAddress> { return Attribute("address")} static var company: Attribute<CDCompany> { return Attribute("company")} } extension CDUser: DomainConvertibleType { func asDomain() -> User { return User(address: address!.asDomain(), company: company!.asDomain(), email: email!, name: name!, phone: phone!, uid: uid!, username: username!, website: website!) } } extension CDUser: Persistable { static var entityName: String { return "CDUser" } static func synced(user: CDUser, with address: CDAddress?, company: CDCompany?) -> CDUser { user.address = address user.company = company return user } } extension User: CoreDataRepresentable { typealias CoreDataType = CDUser func sync(in context: NSManagedObjectContext) -> Observable<CDUser> { let syncSelf = context.rx.sync(entity: self, update: update) let syncAddress = address.sync(in: context).map(Optional.init) let syncCompany = company.sync(in: context).map(Optional.init) return Observable.zip(syncSelf, syncAddress, syncCompany, resultSelector: CDUser.synced) } func update(entity: CDUser) { entity.uid = uid entity.website = website entity.email = email entity.phone = phone entity.username = username } }
mit
2bc18616ee43f929446304fa97492cd1
31.088235
96
0.637947
4.584034
false
false
false
false
EGF2/ios-client
TestSwift/TestSwift/Graph/Graph.swift
1
689
// // Graph.swift // TestSwift // // Created by LuzanovRoman on 10.11.16. // Copyright © 2016 EigenGraph. All rights reserved. // import Foundation import EGF2 var Graph: EGF2Graph = { let graph = EGF2Graph(name: "EGF2")! graph.serverURL = URL(string: "http://guide.eigengraph.com/v1/") graph.webSocketURL = URL(string: "ws://guide.eigengraph.com:980/v1/listen") graph.showLogs = true graph.idsWithModelTypes = [ "03": User.self, "08": Product.self, "33": DesignerRole.self, "09": Collection.self, "12": Post.self, "13": Comment.self, "06": File.self, "16": Message.self ] return graph }()
mit
374f203ed6b5d4d7d960aa1fa673b929
23.571429
79
0.600291
3.155963
false
false
false
false
GraphQLSwift/GraphQL
Sources/GraphQL/Language/Visitor.swift
1
12786
let QueryDocumentKeys: [Kind: [String]] = [ .name: [], .document: ["definitions"], .operationDefinition: ["name", "variableDefinitions", "directives", "selectionSet"], .variableDefinition: ["variable", "type", "defaultValue"], .variable: ["name"], .selectionSet: ["selections"], .field: ["alias", "name", "arguments", "directives", "selectionSet"], .argument: ["name", "value"], .fragmentSpread: ["name", "directives"], .inlineFragment: ["typeCondition", "directives", "selectionSet"], .fragmentDefinition: ["name", "typeCondition", "directives", "selectionSet"], .intValue: [], .floatValue: [], .stringValue: [], .booleanValue: [], .enumValue: [], .listValue: ["values"], .objectValue: ["fields"], .objectField: ["name", "value"], .directive: ["name", "arguments"], .namedType: ["name"], .listType: ["type"], .nonNullType: ["type"], .schemaDefinition: ["directives", "operationTypes"], .operationTypeDefinition: ["type"], .scalarTypeDefinition: ["name", "directives"], .objectTypeDefinition: ["name", "interfaces", "directives", "fields"], .fieldDefinition: ["name", "arguments", "type", "directives"], .inputValueDefinition: ["name", "type", "defaultValue", "directives"], .interfaceTypeDefinition: ["name", "interfaces", "directives", "fields"], .unionTypeDefinition: ["name", "directives", "types"], .enumTypeDefinition: ["name", "directives", "values"], .enumValueDefinition: ["name", "directives"], .inputObjectTypeDefinition: ["name", "directives", "fields"], .typeExtensionDefinition: ["definition"], .directiveDefinition: ["name", "arguments", "locations"], ] /** * visit() will walk through an AST using a depth first traversal, calling * the visitor's enter function at each node in the traversal, and calling the * leave function after visiting that node and all of its child nodes. * * By returning different values from the enter and leave functions, the * behavior of the visitor can be altered, including skipping over a sub-tree of * the AST (by returning `.skip`), editing the AST by returning a value or nil * to remove the value, or to stop the whole traversal by returning `.break`. * * When using visit() to edit an AST, the original AST will not be modified, and * a new version of the AST with the changes applied will be returned from the * visit function. * * let editedAST = visit(ast, Visitor( * enter: { node, key, parent, path, ancestors in * return * .continue: no action * .skip: skip visiting this node * .break: stop visiting altogether * .node(nil): delete this node * .node(newNode): replace this node with the returned value * }, * leave: { node, key, parent, path, ancestors in * return * .continue: no action * .skip: no action * .break: stop visiting altogether * .node(nil): delete this node * .node(newNode): replace this node with the returned value * } * )) */ @discardableResult func visit(root: Node, visitor: Visitor, keyMap: [Kind: [String]] = [:]) -> Node { let visitorKeys = keyMap.isEmpty ? QueryDocumentKeys : keyMap var stack: Stack? var inArray = false var keys: [IndexPathElement] = ["root"] var index: Int = -1 var edits: [(key: IndexPathElement, node: Node)] = [] var parent: NodeResult? var path: [IndexPathElement] = [] var ancestors: [NodeResult] = [] var newRoot = root repeat { index += 1 let isLeaving = index == keys.count var key: IndexPathElement? var node: NodeResult? let isEdited = isLeaving && !edits.isEmpty if !isLeaving { key = parent != nil ? inArray ? index : keys[index] : nil if let parent = parent { switch parent { case let .node(parent): node = parent.get(key: key!.keyValue!) case let .array(parent): node = .node(parent[key!.indexValue!]) } } else { node = .node(newRoot) } if node == nil { continue } if parent != nil { path.append(key!) } } else { key = ancestors.isEmpty ? nil : path.popLast() node = parent parent = ancestors.popLast() if isEdited { // if inArray { // node = node.slice() // } else { // let clone = node // node = clone // } // // var editOffset = 0 // // for ii in 0..<edits.count { // var editKey = edits[ii].key // let editValue = edits[ii].node // // if inArray { // editKey -= editOffset // } // // if inArray && editValue == nil { // node.splice(editKey, 1) // editOffset += 1 // } else { // // if let node = node, case .node(let n) = node { // n.set(value: editValue, key: editKey.keyValue!) // } // } // } } index = stack!.index keys = stack!.keys edits = stack!.edits inArray = stack!.inArray stack = stack!.prev } var result: VisitResult if case let .node(n) = node! { if !isLeaving { result = visitor.enter( node: n, key: key, parent: parent, path: path, ancestors: ancestors ) } else { result = visitor.leave( node: n, key: key, parent: parent, path: path, ancestors: ancestors ) } if case .break = result { break } if case .skip = result, !isLeaving { _ = path.popLast() continue } else if case let .node(n) = result { edits.append((key!, n!)) if !isLeaving { if let n = n { node = .node(n) } else { _ = path.popLast() continue } } } } // if case .continue = result, isEdited { // edits.append((key!, node!)) // } if !isLeaving { stack = Stack(index: index, keys: keys, edits: edits, inArray: inArray, prev: stack) inArray = node!.isArray switch node! { case let .node(node): keys = visitorKeys[node.kind] ?? [] case let .array(array): keys = array.map { _ in "root" } } index = -1 edits = [] if let parent = parent { ancestors.append(parent) } parent = node } } while stack != nil if !edits.isEmpty { newRoot = edits[edits.count - 1].node } return newRoot } final class Stack { let index: Int let keys: [IndexPathElement] let edits: [(key: IndexPathElement, node: Node)] let inArray: Bool let prev: Stack? init( index: Int, keys: [IndexPathElement], edits: [(key: IndexPathElement, node: Node)], inArray: Bool, prev: Stack? ) { self.index = index self.keys = keys self.edits = edits self.inArray = inArray self.prev = prev } } /** * Creates a new visitor instance which delegates to many visitors to run in * parallel. Each visitor will be visited for each node before moving on. * * If a prior visitor edits a node, no following visitors will see that node. */ func visitInParallel(visitors: [Visitor]) -> Visitor { var skipping = [Node?](repeating: nil, count: visitors.count) return Visitor( enter: { node, key, parent, path, ancestors in for i in 0 ..< visitors.count { if skipping[i] == nil { let result = visitors[i].enter( node: node, key: key, parent: parent, path: path, ancestors: ancestors ) if case .skip = result { skipping[i] = node } else if case .break = result { // skipping[i] = BREAK } else if case .node = result { return result } } } return .continue }, leave: { node, key, parent, path, ancestors in for i in 0 ..< visitors.count { if skipping[i] == nil { let result = visitors[i].leave( node: node, key: key, parent: parent, path: path, ancestors: ancestors ) if case .break = result { // skipping[i] = BREAK } else if case .node = result { return result } } // else if skipping[i] == node { // skipping[i] = nil // } } return .continue } ) } public enum VisitResult { case `continue` case skip case `break` case node(Node?) public var isContinue: Bool { if case .continue = self { return true } return false } } /// A visitor is provided to visit, it contains the collection of /// relevant functions to be called during the visitor's traversal. public struct Visitor { /// A visitor is comprised of visit functions, which are called on each node during the visitor's traversal. public typealias Visit = ( Node, IndexPathElement?, NodeResult?, [IndexPathElement], [NodeResult] ) -> VisitResult private let enter: Visit private let leave: Visit public init(enter: @escaping Visit = ignore, leave: @escaping Visit = ignore) { self.enter = enter self.leave = leave } public func enter( node: Node, key: IndexPathElement?, parent: NodeResult?, path: [IndexPathElement], ancestors: [NodeResult] ) -> VisitResult { return enter(node, key, parent, path, ancestors) } public func leave( node: Node, key: IndexPathElement?, parent: NodeResult?, path: [IndexPathElement], ancestors: [NodeResult] ) -> VisitResult { return leave(node, key, parent, path, ancestors) } } public func ignore( node _: Node, key _: IndexPathElement?, parent _: NodeResult?, path _: [IndexPathElement], ancestors _: [NodeResult] ) -> VisitResult { return .continue } /** * Creates a new visitor instance which maintains a provided TypeInfo instance * along with visiting visitor. */ func visitWithTypeInfo(typeInfo: TypeInfo, visitor: Visitor) -> Visitor { return Visitor( enter: { node, key, parent, path, ancestors in typeInfo.enter(node: node) let result = visitor.enter( node: node, key: key, parent: parent, path: path, ancestors: ancestors ) if !result.isContinue { typeInfo.leave(node: node) if case let .node(node) = result, let n = node { typeInfo.enter(node: n) } } return result }, leave: { node, key, parent, path, ancestors in let result = visitor.leave( node: node, key: key, parent: parent, path: path, ancestors: ancestors ) typeInfo.leave(node: node) return result } ) }
mit
a8bd3b4a273ab81b5d6c15817819a4bd
28.943794
112
0.488347
4.767338
false
false
false
false
hanhailong/practice-swift
Courses/stanford/stanford/cs193p/2015/SmashTag/SmashTag/TweetTableViewController.swift
3
3312
// // TweetTableViewController.swift // SmashTag // // Created by Domenico on 11.04.15. // License: MIT // import UIKit class TweetTableViewController: UITableViewController { var tweets = [[Tweet]]() 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 Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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 NO 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
d245b45466f894131edf7af3b9a03a2d
32.795918
157
0.681763
5.566387
false
false
false
false
Msr-B/Msr.LibSwift
UI/UIScrollView+MSRRefreshControl.swift
2
1721
import UIKit import ObjectiveC private var _UIScrollViewMSRUIRefreshControlAssociationKey: UnsafePointer<Void> { struct _Static { static var key = CChar() } return UnsafePointer<Void>(msr_memory: &_Static.key) } extension UIScrollView { var msr_uiRefreshControl: UIRefreshControl? { set { self.msr_uiRefreshControl?.removeFromSuperview() objc_setAssociatedObject(self, _UIScrollViewMSRUIRefreshControlAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN) if self.msr_uiRefreshControl != nil { addSubview(self.msr_uiRefreshControl!) } } get { return objc_getAssociatedObject(self, _UIScrollViewMSRUIRefreshControlAssociationKey) as? UIRefreshControl } } class func msr_installPanGestureTranslationAdjustmentExtension() { struct _Static { static var id: dispatch_once_t = 0 } dispatch_once(&_Static.id) { method_exchangeImplementations( class_getInstanceMethod(self, "setContentInset:"), class_getInstanceMethod(self, "msr_setContentInset:")) } } internal func msr_setContentInset(contentInset: UIEdgeInsets) { if !(nextResponder() is UITableViewController) && tracking { let offset = contentInset.top - self.contentInset.top var translation = panGestureRecognizer.translationInView(self) translation.y -= offset * 3 / 2 panGestureRecognizer.setTranslation(translation, inView: self) } msr_setContentInset(contentInset) // This is correct because the implementation has been exchanged with setContentInset: } }
gpl-2.0
9119d0c4bf5d0caf9ef2dd7ef5143589
39.023256
128
0.661825
5.429022
false
false
false
false
rakuten-frontend/FrontendTaskSwitcher
FrontendTaskSwitcher/FTSActionMenu.swift
1
4139
// // FTSActionMenu.swift // FrontendTaskSwitcher // // Created by Ogasawara, Tsutomu | Oga | CWDD on 2/3/15. // Copyright (c) 2015 Rakuten Front-end. All rights reserved. // import Cocoa import Foundation enum MenuItem : Int { case Start = 1 case Stop case Remove } class FTSActionMenu: NSMenu, NSMenuDelegate { var params : [String : AnyObject]! var task : FTSTask! let items = [ ["title": "Start", "action": "start:", "key": "", "tag": MenuItem.Start.rawValue], ["title": "Stop", "action": "stop:", "key": "", "tag": MenuItem.Stop.rawValue], ["separator": true], ["title": "Open with Terminal", "action": "openWithTerminal:", "key": ""], ["title": "Open with Finder", "action": "openWithFinder:", "key": ""], ["separator": true], ["title": "Remove...", "action": "remove:", "key": "", "tag": MenuItem.Remove.rawValue], ] required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(title aTitle: String) { super.init(title: aTitle) } init(params: [String: AnyObject]) { super.init() self.delegate = self self.params = params self.autoenablesItems = false self.initMenuItems() self.task = FTSTask() } private func initMenuItems() { for item in self.items { var menuItem : NSMenuItem! if ( item["separator"] as? Bool == true ) { menuItem = NSMenuItem.separatorItem() } else { menuItem = NSMenuItem(title: item["title"] as String, action: Selector(item["action"] as String), keyEquivalent: item["key"] as String) menuItem.target = self menuItem.tag = item["tag"] as? Int ?? 0 } self.addItem(menuItem) } } func start(sender: AnyObject) { let dir = self.params["directory"] as String self.task.start("grunt serve", currentDirectory: dir) } func stop(sender: AnyObject) { self.task.interrupt() } func openWithTerminal(sender: AnyObject) { let dir = self.params["directory"] as String self.task.start("open -a /Applications/Utilities/Terminal.app " + dir + ";") } func openWithFinder(sender: AnyObject) { let dir = self.params["directory"] as String self.task.start("open " + dir + ";") } func remove(sender: AnyObject) { let alert = NSAlert() alert.alertStyle = NSAlertStyle.InformationalAlertStyle alert.informativeText = NSLocalizedString("Confirmation", comment: "") alert.messageText = NSLocalizedString("Do you want to remove the task?", comment: "Message of confirmation Dialog") alert.addButtonWithTitle("Cancel") alert.addButtonWithTitle("Remove") NSApplication.sharedApplication().activateIgnoringOtherApps(true) let result = alert.runModal() if ( result == NSAlertSecondButtonReturn ) { // remove self.removeProject() } } // MARK: - func removeProject() { // stop task if self.task.isRunning() { self.stop(self) } // remove project let path = self.params["path"] as String FTSProjects.sharedInstance.removeValueForKey(path) } // MARK: - menu delegate func menuWillOpen(menu: NSMenu) { if ( self.task.isRunning() ) { menu.itemWithTag(MenuItem.Start.rawValue)?.hidden = true menu.itemWithTag(MenuItem.Stop.rawValue)?.hidden = false menu.itemWithTag(MenuItem.Remove.rawValue)?.enabled = false } else { menu.itemWithTag(MenuItem.Start.rawValue)?.hidden = false menu.itemWithTag(MenuItem.Stop.rawValue)?.hidden = true menu.itemWithTag(MenuItem.Remove.rawValue)?.enabled = true } } }
mit
65e0c466f591da35604e8a812b662616
31.085271
116
0.559555
4.523497
false
false
false
false
jonnguy/HSTracker
HSTracker/Logging/CardIds/DefaultDecks.swift
1
8749
// // DefaultDecks.swift // HSTracker // // Created by Fehervari, Istvan on 1/13/18. // Copyright © 2018 Benjamin Michotte. All rights reserved. // import Foundation struct DefaultDecks { struct DungeonRun { static func deck(for playerClass: CardClass) -> [Card] { switch playerClass { case .rogue: return DungeonRun.rogue case .druid: return DungeonRun.druid case .hunter: return DungeonRun.hunter case .mage: return DungeonRun.mage case .paladin: return DungeonRun.paladin case .shaman: return DungeonRun.shaman case .priest: return DungeonRun.priest case .warlock: return DungeonRun.warlock case .warrior: return DungeonRun.warrior default: logger.error("Failed to select dungeon run starter deck: \(playerClass) is not supported") return [] } } static var rogue: [Card] = { return [ Cards.by(cardId: CardIds.Collectible.Rogue.Backstab)!, Cards.by(cardId: CardIds.Collectible.Rogue.DeadlyPoison)!, Cards.by(cardId: CardIds.Collectible.Rogue.PitSnake)!, Cards.by(cardId: CardIds.Collectible.Rogue.SinisterStrike)!, Cards.by(cardId: CardIds.Collectible.Rogue.GilblinStalker)!, Cards.by(cardId: CardIds.Collectible.Rogue.UndercityHuckster)!, Cards.by(cardId: CardIds.Collectible.Rogue.Si7Agent)!, Cards.by(cardId: CardIds.Collectible.Rogue.UnearthedRaptor)!, Cards.by(cardId: CardIds.Collectible.Rogue.Assassinate)!, Cards.by(cardId: CardIds.Collectible.Rogue.Vanish)! ] }() static var warrior: [Card] = { return [ Cards.by(cardId: CardIds.Collectible.Warrior.Warbot)!, Cards.by(cardId: CardIds.Collectible.Neutral.AmaniBerserker)!, Cards.by(cardId: CardIds.Collectible.Warrior.CruelTaskmaster)!, Cards.by(cardId: CardIds.Collectible.Warrior.HeroicStrike)!, Cards.by(cardId: CardIds.Collectible.Warrior.Bash)!, Cards.by(cardId: CardIds.Collectible.Warrior.FieryWarAxe)!, Cards.by(cardId: CardIds.Collectible.Neutral.HiredGun)!, Cards.by(cardId: CardIds.Collectible.Neutral.RagingWorgen)!, Cards.by(cardId: CardIds.Collectible.Neutral.DreadCorsair)!, Cards.by(cardId: CardIds.Collectible.Warrior.Brawl)! ] }() static var shaman: [Card] = { return [ Cards.by(cardId: CardIds.Collectible.Shaman.AirElemental)!, Cards.by(cardId: CardIds.Collectible.Shaman.LightningBolt)!, Cards.by(cardId: CardIds.Collectible.Shaman.FlametongueTotem)!, Cards.by(cardId: CardIds.Collectible.Neutral.MurlocTidehunter)!, Cards.by(cardId: CardIds.Collectible.Shaman.StormforgedAxe)!, Cards.by(cardId: CardIds.Collectible.Shaman.LightningStorm)!, Cards.by(cardId: CardIds.Collectible.Shaman.UnboundElemental)!, Cards.by(cardId: CardIds.Collectible.Neutral.DefenderOfArgus)!, Cards.by(cardId: CardIds.Collectible.Shaman.Hex)!, Cards.by(cardId: CardIds.Collectible.Shaman.FireElemental)! ] }() static var paladin: [Card] = { return [ Cards.by(cardId: CardIds.Collectible.Paladin.BlessingOfMight)!, Cards.by(cardId: CardIds.Collectible.Neutral.GoldshireFootman)!, Cards.by(cardId: CardIds.Collectible.Paladin.NobleSacrifice)!, Cards.by(cardId: CardIds.Collectible.Paladin.ArgentProtector)!, Cards.by(cardId: CardIds.Collectible.Paladin.Equality)!, Cards.by(cardId: CardIds.Collectible.Paladin.HolyLight)!, Cards.by(cardId: CardIds.Collectible.Neutral.EarthenRingFarseer)!, Cards.by(cardId: CardIds.Collectible.Paladin.Consecration)!, Cards.by(cardId: CardIds.Collectible.Neutral.StormwindKnight)!, Cards.by(cardId: CardIds.Collectible.Paladin.TruesilverChampion)! ] }() static var hunter: [Card] = { return [ Cards.by(cardId: CardIds.Collectible.Hunter.HuntersMark)!, Cards.by(cardId: CardIds.Collectible.Neutral.StonetuskBoar)!, Cards.by(cardId: CardIds.Collectible.Neutral.DireWolfAlpha)!, Cards.by(cardId: CardIds.Collectible.Hunter.ExplosiveTrap)!, Cards.by(cardId: CardIds.Collectible.Hunter.AnimalCompanion)!, Cards.by(cardId: CardIds.Collectible.Hunter.DeadlyShot)!, Cards.by(cardId: CardIds.Collectible.Hunter.EaglehornBow)!, Cards.by(cardId: CardIds.Collectible.Neutral.JunglePanther)!, Cards.by(cardId: CardIds.Collectible.Hunter.UnleashTheHounds)!, Cards.by(cardId: CardIds.Collectible.Neutral.OasisSnapjaw)! ] }() static var druid: [Card] = { return [ Cards.by(cardId: CardIds.Collectible.Druid.EnchantedRaven)!, Cards.by(cardId: CardIds.Collectible.Druid.PowerOfTheWild)!, Cards.by(cardId: CardIds.Collectible.Druid.TortollanForager)!, Cards.by(cardId: CardIds.Collectible.Druid.MountedRaptor)!, Cards.by(cardId: CardIds.Collectible.Druid.Mulch)!, Cards.by(cardId: CardIds.Collectible.Neutral.ShadeOfNaxxramas)!, Cards.by(cardId: CardIds.Collectible.Druid.KeeperOfTheGrove)!, Cards.by(cardId: CardIds.Collectible.Druid.SavageCombatant)!, Cards.by(cardId: CardIds.Collectible.Druid.Swipe)!, Cards.by(cardId: CardIds.Collectible.Druid.DruidOfTheClaw)! ] }() static var warlock: [Card] = { return [ Cards.by(cardId: CardIds.Collectible.Warlock.Corruption)!, Cards.by(cardId: CardIds.Collectible.Warlock.MortalCoil)!, Cards.by(cardId: CardIds.Collectible.Warlock.Voidwalker)!, Cards.by(cardId: CardIds.Collectible.Neutral.KnifeJuggler)!, Cards.by(cardId: CardIds.Collectible.Neutral.SunfuryProtector)!, Cards.by(cardId: CardIds.Collectible.Warlock.DrainLife)!, Cards.by(cardId: CardIds.Collectible.Neutral.ImpMaster)!, Cards.by(cardId: CardIds.Collectible.Neutral.DarkIronDwarf)!, Cards.by(cardId: CardIds.Collectible.Warlock.Hellfire)!, Cards.by(cardId: CardIds.Collectible.Warlock.Doomguard)! ] }() static var mage: [Card] = { return [ Cards.by(cardId: CardIds.Collectible.Mage.ArcaneMissiles)!, Cards.by(cardId: CardIds.Collectible.Mage.ManaWyrm)!, Cards.by(cardId: CardIds.Collectible.Neutral.Doomsayer)!, Cards.by(cardId: CardIds.Collectible.Mage.Frostbolt)!, Cards.by(cardId: CardIds.Collectible.Mage.SorcerersApprentice)!, Cards.by(cardId: CardIds.Collectible.Neutral.EarthenRingFarseer)!, Cards.by(cardId: CardIds.Collectible.Mage.IceBarrier)!, Cards.by(cardId: CardIds.Collectible.Neutral.ChillwindYeti)!, Cards.by(cardId: CardIds.Collectible.Mage.Fireball)!, Cards.by(cardId: CardIds.Collectible.Mage.Blizzard)! ] }() static var priest: [Card] = { return [ Cards.by(cardId: CardIds.Collectible.Priest.HolySmite)!, Cards.by(cardId: CardIds.Collectible.Priest.NorthshireCleric)!, Cards.by(cardId: CardIds.Collectible.Priest.PotionOfMadness)!, Cards.by(cardId: CardIds.Collectible.Priest.MindBlast)!, Cards.by(cardId: CardIds.Collectible.Priest.ShadowWordPain)!, Cards.by(cardId: CardIds.Collectible.Priest.DarkCultist)!, Cards.by(cardId: CardIds.Collectible.Priest.AuchenaiSoulpriest)!, Cards.by(cardId: CardIds.Collectible.Priest.Lightspawn)!, Cards.by(cardId: CardIds.Collectible.Neutral.FaerieDragon)!, Cards.by(cardId: CardIds.Collectible.Priest.HolyNova)! ] }() } }
mit
0eb2d350599e7d5f65fc67a43afaeb3f
48.704545
106
0.597508
4.532642
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Schedule/Presenter Tests/Favourite State Changes/WhenNonFavouritedEventBecomesFavourited_SchedulePresenterShould.swift
1
972
@testable import Eurofurence import EurofurenceModel import XCTest class WhenNonFavouritedEventBecomesFavourited_SchedulePresenterShould: XCTestCase { func testTellTheComponentToShowTheFavouriteIndicator() { let eventViewModel = StubScheduleEventViewModel.random eventViewModel.isFavourite = false let scheduleViewModel = CapturingScheduleViewModel.random scheduleViewModel.events = [ScheduleEventGroupViewModel(title: "", events: [eventViewModel])] let interactor = FakeScheduleInteractor(viewModel: scheduleViewModel) let context = SchedulePresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() let indexPath = IndexPath(item: 0, section: 0) let component = CapturingScheduleEventComponent() context.bind(component, forEventAt: indexPath) eventViewModel.favourite() XCTAssertEqual(.visible, component.favouriteIconVisibility) } }
mit
02148a5419bd2f342f486ec7d345bea4
41.26087
101
0.751029
6.270968
false
true
false
false
grandiere/box
box/View/Main/VParent.swift
3
9441
import UIKit class VParent:UIView { weak var panRecognizer:UIPanGestureRecognizer! private weak var controller:CParent! private weak var layoutBarTop:NSLayoutConstraint! private var panningX:CGFloat? private let kAnimationDuration:TimeInterval = 0.4 private let kBarHeight:CGFloat = 70 private let kMaxXPanning:CGFloat = 60 private let kMaxXDelta:CGFloat = 210 private let kMinXDelta:CGFloat = 30 convenience init(controller:CParent) { self.init() clipsToBounds = true backgroundColor = UIColor.white self.controller = controller let panRecognizer:UIPanGestureRecognizer = UIPanGestureRecognizer( target:self, action:#selector(actionPanRecognized(sender:))) panRecognizer.isEnabled = false self.panRecognizer = panRecognizer addGestureRecognizer(panRecognizer) } //MARK: actions func actionPanRecognized(sender panGesture:UIPanGestureRecognizer) { let location:CGPoint = panGesture.location( in:self) let xPos:CGFloat = location.x switch panGesture.state { case UIGestureRecognizerState.began, UIGestureRecognizerState.possible: if xPos < kMaxXPanning { self.panningX = xPos } break case UIGestureRecognizerState.changed: if let panningX:CGFloat = self.panningX { var deltaX:CGFloat = xPos - panningX if deltaX > kMaxXDelta { panRecognizer.isEnabled = false } else { if deltaX < 0 { deltaX = 0 } guard let topView:VView = subviews.last as? VView else { return } topView.layoutLeft.constant = deltaX } } break case UIGestureRecognizerState.cancelled, UIGestureRecognizerState.ended, UIGestureRecognizerState.failed: if let panningX:CGFloat = self.panningX { let deltaX:CGFloat = xPos - panningX if deltaX > kMinXDelta { gesturePop() } else { gestureRestore() } } panningX = nil break } } //MARK: private private func gesturePop() { controller.pop(horizontal:CParent.TransitionHorizontal.fromRight) } private func gestureRestore() { guard let topView:VView = subviews.last as? VView else { return } topView.layoutLeft.constant = 0 UIView.animate(withDuration:kAnimationDuration) { self.layoutIfNeeded() } } //MARK: public func scrollDidScroll(offsetY:CGFloat) { let barTopConstant:CGFloat if offsetY > 0 { barTopConstant = offsetY } else { barTopConstant = 0 } layoutBarTop.constant = -barTopConstant } func mainView(view:VView) { addSubview(view) view.layoutTop = NSLayoutConstraint.topToTop( view:view, toView:self) view.layoutBottom = NSLayoutConstraint.bottomToBottom( view:view, toView:self) view.layoutLeft = NSLayoutConstraint.leftToLeft( view:view, toView:self) view.layoutRight = NSLayoutConstraint.rightToRight( view:view, toView:self) } func slide( currentView:VView, newView:VView, left:CGFloat, completion:@escaping(() -> ())) { addSubview(newView) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self, constant:-left) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self, constant:-left) layoutIfNeeded() currentView.layoutRight.constant = left currentView.layoutLeft.constant = left newView.layoutRight.constant = 0 newView.layoutLeft.constant = 0 UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() }) { (done:Bool) in currentView.removeFromSuperview() completion() } } func push( newView:VView, left:CGFloat, top:CGFloat, background:Bool, completion:@escaping(() -> ())) { if background { let pushBackground:VParentPushBackground = VParentPushBackground() newView.pushBackground = pushBackground addSubview(pushBackground) NSLayoutConstraint.equals( view:pushBackground, toView:self) } addSubview(newView) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self, constant:top) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self, constant:top) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self, constant:left) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self, constant:left) layoutIfNeeded() if top >= 0 { newView.layoutTop.constant = 0 newView.layoutBottom.constant = 0 } else { newView.layoutBottom.constant = 0 newView.layoutTop.constant = 0 } if left >= 0 { newView.layoutLeft.constant = 0 newView.layoutRight.constant = 0 } else { newView.layoutRight.constant = 0 newView.layoutLeft.constant = 0 } UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() newView.pushBackground?.alpha = 1 }) { (done:Bool) in completion() } } func animateOver( newView:VView, completion:@escaping(() -> ())) { newView.alpha = 0 addSubview(newView) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self) UIView.animate( withDuration:kAnimationDuration, animations: { [weak newView] in newView?.alpha = 1 }) { (done:Bool) in completion() } } func pop( currentView:VView, left:CGFloat, top:CGFloat, completion:@escaping(() -> ())) { currentView.layoutTop.constant = top currentView.layoutBottom.constant = top currentView.layoutRight.constant = left currentView.layoutLeft.constant = left UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() currentView.pushBackground?.alpha = 0 }) { (done:Bool) in currentView.pushBackground?.removeFromSuperview() currentView.removeFromSuperview() completion() } } func dismissAnimateOver( currentView:VView, completion:@escaping(() -> ())) { UIView.animate( withDuration:kAnimationDuration, animations: { [weak currentView] in currentView?.alpha = 0 }) { [weak currentView] (done:Bool) in currentView?.removeFromSuperview() completion() } } }
mit
bd4e4b1e5d70e4b339c9a4f437432e40
25.08011
78
0.495181
6.370445
false
false
false
false
sagiii/iOSAccelerometerExample
CoreMotionExample/LineGraphView.swift
1
2004
// // LineGraphView.swift // iOSAccelerometerExample // // Created by 鷺坂隆志 on 2017/09/18. // Copyright © 2017年 Maxim Bilan. All rights reserved. // import UIKit import CoreMotion class LineGraphView: UIView { var data:[CMAccelerometerData] = [] override func draw(_ rect: CGRect) { var data_ = data let MAGNIFY: Double = Double(rect.height / 3) let ORG_X: CGFloat = 0 let ORG_Y: CGFloat = rect.height / 2 if (data_.count > 0) { var line = UIBezierPath() line.move(to: CGPoint(x: ORG_X, y: ORG_Y)) line.addLine(to: CGPoint(x: ORG_X + rect.width, y: ORG_Y)) UIColor.black.setStroke() line.lineWidth = 1 line.stroke() line = UIBezierPath() line.move(to: CGPoint(x: ORG_X, y: ORG_Y)) for i in 0...(data_.count - 1) { line.addLine(to: CGPoint(x: ORG_X + CGFloat(Float(i) / Float(data_.count)) * rect.width, y: ORG_Y + CGFloat(data_[i].acceleration.x * MAGNIFY))) } UIColor.red.setStroke() line.lineWidth = 1 line.stroke(); line = UIBezierPath() line.move(to: CGPoint(x: ORG_X, y: ORG_Y)) for i in 0...(data_.count - 1) { line.addLine(to: CGPoint(x: ORG_X + CGFloat(Float(i) / Float(data_.count)) * rect.width, y: ORG_Y + CGFloat(data_[i].acceleration.y * MAGNIFY))) } UIColor.green.setStroke() line.lineWidth = 1 line.stroke(); line = UIBezierPath() line.move(to: CGPoint(x: ORG_X, y: ORG_Y)) for i in 0...(data_.count - 1) { line.addLine(to: CGPoint(x: ORG_X + CGFloat(Float(i) / Float(data_.count)) * rect.width, y: ORG_Y + CGFloat(data_[i].acceleration.z * MAGNIFY))) } UIColor.blue.setStroke() line.lineWidth = 1 line.stroke(); } } }
mit
cea5f0d47f33e95f4d5e7f8529ddc314
33.362069
160
0.521826
3.603978
false
false
false
false
WenjieZhang1988/WJSimpleNetwork
WJSimpleNetwork/WJSimpleNetwork/WJSimpleNetwork.swift
1
10169
// // WJSimpleNetwork.swift // WJSimpleNetwork // // Created by Kevin on 15/3/23. // Copyright (c) 2015年 Kevin. All rights reserved. // import Foundation import UIKit /// 常用的网络访问方法 /// /// - GET: 参数在URL中 /// - POST: 参数在请求体中 enum HTTPMethod: String { case GET = "GET" case POST = "POST" } class WJSimpleNetwork { /// 定义闭包类型,类型别名-> 首字母一定要大写 /// /// :param: result 请求结果 /// :param: error 错误信息 typealias Completion = (result: AnyObject?, error: NSError?) -> () /// 异步下载网络图像 /// /// :param: urlString urlString /// :param: completion 完成回调 func requestImage(urlString: String, _ completion: Completion) { // 1. 调用 download 下载图像,如果图片已经被缓存过,就不会再次下载 downloadImage(urlString) { (_, error) -> () in // 2.1 错误处理 if error != nil { completion(result: nil, error: error) } else { // 2.2 图像是保存在沙盒路径中的,文件名是 url + md5 let path = self.fullImageCachePath(urlString) // 将图像从沙盒加载到内存 var image = UIImage(contentsOfFile: path) // 提示:尾随闭包,如果没有参数,没有返回值,都可以省略! dispatch_async(dispatch_get_main_queue()) { completion(result: image, error: nil) } } } } /// 完整的图片 URL 缓存路径 func fullImageCachePath(urlString: String) -> String { var path = urlString.md5 return cachePath!.stringByAppendingPathComponent(path) } /// 下载多张图片 - 对于多张图片下载,并不处理错误! /// /// :param: urls 图片 URL 数组 /// :param: completion 所有图片下载完成后的回调 func downloadImages(urls: [String], _ completion: Completion) { // 利用调度组统一监听一组异步任务执行完毕 let group = dispatch_group_create() // 遍历数组 for url in urls { // 进入调度组 dispatch_group_enter(group) downloadImage(url) { (result, error) -> () in // 离开调度组 dispatch_group_leave(group) } } // 在主线程回调 dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in // 所有任务完成后回调 completion(result: nil, error: nil) } } /// 下载单张图片并且保存到沙盒 /// /// :param: urlString urlString /// :param: completion 完成回调 func downloadImage(urlString: String, _ completion: Completion) { // 1.目标路径 let path = fullImageCachePath(urlString) // 2. 缓存检测,如果文件已经下载完成直接返回 if NSFileManager.defaultManager().fileExistsAtPath(path) { // println("\(urlString) 图片已经缓存") completion(result: nil, error: nil) return } // 3. 下载图像 - 如果 url 真的无法从字符串创建 // 不会调用 completion 的回调 if let url = NSURL(string: urlString) { self.session!.downloadTaskWithURL(url) { (location, _, error) -> Void in // 错误处理 if error != nil { completion(result: nil, error: error) return } // 将文件赋值到缓存路径 NSFileManager.defaultManager().copyItemAtPath(location.path!, toPath: path, error: nil) // 直接回调,不传递任何参数 completion(result: nil, error: nil) }.resume() } else { let error = NSError(domain: WJSimpleNetwork.errorDomain, code: -1, userInfo: ["error": "无法创建 URL"]) completion(result: nil, error: error) } } // 在 swift 中,一个命名空间内部,几乎都是开放的,彼此可以互相访问 // 如果不想开发的内容,可以使用 private 保护起来 /// 完整图像缓存路径 private lazy var cachePath: String? = { // 1.cache var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String path = path.stringByAppendingPathComponent(imageCachePath) // 2. 检查缓存路径是否存在 - 注意:必须准确地指出类型 ObjCBool var isDirectory: ObjCBool = true // 无论存在目录还是文件,都会返回 true,是否是路径由 isDirectory 来决定 let exists = NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) // println("isDirectory: \(isDirectory) exists \(exists) path: \(path)") // 3. 如果有同名的文件就删除,判断是否是文件,否则目录也同样会被删除 if exists && !isDirectory { NSFileManager.defaultManager().removeItemAtPath(path, error: nil) } // 4. 直接创建目录,如果目录已经存在,就什么都不做 // withIntermediateDirectories -> 是否智能创建层级目录 NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil, error: nil) return path }() /// 缓存路径的常量 - 类变量不能存储内容,但是可以返回数值 private static var imageCachePath = "com.baidu.imagecache" // MARK: - 请求 JSON /// 请求 JSON /// /// :param: method HTTP 访问方法 /// :param: urlString urlString /// :param: params 可选参数字典 /// :param: completion 完成回调 func requestJSON(method: HTTPMethod, _ urlString: String, _ params: [String: String]?, _ completion: Completion) { // 实例化网络请求 if let request = request(method, urlString, params) { // 访问网络 session!.dataTaskWithRequest(request, completionHandler: { (data, _, error) -> Void in // 如果有错误,直接回调,将网络访问的错误传回 if error != nil { completion(result: nil, error: error) return } // 反序列化 -> 字典或者数组 let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) // JSON为空 if json == nil { let error = NSError(domain: WJSimpleNetwork.errorDomain, code: -1, userInfo: ["error": "反序列化失败"]) completion(result: nil, error: error) } else { // JSON有值 dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(result: json, error: nil) }) } }).resume() return } // 如果网络请求没有创建成功,应该生成一个错误,提供给其他的开发者 // domain: 错误所属领域字符串 com.itheima.error // code: 如果是复杂的系统,可以自己定义错误编号 // userInfo: 错误信息字典 let error = NSError(domain: WJSimpleNetwork.errorDomain, code: -1, userInfo: ["error": "请求建立失败"]) completion(result: nil, error: error) } // 错误页面,静态属性,跟对象无关 private static let errorDomain = "com.baidu.error" /// 返回网络访问的请求 /// /// :param: method HTTP 访问方法 /// :param: urlString urlString /// :param: params 可选参数字典 /// /// :returns: 可选网络请求 func request(method: HTTPMethod, _ urlString: String, _ params: [String: String]?) -> NSURLRequest? { // isEmpty 是 "" 或者 nil if urlString.isEmpty { return nil } // 记录 urlString,因为传入的参数是不可变的 var urlStr = urlString var req: NSMutableURLRequest? // GET 请求 if method == .GET { // 生成查询字符串 let query = queryString(params) // 如果有拼接参数 if query != nil { urlStr += "?" + query! } // 实例化请求 req = NSMutableURLRequest(URL: NSURL(string: urlStr)!) // POST 请求 } else { if let query = queryString(params) { req = NSMutableURLRequest(URL: NSURL(string: urlStr)!) // 设置请求方法,swift 语言中,枚举类型,取返回值需要使用一个 rawValue req!.HTTPMethod = method.rawValue // 设置数据体 req!.HTTPBody = query.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) } } return req } /// 生成查询字符串 /// /// :param: params 可选字典 /// /// :returns: 拼接完成的字符串 private func queryString(params: [String: String]?) -> String? { // 判断参数 if params == nil { return nil } // 定义一个数组 var array = [String]() // 遍历字典 for (k, v) in params! { let str = k + "=" + v.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! array.append(str) } return join("&", array) } /// 全局网络会话,可以利用构造函数,设置不同的网络会话配置 private lazy var session: NSURLSession? = { return NSURLSession.sharedSession() }() }
mit
86e12be71a779d50f3c2a90abaae8f31
33.193548
154
0.537563
4.293165
false
false
false
false
zzxuxu/TestKitchen
TestKitchen/TestKitchen/Classes/Common/BaseViewController.swift
1
1191
// // BaseViewController.swift // TestKitchen // // Created by 王健旭 on 2016/10/21. // Copyright © 2016年 王健旭. All rights reserved. // import UIKit /* 视图控制器的公共父类 用来封装一些共有的代码 */ class BaseViewController: UIViewController { //导航上面添加按钮 func addNavBtn(imageName: String, target: AnyObject?, action:Selector, isLeft: Bool) { let btn = UIButton.createBtn(nil, bgImageName: imageName, highlightImageName: nil, selectImageName: nil, target: target, action: action) btn.frame = CGRectMake(0, 0, 30, 45) let barBtn = UIBarButtonItem(customView: btn) if isLeft { //左边按钮 navigationItem.leftBarButtonItem = barBtn }else { //右边按钮 navigationItem.rightBarButtonItem = barBtn } } override func viewDidLoad() { super.viewDidLoad() //设置背景颜色 view.backgroundColor = UIColor(white: 0.95, alpha: 1.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
674cebf2f11e094d69a86e18a9a47b79
21.244898
144
0.63211
4.27451
false
false
false
false
MagicianDL/Shark
Shark/Extensions/UIColor+Shark.swift
1
3735
// // UIColor+Shark.swift // Shark // // Created by Dalang on 2017/3/2. // Copyright © 2017年 青岛鲨鱼汇信息技术有限公司. All rights reserved. // import UIKit extension UIColor { class var mainBlue: UIColor { return UIColor(hexString: "#3E71A0") } class var mainGray: UIColor { return UIColor(hexString: "#F2F2F2") } class var random: UIColor { let red = CGFloat(arc4random_uniform(256)) let green = CGFloat(arc4random_uniform(256)) let blue = CGFloat(arc4random_uniform(256)) let alpha = CGFloat(arc4random_uniform(256)) return UIColor(r: red, g: green, b: blue, a: alpha) } } // MARK: Hex extension UIColor { /// 通过32位整型创建颜色 /// /// - Parameter hex: UInt32 convenience init(hex: UInt32) { let mask = 0x000000FF let r = Int(hex >> 16) & mask let g = Int(hex >> 8) & mask let b = Int(hex) & mask let red = CGFloat(r) / 255.0 let green = CGFloat(g) / 255.0 let blue = CGFloat(b) / 255.0 self.init(red:red, green:green, blue:blue, alpha:1) } /// 通过32位整型字符串创建颜色 /// /// - Parameter hexString: UInt32 字符串 convenience init(hexString: String) { let hexString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let scanner = Scanner(string: hexString) if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var color: UInt32 = 0 if scanner.scanHexInt32(&color) { self.init(hex: color) } else { self.init(hex: 0x000000) } } /// 颜色 -> UInt32 /// /// - Returns: UInt32 final func toHex() -> UInt32 { let rgba: RGBA = toRGBAComponents() let colorToUInt32 = roundToHex(rgba.r) << 16 | roundToHex(rgba.g) << 8 | roundToHex(rgba.b) return colorToUInt32 } /// 颜色 -> UInt32 String /// /// - Returns: UInt32 String final func toHexString() -> String { return String(format:"#%06x", toHex()) } } // MARK: RGBA extension UIColor { typealias RGBA = (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) /// 通过rgba初始化 /// /// - Parameters: /// - r: 0 ~ 255 /// - g: 0 ~ 255 /// - b: 0 ~ 255 /// - a: 0 ~ 255, 默认 255 convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 255) { self.init(red: clip(r, 0, 255) / 255, green: clip(g, 0, 255) / 255, blue: clip(b, 0, 255) / 255, alpha: clip(a, 0, 255) / 255) } /// 获取 rgba 属性 /// /// - Returns: RGBA final func toRGBAComponents() -> RGBA { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) } /// R 属性 final var redComponent: CGFloat { return self.toRGBAComponents().r } /// G 属性 final var greenComponent: CGFloat { return self.toRGBAComponents().g } /// B 属性 final var blueComponent: CGFloat { return self.toRGBAComponents().b } /// A 属性 final var alphaComponent: CGFloat { return self.toRGBAComponents().a } } // MARK: Utils func clip<T: Comparable>(_ v: T, _ minimum: T, _ maximum: T) -> T { return max(min(v, maximum), minimum) } func roundToHex(_ x: CGFloat) -> UInt32 { return UInt32(round(1000 * x) / 1000 * 255) }
mit
693e5176a6b4f0901c5574f0a8d51c55
22.75
134
0.529363
3.710175
false
false
false
false
rsrose21/cluelist
ClueList/ClueList/ToDoCellTableViewCell.swift
1
17610
// // ToDoCellTableViewCell.swift // ClueList // // Created by Ryan Rose on 10/12/15. // Copyright © 2015 GE. All rights reserved. // This is a TableViewCell with AutoLayout where the cell row height dynamically changes to fit the cell contents // http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights // import UIKit import PureLayout // A protocol that the TableViewCell uses to inform its delegate of state change protocol TableViewCellDelegate { // Indicates that the edit process has begun for the given cell func cellDidBeginEditing(editingCell: ToDoCellTableViewCell) // Indicates that the edit process has committed for the given cell func cellDidEndEditing(editingCell: ToDoCellTableViewCell) } class ToDoCellTableViewCell: UITableViewCell, UITextFieldDelegate, UIButtonDelegate { //Defining fonts of size and type let titleFont:UIFont = UIFont(name: Constants.UIFonts.HEADLINE_FONT, size: Constants.UIFonts.HEADLINE_FONT_SIZE)! let bodyFont:UIFont = UIFont(name: Constants.UIFonts.BODY_FONT, size: Constants.UIFonts.BASE_FONT_SIZE)! var originalCenter = CGPoint() var hintOnDragRelease = false, revealOnDragRelease = false // The object that acts as delegate for this cell. var delegate: TableViewCellDelegate? // The item that this cell renders. var toDoItem: ToDoItem? { didSet { let item = toDoItem! // reset the cell label contents titleLabel.text = nil bodyLabel.text = nil editLabel.text = nil if item.text == Constants.Messages.PLACEHOLDER_TEXT { editLabelOnly = true } else { editLabelOnly = false //if we have some factoids then randomly select one to display as the To Do label titleLabel.text = item.getRandomFactoid() if titleLabel.text == nil { //no factoids returned for this task, show the original task instead titleLabel.text = item.text } if item.deadline != nil { bodyLabel.text = "Due " + timeAgoSinceDate(item.deadline!, numericDates: false) } toggleCompleted(item.completed) } setNeedsLayout() } } //labels that serve as contextual clues for our swipe left/right gestures var tickLabel: UILabel!, clueLabel: UILabel! let kUICuesMargin: CGFloat = 10.0, kUICuesWidth: CGFloat = 50.0 var didSetupConstraints = false var titleLabel: UILabel = UILabel.newAutoLayoutView() var bodyLabel: UILabel = UILabel.newAutoLayoutView() var editLabel: UITextField = UITextField() var checkbox: DOCheckbox! var editLabelOnly: Bool = false override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } // utility method for creating the contextual cues func createCueLabel() -> UILabel { let label = UILabel(frame: CGRect.null) label.textColor = UIColor.whiteColor() label.font = UIFont.boldSystemFontOfSize(32.0) label.backgroundColor = UIColor.clearColor() return label } func setupViews() { backgroundColor = UIColor.clearColor() //prevent highlight from selecting cell when clicking to drag selectionStyle = .None editLabel.delegate = self editLabel.contentVerticalAlignment = .Center editLabel.placeholder = Constants.Messages.PLACEHOLDER_TEXT if Constants.Data.DEBUG_LAYERS { editLabel.layer.borderColor = UIColor.blackColor().CGColor editLabel.layer.borderWidth = 1.0; } contentView.addSubview(editLabel) titleLabel.lineBreakMode = .ByTruncatingTail titleLabel.numberOfLines = 0 titleLabel.textAlignment = .Left if Constants.Data.DEBUG_LAYERS { titleLabel.textColor = UIColor.blackColor() titleLabel.backgroundColor = UIColor(hexString: "#eeeeeeff") } contentView.addSubview(titleLabel) bodyLabel.lineBreakMode = .ByTruncatingTail bodyLabel.numberOfLines = 1 bodyLabel.textAlignment = .Left if Constants.Data.DEBUG_LAYERS { bodyLabel.textColor = UIColor.darkGrayColor() bodyLabel.backgroundColor = UIColor(hexString: "#ccccccff") } contentView.addSubview(bodyLabel) checkbox = layoutCheckbox(UIColor(red: 231/255, green: 76/255, blue: 60/255, alpha: 1.0)) contentView.addSubview(checkbox) // add a pan recognizer for handling cell dragging let recognizer = UIPanGestureRecognizer(target: self, action: "handlePan:") recognizer.delegate = self addGestureRecognizer(recognizer) // tick and cross labels for context cues tickLabel = createCueLabel() tickLabel.text = "\u{2713}" tickLabel.textAlignment = .Right addSubview(tickLabel) clueLabel = createCueLabel() clueLabel.text = "?" clueLabel.textAlignment = .Left addSubview(clueLabel) updateFonts() } let kLabelLeftMargin: CGFloat = 15.0 override func layoutSubviews() { super.layoutSubviews() layoutFrames() } func layoutFrames() { // ensure the background occupies the full bounds contentView.frame = bounds //set up default dimensions let padding: CGFloat = 5 let buttonWidth: CGFloat = 40 var marginLeft: CGFloat = 0.0 var width = frame.width var height = frame.height if editLabelOnly == false { editLabel.hidden = true //position our contextual clue labels off screen tickLabel.frame = CGRect(x: -kUICuesWidth - kUICuesMargin, y: 0, width: kUICuesWidth, height: bounds.size.height) clueLabel.frame = CGRect(x: bounds.size.width + kUICuesMargin, y: 0, width: kUICuesWidth, height: bounds.size.height) if !checkbox.hidden { marginLeft = CGRectGetMaxX(checkbox.frame) + 10 //give some room for the accessory button width = (frame.width - marginLeft) - buttonWidth } else { //give some room for the move button width = (frame.width - marginLeft) - (buttonWidth * 2) } height = frame.height - 35.0 checkbox.frame = CGRectMake(padding, (frame.height - 25)/2, 25, 25) titleLabel.frame = CGRectMake(marginLeft, 0, width, height) bodyLabel.frame = CGRectMake(marginLeft, CGRectGetMaxY(titleLabel.frame), width, 35.0) } else { //show textfield and hide checkbox and accessory button when editing editLabel.hidden = false checkbox.hidden = true titleLabel.hidden = false bodyLabel.hidden = false accessoryType = .None } if Constants.Data.DEBUG_LAYERS { editLabel.backgroundColor = UIColor(hexString: "#eeeeeeff") } editLabel.frame = CGRectMake(marginLeft, 0, width, Constants.UIFonts.HEADLINE_FONT_SIZE) } func layoutCheckbox(color: UIColor?) -> DOCheckbox { let style: DOCheckboxStyle = .FilledRoundedSquare let size: CGFloat = 25.0 let frame: CGFloat = 25.0 let checkBoxPosition = (size - frame) / 2 let checkbox = DOCheckbox(frame: CGRectMake(25.0, 25.0, size, size), checkboxFrame: CGRectMake(checkBoxPosition, checkBoxPosition, frame, frame)) checkbox.setPresetStyle(style, baseColor: color) return checkbox } override func updateConstraints() { if !didSetupConstraints { // Note: if the constraints you add below require a larger cell size than the current size (which is likely to be the default size {320, 44}), you'll get an exception. // As a fix, you can temporarily increase the size of the cell's contentView so that this does not occur using code similar to the line below. // See here for further discussion: https://github.com/Alex311/TableCellWithAutoLayout/commit/bde387b27e33605eeac3465475d2f2ff9775f163#commitcomment-4633188 //contentView.bounds = CGRect(x: 0.0, y: 0.0, width: 99999.0, height: 99999.0) if !editLabelOnly { // Prevent the two UILabels from being compressed below their intrinsic content height NSLayoutConstraint.autoSetPriority(UILayoutPriorityRequired) { self.titleLabel.autoSetContentCompressionResistancePriorityForAxis(.Vertical) self.bodyLabel.autoSetContentCompressionResistancePriorityForAxis(.Vertical) } titleLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_TOP) titleLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_LEFT) titleLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_RIGHT) // This constraint is an inequality so that if the cell is slightly taller than actually required, extra space will go here bodyLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: titleLabel, withOffset: 0.0, relation: .GreaterThanOrEqual) bodyLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_LEFT) bodyLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_RIGHT) bodyLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_BOTTOM) } //we overlay the editLabel on top of the titleLabel so we set the constraints for both to be the same editLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_TOP) editLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_LEFT) editLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_RIGHT) editLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: Constants.UIDimensions.TABLE_CELL_PADDING_BOTTOM) didSetupConstraints = true } super.updateConstraints() } func updateFonts() { if !editLabelOnly { titleLabel.font = titleFont bodyLabel.font = bodyFont } editLabel.font = titleFont } func resetConstraints() { //didSetupConstraints = false updateFonts() setNeedsUpdateConstraints() updateConstraintsIfNeeded() } //highlight text in a UILabel: http://stackoverflow.com/questions/3586871/bold-non-bold-text-in-a-single-uilabel func highlightText(haystack: NSString, needle: NSString) -> NSMutableAttributedString { //Making dictionaries of fonts that will be passed as an attribute let textDict:NSDictionary = NSDictionary(object: titleFont, forKey: NSFontAttributeName) let attributedString = NSMutableAttributedString(string: haystack as String, attributes: textDict as? [String : AnyObject]) //the clue could be multiple words, so we break them up here for separate highlighting let parts = needle.componentsSeparatedByString(" ") //loop through each word and highlight them in subject for word in parts { do { try attributedString.highlightStrings(word as String, fontName: Constants.UIFonts.HIGHLIGHT_FONT, fontSize: Constants.UIFonts.HEADLINE_FONT_SIZE) } catch { NSLog("Error highlighting text: \(error)") } } return attributedString } func strikeThrough(str: String, style: Int) -> NSAttributedString { //http://stackoverflow.com/questions/13133014/uilabel-with-text-struck-through let attributeString = NSAttributedString(string: str, attributes: [NSStrikethroughStyleAttributeName: style, NSStrikethroughColorAttributeName: UIColor.redColor()]) return attributeString } //helper to indicate a table view cell item is completed/not completed func toggleCompleted(completed: Bool) { if completed { // fade completed cell contentView.alpha = 0.6 titleLabel.attributedText = strikeThrough(titleLabel.text!, style: NSUnderlineStyle.StyleSingle.rawValue) editLabel.attributedText = strikeThrough(editLabel.text!, style: NSUnderlineStyle.StyleSingle.rawValue) // hide due date for completed items bodyLabel.hidden = true } else { // make cell opaque contentView.alpha = 1.0 titleLabel.attributedText = strikeThrough(titleLabel.text!, style: NSUnderlineStyle.StyleNone.rawValue) editLabel.attributedText = strikeThrough(editLabel.text!, style: NSUnderlineStyle.StyleNone.rawValue) bodyLabel.hidden = false } } //MARK: - horizontal pan gesture methods //http://www.raywenderlich.com/77974/making-a-gesture-driven-to-do-list-app-like-clear-in-swift-part-1 func handlePan(recognizer: UIPanGestureRecognizer) { // 1 if recognizer.state == .Began { // when the gesture begins, record the current center location originalCenter = center } // 2 if recognizer.state == .Changed { let translation = recognizer.translationInView(self) center = CGPointMake(originalCenter.x + translation.x, originalCenter.y) // has the user dragged the item far enough to initiate a hint/reveal? hintOnDragRelease = frame.origin.x < -frame.size.width / 2.0 revealOnDragRelease = frame.origin.x > frame.size.width / 2.0 // fade the contextual clues let cueAlpha = fabs(frame.origin.x) / (frame.size.width / 2.0) tickLabel.alpha = cueAlpha clueLabel.alpha = cueAlpha // indicate when the user has pulled the item far enough to invoke the given action tickLabel.textColor = revealOnDragRelease ? UIColor.greenColor() : UIColor.whiteColor() clueLabel.textColor = hintOnDragRelease ? UIColor.redColor() : UIColor.whiteColor() } // 3 if recognizer.state == .Ended { let originalFrame = CGRect(x: 0, y: frame.origin.y, width: bounds.size.width, height: bounds.size.height) if hintOnDragRelease { //highlight the "clue" in the factoid for the user titleLabel.attributedText = highlightText((titleLabel.text)!, needle: (toDoItem?.clue)!) // Make sure the constraints have been added to this cell, since it may have just been created from scratch resetConstraints() layoutFrames() } else if revealOnDragRelease { //reveal the original description editLabel.text = toDoItem?.text titleLabel.hidden = true editLabel.hidden = false } UIView.animateWithDuration(0.2, animations: {self.frame = originalFrame}) } } //only allow horizontal pans override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer { let translation = panGestureRecognizer.translationInView(superview!) if fabs(translation.x) > fabs(translation.y) { return true } return false } return false } // MARK: - UITextFieldDelegate methods func textFieldShouldReturn(textField: UITextField) -> Bool { // close the keyboard on Enter textField.resignFirstResponder() return false } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { // disable editing of completed to-do items if toDoItem != nil { return !toDoItem!.completed } return false } func textFieldDidEndEditing(textField: UITextField) { if toDoItem != nil { toDoItem!.text = textField.text! } if delegate != nil { delegate!.cellDidEndEditing(self) } } func textFieldDidBeginEditing(textField: UITextField) { if delegate != nil { delegate!.cellDidBeginEditing(self) } } // MARK: - UIButtonDelegate methods func toDoItemCompleted(toDoItem: ToDoItem) { //update cell to mark/unmark item completed status toggleCompleted(!toDoItem.completed) } }
mit
766eba4d618a496a35a12137ffd4ef2e
41.740291
179
0.637174
5.289576
false
false
false
false
prcela/NKNetworkKit
Example/Tests/Tests.swift
1
1201
// https://github.com/Quick/Quick import Quick import Nimble import NKNetworkKit 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" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
a56c13bcde6155a543b202799bde0fc7
22.9
63
0.358159
5.021008
false
false
false
false
XSega/Words
Words/UIColor+Extension.swift
1
1774
// // UIColor+Extension.swift // ThreatNet // // Created by Admin on 03/02/2017. // Copyright © 2017 Baron Services Inc. All rights reserved. // import UIKit extension UIColor { convenience init(hexString: String) { let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let a, r, g, b: UInt32 switch hex.characters.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: (a, r, g, b) = (255, 0, 0, 0) } self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } public class var wrong: UIColor { get { return UIColor(hexString: "FF8686") } } public class var correct: UIColor { get { return UIColor(hexString: "8CC252") } } public class var skip: UIColor { get { return UIColor(hexString: "56667D") } } public class var blueBackground: UIColor { get { return UIColor(red:0.36, green:0.61, blue:0.93, alpha:1.0) } } public class var varianTextColor: UIColor { get { return UIColor(hexString: "333333") } } public class var hintTextColor: UIColor { get { return UIColor(hexString: "8DBAF3") } } }
mit
05701e49e2829bc03063abd7184b4ec8
26.703125
114
0.50987
3.510891
false
false
false
false
1aurabrown/eidolon
Kiosk/Help/HelpViewController.swift
1
7684
import UIKit class HelpViewController: UIViewController { var positionConstraints: NSArray? private let stackView = ORStackView() private let sideMargin: Float = 90.0 private let topMargin: Float = 45.0 private let headerMargin: Float = 30.0 private let inbetweenMargin: Float = 10.0 override func viewDidLoad() { super.viewDidLoad() // Configure view view.backgroundColor = UIColor.whiteColor() // Configure subviews let assistanceLabel = ARSerifLabel() assistanceLabel.font = assistanceLabel.font.fontWithSize(35) assistanceLabel.text = "Assistance" let stuckLabel = titleLabel() stuckLabel.text = "Stuck in the process?" let stuckExplainLabel = wrappingSerifLabel() stuckExplainLabel.text = "Find the nearest Artsy representative and they will assist you with anything you may need help with." let bidLabel = titleLabel() bidLabel.text = "How do I place a bid?" let bidExplainLabel = wrappingSerifLabel() bidExplainLabel.text = "Enter the amount you would like to bid. You will confirm this bid in the next step.\n\nEnter your mobile number or bidder number and PIN that you received when you registered." bidExplainLabel.makeSubstringsBold(["mobile number", "bidder number", "PIN"]) let registerButton = ARBlackFlatButton() registerButton.setTitle("Register", forState: .Normal) registerButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (_) -> Void in (UIApplication.sharedApplication().delegate as? AppDelegate)?.showRegistration() return } let txtLabel = wrappingSerifLabel() txtLabel.text = "We will send you a text message and email to update you on the status of your bid." let bidderDetailsLabel = titleLabel() bidderDetailsLabel.text = "What Are Bidder Details?" let bidderDetailsExplainLabel = wrappingSerifLabel() bidderDetailsExplainLabel.text = "The bidder number is how you can identify yourself to bid and see your place in bid history. The PIN is a four digit number that authenticates your bid." bidderDetailsExplainLabel.makeSubstringsBold(["bidder number", "PIN"]) let questionsLabel = titleLabel() questionsLabel.text = "Questions About Artsy Auctions?" let questionsExplainView: UIView = { let view = UIView() let conditionsLabel = ARSerifLabel() conditionsLabel.font = conditionsLabel.font.fontWithSize(18) conditionsLabel.text = "View our " let conditionsButton = ARUnderlineButton() conditionsButton.setTitle("Conditions of Sale".uppercaseString, forState: .Normal) conditionsButton.setTitleColor(UIColor.blackColor(), forState: .Normal) conditionsButton.titleLabel?.font = UIFont.sansSerifFontWithSize(15) conditionsButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (_) -> Void in (UIApplication.sharedApplication().delegate as? AppDelegate)?.showConditionsOfSale() return }) let privacyLabel = ARSerifLabel() privacyLabel.font = conditionsLabel.font.fontWithSize(18) privacyLabel.text = "View our " let privacyButton = ARUnderlineButton() privacyButton.setTitle("Privacy Policy".uppercaseString, forState: .Normal) privacyButton.setTitleColor(UIColor.blackColor(), forState: .Normal) privacyButton.titleLabel?.font = UIFont.sansSerifFontWithSize(15) privacyButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (_) -> Void in (UIApplication.sharedApplication().delegate as? AppDelegate)?.showPrivacyPolicy() return }) view.addSubview(conditionsLabel) view.addSubview(conditionsButton) view.addSubview(privacyLabel) view.addSubview(privacyButton) conditionsLabel.alignTop("0", leading: "0", toView: view) conditionsLabel.alignBaselineWithView(conditionsButton, predicate: nil) conditionsButton.alignAttribute(.Left, toAttribute: .Right, ofView: conditionsLabel, predicate: "0") privacyLabel.alignAttribute(.Left, toAttribute: .Left, ofView: conditionsLabel, predicate: "0") privacyLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: conditionsLabel, predicate: "10") privacyLabel.alignAttribute(.Bottom, toAttribute: .Bottom, ofView: view, predicate: "-20") privacyLabel.alignBaselineWithView(privacyButton, predicate: nil) privacyButton.alignAttribute(.Left, toAttribute: .Right, ofView: privacyLabel, predicate: "0") return view }() // Add subviews view.addSubview(stackView) stackView.alignTop("0", leading: "0", bottom: nil, trailing: "0", toView: view) stackView.addSubview(assistanceLabel, withTopMargin: "\(topMargin)", sideMargin: "\(sideMargin)") stackView.addSubview(stuckLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)") stackView.addSubview(stuckExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)") stackView.addSubview(bidLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)") stackView.addSubview(bidExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)") stackView.addSubview(registerButton, withTopMargin: "20", sideMargin: "\(sideMargin)") stackView.addSubview(txtLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)") stackView.addSubview(bidderDetailsLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)") stackView.addSubview(bidderDetailsExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)") stackView.addSubview(questionsLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)") stackView.addSubview(questionsExplainView, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(self.sideMargin)") } private func wrappingSerifLabel() -> UILabel { let label = ARSerifLabel() label.font = label.font.fontWithSize(18) label.lineBreakMode = .ByWordWrapping label.preferredMaxLayoutWidth = CGFloat(HelpViewController.width - sideMargin) return label } private func titleLabel() -> ARSansSerifLabel { let label = ARSansSerifLabel() label.font = UIFont.sansSerifFontWithSize(14) return label } } extension UILabel { func makeSubstringsBold(text: [String]) { text.map { self.makeSubstringBold($0) } } func makeSubstringBold(text: String) { let attributedText = self.attributedText.mutableCopy() as NSMutableAttributedString let range: NSRange! = (self.text ?? NSString()).rangeOfString(text) if range.location != NSNotFound { attributedText.setAttributes([NSFontAttributeName: UIFont.serifSemiBoldFontWithSize(self.font.pointSize)], range: range) } self.attributedText = attributedText } } extension HelpViewController { class var width: Float { get { return 415.0 } } }
mit
17f02167f5adbd5b730898b47f400dfe
46.147239
208
0.654217
5.7429
false
false
false
false
SereivoanYong/Charts
Source/Charts/Data/Implementations/Standard/BubbleDataSet.swift
1
1160
// // BubbleDataSet.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import UIKit open class BubbleDataSet: BarLineScatterCandleBubbleDataSet, IBubbleChartDataSet { // MARK: - Data functions and accessors open internal(set) var maxSize: CGFloat = 0.0 open var isNormalizeSizeEnabled: Bool = true open override func calcMinMax(entry e: Entry) { guard let e = e as? BubbleEntry else { return } super.calcMinMax(entry: e) let size = e.size if size > maxSize { maxSize = size } } // MARK: - Styling functions and accessors /// Sets/gets the width of the circle that surrounds the bubble when highlighted open var highlightCircleWidth: CGFloat = 2.5 // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! BubbleDataSet copy._xMin = _xMin copy._xMax = _xMax copy.maxSize = maxSize copy.highlightCircleWidth = highlightCircleWidth return copy } }
apache-2.0
96684200eeea357f74be6eea6b812fb6
22.2
82
0.673276
4.296296
false
false
false
false
brokenhandsio/vapor-oauth
Sources/VaporOAuth/Models/Tokens/AccessToken.swift
1
596
import Foundation import Core import Node public final class AccessToken: Extendable { public let tokenString: String public let clientID: String public let userID: Identifier? public let scopes: [String]? public let expiryTime: Date public var extend: [String: Any] = [:] public init(tokenString: String, clientID: String, userID: Identifier?, scopes: [String]? = nil, expiryTime: Date) { self.tokenString = tokenString self.clientID = clientID self.userID = userID self.scopes = scopes self.expiryTime = expiryTime } }
mit
18aa7c529dfe9b605fc7a33f4ef38c3f
27.380952
120
0.676174
4.584615
false
false
false
false
aschwaighofer/swift
test/IDE/complete_cross_import_indirect.swift
1
2086
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test -code-completion -source-filename %s -enable-cross-import-overlays -I %S/Inputs/CrossImport -code-completion-token=COMPLETE > %t/results.tmp // RUN: %FileCheck --input-file %t/results.tmp --check-prefix=COMPLETE %s // RUN: %FileCheck --input-file %t/results.tmp --check-prefix=COMPLETE-NEGATIVE %s // RUN: %target-swift-ide-test -code-completion -source-filename %s -enable-cross-import-overlays -I %S/Inputs/CrossImport -code-completion-token=IMPORT > %t/results.tmp // RUN: %FileCheck --input-file %t/results.tmp --check-prefix=IMPORT %s // RUN: %FileCheck --input-file %t/results.tmp --check-prefix=IMPORT-NEGATIVE %s // C exports A and B, and A has a cross import with B of _ABAdditions import C func foo() { #^COMPLETE^# } // COMPLETE-DAG: Decl[Module]/None: swift_ide_test[#Module#]; name=swift_ide_test // COMPLETE-DAG: Decl[Module]/None: Swift[#Module#]; name=Swift // COMPLETE-DAG: Decl[Module]/None: B[#Module#]; name=B // COMPLETE-DAG: Decl[Module]/None: A[#Module#]; name=A // COMPLETE-DAG: Decl[FreeFunction]/OtherModule[C]: fromC()[#Void#]; name=fromC() // COMPLETE-DAG: Decl[FreeFunction]/OtherModule[B]: fromB()[#Void#]; name=fromB() // COMPLETE-DAG: Decl[FreeFunction]/OtherModule[A]: fromA()[#Void#]; name=fromA() // COMPLETE-DAG: Decl[FreeFunction]/OtherModule[A]: from_ABAdditions()[#Void#]; name=from_ABAdditions() // COMPLETE-NEGATIVE-NOT: [_ABAdditions] // COMPLETE-NEGATIVE-NOT: [__ABAdditionsDAdditions] // COMPLETE-NEGATIVE-NOT: name=_ABAdditions // COMPLETE-NEGATIVE-NOT: name=__ABAdditionsDAdditions import #^IMPORT^# // IMPORT-DAG: Decl[Module]/None/NotRecommended: A[#Module#]; name=A // IMPORT-DAG: Decl[Module]/None/NotRecommended: B[#Module#]; name=B // IMPORT-DAG: Decl[Module]/None/NotRecommended: C[#Module#]; name=C // IMPORT-DAG: Decl[Module]/None: D[#Module#]; name=D // IMPORT-DAG: Decl[Module]/None: DBAdditions[#Module#]; name=DBAdditions // IMPORT-NEGATIVE-NOT: _ABAdditions // IMPORT-NEGATIVE-NOT: __ABAdditionsDAdditions
apache-2.0
067ed7d3f98073fc0363093b6621cb08
48.666667
171
0.700384
3.285039
false
true
false
false
naokits/my-programming-marathon
YoutubeClient/Pods/youtube-parser/youtube-parser/Youtube.swift
1
5878
// // Youtube.swift // youtube-parser // // Created by Toygar Dündaralp on 7/5/15. // Copyright (c) 2015 Toygar Dündaralp. All rights reserved. // import UIKit public extension NSURL { /** Parses a query string of an NSURL @return key value dictionary with each parameter as an array */ func dictionaryForQueryString() -> [String: AnyObject]? { return self.query?.dictionaryFromQueryStringComponents() } } public extension NSString { /** Convenient method for decoding a html encoded string */ func stringByDecodingURLFormat() -> String { let result = self.stringByReplacingOccurrencesOfString("+", withString:" ") return result.stringByRemovingPercentEncoding! } /** Parses a query string @return key value dictionary with each parameter as an array */ func dictionaryFromQueryStringComponents() -> [String: AnyObject] { var parameters = [String: AnyObject]() for keyValue in componentsSeparatedByString("&") { let keyValueArray = keyValue.componentsSeparatedByString("=") if keyValueArray.count < 2 { continue } let key = keyValueArray[0].stringByDecodingURLFormat() let value = keyValueArray[1].stringByDecodingURLFormat() parameters[key] = value } return parameters } } public class Youtube: NSObject { static let infoURL = "http://www.youtube.com/get_video_info?video_id=" static var userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4" /** Method for retrieving the youtube ID from a youtube URL @param youtubeURL the the complete youtube video url, either youtu.be or youtube.com @return string with desired youtube id */ public static func youtubeIDFromYoutubeURL(youtubeURL: NSURL) -> String? { if let youtubeHost = youtubeURL.host, youtubePathComponents = youtubeURL.pathComponents { let youtubeAbsoluteString = youtubeURL.absoluteString if youtubeHost == "youtu.be" as String? { return youtubePathComponents[1] } else if youtubeAbsoluteString.rangeOfString("www.youtube.com/embed") != nil { return youtubePathComponents[2] } else if youtubeHost == "youtube.googleapis.com" || youtubeURL.pathComponents!.first == "www.youtube.com" as String? { return youtubePathComponents[2] } else if let queryString = youtubeURL.dictionaryForQueryString(), searchParam = queryString["v"] as? String { return searchParam } } return nil } /** Method for retreiving a iOS supported video link @param youtubeURL the the complete youtube video url @return dictionary with the available formats for the selected video */ public static func h264videosWithYoutubeID(youtubeID: String) -> [String: AnyObject]? { let urlString = String(format: "%@%@", infoURL, youtubeID) as String let url = NSURL(string: urlString)! let request = NSMutableURLRequest(URL: url) request.timeoutInterval = 5.0 request.setValue(userAgent, forHTTPHeaderField: "User-Agent") request.HTTPMethod = "GET" var responseString = NSString() let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let group = dispatch_group_create() dispatch_group_enter(group) session.dataTaskWithRequest(request, completionHandler: { (data, response, _) -> Void in if let data = data as NSData? { responseString = NSString(data: data, encoding: NSUTF8StringEncoding)! } dispatch_group_leave(group) }).resume() dispatch_group_wait(group, DISPATCH_TIME_FOREVER) let parts = responseString.dictionaryFromQueryStringComponents() if parts.count > 0 { var videoTitle: String = "" var streamImage: String = "" if let title = parts["title"] as? String { videoTitle = title } if let image = parts["iurl"] as? String { streamImage = image } if let fmtStreamMap = parts["url_encoded_fmt_stream_map"] as? String { // Live Stream if let _: AnyObject = parts["live_playback"]{ if let hlsvp = parts["hlsvp"] as? String { return [ "url": "\(hlsvp)", "title": "\(videoTitle)", "image": "\(streamImage)", "isStream": true ] } } else { let fmtStreamMapArray = fmtStreamMap.componentsSeparatedByString(",") for videoEncodedString in fmtStreamMapArray { var videoComponents = videoEncodedString.dictionaryFromQueryStringComponents() videoComponents["title"] = videoTitle videoComponents["isStream"] = false return videoComponents as [String: AnyObject] } } } } return nil } /** Block based method for retreiving a iOS supported video link @param youtubeURL the the complete youtube video url @param completeBlock the block which is called on completion */ public static func h264videosWithYoutubeURL(youtubeURL: NSURL,completion: (( videoInfo: [String: AnyObject]?, error: NSError?) -> Void)?) { let priority = DISPATCH_QUEUE_PRIORITY_BACKGROUND dispatch_async(dispatch_get_global_queue(priority, 0)) { if let youtubeID = self.youtubeIDFromYoutubeURL(youtubeURL), videoInformation = self.h264videosWithYoutubeID(youtubeID) { dispatch_async(dispatch_get_main_queue()) { completion?(videoInfo: videoInformation, error: nil) } }else{ dispatch_async(dispatch_get_main_queue()) { completion?(videoInfo: nil, error: NSError(domain: "com.player.youtube.backgroundqueue", code: 1001, userInfo: ["error": "Invalid YouTube URL"])) } } } } }
mit
51363a280355cb312031162d58875308
35.271605
157
0.663036
4.832237
false
false
false
false
asbhat/stanford-ios10-apps
Cassini/Cassini/DemoURL.swift
1
816
// // DemoURL.swift // // Created by CS193p Instructor. // Copyright (c) 2017 Stanford University. All rights reserved. // import Foundation struct DemoURL { static let stanford = URL(string: "http://visit.stanford.edu/assets/cardinal/images/home_palm_drive.jpg") static var NASA: Dictionary<String,URL> = { let NASAURLStrings = [ "Cassini" : "http://www.jpl.nasa.gov/images/cassini/20090202/pia03883-full.jpg", "Earth" : "http://www.nasa.gov/sites/default/files/wave_earth_mosaic_3.jpg", "Saturn" : "http://www.nasa.gov/sites/default/files/saturn_collage.jpg" ] var urls = Dictionary<String,URL>() for (key, value) in NASAURLStrings { urls[key] = URL(string: value) } return urls }() }
apache-2.0
bcf2af204297b6d6f2b3bb6fa70f2e5a
31.64
109
0.610294
3.330612
false
false
false
false
jeffreybergier/SwiftLint
Source/swiftlint/Helpers/Benchmark.swift
1
1719
// // Benchmark.swift // SwiftLint // // Created by JP Simard on 1/25/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation import SourceKittenFramework struct BenchmarkEntry { let id: String // swiftlint:disable:this identifier_name let time: Double } struct Benchmark { private let name: String private var entries = [BenchmarkEntry]() init(name: String) { self.name = name } // swiftlint:disable:next identifier_name mutating func record(id: String, time: Double) { entries.append(BenchmarkEntry(id: id, time: time)) } mutating func record(file: File, from start: Date) { record(id: file.path ?? "<nopath>", time: -start.timeIntervalSinceNow) } func save() { let string = entries .reduce([String: Double]()) { accu, idAndTime in var accu = accu accu[idAndTime.id] = (accu[idAndTime.id] ?? 0) + idAndTime.time return accu } .sorted { $0.1 < $1.1 } .map { "\(numberFormatter.string(from: NSNumber(value: $0.1))!): \($0.0)" } .joined(separator: "\n") let data = (string + "\n").data(using: .utf8) let url = URL(fileURLWithPath: "benchmark_\(name)_\(timestamp).txt") try? data?.write(to: url, options: [.atomic]) } } private let numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.minimumFractionDigits = 3 return formatter }() private let timestamp: String = { let formatter = DateFormatter() formatter.dateFormat = "yyyy_MM_dd_HH_mm_ss" return formatter.string(from: Date()) }()
mit
73091ab06ac03b5c327efa5013c5614a
27.163934
87
0.608265
3.958525
false
false
false
false
Roommate-App/roomy
roomy/Pods/IBAnimatable/Sources/Animators/TransitionAnimator/ExplodeAnimator.swift
3
4104
// // Created by Tom Baranes on 03/04/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class ExplodeAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - private fileprivate var xFactor: CGFloat fileprivate var minAngle: CGFloat fileprivate var maxAngle: CGFloat public init(xFactor: CGFloat?, minAngle: CGFloat?, maxAngle: CGFloat?, duration: Duration) { transitionDuration = duration self.xFactor = xFactor ?? 10.0 self.minAngle = minAngle ?? -10.0 self.maxAngle = maxAngle ?? 10.0 transitionAnimationType = .explode(xFactor: self.xFactor, minAngle: self.minAngle, maxAngle: self.maxAngle) reverseAnimationType = .explode(xFactor: self.xFactor, minAngle: self.minAngle, maxAngle: self.maxAngle) super.init() } } extension ExplodeAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let (tempfromView, tempToView, tempContainerView) = retrieveViews(transitionContext: transitionContext) guard let fromView = tempfromView, let toView = tempToView, let containerView = tempContainerView else { transitionContext.completeTransition(true) return } containerView.insertSubview(toView, at: 0) let snapshots = makeSnapshots(toView: toView, fromView: fromView, containerView: containerView) containerView.sendSubview(toBack: fromView) animateSnapshotsExplode(snapshots) { if transitionContext.transitionWasCancelled { containerView.bringSubview(toFront: fromView) } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } } private extension ExplodeAnimator { func makeSnapshots(toView: UIView, fromView: UIView, containerView: UIView) -> [UIView] { let size = toView.frame.size var snapshots = [UIView]() let yFactor = xFactor * size.height / size.width let fromViewSnapshot = fromView.snapshotView(afterScreenUpdates: false) for x in stride(from: 0.0, to: Double(size.width), by: Double(size.width / xFactor)) { for y in stride(from: 0.0, to: Double(size.height), by: Double(size.width / yFactor)) { let snapshotRegion = CGRect(x: CGFloat(x), y: CGFloat(y), width: size.width / xFactor, height: size.height / yFactor) let snapshot = fromViewSnapshot?.resizableSnapshotView(from: snapshotRegion, afterScreenUpdates: false, withCapInsets: .zero) snapshot?.frame = snapshotRegion containerView.addSubview(snapshot!) snapshots.append(snapshot!) } } return snapshots } func animateSnapshotsExplode(_ snapshots: [UIView], completion: @escaping AnimatableCompletion) { UIView.animate(withDuration: transitionDuration, animations: { snapshots.forEach { let xOffset = self.randomFloat(from: -100.0, to: 100.0) let yOffset = self.randomFloat(from: -100.0, to: 100.0) let angle = self.randomFloat(from: self.minAngle, to: self.maxAngle) let translateTransform = CGAffineTransform(translationX: $0.frame.origin.x - xOffset, y: $0.frame.origin.y - yOffset) let angleTransform = translateTransform.rotated(by: angle) let scaleTransform = angleTransform.scaledBy(x: 0.01, y: 0.01) $0.transform = scaleTransform $0.alpha = 0.0 } }, completion: { _ in snapshots.forEach { $0.removeFromSuperview() } completion() }) } func randomFloat(from lower: CGFloat, to upper: CGFloat) -> CGFloat { return CGFloat(arc4random_uniform(UInt32(upper - lower))) + lower } }
mit
3da16111d62ef46ab2ee917655eb7ee7
38.07619
133
0.728004
4.678449
false
false
false
false
stephentyrone/swift
stdlib/public/core/Substring.swift
3
24704
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String { // FIXME(strings): at least temporarily remove it to see where it was applied /// Creates a new string from the given substring. /// /// - Parameter substring: A substring to convert to a standalone `String` /// instance. /// /// - Complexity: O(*n*), where *n* is the length of `substring`. @inlinable public init(_ substring: __shared Substring) { self = String._fromSubstring(substring) } } /// A slice of a string. /// /// When you create a slice of a string, a `Substring` instance is the result. /// Operating on substrings is fast and efficient because a substring shares /// its storage with the original string. The `Substring` type presents the /// same interface as `String`, so you can avoid or defer any copying of the /// string's contents. /// /// The following example creates a `greeting` string, and then finds the /// substring of the first sentence: /// /// let greeting = "Hi there! It's nice to meet you! 👋" /// let endOfSentence = greeting.firstIndex(of: "!")! /// let firstSentence = greeting[...endOfSentence] /// // firstSentence == "Hi there!" /// /// You can perform many string operations on a substring. Here, we find the /// length of the first sentence and create an uppercase version. /// /// print("'\(firstSentence)' is \(firstSentence.count) characters long.") /// // Prints "'Hi there!' is 9 characters long." /// /// let shoutingSentence = firstSentence.uppercased() /// // shoutingSentence == "HI THERE!" /// /// Converting a Substring to a String /// ================================== /// /// This example defines a `rawData` string with some unstructured data, and /// then uses the string's `prefix(while:)` method to create a substring of /// the numeric prefix: /// /// let rawInput = "126 a.b 22219 zzzzzz" /// let numericPrefix = rawInput.prefix(while: { "0"..."9" ~= $0 }) /// // numericPrefix is the substring "126" /// /// When you need to store a substring or pass it to a function that requires a /// `String` instance, you can convert it to a `String` by using the /// `String(_:)` initializer. Calling this initializer copies the contents of /// the substring to a new string. /// /// func parseAndAddOne(_ s: String) -> Int { /// return Int(s, radix: 10)! + 1 /// } /// _ = parseAndAddOne(numericPrefix) /// // error: cannot convert value... /// let incrementedPrefix = parseAndAddOne(String(numericPrefix)) /// // incrementedPrefix == 127 /// /// Alternatively, you can convert the function that takes a `String` to one /// that is generic over the `StringProtocol` protocol. The following code /// declares a generic version of the `parseAndAddOne(_:)` function: /// /// func genericParseAndAddOne<S: StringProtocol>(_ s: S) -> Int { /// return Int(s, radix: 10)! + 1 /// } /// let genericallyIncremented = genericParseAndAddOne(numericPrefix) /// // genericallyIncremented == 127 /// /// You can call this generic function with an instance of either `String` or /// `Substring`. /// /// - Important: Don't store substrings longer than you need them to perform a /// specific operation. A substring holds a reference to the entire storage /// of the string it comes from, not just to the portion it presents, even /// when there is no other reference to the original string. Storing /// substrings may, therefore, prolong the lifetime of string data that is /// no longer otherwise accessible, which can appear to be memory leakage. @frozen public struct Substring { @usableFromInline internal var _slice: Slice<String> @inlinable internal init(_ slice: Slice<String>) { let _guts = slice.base._guts let start = _guts.scalarAlign(slice.startIndex) let end = _guts.scalarAlign(slice.endIndex) self._slice = Slice( base: slice.base, bounds: Range(uncheckedBounds: (start, end))) _invariantCheck() } @inline(__always) internal init(_ slice: _StringGutsSlice) { self.init(String(slice._guts)[slice.range]) } /// Creates an empty substring. @inlinable @inline(__always) public init() { self.init(Slice()) } } extension Substring { /// Returns the underlying string from which this Substring was derived. @_alwaysEmitIntoClient public var base: String { return _slice.base } @inlinable @inline(__always) internal var _wholeGuts: _StringGuts { return base._guts } @inlinable @inline(__always) internal var _offsetRange: Range<Int> { return Range( uncheckedBounds: (startIndex._encodedOffset, endIndex._encodedOffset)) } #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { // Indices are always scalar aligned _internalInvariant( _slice.startIndex == base._guts.scalarAlign(_slice.startIndex) && _slice.endIndex == base._guts.scalarAlign(_slice.endIndex)) self.base._invariantCheck() } #endif // INTERNAL_CHECKS_ENABLED } extension Substring: StringProtocol { public typealias Index = String.Index public typealias SubSequence = Substring @inlinable @inline(__always) public var startIndex: Index { return _slice.startIndex } @inlinable @inline(__always) public var endIndex: Index { return _slice.endIndex } @inlinable @inline(__always) public func index(after i: Index) -> Index { _precondition(i < endIndex, "Cannot increment beyond endIndex") _precondition(i >= startIndex, "Cannot increment an invalid index") return _slice.index(after: i) } @inlinable @inline(__always) public func index(before i: Index) -> Index { _precondition(i <= endIndex, "Cannot decrement an invalid index") _precondition(i > startIndex, "Cannot decrement beyond startIndex") return _slice.index(before: i) } @inlinable @inline(__always) public func index(_ i: Index, offsetBy n: Int) -> Index { let result = _slice.index(i, offsetBy: n) _precondition( (_slice._startIndex ... _slice.endIndex).contains(result), "Operation results in an invalid index") return result } @inlinable @inline(__always) public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { let result = _slice.index(i, offsetBy: n, limitedBy: limit) _precondition(result.map { (_slice._startIndex ... _slice.endIndex).contains($0) } ?? true, "Operation results in an invalid index") return result } @inlinable @inline(__always) public func distance(from start: Index, to end: Index) -> Int { return _slice.distance(from: start, to: end) } @inlinable public subscript(i: Index) -> Character { @inline(__always) get { return _slice[i] } } public mutating func replaceSubrange<C>( _ bounds: Range<Index>, with newElements: C ) where C: Collection, C.Iterator.Element == Iterator.Element { _slice.replaceSubrange(bounds, with: newElements) } public mutating func replaceSubrange( _ bounds: Range<Index>, with newElements: Substring ) { replaceSubrange(bounds, with: newElements._slice) } /// Creates a string from the given Unicode code units in the specified /// encoding. /// /// - Parameters: /// - codeUnits: A collection of code units encoded in the encoding /// specified in `sourceEncoding`. /// - sourceEncoding: The encoding in which `codeUnits` should be /// interpreted. @inlinable // specialization public init<C: Collection, Encoding: _UnicodeEncoding>( decoding codeUnits: C, as sourceEncoding: Encoding.Type ) where C.Iterator.Element == Encoding.CodeUnit { self.init(String(decoding: codeUnits, as: sourceEncoding)) } /// Creates a string from the null-terminated, UTF-8 encoded sequence of /// bytes at the given pointer. /// /// - Parameter nullTerminatedUTF8: A pointer to a sequence of contiguous, /// UTF-8 encoded bytes ending just before the first zero byte. public init(cString nullTerminatedUTF8: UnsafePointer<CChar>) { self.init(String(cString: nullTerminatedUTF8)) } /// Creates a string from the null-terminated sequence of bytes at the given /// pointer. /// /// - Parameters: /// - nullTerminatedCodeUnits: A pointer to a sequence of contiguous code /// units in the encoding specified in `sourceEncoding`, ending just /// before the first zero code unit. /// - sourceEncoding: The encoding in which the code units should be /// interpreted. @inlinable // specialization public init<Encoding: _UnicodeEncoding>( decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>, as sourceEncoding: Encoding.Type ) { self.init( String(decodingCString: nullTerminatedCodeUnits, as: sourceEncoding)) } /// Calls the given closure with a pointer to the contents of the string, /// represented as a null-terminated sequence of UTF-8 code units. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withCString(_:)`. Do not store or return the pointer for /// later use. /// /// - Parameter body: A closure with a pointer parameter that points to a /// null-terminated sequence of UTF-8 code units. If `body` has a return /// value, that value is also used as the return value for the /// `withCString(_:)` method. The pointer argument is valid only for the /// duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable // specialization public func withCString<Result>( _ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result { // TODO(String performance): Detect when we cover the rest of a nul- // terminated String, and thus can avoid a copy. return try String(self).withCString(body) } /// Calls the given closure with a pointer to the contents of the string, /// represented as a null-terminated sequence of code units. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withCString(encodedAs:_:)`. Do not store or return the /// pointer for later use. /// /// - Parameters: /// - body: A closure with a pointer parameter that points to a /// null-terminated sequence of code units. If `body` has a return /// value, that value is also used as the return value for the /// `withCString(encodedAs:_:)` method. The pointer argument is valid /// only for the duration of the method's execution. /// - targetEncoding: The encoding in which the code units should be /// interpreted. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable // specialization public func withCString<Result, TargetEncoding: _UnicodeEncoding>( encodedAs targetEncoding: TargetEncoding.Type, _ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result ) rethrows -> Result { // TODO(String performance): Detect when we cover the rest of a nul- // terminated String, and thus can avoid a copy. return try String(self).withCString(encodedAs: targetEncoding, body) } } extension Substring: CustomReflectable { public var customMirror: Mirror { return String(self).customMirror } } extension Substring: CustomStringConvertible { @inlinable @inline(__always) public var description: String { return String(self) } } extension Substring: CustomDebugStringConvertible { public var debugDescription: String { return String(self).debugDescription } } extension Substring: LosslessStringConvertible { @inlinable public init(_ content: String) { self = content[...] } } extension Substring { @frozen public struct UTF8View { @usableFromInline internal var _slice: Slice<String.UTF8View> } } extension Substring.UTF8View: BidirectionalCollection { public typealias Index = String.UTF8View.Index public typealias Indices = String.UTF8View.Indices public typealias Element = String.UTF8View.Element public typealias SubSequence = Substring.UTF8View /// Creates an instance that slices `base` at `_bounds`. @inlinable internal init(_ base: String.UTF8View, _bounds: Range<Index>) { _slice = Slice( base: String(base._guts).utf8, bounds: _bounds) } // // Plumb slice operations through // @inlinable public var startIndex: Index { return _slice.startIndex } @inlinable public var endIndex: Index { return _slice.endIndex } @inlinable public subscript(index: Index) -> Element { return _slice[index] } @inlinable public var indices: Indices { return _slice.indices } @inlinable public func index(after i: Index) -> Index { return _slice.index(after: i) } @inlinable public func formIndex(after i: inout Index) { _slice.formIndex(after: &i) } @inlinable public func index(_ i: Index, offsetBy n: Int) -> Index { return _slice.index(i, offsetBy: n) } @inlinable public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { return _slice.index(i, offsetBy: n, limitedBy: limit) } @inlinable public func distance(from start: Index, to end: Index) -> Int { return _slice.distance(from: start, to: end) } @_alwaysEmitIntoClient @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return try _slice.withContiguousStorageIfAvailable(body) } @inlinable public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) { _slice._failEarlyRangeCheck(index, bounds: bounds) } @inlinable public func _failEarlyRangeCheck( _ range: Range<Index>, bounds: Range<Index> ) { _slice._failEarlyRangeCheck(range, bounds: bounds) } @inlinable public func index(before i: Index) -> Index { return _slice.index(before: i) } @inlinable public func formIndex(before i: inout Index) { _slice.formIndex(before: &i) } @inlinable public subscript(r: Range<Index>) -> Substring.UTF8View { // FIXME(strings): tests. _precondition(r.lowerBound >= startIndex && r.upperBound <= endIndex, "UTF8View index range out of bounds") return Substring.UTF8View(_slice.base, _bounds: r) } } extension Substring { @inlinable public var utf8: UTF8View { get { return base.utf8[startIndex..<endIndex] } set { self = Substring(newValue) } } /// Creates a Substring having the given content. /// /// - Complexity: O(1) public init(_ content: UTF8View) { self = String( content._slice.base._guts )[content.startIndex..<content.endIndex] } } extension String { /// Creates a String having the given content. /// /// If `codeUnits` is an ill-formed code unit sequence, the result is `nil`. /// /// - Complexity: O(N), where N is the length of the resulting `String`'s /// UTF-16. public init?(_ codeUnits: Substring.UTF8View) { let guts = codeUnits._slice.base._guts guard guts.isOnUnicodeScalarBoundary(codeUnits._slice.startIndex), guts.isOnUnicodeScalarBoundary(codeUnits._slice.endIndex) else { return nil } self = String(Substring(codeUnits)) } } extension Substring { @frozen public struct UTF16View { @usableFromInline internal var _slice: Slice<String.UTF16View> } } extension Substring.UTF16View: BidirectionalCollection { public typealias Index = String.UTF16View.Index public typealias Indices = String.UTF16View.Indices public typealias Element = String.UTF16View.Element public typealias SubSequence = Substring.UTF16View /// Creates an instance that slices `base` at `_bounds`. @inlinable internal init(_ base: String.UTF16View, _bounds: Range<Index>) { _slice = Slice( base: String(base._guts).utf16, bounds: _bounds) } // // Plumb slice operations through // @inlinable public var startIndex: Index { return _slice.startIndex } @inlinable public var endIndex: Index { return _slice.endIndex } @inlinable public subscript(index: Index) -> Element { return _slice[index] } @inlinable public var indices: Indices { return _slice.indices } @inlinable public func index(after i: Index) -> Index { return _slice.index(after: i) } @inlinable public func formIndex(after i: inout Index) { _slice.formIndex(after: &i) } @inlinable public func index(_ i: Index, offsetBy n: Int) -> Index { return _slice.index(i, offsetBy: n) } @inlinable public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { return _slice.index(i, offsetBy: n, limitedBy: limit) } @inlinable public func distance(from start: Index, to end: Index) -> Int { return _slice.distance(from: start, to: end) } @inlinable public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) { _slice._failEarlyRangeCheck(index, bounds: bounds) } @inlinable public func _failEarlyRangeCheck( _ range: Range<Index>, bounds: Range<Index> ) { _slice._failEarlyRangeCheck(range, bounds: bounds) } @inlinable public func index(before i: Index) -> Index { return _slice.index(before: i) } @inlinable public func formIndex(before i: inout Index) { _slice.formIndex(before: &i) } @inlinable public subscript(r: Range<Index>) -> Substring.UTF16View { return Substring.UTF16View(_slice.base, _bounds: r) } } extension Substring { @inlinable public var utf16: UTF16View { get { return base.utf16[startIndex..<endIndex] } set { self = Substring(newValue) } } /// Creates a Substring having the given content. /// /// - Complexity: O(1) public init(_ content: UTF16View) { self = String( content._slice.base._guts )[content.startIndex..<content.endIndex] } } extension String { /// Creates a String having the given content. /// /// If `codeUnits` is an ill-formed code unit sequence, the result is `nil`. /// /// - Complexity: O(N), where N is the length of the resulting `String`'s /// UTF-16. public init?(_ codeUnits: Substring.UTF16View) { let guts = codeUnits._slice.base._guts guard guts.isOnUnicodeScalarBoundary(codeUnits._slice.startIndex), guts.isOnUnicodeScalarBoundary(codeUnits._slice.endIndex) else { return nil } self = String(Substring(codeUnits)) } } extension Substring { @frozen public struct UnicodeScalarView { @usableFromInline internal var _slice: Slice<String.UnicodeScalarView> } } extension Substring.UnicodeScalarView: BidirectionalCollection { public typealias Index = String.UnicodeScalarView.Index public typealias Indices = String.UnicodeScalarView.Indices public typealias Element = String.UnicodeScalarView.Element public typealias SubSequence = Substring.UnicodeScalarView /// Creates an instance that slices `base` at `_bounds`. @inlinable internal init(_ base: String.UnicodeScalarView, _bounds: Range<Index>) { _slice = Slice( base: String(base._guts).unicodeScalars, bounds: _bounds) } // // Plumb slice operations through // @inlinable public var startIndex: Index { return _slice.startIndex } @inlinable public var endIndex: Index { return _slice.endIndex } @inlinable public subscript(index: Index) -> Element { return _slice[index] } @inlinable public var indices: Indices { return _slice.indices } @inlinable public func index(after i: Index) -> Index { return _slice.index(after: i) } @inlinable public func formIndex(after i: inout Index) { _slice.formIndex(after: &i) } @inlinable public func index(_ i: Index, offsetBy n: Int) -> Index { return _slice.index(i, offsetBy: n) } @inlinable public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { return _slice.index(i, offsetBy: n, limitedBy: limit) } @inlinable public func distance(from start: Index, to end: Index) -> Int { return _slice.distance(from: start, to: end) } @inlinable public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) { _slice._failEarlyRangeCheck(index, bounds: bounds) } @inlinable public func _failEarlyRangeCheck( _ range: Range<Index>, bounds: Range<Index> ) { _slice._failEarlyRangeCheck(range, bounds: bounds) } @inlinable public func index(before i: Index) -> Index { return _slice.index(before: i) } @inlinable public func formIndex(before i: inout Index) { _slice.formIndex(before: &i) } @inlinable public subscript(r: Range<Index>) -> Substring.UnicodeScalarView { return Substring.UnicodeScalarView(_slice.base, _bounds: r) } } extension Substring { @inlinable public var unicodeScalars: UnicodeScalarView { get { return base.unicodeScalars[startIndex..<endIndex] } set { self = Substring(newValue) } } /// Creates a Substring having the given content. /// /// - Complexity: O(1) public init(_ content: UnicodeScalarView) { self = String( content._slice.base._guts )[content.startIndex..<content.endIndex] } } extension String { /// Creates a String having the given content. /// /// - Complexity: O(N), where N is the length of the resulting `String`'s /// UTF-16. public init(_ content: Substring.UnicodeScalarView) { self = String(Substring(content)) } } // FIXME: The other String views should be RangeReplaceable too. extension Substring.UnicodeScalarView: RangeReplaceableCollection { @inlinable public init() { _slice = Slice.init() } public mutating func replaceSubrange<C: Collection>( _ target: Range<Index>, with replacement: C ) where C.Element == Element { _slice.replaceSubrange(target, with: replacement) } } extension Substring: RangeReplaceableCollection { @_specialize(where S == String) @_specialize(where S == Substring) @_specialize(where S == Array<Character>) public init<S: Sequence>(_ elements: S) where S.Element == Character { if let str = elements as? String { self = str[...] return } if let subStr = elements as? Substring { self = subStr return } self = String(elements)[...] } @inlinable // specialize public mutating func append<S: Sequence>(contentsOf elements: S) where S.Element == Character { var string = String(self) self = Substring() // Keep unique storage if possible string.append(contentsOf: elements) self = Substring(string) } } extension Substring { public func lowercased() -> String { return String(self).lowercased() } public func uppercased() -> String { return String(self).uppercased() } public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> String { return try String(self.lazy.filter(isIncluded)) } } extension Substring: TextOutputStream { public mutating func write(_ other: String) { append(contentsOf: other) } } extension Substring: TextOutputStreamable { @inlinable // specializable public func write<Target: TextOutputStream>(to target: inout Target) { target.write(String(self)) } } extension Substring: ExpressibleByUnicodeScalarLiteral { @inlinable public init(unicodeScalarLiteral value: String) { self.init(value) } } extension Substring: ExpressibleByExtendedGraphemeClusterLiteral { @inlinable public init(extendedGraphemeClusterLiteral value: String) { self.init(value) } } extension Substring: ExpressibleByStringLiteral { @inlinable public init(stringLiteral value: String) { self.init(value) } } // String/Substring Slicing extension String { @inlinable @available(swift, introduced: 4) public subscript(r: Range<Index>) -> Substring { _boundsCheck(r) return Substring(Slice(base: self, bounds: r)) } } extension Substring { @inlinable @available(swift, introduced: 4) public subscript(r: Range<Index>) -> Substring { return Substring(_slice[r]) } }
apache-2.0
66060d8d13487c33925b188adc33b41b
29.233782
80
0.678313
4.191583
false
false
false
false
openHPI/xikolo-ios
iOS/ViewControllers/Account/AppearanceSettingsViewController.swift
1
1695
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import UIKit class AppearanceSettingsViewController: UITableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if #available(iOS 13.0, *) { return Theme.allCases.count } else { return 0 } } // delegate override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingsOptionBasicCell", for: indexPath) if #available(iOS 13.0, *) { cell.textLabel?.text = Theme.allCases[indexPath.row].title cell.accessoryType = indexPath.row == UserDefaults.standard.theme.rawValue ? .checkmark : .none } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if #available(iOS 13.0, *) { if indexPath.row != UserDefaults.standard.theme.rawValue { let oldAppearanceSettingIndexPath = IndexPath(row: UserDefaults.standard.theme.rawValue, section: indexPath.section) UserDefaults.standard.theme = Theme(rawValue: indexPath.row) ?? .device tableView.reloadRows(at: [oldAppearanceSettingIndexPath, indexPath], with: .none) } } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return NSLocalizedString("settings.cell-title.appearance", comment: "cell title for appearance settings") } }
gpl-3.0
8f39a01052e41dcf7a69a0fe03706a2d
37.5
132
0.667651
4.953216
false
false
false
false
scihant/CTShowcase
Source/CTRegionHighlighter.swift
1
7161
// // CTShowcaseHighlighter.swift // CTShowcase // // Created by Cihan Tek on 21/12/15. // Copyright © 2015 Cihan Tek. All rights reserved. // import UIKit @objc public enum CTHighlightType : Int { case rect, circle } /// Any class conforming to this protocol can be used as a highlighter by the ShowcaseView @objc public protocol CTRegionHighlighter { /** This is the only method needed to draw static (non-animated) highlights. For static highlights, it should draw the highlight around the provided rect. For dynamic highlights, it usually should do nothing except clearing the region covering the view that's gonna be highlighted. rect is in the coordinate system of the ShowcaseView's layer. - parameter context: The drawing context of the entire ShowcaseView - parameter rect: The rectangular region within the context to highlight. */ func draw(on context: CGContext, rect: CGRect) /** ShowcaseView adds the layer returned form this method to its layer as a sublayer. Needs to return a non-nil value for animated highlights - parameter rect: The rectangular region within ctx to highlight. - returns: A layer that contains the highlight effect with or without animation */ func layer(for rect: CGRect) -> CALayer? } /// Provides a dynamic glow highlight with animation @objcMembers public class CTDynamicGlowHighlighter: NSObject, CTRegionHighlighter { // MARK: Properties /// The highlight color public var highlightColor = UIColor.yellow /// Type of the highlight public var highlightType: CTHighlightType = .rect /// The size of the glow around the highlight border public var glowSize: CGFloat = 5.0 /// Maximum spacing between the highlight and the view it highlights public var maxOffset: CGFloat = 10.0 /// The duration of the animation in one direction (The full cycle will take 2x time) public var animDuration: CFTimeInterval = 0.5 // MARK: CTRegionHighlighter method implementations public func draw(on context: CGContext, rect: CGRect) { if (highlightType == .rect) { context.clear(rect) } else { let maxDim = max(rect.size.width, rect.size.height) let radius = maxDim/2 + 1; let center = CGPoint(x: rect.midX, y: rect.midY) context.setBlendMode(.clear) context.addArc(center: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true) context.fillPath() context.setBlendMode(.normal) } } public func layer(for rect: CGRect) -> CALayer? { // Create a shape layer that's gonna be used as the highlight effect let layer = CAShapeLayer() layer.frame = rect layer.contentsScale = UIScreen.main.scale layer.shadowOffset = CGSize(width: 0, height: 0) layer.strokeColor = highlightColor.cgColor layer.fillColor = UIColor.clear.cgColor layer.shadowColor = highlightColor.cgColor layer.lineWidth = 3 layer.shadowOpacity = 1 // Create the shrinked and grown versions of the path var innerPath: UIBezierPath var outerPath: UIBezierPath if (highlightType == .rect) { innerPath = UIBezierPath(rect: layer.bounds) outerPath = UIBezierPath(rect: layer.bounds.insetBy(dx: -maxOffset, dy: -maxOffset)) } else { let maxDim = max(layer.bounds.size.width, layer.bounds.size.height) let radius = maxDim/2 + 1; let center = CGPoint(x: layer.bounds.size.width / 2, y: layer.bounds.size.height / 2) innerPath = UIBezierPath() innerPath.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true) outerPath = UIBezierPath() outerPath.addArc(withCenter: center, radius: radius + maxOffset, startAngle: 0, endAngle: 2 * .pi, clockwise: true) } // Grow and shrink the path with animation let pathAnim = CABasicAnimation() pathAnim.keyPath = "path" pathAnim.fromValue = innerPath.cgPath pathAnim.toValue = outerPath.cgPath // Animate the size of the glow according to the distance between the highlight's inside border and the region that's being highlighted. // As the border grows, so will the glow, and vice-versa let glowAnim = CABasicAnimation() glowAnim.keyPath = "shadowRadius" glowAnim.fromValue = 0 glowAnim.toValue = glowSize // Group the two animations created above and add the group to the layer let animGroup = CAAnimationGroup() animGroup.repeatCount = Float.infinity animGroup.duration = animDuration animGroup.autoreverses = true animGroup.animations = [pathAnim, glowAnim] layer.add(animGroup, forKey: nil) return layer } } /// Provides a static glow highlight with no animation @objcMembers public class CTStaticGlowHighlighter: NSObject, CTRegionHighlighter { // MARK: Properties /// The highlight color public var highlightColor = UIColor.yellow /// Type of the highlight public var highlightType : CTHighlightType = .rect // MARK: CTRegionHighlighter method implementations public func draw(on context: CGContext, rect: CGRect) { context.setLineWidth(2.0) context.setShadow(offset: CGSize.zero, blur: 30.0, color: highlightColor.cgColor) context.setStrokeColor(highlightColor.cgColor) if (highlightType == .rect) { // Draw the rect and its shadow context.addPath(UIBezierPath(rect: rect).cgPath) context.drawPath(using: .fillStroke) // Clear the inner region to prevent the highlighted region from being covered by the highlight context.setFillColor(UIColor.clear.cgColor) context.setBlendMode(.clear) context.addRect(rect) context.drawPath(using: .fill) } else { let radius = rect.size.width/2 + 1; let center = CGPoint(x: rect.origin.x + rect.size.width / 2, y: rect.origin.y + rect.size.height / 2.0) // Draw the circle and its shadow context.addArc(center: center, radius: radius, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: false) context.drawPath(using: .fillStroke) // Clear the inner region to prevent the highlighted region from being covered by the highlight context.setFillColor(UIColor.clear.cgColor) context.setBlendMode(.clear) context.addArc(center: center, radius: radius - 0.5, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: false) context.drawPath(using: .fill) } } public func layer(for rect: CGRect) -> CALayer? { return nil } }
mit
579ccce9154cd257bc0109c577711ca2
36.291667
144
0.640503
4.776518
false
false
false
false
piars777/TheMovieDatabaseSwiftWrapper
Sources/Models/MovieMDB.swift
1
10647
// // MoviesMDB.swift // MDBSwiftWrapper // // Created by George on 2016-02-12. // Copyright © 2016 GeorgeKye. All rights reserved. // import Foundation extension MovieMDB{ ///Get the basic movie information for a specific movie id. public class func movie(api_key: String!, movieID: Int!, language: String?, completion: (clientReturn: ClientReturn, data: MovieDetailedMDB?) -> ()) -> (){ Client.Movies("\(movieID)", api_key: api_key, page: nil, language: language){ apiReturn in var detailed = MovieDetailedMDB?() if(apiReturn.error == nil){ detailed = MovieDetailedMDB.init(results: apiReturn.json!) } completion(clientReturn: apiReturn, data: detailed) } } ///Get the alternative titles for a specific movie id. public class func alternativeTitles(api_key: String!, movieID: Int!, country: String?, completion: (clientReturn: ClientReturn, altTitles: Alternative_TitlesMDB?) -> ()) -> (){ //language changed to country to avoid modifiying multiple defined functions. Client.Movies("\(movieID)/alternative_titles", api_key: api_key, page: nil, language: country){ apiReturn in var alt = Alternative_TitlesMDB?() if(apiReturn.error == nil){ alt = Alternative_TitlesMDB.init(results: apiReturn.json!) } completion(clientReturn: apiReturn, altTitles: alt) } } ///Get the cast and crew information for a specific movie id. public class func credits(api_key: String!, movieID: Int!, completion: (clientReturn: ClientReturn, credits: MovieCreditsMDB?) -> ()) -> (){ Client.Movies("\(movieID)/credits", api_key: api_key, page: nil, language: nil){ apiReturn in var credits = MovieCreditsMDB?() if(apiReturn.error == nil){ credits = MovieCreditsMDB.init(results: apiReturn.json!) } completion(clientReturn: apiReturn, credits: credits) } } ///Get the images (posters and backdrops) for a specific movie id. public class func images(api_key: String!, movieID: Int!, language: String?, completion: (clientReturn: ClientReturn, images: ImagesMDB?) -> ()) -> (){ Client.Movies("\(movieID)/images", api_key: api_key, page: nil, language: language){ apiReturn in var images = ImagesMDB?() if(apiReturn.error == nil){ images = ImagesMDB.init(results: apiReturn.json!) } completion(clientReturn: apiReturn, images: images) } } ///Get the plot keywords for a specific movie id. public class func keywords(api_key: String!, movieID: Int, completion: (clientReturn: ClientReturn, keywords: [KeywordsMDB]?) -> ()) -> (){ Client.Movies("\(movieID)/keywords", api_key: api_key, page: nil, language: nil){ apiReturn in var keywords = [KeywordsMDB]?() if(apiReturn.error == nil){ keywords = KeywordsMDB.initialize(json: apiReturn.json!["keywords"]) } completion(clientReturn: apiReturn, keywords: keywords) } } ///Get the release dates, certifications and related information by country for a specific movie id. public class func release_dates(api_key: String!, movieID: Int, completion: (clientReturn: ClientReturn, releatedDates: [MovieReleaseDatesMDB]?) -> ()) -> (){ Client.Movies("\(movieID)/release_dates", api_key: api_key, page: nil, language: nil){ apiReturn in var releatedDates = [MovieReleaseDatesMDB]?() if(apiReturn.error == nil){ releatedDates = MovieReleaseDatesMDB.initialize(json: apiReturn.json!["results"]) } completion(clientReturn: apiReturn, releatedDates: releatedDates) } } ///Get the videos (trailers, teasers, clips, etc...) for a specific movie id. public class func videos(api_key: String!, movieID: Int!, language: String?, completion: (clientReturn: ClientReturn, videos: [VideosMDB]?) -> ()) -> (){ Client.Movies("\(movieID)/videos", api_key: api_key, page: nil, language: language){ apiReturn in var videos = [VideosMDB]?() if(apiReturn.error == nil){ videos = VideosMDB.initialize(json: apiReturn.json!["results"]) } completion(clientReturn: apiReturn, videos: videos) } } ///Get the translations for a specific movie id. public class func translations(api_key: String!, movieID: Int!, completion: (clientReturn: ClientReturn, translations: TranslationsMDB? ) -> ()) -> (){ Client.Movies("\(movieID)/translations", api_key: api_key, page: nil, language: nil){ apiReturn in var trans = TranslationsMDB?() if(apiReturn.error == nil){ trans = TranslationsMDB.init(results: apiReturn.json!["translations"]) } completion(clientReturn: apiReturn, translations: trans) } } ///Get the similar movies for a specific movie id. public class func similar(api_key: String!, movieID: Int!, page: Int?, language: String?, completion: (clientReturn: ClientReturn, movie: [MovieMDB]?) -> ()) -> (){ Client.Movies("\(movieID)/similar", api_key: api_key, page: page, language: language){ apiReturn in var movie = [MovieMDB]?() if(apiReturn.error == nil){ if(apiReturn.json!["results"].count > 0){ movie = MovieMDB.initialize(json: apiReturn.json!["results"]) } } completion(clientReturn: apiReturn, movie: movie) } } ///Get the reviews for a particular movie id. public class func reviews(api_key: String!, movieID: Int!, page: Int?, language: String, completion: (clientReturn: ClientReturn, reviews: [MovieReviewsMDB]?) -> ()) -> (){ Client.Movies("\(movieID)/reviews", api_key: api_key, page: page, language: language){ apiReturn in var reviews = [MovieReviewsMDB]?() if(apiReturn.error == nil){ if(apiReturn.json!["results"].count > 0){ reviews = MovieReviewsMDB.initialize(json: apiReturn.json!["results"]) } } completion(clientReturn: apiReturn, reviews: reviews) } } ///Get the lists that the movie belongs to. public class func list(api_key: String!, movieID: Int!, page: NSNumber?, language: String, completion: (clientReturn: ClientReturn, list: [MovieListMDB]?) -> ()) -> (){ Client.Movies("\(movieID)/lists", api_key: api_key, page: page?.integerValue, language: language){ apiReturn in var list = [MovieListMDB]?() if(apiReturn.error == nil){ if(apiReturn.json!["results"].count > 0){ list = MovieListMDB.initialize(json: apiReturn.json!["results"]) } } completion(clientReturn: apiReturn, list: list) } } ///Get the latest movie id. public class func latest(api_key: String!, completion: (clientReturn: ClientReturn, moviesDetailed: MovieDetailedMDB?) -> ()) -> (){ Client.Movies("latest", api_key: api_key, page: nil, language: nil){ apiReturn in var movie = MovieDetailedMDB?() if(apiReturn.error == nil){ movie = MovieDetailedMDB.init(results: apiReturn.json!) } completion(clientReturn: apiReturn, moviesDetailed: movie) } } ///Get the list of movies playing that have been, or are being released this week. This list refreshes every day. public class func nowplaying(api_key: String!,language: String?, page: Int?, completion: (clientReturn: ClientReturn, movie: [MovieMDB]?) -> ()) -> (){ Client.Movies("now_playing", api_key: api_key, page: page, language: language){ apiReturn in var movie = [MovieMDB]?() if(apiReturn.error == nil){ if(apiReturn.json!["results"].count > 0){ movie = MovieMDB.initialize(json: apiReturn.json!["results"]) } } completion(clientReturn: apiReturn, movie: movie) } } ///Get the list of popular movies on The Movie Database. This list refreshes every day. public class func popular(api_key: String!,language: String?, page: Int?, completion: (clientReturn: ClientReturn, movie: [MovieMDB]?) -> ()) -> (){ Client.Movies("popular", api_key: api_key, page: page, language: language){ apiReturn in var movie = [MovieMDB]?() if(apiReturn.error == nil){ if(apiReturn.json!["results"].count > 0){ movie = MovieMDB.initialize(json: apiReturn.json!["results"]) } } completion(clientReturn: apiReturn, movie: movie) } } ///Get the list of top rated movies. By default, this list will only include movies that have 50 or more votes. This list refreshes every day. public class func toprated(api_key: String!,language: String?, page: Int?, completion: (clientReturn: ClientReturn, movie: [MovieMDB]?) -> ()) -> (){ Client.Movies("top_rated", api_key: api_key, page: page, language: language){ apiReturn in var movie = [MovieMDB]?() if(apiReturn.error == nil){ if(apiReturn.json!["results"].count > 0){ movie = MovieMDB.initialize(json: apiReturn.json!["results"]) } } completion(clientReturn: apiReturn, movie: movie) } } ///Get the list of upcoming movies by release date. This list refreshes every day. public class func upcoming(api_key: String!, page: Int?, language: String?, completion: (clientReturn: ClientReturn, movie: [MovieMDB]?) -> ()) -> (){ Client.Movies("upcoming", api_key: api_key, page: page, language: language){ apiReturn in var movie = [MovieMDB]?() if(apiReturn.error == nil){ if(apiReturn.json!["results"].count > 0){ movie = MovieMDB.initialize(json: apiReturn.json!["results"]) } } completion(clientReturn: apiReturn, movie: movie) } } }
mit
3b797b3c98ac1d13cc8f69bbdf9aeb26
46.73991
180
0.58623
4.742094
false
false
false
false
huyphams/LYTabView
LYTabView/LYTabView.swift
1
4889
// // LYTabView.swift // LYTabView // // Created by Lu Yibin on 16/4/13. // Copyright © 2016年 Lu Yibin. All rights reserved. // import Foundation import Cocoa /// Description public class LYTabView: NSView { /// Tab bar view of the LYTabView public let tabBarView: LYTabBarView = LYTabBarView(frame: .zero) /// Native NSTabView of the LYTabView public let tabView: NSTabView = NSTabView(frame: .zero) // private let stackView: NSStackView = NSStackView(frame: .zero) /// delegate of LYTabView public var delegate: NSTabViewDelegate? { get { return tabBarView.delegate } set(newDelegate) { tabBarView.delegate = newDelegate } } public var numberOfTabViewItems: Int { return self.tabView.numberOfTabViewItems } public var tabViewItems: [NSTabViewItem] { return self.tabView.tabViewItems } public var selectedTabViewItem: NSTabViewItem? { return self.tabView.selectedTabViewItem } final private func setupViews() { tabView.delegate = tabBarView tabView.tabViewType = .noTabsNoBorder tabBarView.tabView = tabView stackView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(stackView) stackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true tabView.translatesAutoresizingMaskIntoConstraints = false tabBarView.translatesAutoresizingMaskIntoConstraints = false stackView.addView(tabBarView, in: .center) stackView.addView(tabView, in: .center) stackView.orientation = .vertical stackView.distribution = .fill stackView.alignment = .centerX stackView.spacing = 0 stackView.leadingAnchor.constraint(equalTo: tabBarView.leadingAnchor).isActive = true stackView.trailingAnchor.constraint(equalTo: tabBarView.trailingAnchor).isActive = true stackView.leadingAnchor.constraint(equalTo:tabView.leadingAnchor).isActive = true stackView.trailingAnchor.constraint(equalTo:tabView.trailingAnchor).isActive = true let lowerPriority = NSLayoutConstraint.Priority(rawValue:NSLayoutConstraint.Priority.defaultLow.rawValue-10) tabView.setContentHuggingPriority(lowerPriority, for: .vertical) tabBarView.setContentCompressionResistancePriority(NSLayoutConstraint.Priority.defaultHigh, for: .vertical) tabBarView.setContentHuggingPriority(NSLayoutConstraint.Priority.defaultHigh, for: .vertical) } required public init?(coder: NSCoder) { super.init(coder: coder) setupViews() } required public override init(frame frameRect: NSRect) { super.init(frame: frameRect) setupViews() } } public extension LYTabView { public func addTabViewItem(_ tabViewItem: NSTabViewItem) { self.tabBarView.addTabViewItem(tabViewItem) } public func insertTabViewItem(_ tabViewItem: NSTabViewItem, atIndex index: Int) { self.tabView.insertTabViewItem(tabViewItem, at: index) } public func removeTabViewItem(_ tabViewItem: NSTabViewItem) { self.tabBarView.removeTabViewItem(tabViewItem) } public func indexOfTabViewItem(_ tabViewItem: NSTabViewItem) -> Int { return self.tabView.indexOfTabViewItem(tabViewItem) } public func indexOfTabViewItemWithIdentifier(_ identifier: AnyObject) -> Int { return self.tabView.indexOfTabViewItem(withIdentifier: identifier) } public func tabViewItem(at index: Int) -> NSTabViewItem { return self.tabView.tabViewItem(at: index) } public func selectFirstTabViewItem(_ sender: AnyObject?) { self.tabView.selectFirstTabViewItem(sender) } public func selectLastTabViewItem(_ sender: AnyObject?) { self.tabView.selectLastTabViewItem(sender) } public func selectNextTabViewItem(_ sender: AnyObject?) { self.tabView.selectNextTabViewItem(sender) } public func selectPreviousTabViewItem(_ sender: AnyObject?) { self.tabView.selectPreviousTabViewItem(sender) } public func selectTabViewItem(_ tabViewItem: NSTabViewItem?) { self.tabView.selectTabViewItem(tabViewItem) } public func selectTabViewItem(at index: Int) { self.tabView.selectTabViewItem(at: index) } public func selectTabViewItem(withIdentifier identifier: AnyObject) { self.tabView.selectTabViewItem(withIdentifier: identifier) } public func takeSelectedTabViewItemFromSender(_ sender: AnyObject?) { self.tabView.takeSelectedTabViewItemFromSender(sender) } }
mit
220174030d2c44e555f1dfe4f994a509
34.664234
116
0.717765
5.148577
false
false
false
false
TCA-Team/iOS
TUM Campus App/DataSources/ComposedDataSource.swift
1
7238
// // ComposedDataSource.swift // Campus // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // 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, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit protocol TUMDataSourceDelegate { func didRefreshDataSources() func didBeginRefreshingDataSources() func didEncounterNetworkTimout() } protocol TUMDataSource: UICollectionViewDataSource { var sectionColor: UIColor {get} var cellType: AnyClass {get} var cellReuseID: String {get} var cardReuseID: String {get} var isEmpty: Bool {get} var cardKey: CardKey {get} var flowLayoutDelegate: ColumnsFlowLayoutDelegate {get} var preferredHeight: CGFloat {get} func refresh(group: DispatchGroup) } @objc protocol TUMInteractiveDataSource { @objc optional func onItemSelected(at indexPath: IndexPath) @objc optional func onShowMore() } extension TUMDataSource { var sectionColor: UIColor { return Constants.tumBlue } var cellReuseID: String { return cardKey.description.replacingOccurrences(of: " ", with: "")+"Cell" } var cardReuseID: String { return cardKey.description.replacingOccurrences(of: " ", with: "")+"Card" } var preferredHeight: CGFloat { return 220.0 } var indexInOrder: Int { let cards = PersistentCardOrder.value.cards guard let index = cards.index(of: cardKey) else { return cards.lastIndex } return cards.startIndex.distance(to: index) } } class ComposedDataSource: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var dataSources: [TUMDataSource] = [] var manager: TumDataManager var delegate: TUMDataSourceDelegate? var cardKeys: [CardKey] { return PersistentCardOrder.value.cards } let margin: CGFloat = 20.0 let updateQueue = DispatchQueue(label: "TUMCampusApp.BackgroundQueue", qos: .userInitiated) private var sortedDataSourcesCache: [TUMDataSource]? var sortedDataSources: [TUMDataSource] { if sortedDataSourcesCache == nil { let keys = Set(cardKeys) sortedDataSourcesCache = dataSources .filter { !$0.isEmpty } .filter { keys.contains($0.cardKey) } .sorted(ascending: \.indexInOrder) } return sortedDataSourcesCache! } init(parent: CardViewController, manager: TumDataManager) { self.manager = manager self.dataSources = [ NewsDataSource(parent: parent, manager: manager.newsManager), NewsSpreadDataSource(parent: parent, manager: manager.newsSpreadManager), CafeteriaDataSource(parent: parent, manager: manager.cafeteriaManager), TUFilmDataSource(parent: parent, manager: manager.tuFilmNewsManager), CalendarDataSource(parent: parent, manager: manager.calendarManager), TuitionDataSource(parent: parent, manager: manager.tuitionManager), MVGStationDataSource(parent: parent, manager: manager.mvgManager), GradesDataSource(parent: parent, manager: manager.gradesManager), LecturesDataSource(parent: parent, manager: manager.lecturesManager), StudyRoomsDataSource(parent: parent, manager: manager.studyRoomsManager) ] super.init() } func invalidateSortedDataSources() { sortedDataSourcesCache = nil } func refresh() { delegate?.didBeginRefreshingDataSources() let group = DispatchGroup() dataSources.forEach{$0.refresh(group: group)} updateQueue.async { let result = group.wait(timeout: .now() + .seconds(10)) DispatchQueue.main.async { switch result { case .success: self.invalidateSortedDataSources() self.delegate?.didRefreshDataSources() case .timedOut: self.sortedDataSourcesCache = [] self.delegate?.didEncounterNetworkTimout() } } } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return sortedDataSources.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let dataSource = sortedDataSources[indexPath.row] let cell = collectionView.dequeueReusableCell( withReuseIdentifier: dataSource.cardReuseID, for: indexPath) as! DataSourceCollectionViewCell let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let nib = UINib(nibName: String(describing: dataSource.cellType), bundle: .main) cell.collectionView.register(nib, forCellWithReuseIdentifier: dataSource.cellReuseID) cell.collectionView.collectionViewLayout = layout cell.collectionView.clipsToBounds = false cell.cardNameLabel.text = dataSource.cardKey.description.uppercased() cell.cardNameLabel.textColor = dataSource.sectionColor cell.showAllButton?.setTitleColor(dataSource.sectionColor, for: .normal) cell.collectionView.backgroundColor = .clear cell.collectionView.dataSource = dataSource cell.collectionView.delegate = dataSource.flowLayoutDelegate cell.collectionView.reloadData() cell.onShowAll = { if let dataSource = dataSource as? TUMInteractiveDataSource { dataSource.onShowMore?() } } return cell } //MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return margin } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets.zero } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let dataSource = sortedDataSources[indexPath.row] let height = dataSource.preferredHeight let width = collectionView.frame.size.width return CGSize(width: width, height: height) } }
gpl-3.0
616ddeedc28842affcd3d60a48894447
37.913978
121
0.666068
5.27551
false
false
false
false
paterson/DatePickerDialog-iOS-Swift
Demo/Library/DatePickerDialog.swift
1
12810
// // DatePicker.swift import Foundation import UIKit import QuartzCore class DatePickerDialog: UIView { /* Consts */ private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50 private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1 private let kDatePickerDialogCornerRadius: CGFloat = 7 private let kDatePickerDialogCancelButtonTag: Int = 1 private let kDatePickerDialogDoneButtonTag: Int = 2 /* Views */ private var dialogView: UIView! private var titleLabel: UILabel! private var datePicker: UIDatePicker! private var cancelButton: UIButton! private var doneButton: UIButton! /* Vars */ private var title: String! private var doneButtonTitle: String! private var cancelButtonTitle: String! private var defaultDate: NSDate! private var minimumDate: NSDate! private var maximumDate: NSDate! private var datePickerMode: UIDatePickerMode! private var callback: ((date: NSDate) -> Void)! /* Overrides */ init() { super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) NSNotificationCenter.defaultCenter().addObserver(self, selector: "deviceOrientationDidChange:", name: UIDeviceOrientationDidChangeNotification, object: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* Handle device orientation changes */ func deviceOrientationDidChange(notification: NSNotification) { /* TODO */ } /* Create the dialog view, and animate opening the dialog */ func show(title: String, datePickerMode: UIDatePickerMode = .DateAndTime, callback: ((date: NSDate) -> Void)) { show(title, doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: datePickerMode, callback: callback) } func show(title: String, doneButtonTitle: String, cancelButtonTitle: String, defaultDate: NSDate = NSDate(), maximumDate: NSDate = NSDate(), minimumDate: NSDate = NSDate(timeIntervalSince1970: 0), datePickerMode: UIDatePickerMode = .DateAndTime, callback: ((date: NSDate) -> Void)) { self.title = title self.doneButtonTitle = doneButtonTitle self.cancelButtonTitle = cancelButtonTitle self.datePickerMode = datePickerMode self.callback = callback self.defaultDate = defaultDate self.maximumDate = maximumDate self.minimumDate = minimumDate self.dialogView = createContainerView() self.dialogView!.layer.shouldRasterize = true self.dialogView!.layer.rasterizationScale = UIScreen.mainScreen().scale self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.mainScreen().scale self.dialogView!.layer.opacity = 0.5 self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1) self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.addSubview(self.dialogView!) /* Attached to the top most window (make sure we are using the right orientation) */ let interfaceOrientation = UIApplication.sharedApplication().statusBarOrientation switch(interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft: let t: Double = M_PI * 270 / 180 self.transform = CGAffineTransformMakeRotation(CGFloat(t)) break case UIInterfaceOrientation.LandscapeRight: let t: Double = M_PI * 90 / 180 self.transform = CGAffineTransformMakeRotation(CGFloat(t)) break case UIInterfaceOrientation.PortraitUpsideDown: let t: Double = M_PI * 180 / 180 self.transform = CGAffineTransformMakeRotation(CGFloat(t)) break default: break } self.frame = CGRectMake(0, 0, self.frame.width, self.frame.size.height) UIApplication.sharedApplication().windows.first!.addSubview(self) /* Anim */ UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) self.dialogView!.layer.opacity = 1 self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1) }, completion: nil ) } /* Dialog close animation then cleaning and removing the view from the parent */ private func close() { let currentTransform = self.dialogView.layer.transform let startRotation = (self.valueForKeyPath("layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0 let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + M_PI * 270 / 180), 0, 0, 0) self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1)) self.dialogView.layer.opacity = 1 UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1)) self.dialogView.layer.opacity = 0 }) { (finished: Bool) -> Void in for v in self.subviews { v.removeFromSuperview() } self.removeFromSuperview() } } /* Creates the container view here: create the dialog, then add the custom content and buttons */ private func createContainerView() -> UIView { let screenSize = countScreenSize() let dialogSize = CGSizeMake( 300, 230 + kDatePickerDialogDefaultButtonHeight + kDatePickerDialogDefaultButtonSpacerHeight) // For the black background self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height) // This is the dialog's container; we attach the custom content and the buttons to this one let dialogContainer = UIView(frame: CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height)) // First, we style the dialog to match the iOS8 UIAlertView >>> let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer) gradient.frame = dialogContainer.bounds gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor, UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).CGColor, UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor] let cornerRadius = kDatePickerDialogCornerRadius gradient.cornerRadius = cornerRadius dialogContainer.layer.insertSublayer(gradient, atIndex: 0) dialogContainer.layer.cornerRadius = cornerRadius dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).CGColor dialogContainer.layer.borderWidth = 1 dialogContainer.layer.shadowRadius = cornerRadius + 5 dialogContainer.layer.shadowOpacity = 0.1 dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius + 5) / 2, 0 - (cornerRadius + 5) / 2) dialogContainer.layer.shadowColor = UIColor.blackColor().CGColor dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).CGPath // There is a line above the button let lineView = UIView(frame: CGRectMake(0, dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, dialogContainer.bounds.size.width, kDatePickerDialogDefaultButtonSpacerHeight)) lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1) dialogContainer.addSubview(lineView) // ˆˆˆ //Title self.titleLabel = UILabel(frame: CGRectMake(10, 10, 280, 30)) self.titleLabel.textAlignment = NSTextAlignment.Center self.titleLabel.font = UIFont.boldSystemFontOfSize(17) self.titleLabel.text = self.title dialogContainer.addSubview(self.titleLabel) self.datePicker = UIDatePicker(frame: CGRectMake(0, 30, 0, 0)) self.datePicker.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin self.datePicker.frame.size.width = 300 self.datePicker.datePickerMode = self.datePickerMode self.datePicker.date = self.defaultDate self.datePicker.maximumDate = self.maximumDate self.datePicker.minimumDate = self.minimumDate dialogContainer.addSubview(self.datePicker) // Add the buttons addButtonsToView(dialogContainer) return dialogContainer } /* Add buttons to container */ private func addButtonsToView(container: UIView) { let buttonWidth = container.bounds.size.width / 2 self.cancelButton = UIButton(type: UIButtonType.Custom) as UIButton self.cancelButton.frame = CGRectMake( 0, container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, buttonWidth, kDatePickerDialogDefaultButtonHeight ) self.cancelButton.tag = kDatePickerDialogCancelButtonTag self.cancelButton.setTitle(self.cancelButtonTitle, forState: UIControlState.Normal) self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal) self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted) self.cancelButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14) self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.cancelButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.cancelButton) self.doneButton = UIButton(type: UIButtonType.Custom) as UIButton self.doneButton.frame = CGRectMake( buttonWidth, container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, buttonWidth, kDatePickerDialogDefaultButtonHeight ) self.doneButton.tag = kDatePickerDialogDoneButtonTag self.doneButton.setTitle(self.doneButtonTitle, forState: UIControlState.Normal) self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal) self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted) self.doneButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14) self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.doneButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.doneButton) } func buttonTapped(sender: UIButton!) { if sender.tag == kDatePickerDialogDoneButtonTag { self.callback(date: self.datePicker.date) } else if sender.tag == kDatePickerDialogCancelButtonTag { //There's nothing do to here \o\ } close() } /* Helper function: count and return the screen's size */ func countScreenSize() -> CGSize { var screenWidth = UIScreen.mainScreen().bounds.size.width var screenHeight = UIScreen.mainScreen().bounds.size.height let interfaceOrientaion = UIApplication.sharedApplication().statusBarOrientation if UIInterfaceOrientationIsLandscape(interfaceOrientaion) { let tmp = screenWidth screenWidth = screenHeight screenHeight = tmp } return CGSizeMake(screenWidth, screenHeight) } }
mit
0618a501d4547c411a71eb6a41c98995
44.570909
287
0.646131
5.452107
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-02
demos/ReadingList/ReadingListModel/ReadingListStore.swift
1
1988
// // Copyright (C) 2014 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this example's licensing information. // import Foundation let documentsURLs = FileManager.default.urls( for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask) // MARK: - File Utilities func fileURLForDocument(_ name: String, type: String) -> URL { precondition(!documentsURLs.isEmpty, "Documents directory must exist.") let fileURL = documentsURLs.first! return fileURL.appendingPathComponent(name).appendingPathExtension(type) } // MARK: - ReadingListStore open class ReadingListStore : NSObject { let storeType = "plist" let storeName: String let documentURL: URL override convenience init() { self.init(storeName: nil) } public init(storeName: String? = "BooksAndAuthors") { self.storeName = storeName ?? "" documentURL = fileURLForDocument(self.storeName, type: storeType) super.init() } open func fetchReadingList() -> ReadingList { if FileManager.default.fileExists(atPath: documentURL.path), let dict = NSDictionary(contentsOf: documentURL) as? [String: AnyObject] { return ReadingList(dictionary: dict) } let bundle = Bundle(for: ReadingListStore.self) guard let URL = bundle.url(forResource: storeName, withExtension: storeType) else { fatalError("Unable to locate \(storeName) in app bundle") } guard let dict = NSDictionary(contentsOf: URL) as? [String: AnyObject] else { fatalError("Unable to load \(storeName) with bundle URL \(URL)") } return ReadingList(dictionary: dict) } open func saveReadingList(_ readingList: ReadingList) { let dict = readingList.dictionaryRepresentation() as NSDictionary dict.write(to: documentURL, atomically: true) } }
mit
b0497925ccf3ff07085d30e6eadae541
29.584615
91
0.668008
4.790361
false
false
false
false
mohamede1945/quran-ios
VFoundation/Crasher.swift
1
3112
// // Crasher.swift // Quran // // Created by Mohamed Afifi on 4/28/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // public class CrasherKeyBase {} public final class CrasherKey<Type>: CrasherKeyBase { public let key: String public init(key: String) { self.key = key } } public protocol Crasher { var tag: StaticString { get } func setValue<T>(_ value: T?, forKey key: CrasherKey<T>) func recordError(_ error: Error, reason: String, fatalErrorOnDebug: Bool, file: StaticString, line: UInt) func log(_ message: String) func logCriticalIssue(_ message: String) var localizedUnkownError: String { get } } public struct Crash { // should be set at the very begining of the app. public static var crasher: Crasher? public static func recordError(_ error: Error, reason: String, fatalErrorOnDebug: Bool = true, file: StaticString = #file, line: UInt = #line) { Crash.crasher?.recordError(error, reason: reason, fatalErrorOnDebug: fatalErrorOnDebug, file: file, line: line) } public static func setValue<T>(_ value: T?, forKey key: CrasherKey<T>) { Crash.crasher?.setValue(value, forKey: key) } } public func log(_ items: Any..., separator: String = " ", terminator: String = "\n") { let message = "[\(Crash.crasher?.tag ?? "_")]: " + items.map { "\($0)" }.joined(separator: separator) + terminator NSLog(message) } public func CLog(_ items: Any..., separator: String = " ", terminator: String = "\n") { let message = "[\(Crash.crasher?.tag ?? "_")]: " + items.map { "\($0)" }.joined(separator: separator) + terminator NSLog(message) Crash.crasher?.log(message) } public func logCriticalIssue(_ items: Any..., separator: String = " ", terminator: String = "\n") { let message = "[\(Crash.crasher?.tag ?? "_")]: " + items.map { "\($0)" }.joined(separator: separator) + terminator NSLog(message) Crash.crasher?.logCriticalIssue(message) } public func fatalError(_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) -> Never { CLog("message: \(message()), file:\(file.description), line:\(line)") Swift.fatalError(message, file: file, line: line) } public func fatalError(_ message: @autoclosure () -> String = "", _ error: Error, file: StaticString = #file, line: UInt = #line) -> Never { let fullMessage = "\(message()), error: \(error)" CLog("message: \(fullMessage), file:\(file.description), line:\(line)") Swift.fatalError(fullMessage, file: file, line: line) }
gpl-3.0
498da18cb3199ff0ae871ac4d8a287bd
38.392405
148
0.664203
3.823096
false
false
false
false
soapyigu/Swift30Projects
Project 22 - HonoluluArt/HonoluluArt/Artwork.swift
2
2567
// // Artwork.swift // HonoluluArt // // Copyright © 2017 Yi Gu. All rights reserved. // import Foundation import MapKit import Contacts class Artwork: NSObject, MKAnnotation { /// Title for annotation view. let title: String? /// Location name for subtitle. let locationName: String /// Discipline of the artwork. let discipline: String /// Coordinate data of the artwork location. let coordinate: CLLocationCoordinate2D /// Subtitle for annotation view. var subtitle: String? { return locationName } /// Initializer. /// /// - Parameters: /// - title: Name of the artwork. /// - locationName: Location of the artwork. /// - discipline: Category of the artwork. /// - coordinate: Longitude and latitude of the artwork. init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) { self.title = title self.locationName = locationName self.discipline = discipline self.coordinate = coordinate super.init() } /// Convert the artwork to a map item as an annotation on map. /// /// - Returns: Map Item with coordinate. func mapItem() -> MKMapItem { if let subtitle = subtitle { let addressDict = [CNPostalAddressStreetKey: subtitle] let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict) let mapItem = MKMapItem(placemark: placemark) mapItem.name = title return mapItem } else { fatalError("Subtitle is nil") } } /// Set up annotation color based on discipline. /// /// - Returns: THe color for a specific discipline. func pinColor() -> UIColor { switch discipline { case "Sculpture", "Plaque": return MKPinAnnotationView.redPinColor() case "Mural", "Monument": return MKPinAnnotationView.purplePinColor() default: return MKPinAnnotationView.greenPinColor() } } /// Parse JSON data to Artwork model. /// /// - Parameter json: JSON data to be parsed. /// - Returns: Artwork model. static func fromJSON(json: [JSONValue]) -> Artwork? { let locationName = json[12].string let discipline = json[15].string let latitude = (json[18].string! as NSString).doubleValue let longitude = (json[19].string! as NSString).doubleValue let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) return Artwork(title: json[16].string ?? "", locationName: locationName!, discipline: discipline!, coordinate: coordinate) } }
apache-2.0
f144cb4673e9ef148ff859efd9c3d231
26.891304
126
0.668745
4.565836
false
false
false
false
TonnyTao/Acornote
Acornote_iOS/Pods/SugarRecord/SugarRecord/Source/CoreData/Storages/CoreDataDefaultStorage.swift
1
8872
import Foundation import CoreData public class CoreDataDefaultStorage: Storage { // MARK: - Attributes internal let store: CoreDataStore internal var objectModel: NSManagedObjectModel! = nil internal var persistentStore: NSPersistentStore! = nil internal var persistentStoreCoordinator: NSPersistentStoreCoordinator! = nil internal var rootSavingContext: NSManagedObjectContext! = nil // MARK: - Storage conformance public var description: String { get { return "CoreDataDefaultStorage" } } public var type: StorageType = .coreData public var mainContext: Context! private var _saveContext: Context! public var saveContext: Context! { if let context = self._saveContext { return context } let _context = cdContext(withParent: .context(self.rootSavingContext), concurrencyType: .privateQueueConcurrencyType, inMemory: false) _context.observe(inMainThread: true) { [weak self] (notification) -> Void in (self?.mainContext as? NSManagedObjectContext)?.mergeChanges(fromContextDidSave: notification as Notification) } self._saveContext = _context return _context } public var memoryContext: Context! { let _context = cdContext(withParent: .context(self.rootSavingContext), concurrencyType: .privateQueueConcurrencyType, inMemory: true) return _context } public func operation<T>(_ operation: @escaping (_ context: Context, _ save: @escaping () -> Void) throws -> T) throws -> T { let context: NSManagedObjectContext = self.saveContext as! NSManagedObjectContext var _error: Error! var returnedObject: T! context.performAndWait { do { returnedObject = try operation(context, { () -> Void in do { try context.save() } catch { _error = error } self.rootSavingContext.performAndWait({ if self.rootSavingContext.hasChanges { do { try self.rootSavingContext.save() } catch { _error = error } } }) }) } catch { _error = error } } if let error = _error { throw error } return returnedObject } public func backgroundOperation(_ operation: @escaping (_ context: Context, _ save: @escaping () -> Void) -> (), completion: @escaping (Error?) -> ()) { let context: NSManagedObjectContext = self.saveContext as! NSManagedObjectContext var _error: Error! context.perform { operation(context, { () -> Void in do { try context.save() } catch { _error = error } self.rootSavingContext.perform { if self.rootSavingContext.hasChanges { do { try self.rootSavingContext.save() } catch { _error = error } } completion(_error) } }) } } public func removeStore() throws { try FileManager.default.removeItem(at: store.path() as URL) _ = try? FileManager.default.removeItem(atPath: "\(store.path().absoluteString)-shm") _ = try? FileManager.default.removeItem(atPath: "\(store.path().absoluteString)-wal") } // MARK: - Init public convenience init(store: CoreDataStore, model: CoreDataObjectModel, migrate: Bool = true) throws { try self.init(store: store, model: model, migrate: migrate, versionController: VersionController()) } internal init(store: CoreDataStore, model: CoreDataObjectModel, migrate: Bool = true, versionController: VersionController) throws { self.store = store self.objectModel = model.model()! self.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: objectModel) self.persistentStore = try cdInitializeStore(store: store, storeCoordinator: persistentStoreCoordinator, migrate: migrate) self.rootSavingContext = cdContext(withParent: .coordinator(self.persistentStoreCoordinator), concurrencyType: .privateQueueConcurrencyType, inMemory: false) self.mainContext = cdContext(withParent: .context(self.rootSavingContext), concurrencyType: .mainQueueConcurrencyType, inMemory: false) #if DEBUG versionController.check() #endif } // MARK: - Public #if os(iOS) || os(tvOS) || os(watchOS) public func observable<T: NSManagedObject>(request: FetchRequest<T>) -> RequestObservable<T> where T:Equatable { return CoreDataObservable(request: request, context: self.mainContext as! NSManagedObjectContext) } #endif } // MARK: - Internal internal func cdContext(withParent parent: CoreDataContextParent?, concurrencyType: NSManagedObjectContextConcurrencyType, inMemory: Bool) -> NSManagedObjectContext { var context: NSManagedObjectContext? if inMemory { context = NSManagedObjectMemoryContext(concurrencyType: concurrencyType) } else { context = NSManagedObjectContext(concurrencyType: concurrencyType) } if let parent = parent { switch parent { case .context(let parentContext): context!.parent = parentContext case .coordinator(let storeCoordinator): context!.persistentStoreCoordinator = storeCoordinator } } context!.observeToGetPermanentIDsBeforeSaving() return context! } internal func cdInitializeStore(store: CoreDataStore, storeCoordinator: NSPersistentStoreCoordinator, migrate: Bool) throws -> NSPersistentStore { try cdCreateStoreParentPathIfNeeded(store: store) let options = migrate ? CoreDataOptions.migration : CoreDataOptions.basic return try cdAddPersistentStore(store: store, storeCoordinator: storeCoordinator, options: options.dict()) } internal func cdCreateStoreParentPathIfNeeded(store: CoreDataStore) throws { let databaseParentPath = store.path().deletingLastPathComponent() try FileManager.default.createDirectory(at: databaseParentPath, withIntermediateDirectories: true, attributes: nil) } internal func cdAddPersistentStore(store: CoreDataStore, storeCoordinator: NSPersistentStoreCoordinator, options: [String: AnyObject]) throws -> NSPersistentStore { var addStore: ((_ store: CoreDataStore, _ storeCoordinator: NSPersistentStoreCoordinator, _ options: [String: AnyObject], _ cleanAndRetryIfMigrationFails: Bool) throws -> NSPersistentStore)? addStore = { (store: CoreDataStore, coordinator: NSPersistentStoreCoordinator, options: [String: AnyObject], retry: Bool) throws -> NSPersistentStore in var persistentStore: NSPersistentStore? var error: NSError? coordinator.performAndWait({ () -> Void in do { persistentStore = try storeCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: store.path() as URL, options: options) } catch let _error as NSError { error = _error } }) if let error = error { let isMigrationError = error.code == NSPersistentStoreIncompatibleVersionHashError || error.code == NSMigrationMissingSourceModelError if isMigrationError && retry { _ = try? cdCleanStoreFilesAfterFailedMigration(store: store) return try addStore!(store, coordinator, options, false) } else { throw error } } else if let persistentStore = persistentStore { return persistentStore } throw CoreDataError.persistenceStoreInitialization } return try addStore!(store, storeCoordinator, options, true) } internal func cdCleanStoreFilesAfterFailedMigration(store: CoreDataStore) throws { let rawUrl: String = store.path().absoluteString let shmSidecar: NSURL = NSURL(string: rawUrl.appending("-shm"))! let walSidecar: NSURL = NSURL(string: rawUrl.appending("-wal"))! try FileManager.default.removeItem(at: store.path() as URL) try FileManager.default.removeItem(at: shmSidecar as URL) try FileManager.default.removeItem(at: walSidecar as URL) }
apache-2.0
b487ad0c6daea63692cb4f77866f1d83
40.457944
195
0.624549
5.698137
false
false
false
false
Chris-Perkins/Lifting-Buddy
Lifting Buddy/CreateWorkoutView.swift
1
25672
// // CreateWorkoutView.swift // Lifting Buddy // // Created by Christopher Perkins on 8/11/17. // Copyright © 2017 Christopher Perkins. All rights reserved. // import UIKit import Realm import RealmSwift class CreateWorkoutView: UIScrollView { // MARK: View properties // Padding between views let viewPadding: CGFloat = 20.0 // Delegate that does something when workout complete public var dataDelegate: CreateWorkoutViewDelegate? // Delegate to show a view public var showViewDelegate: ShowViewDelegate? // variable stating how many cells are in the exercise table view private var prevDataCount = -1 // the exercise the user is editing private var editingWorkout: Workout? = nil // labels this view private let createWorkoutLabel: UILabel // Field to enter name private let nameEntryField: BetterTextField // Exercise Table Label private let exerciseTableLabel: UILabel // Table holding all of our exercises private let editExerciseTableView: EditExerciseTableView // button to add a new exercise to this view private let addExerciseButton: PrettyButton // repeat label private let repeatLabel: UILabel // repeat contents private let repeatButtonView: UIView // all of the repeat buttons private var repeatButtons: [ToggleablePrettyButton] // Button to create our workout private let createWorkoutButton: PrettyButton // Cancel button private let cancelButton: PrettyButton // MARK: View inits init(workout: Workout? = nil, frame: CGRect) { editingWorkout = workout createWorkoutLabel = UILabel() nameEntryField = BetterTextField(defaultString: NSLocalizedString("ExerciseView.Textfield.Name", comment: ""), frame: .zero) exerciseTableLabel = UILabel() editExerciseTableView = EditExerciseTableView() repeatLabel = UILabel() repeatButtonView = UIView() repeatButtons = [ToggleablePrettyButton]() addExerciseButton = PrettyButton() createWorkoutButton = PrettyButton() cancelButton = PrettyButton() super.init(frame: frame) addSubview(createWorkoutLabel) addSubview(nameEntryField) addSubview(exerciseTableLabel) addSubview(editExerciseTableView) addSubview(addExerciseButton) addSubview(repeatLabel) addSubview(repeatButtonView) addSubview(createWorkoutButton) addSubview(cancelButton) createAndActivateCreateWorkoutLabelConstraints() createAndActivateNameEntryFieldConstraints() createAndActivateExerciseTableLabelConstraints() createAndActivateEditExerciseTableViewConstraints() createAndActivateAddExerciseButtonConstraints() createAndActivateRepeatLabelConstraints() createAndActivateRepeatButtonViewConstraints() createAndActivateCreateWorkoutButtonConstraints() createAndActivateCancelButtonConstraints() createRepeatButtons(encapsulatingView: repeatButtonView) addExerciseButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) createWorkoutButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) cancelButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) // If we're editing... if let workout = editingWorkout { nameEntryField.textfield.text = workout.getName() for exercise in workout.getExercises() { editExerciseTableView.appendDataToTableView(data: exercise) } let repeatOnDays = workout.getsDayOfTheWeek() for (index, button) in repeatButtons.enumerated() { button.setIsToggled(toggled: repeatOnDays[index].value) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // View overrides override func layoutSubviews() { super.layoutSubviews() // Self stuff backgroundColor = .lightestBlackWhiteColor contentSize.height = cancelButton.frame.maxY + viewPadding // Label createWorkoutLabel.setDefaultProperties() createWorkoutLabel.text = editingWorkout != nil ? NSLocalizedString("WorkoutView.Label.EditWorkout", comment: ""): NSLocalizedString("WorkoutView.Label.CreateWorkout", comment: "") createWorkoutLabel.backgroundColor = UILabel.titleLabelBackgroundColor createWorkoutLabel.textColor = UILabel.titleLabelTextColor // Name Entry Field nameEntryField.setDefaultProperties() nameEntryField.setLabelTitle(title: NSLocalizedString("ExerciseView.Label.Name", comment: "")) // Repeat Label repeatLabel.setDefaultProperties() repeatLabel.text = NSLocalizedString("WorkoutView.Label.Repeat", comment: "") // Repeat Buton for repeatButton in repeatButtons { repeatButton.setToggleViewColor(color: .niceYellow) repeatButton.setToggleTextColor(color: .white) repeatButton.setDefaultTextColor(color: UIColor.oppositeBlackWhiteColor.withAlphaComponent(0.25)) repeatButton.setDefaultViewColor(color: .primaryBlackWhiteColor) repeatButton.layer.cornerRadius = (repeatButton.frame.width / 2) } // Exercise Table Label exerciseTableLabel.setDefaultProperties() exerciseTableLabel.text = NSLocalizedString("WorkoutView.Label.Exercises", comment: "") // Exercise Table View // Prevent clipping as we can click and drag cells editExerciseTableView.clipsToBounds = false editExerciseTableView.isScrollEnabled = false editExerciseTableView.backgroundColor = .clear // Add exercise button addExerciseButton.setDefaultProperties() addExerciseButton.setTitle(NSLocalizedString("WorkoutView.Button.AddExercise", comment: ""), for: .normal) // Create workout button // Give it standard default properties createWorkoutButton.setDefaultProperties() createWorkoutButton.setTitle(editingWorkout != nil ? NSLocalizedString("WorkoutView.Button.SaveWorkout", comment: "") : NSLocalizedString("WorkoutView.Button.CreateWorkout", comment: ""), for: .normal) // Cancel Button cancelButton.setDefaultProperties() cancelButton.setTitle(NSLocalizedString("Button.Cancel", comment: ""), for: .normal) cancelButton.backgroundColor = .niceRed } // MARK: Event functions @objc func buttonPress(sender: PrettyButton) { // Resigns all keyboards endEditing(true) switch (sender) { case addExerciseButton: /* * We use superview here as this view is a scrollview. This could * alternatively be done by having an encasing view for every workoutview. * That may be considered best practice... So, TODO */ let exercisePickerView = ExercisesView(selectingExercise: true, frame: .zero) exercisePickerView.exercisePickerDelegate = self guard let showViewDelegate = showViewDelegate else { fatalError("ShowViewDelegate not set for ExercisePicker") } showViewDelegate.showView(exercisePickerView) case createWorkoutButton: if checkRequirementsFulfilled() { // Send info to delegate, animate up then remove self let savedWorkout = saveAndReturnWorkout() MessageQueue.shared.append(Message(type: editingWorkout == nil ? .objectCreated: .objectSaved, identifier: savedWorkout.getName(), value: nil)) // Prevent user interaction with all subviews for subview in subviews { subview.isUserInteractionEnabled = false } // Slide up, then remove from view UIView.animate(withDuration: 0.2, animations: { self.frame = CGRect(x: 0, y: -self.frame.height, width: self.frame.width, height: self.frame.height) }, completion: { (finished:Bool) -> Void in self.dataDelegate?.finishedWithWorkout(workout: savedWorkout) self.removeFromSuperview() }) } break case cancelButton: removeSelfNicelyWithAnimation() break default: fatalError("Button pressed was not assigned function") } } // MARK: Private functions // Check if requirements per workout are completed private func checkRequirementsFulfilled() -> Bool { var fulfilled = true if nameEntryField.textfield.text?.count == 0 { nameEntryField.textfield.backgroundColor = .niceRed fulfilled = false } return fulfilled } // Use data on this form to create the workout private func saveAndReturnWorkout() -> Workout { let savedWorkout = editingWorkout ?? Workout() savedWorkout.setName(name: nameEntryField.text) savedWorkout.setDaysOfTheWeek(daysOfTheWeek: getDaysOfTheWeek()) savedWorkout.removeExercies() for exercise in editExerciseTableView.getData() { savedWorkout.addExercise(exercise: exercise) } // If this is a new workout, save it. if editingWorkout == nil { let realm = try! Realm() try! realm.write { realm.add(savedWorkout) } } // Return this workout return savedWorkout } // Creates the repeat buttons private func createRepeatButtons(encapsulatingView: UIView) { var prevView = encapsulatingView for dayChar in daysOfTheWeekChars { let dayButton = ToggleablePrettyButton() dayButton.setTitle(dayChar, for: .normal) addSubview(dayButton) repeatButtons.append(dayButton) // MARK: dayButton constraints dayButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: prevView, attribute: prevView == encapsulatingView ? .left : .right, relatedBy: .equal, toItem: dayButton, attribute: .left, multiplier: 1, constant: prevView == encapsulatingView ? -2.5 : -5).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: dayButton, withCopyView: encapsulatingView, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: dayButton, withCopyView: encapsulatingView, attribute: .width, multiplier: 1/CGFloat(daysOfTheWeekChars.count), plusConstant: -5 * CGFloat(daysOfTheWeekChars.count) ).isActive = true // Constraint makes sure these buttons are circles NSLayoutConstraint(item: dayButton, attribute: .height, relatedBy: .equal, toItem: dayButton, attribute: .width, multiplier: 1, constant: 0).isActive = true // reset prevView to this view for constraints prevView = dayButton } } private func getDaysOfTheWeek() -> List<RLMBool> { let toggledIndices = List<RLMBool>() for button in repeatButtons { let rlmBool = RLMBool() rlmBool.value = button.isToggled toggledIndices.append(rlmBool) } return toggledIndices } // MARK: Constraints // cling to left, top of self ; height of title default ; copy width private func createAndActivateCreateWorkoutLabelConstraints() { createWorkoutLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: createWorkoutLabel, withCopyView: self, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: createWorkoutLabel, withCopyView: self, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: createWorkoutLabel, withCopyView: self, attribute: .width).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: createWorkoutLabel, height: UILabel.titleLabelHeight).isActive = true } // Center horiz in view; place below self ; height of default height ; width of this view - 40 private func createAndActivateNameEntryFieldConstraints() { // Name entry field nameEntryField.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: nameEntryField, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewBelowViewConstraint(view: nameEntryField, belowView: createWorkoutLabel, withPadding: viewPadding).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: nameEntryField, height: BetterTextField.defaultHeight).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: nameEntryField, withCopyView: self, attribute: .width, plusConstant: -40).isActive = true } // Center horiz in view ; place below nameEntryField ; height of 20 ; width of this view - 80 private func createAndActivateExerciseTableLabelConstraints() { exerciseTableLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: exerciseTableLabel, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewBelowViewConstraint(view: exerciseTableLabel, belowView: nameEntryField, withPadding: viewPadding * 2).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: exerciseTableLabel, height: 20).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: exerciseTableLabel, withCopyView: self, attribute: .width, plusConstant: -20).isActive = true } // Center horiz in view ; place below exerciseTableLabel ; Default height of 0 ; Width of this view - 40 private func createAndActivateEditExerciseTableViewConstraints() { editExerciseTableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: editExerciseTableView, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewBelowViewConstraint(view: editExerciseTableView, belowView: exerciseTableLabel, withPadding: viewPadding / 2).isActive = true // Height constraint property assigning; increases based on number of cells editExerciseTableView.heightConstraint = NSLayoutConstraint.createHeightConstraintForView(view: editExerciseTableView, height: 0) editExerciseTableView.heightConstraint?.isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: editExerciseTableView, withCopyView: self, attribute: .width, plusConstant: -50).isActive = true } // place below exercisetableview ; left/right match to exercisetableview ; height of default height private func createAndActivateAddExerciseButtonConstraints() { addExerciseButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewBelowViewConstraint(view: addExerciseButton, belowView: editExerciseTableView, withPadding: 0).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: addExerciseButton, withCopyView: editExerciseTableView, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: addExerciseButton, withCopyView: editExerciseTableView, attribute: .right).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: addExerciseButton, height: PrettyButton.defaultHeight).isActive = true } // center horiz in view ; place below name entry field ; height 20 ; width of this view - 20 private func createAndActivateRepeatLabelConstraints() { repeatLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: repeatLabel, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewBelowViewConstraint(view: repeatLabel, belowView: addExerciseButton, withPadding: viewPadding * 2).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: repeatLabel, height: 20).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: repeatLabel, withCopyView: self, attribute: .width, plusConstant: -20).isActive = true } // center horiz in view ; place below name entry field ; height 20 ; width of this view - 20 private func createAndActivateRepeatButtonViewConstraints() { repeatButtonView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: repeatButtonView, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewBelowViewConstraint(view: repeatButtonView, belowView: repeatLabel, withPadding: viewPadding / 2).isActive = true NSLayoutConstraint(item: repeatButtonView, attribute: .width, relatedBy: .equal, toItem: repeatButtonView, attribute: .height, multiplier: CGFloat(daysOfTheWeekChars.count), constant: 5 * CGFloat(daysOfTheWeekChars.count)).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: repeatButtonView, withCopyView: self, attribute: .width, plusConstant: -20).isActive = true } // center horiz in view ; place below add exercise button ; height of default ; width of this view - 50 private func createAndActivateCreateWorkoutButtonConstraints() { createWorkoutButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: createWorkoutButton, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewBelowViewConstraint(view: createWorkoutButton, belowView: repeatButtonView, withPadding: viewPadding * 2).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: createWorkoutButton, height: PrettyButton.defaultHeight).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: createWorkoutButton, withCopyView: self, attribute: .width, plusConstant: -50).isActive = true } // center horiz in view ; place below createWorkoutButton; height 30 ; width of createWorkoutButton - 40 private func createAndActivateCancelButtonConstraints() { cancelButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: cancelButton, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewBelowViewConstraint(view: cancelButton, belowView: createWorkoutButton, withPadding: viewPadding).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: cancelButton, height: 40).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: cancelButton, withCopyView: createWorkoutButton, attribute: .width, plusConstant: 0).isActive = true } } extension CreateWorkoutView: ExercisePickerDelegate { // whenever an exercise is selected from our select exercise view func didSelectExercise(exercise: Exercise) { editExerciseTableView.appendDataToTableView(data: exercise) } }
mit
4bea13ca1e2fd5183230aaae5a3d6b74
48.94358
117
0.548946
7.713642
false
false
false
false
ericosg/playmetodeath
playmetodeath.spritebuilder/Level2Scene.swift
1
3254
// // Level1Scene.swift // playmetodeath // // Created by developer on 27/06/15. // Copyright (c) 2015 Apportable. All rights reserved. // import Foundation class Level2Scene: LevelScene { var _ground: CCSprite? override init() { super.init() self._level = 2 self._levelPart = 1 } override func didLoadFromCCB() { super.didLoadFromCCB() makeBall(64, offsetY: 100, duration: 1) makeBall(256, offsetY: 300, duration: 1) makeBall(384, offsetY: 200, duration: 1) makeBall(462, offsetY: 500, duration: 3) makeBall(30, offsetY: 320, duration: 3) makeBall(300, offsetY: 960, duration: 4) makeBall(285, offsetY: 1360, duration: 5) makeBall(199, offsetY: 2360, duration: 6) makeBall(220, offsetY: 360, duration: 5) makeBall(500, offsetY: 6500, duration: 9) makeBall(400, offsetY: 8560, duration: 10) makeBall(344, offsetY: 1700, duration: 11) moveGround() makeBall(356, offsetY: 3960, duration: 12) makeBall(295, offsetY: 1560, duration: 12.5) makeBall(139, offsetY: 4360, duration: 13) makeBall(120, offsetY: 2360, duration: 13, end: true) } func makeBall(x: CGFloat, offsetY:CGFloat, duration:CCTime, end: Bool = false, force: Bool = false) { let ball = CCBReader.load("Ball") ball.position = CGPoint(x: x, y: 768+offsetY) if let physicsNode = _physicsNode { physicsNode.addChild(ball) } ball.physicsBody.affectedByGravity = false if(force) { // let rotationRadians = CC_DEGREES_TO_RADIANS(210) // // let directionVector = ccp(CGFloat(sinf(rotationRadians)), CGFloat(cosf(rotationRadians))) // let ballOffset = ccpMult(directionVector, 50) // // ball.position = ccpAdd(_launcher!.position, ballOffset) // // var useTheForceLucas += CGFloat(10000) // let force = ccpMult(directionVector, useTheForceLucas) // // ball.physicsBody.applyForce(force) } let delay = CCActionDelay(duration: duration) let holdup = CCActionCallBlock { () -> Void in ball.physicsBody.affectedByGravity = true } if(end) { let endDelay = CCActionDelay(duration: 10) let endCall = CCActionCallBlock(block: { () -> Void in self.stageEnd(self) }) ball.runAction(CCActionSequence(array: [delay, holdup, endDelay, endCall])) } else { ball.runAction(CCActionSequence(array: [delay, holdup])) } } func moveGround() { if let ground = _ground { let delay = CCActionDelay(duration: 15) let move = CCActionMoveTo(duration: 1, position: CGPoint(x: 256, y: -58)) let disable = CCActionCallBlock { () -> Void in ground.physicsNode().removeChild(ground, cleanup: true) } ground.runAction(CCActionSequence(array: [delay, move, disable])) } } }
apache-2.0
9ed84a00b51a2bd2240325b8f820facf
32.556701
105
0.562692
4.129442
false
false
false
false
wscqs/FMDemo-
FMDemo/Classes/Module/Main/MainTableViewCell.swift
1
1918
// // MainTableViewCell.swift // FMDemo // // Created by mba on 17/2/9. // Copyright © 2017年 mbalib. All rights reserved. // import UIKit import ObjectMapper class MainTableViewCell: RefreshBaseTableViewCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var statusImg: UIImageView! @IBOutlet weak var statusLabel: UILabel! override func setContent(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath, dataList: [Mappable]) { guard let bean = dataList[indexPath.row] as? GetCoursesData else{return} title.text = bean.title timeLabel.text = bean.createtime let state = bean.state ?? "unrecorded" status(state: state) } func status(state: String) { //state:unrecorded未录制 enable(会有url地址) 上架 disable 已保存 if "enable" == state { statusImg.image = #imageLiteral(resourceName: "course_chapt_state3_ico") statusLabel.text = "上架中" statusLabel.textColor = UIColor.colorWithHexString("58acff") } else if "unrecorded" == state { statusImg.image = #imageLiteral(resourceName: "course_chapt_state1_ico") statusLabel.text = "未录制" statusLabel.textColor = UIColor.colorWithHexString("f45e5e") } else if "disable" == state { statusImg.image = #imageLiteral(resourceName: "course_chapt_state2_ico") statusLabel.text = "已保存" statusLabel.textColor = UIColor.colorWithHexString("5dd89d") } } override func awakeFromNib() { super.awakeFromNib() contentView.backgroundColor = UIColor.colorWithHexString(kGlobalBgColor) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
apache-2.0
0151db94e9333cdfdb2644f8e3902752
32.945455
122
0.651848
4.36215
false
false
false
false
sschiau/swift
test/Parse/omit_return.swift
5
31481
// RUN: %target-swift-frontend %s -typecheck -verify // MARK: - Helpers @discardableResult func logAndReturn<T : CustomStringConvertible>(_ t: T) -> String { let log = "\(t)" print(log) return log } @discardableResult func failableLogAndReturn<T : CustomStringConvertible>(_ t: T) throws -> String { let log = "\(t)" print(log) return log } typealias MyOwnVoid = () func failableIdentity<T>(_ t: T) throws -> T { t } enum MyOwnNever {} func myOwnFatalError() -> MyOwnNever { fatalError() } struct MyOwnInt : ExpressibleByIntegerLiteral { init(integerLiteral: Int) {} } struct MyOwnFloat : ExpressibleByFloatLiteral { init(floatLiteral: Double) {} } struct MyOwnBoolean : ExpressibleByBooleanLiteral { init(booleanLiteral: Bool) {} } struct MyOwnString : ExpressibleByStringLiteral { init(stringLiteral: String) {} } struct MyOwnInterpolation : ExpressibleByStringInterpolation { init(stringLiteral: String) {} } enum Unit { case only } struct Initable {} struct StructWithProperty { var foo: Int } @dynamicMemberLookup struct DynamicStruct { subscript(dynamicMember input: String) -> String { return input } } struct MyOwnArray<Element> : ExpressibleByArrayLiteral { init(arrayLiteral elements: Element...) {} } struct MyOwnDictionary<Key, Value> : ExpressibleByDictionaryLiteral { init(dictionaryLiteral elements: (Key, Value)...) {} } struct SubscriptableStruct { subscript(int: Int) -> Int { int } } extension Int { var zero: Int { 0 } } extension Optional where Wrapped == Int { var someZero: Int? { .some(0) } } protocol SomeProto { func foo() -> String } struct SomeProtoConformer : SomeProto { func foo() -> String { "howdy" } } class Base {} class Derived : Base {} extension Int { init() { self = 0 } } // MARK: - Notable Free Functions func identity<T>(_ t: T) -> T { t } internal func _fatalErrorFlags() -> UInt32 { return 0 } internal func _assertionFailure( _ prefix: StaticString, _ message: String, flags: UInt32 ) -> Never { fatalError() } internal func _diagnoseUnexpectedEnumCaseValue<SwitchedValue, RawValue>( type: SwitchedValue.Type, rawValue: RawValue ) -> Never { _assertionFailure("Fatal error", "unexpected enum case '\(type)(rawValue: \(rawValue))'", flags: _fatalErrorFlags()) } // MARK: - Free Functions func ff_nop() { } func ff_missing() -> String { } func ff_implicit() -> String { "hello" } func ff_explicit() -> String { return "hello" } func ff_explicitClosure() -> () -> Void { return { print("howdy") } } func ff_implicitClosure() -> () -> Void { { print("howdy") } } func ff_explicitMultilineClosure() -> () -> String { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } func ff_implicitMultilineClosure() -> () -> String { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } func ff_implicitWrong() -> String { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } func ff_explicitWrong() -> String { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } func ff_implicitMulti() -> String { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } func ff_explicitMulti() -> String { print("okay") return "all right" } func ff_effectfulUsed() -> String { logAndReturn("okay") } // Unused Returns func ff_effectfulIgnored() { logAndReturn("okay") } func ff_effectfulIgnoredExplicitReturnTypeVoid() -> Void { logAndReturn("okay") } func ff_effectfulIgnoredExplicitReturnTypeSwiftVoid() -> Swift.Void { logAndReturn("okay") } func ff_effectfulIgnoredExplicitReturnTypeMyVoidTypealias() -> MyOwnVoid { logAndReturn("okay") } func ff_effectfulIgnoredExplicitReturnTypeEmptyTuple() -> () { logAndReturn("okay") } // Stubs func ff_stubImplicitReturn() { fatalError() } func ff_stubExplicitReturnTypeVoid() -> Void { fatalError() } func ff_stubExplicitReturnTypeSwiftVoid() -> Swift.Void { fatalError() } func ff_stubExplicitReturnTypeMyVoidTypealias() -> MyOwnVoid { fatalError() } func ff_stubExplicitReturnTypeEmptyTuple() -> () { fatalError() } func ff_stubImplicitReturnNever() -> Never { fatalError() } func ff_stubExplicitReturnNever() -> Never { return fatalError() } func ff_stubExplicitReturnNeverAsMyOwnNever() -> MyOwnNever { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } func ff_stubExplicitReturnMyOwnNeverAsNever() -> Never { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } func ff_stubImplicitReturnNeverAsMyOwnNever() -> MyOwnNever { fatalError() } func ff_stubImplicitReturnMyOwnNeverAsNever() -> Never { myOwnFatalError() } func ff_stubReturnString() -> String { fatalError() } func ff_stubReturnGeneric<T>() -> T { fatalError() } // Trying func ff_tryExplicit() throws -> String { return try failableIdentity("shucks") } func ff_tryImplicit() throws -> String { try failableIdentity("howdy") } func ff_tryExplicitMissingThrows() -> String { return try failableIdentity("shucks") // expected-error {{errors thrown from here are not handled}} } func ff_tryImplicitMissingThrows() -> String { try failableIdentity("howdy") // expected-error {{errors thrown from here are not handled}} } // Forced Trying func ff_forceTryExplicit() -> String { return try! failableIdentity("howdy") } func ff_forceTryImplicit() -> String { try! failableIdentity("shucks") } func ff_forceTryExplicitAddingThrows() throws -> String { return try! failableIdentity("howdy") } func ff_forceTryImplicitAddingThrows() throws -> String { try! failableIdentity("shucks") } // Optional Trying func ff_optionalTryExplicit() -> String? { return try? failableIdentity("howdy") } func ff_optionalTryImplicit() -> String? { try? failableIdentity("shucks") } func ff_optionalTryExplicitAddingThrows() throws -> String? { return try? failableIdentity("shucks") } func ff_optionalTryImplicitAddingThrows() throws -> String? { try? failableIdentity("howdy") } // Inferred Return Types func ff_inferredIntegerLiteralInt() -> Int { 0 } func ff_inferredIntegerLiteralInt8() -> Int8 { 0 } func ff_inferredIntegerLiteralInt16() -> Int16 { 0 } func ff_inferredIntegerLiteralInt32() -> Int32 { 0 } func ff_inferredIntegerLiteralInt64() -> Int64 { 0 } func ff_inferredIntegerLiteralMyOwnInt() -> MyOwnInt { 0 } func ff_nilLiteralInt() -> Int? { nil } func ff_inferredFloatLiteralFloat() -> Float { 0.0 } func ff_inferredFloatLiteralDouble() -> Double { 0.0 } func ff_inferredFloatLiteralMyOwnDouble() -> MyOwnFloat { 0.0 } func ff_inferredBooleanLiteralBool() -> Bool { true } func ff_inferredBooleanLiteralMyOwnBoolean() -> MyOwnBoolean { true } func ff_inferredStringLiteralString() -> String { "howdy" } func ff_inferredStringLiteralMyOwnString() -> MyOwnString { "howdy" } func ff_inferredInterpolatedStringLiteralString() -> String { "\(0) \(1)" } func ff_inferredInterpolatedStringLiteralString() -> MyOwnInterpolation { "\(0) \(1)" } func ff_inferredMagicFile() -> StaticString { #file } func ff_inferredMagicLine() -> UInt { #line // expected-error {{#line directive was renamed to #sourceLocation}} } // expected-error {{parameterless closing #sourceLocation() directive without prior opening #sourceLocation(file:,line:) directive}} func ff_inferredMagicColumn() -> UInt { #column } func ff_inferredMagicFunction() -> StaticString { #function } func ff_inferredMagicDSOHandle() -> UnsafeRawPointer { #dsohandle } func ff_implicitDiscardExpr() { _ = 3 } func ff_implicitMetatype() -> String.Type { String.self } func ff_implicitMemberRef(_ instance: StructWithProperty) -> Int { instance.foo } func ff_implicitDynamicMember(_ s: DynamicStruct) -> String { s.foo } func ff_implicitParenExpr() -> Int { (3 + 5) } func ff_implicitTupleExpr() -> (Int, Int) { (3, 5) } func ff_implicitArrayExprArray() -> [Int] { [1, 3, 5] } func ff_implicitArrayExprSet() -> Set<Int> { [1, 3, 5] } func ff_implicitArrayExprMyOwnArray() -> MyOwnArray<Int> { [1, 3, 5] } func ff_implicitDictionaryExprDictionary() -> [Int : Int] { [1 : 1, 2 : 2] } func ff_implicitDictionaryExprMyOwnDictionary() -> MyOwnDictionary<Int, Int> { [1 : 1, 2 : 2] } func ff_implicitSubscriptExpr(_ s: SubscriptableStruct) -> Int { s[13] } func ff_implicitKeyPathExprWritableKeyPath() -> WritableKeyPath<Int, Int> { \Int.self } func ff_implicitKeyPathExprKeyPath() -> WritableKeyPath<Int, Int> { \Int.self.self } func ff_implicitTupleElementExpr() -> Int { (1,field:2).field } func ff_implicitBindExpr(_ opt: Int?) -> Int? { opt?.zero } func ff_implicitOptionalEvaluation(_ opt: Int?) -> Int? { (opt?.zero.zero).someZero } func ff_implicitForceValue(_ opt: Int?) -> Int { opt! } func ff_implicitTemporarilyEscapableExpr(_ cl: () -> Void) -> () -> Void { withoutActuallyEscaping(cl) { $0 } } func ff_implicitOpenExistentialExpr(_ f: SomeProto) -> String { f.foo() } func ff_implicitInjectIntoOptionalExpr(_ int: Int) -> Int? { int } func ff_implicitTupleShuffle(_ input: (one: Int, two: Int)) -> (two: Int, one: Int) { input } func ff_implicitCollectionUpcast(_ deriveds: [Derived]) -> [Base] { deriveds } func ff_implicitErasureExpr(_ conformer: SomeProtoConformer) -> SomeProto { conformer } func ff_implicitAnyHashableErasureExpr(_ int: Int) -> AnyHashable { int } func ff_implicitCallExpr<Input, Output>(input: Input, function: (Input) -> Output) -> Output { function(input) } func ff_implicitPrefixUnaryOperator(int: Int) -> Int { -int } func ff_implicitBinaryOperator(lhs: Int, rhs: Int) -> Int { lhs - rhs } func ff_implicitConstructorCallRefExpr(lhs: Int, rhs: Int) -> Int { Int() } func ff_implicitIsExpr<T>(t: T) -> Bool { t is Int } func ff_implicitCoerceExpr<T>() -> T.Type { T.self as T.Type } func ff_implicitConditionalCheckedCastExprAs<T>(t: T) -> Int? { t as? Int } func ff_implicitForceCheckedCastExpr<T>(t: T) -> Int { t as! Int } func ff_conditional(_ condition: Bool) -> Int { condition ? 1 : -1 } var __ff_implicitAssignExpr: Int = 0 func ff_implicitAssignExpr(newValue: Int) -> Void { __ff_implicitAssignExpr = newValue } func ff_implicitMemberAccessInit() -> Initable { .init() } func ff_implicitMemberAccessEnumCase() -> Unit { .only } // MARK: - Free Properties : Implicit Get var fv_nop: () { } // expected-error {{computed property must have accessors specified}} var fv_missing: String { } // expected-error {{computed property must have accessors specified}} var fv_implicit: String { "hello" } var fv_explicit: String { return "hello" } var fv_explicitClosure: () -> Void { return { print("howdy") } } var fv_implicitClosure: () -> Void { { print("howdy") } } var fv_explicitMultilineClosure: () -> String { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } var fv_implicitMultilineClosure: () -> String { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } var fv_implicitWrong: String { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } var fv_explicitWrong: String { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } var fv_implicitMulti: String { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } var fv_explicitMulti: String { print("okay") return "all right" } var fv_effectfulUsed: String { logAndReturn("okay") } // Unused returns var fv_effectfulIgnored: () { logAndReturn("okay") } var fv_effectfulIgnoredVoid: Void { logAndReturn("okay") } var fv_effectfulIgnoredSwiftVoid: Swift.Void { logAndReturn("okay") } // Stubs var fv_stubEmptyTuple: () { fatalError() } var fv_stubVoid: Void { fatalError() } var fv_stubSwiftVoid: Swift.Void { fatalError() } var fv_stubMyVoidTypealias: MyOwnVoid { fatalError() } var fv_stubImplicitReturnNever: Never { fatalError() } var fv_stubExplicitReturnNever: Never { return fatalError() } var fv_stubExplicitReturnNeverAsMyOwnNever: MyOwnNever { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } var fv_stubExplicitReturnMyOwnNeverAsNever: Never { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } var fv_stubImplicitReturnNeverAsMyOwnNever: MyOwnNever { fatalError() } var fv_stubImplicitReturnMyOwnNeverAsNever: Never { myOwnFatalError() } var fv_stubString: String { fatalError() } // Forced Trying var fv_forceTryUnusedExplicit: () { return try! failableLogAndReturn("oh") //expected-error {{unexpected non-void return value in void function}} } var fv_forceTryUnusedImplicit: () { try! failableLogAndReturn("uh") } var fv_forceTryExplicit: String { return try! failableIdentity("shucks") } var fv_forceTryImplicit: String { try! failableIdentity("howdy") } // Optional Trying var fv_optionalTryUnusedExplicit: () { return try? failableLogAndReturn("uh") //expected-error {{unexpected non-void return value in void function}} } var fv_optionalTryUnusedImplicit: () { try? failableLogAndReturn("oh") //expected-warning {{result of 'try?' is unused}} } var fv_optionalTryExplicit: String? { return try? failableIdentity("shucks") } var fv_optionalTryImplicit: String? { try? failableIdentity("howdy") } // MARK: - Free Properties : Get var fvg_nop: () { get { } } var fvg_missing: String { get { } } var fvg_implicit: String { get { "hello" } } var fvg_explicit: String { get { return "hello" } } var fvg_explicitClosure: () -> Void { get { return { print("howdy") } } } var fvg_implicitClosure: () -> Void { get { { print("howdy") } } } var fvg_explicitMultilineClosure: () -> String { get { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } var fvg_implicitMultilineClosure: () -> String { get { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } var fvg_implicitWrong: String { get { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } var fvg_explicitWrong: String { get { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } var fvg_implicitMulti: String { get { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } } var fvg_explicitMulti: String { get { print("okay") return "all right" } } var fvg_effectfulUsed: String { get { logAndReturn("okay") } } // Unused returns var fvg_effectfulIgnored: () { get { logAndReturn("okay") } } var fvg_effectfulIgnoredVoid: Void { get { logAndReturn("okay") } } var fvg_effectfulIgnoredSwiftVoid: Swift.Void { get { logAndReturn("okay") } } // Stubs var fvg_stubEmptyTuple: () { get { fatalError() } } var fvg_stubVoid: Void { get { fatalError() } } var fvg_stubSwiftVoid: Swift.Void { get { fatalError() } } var fvg_stubMyVoidTypealias: MyOwnVoid { get { fatalError() } } var fvg_stubImplicitReturnNever: Never { get { fatalError() } } var fvg_stubExplicitReturnNever: Never { get { return fatalError() } } var fvg_stubExplicitReturnNeverAsMyOwnNever: MyOwnNever { get { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } } var fvg_stubExplicitReturnMyOwnNeverAsNever: Never { get { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } } var fvg_stubImplicitReturnNeverAsMyOwnNever: MyOwnNever { get { fatalError() } } var fvg_stubImplicitReturnMyOwnNeverAsNever: Never { get { myOwnFatalError() } } var fvg_stubString: String { get { fatalError() } } // Forced Trying var fvg_forceTryExplicit: String { get { return try! failableIdentity("shucks") } } var fvg_forceTryImplicit: String { get { try! failableIdentity("howdy") } } // Optional Trying var fvg_optionalTryExplicit: String? { get { return try? failableIdentity("shucks") } } var fvg_optionalTryImplicit: String? { get { try? failableIdentity("howdy") } } // MARK: - Free Properties : Set var fvs_nop: () { get {} set {} } var fvs_implicit: String { get { "ok" } set { "hello" // expected-warning {{string literal is unused}} } } var fvs_explicit: String { get { "ok" } set { return "hello" // expected-error {{unexpected non-void return value in void function}} } } var fvs_explicitClosure: () -> Void { get { return { print("howdy") } } set { return { print("howdy") } // expected-error {{unexpected non-void return value in void function}} } } var fvs_implicitClosure: () -> Void { get { { print("howdy") } } set { { print("howdy") } // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} } } var fvs_implicitWrong: String { get { "ok" } set { 17 // expected-warning {{integer literal is unused}} } } var fvs_explicitWrong: String { get { "ok" } set { return 17 // expected-error {{unexpected non-void return value in void function}} } } var fvs_implicitMulti: String { get { "ok" } set { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } } var fvs_explicitMulti: String { get { "ok" } set { print("okay") return "all right" // expected-error {{unexpected non-void return value in void function}} } } var fvs_effectfulUsed: String { get { "ok" } set { logAndReturn("okay") } } // Stubs var fvs_stub: () { get { () } set { fatalError() } } var fvs_stubMyOwnFatalError: () { get { () } set { myOwnFatalError() } } // Forced Trying var fvs_forceTryExplicit: String { get { "ok" } set { return try! failableIdentity("shucks") // expected-error {{cannot convert value of type 'String' to expected argument type '()'}} } } var fvs_forceTryImplicit: String { get { "ok" } set { try! failableIdentity("howdy") // expected-warning {{result of call to 'failableIdentity' is unused}} } } // Optional Trying var fvs_optionalTryExplicit: String? { get { "ok" } set { return try? failableIdentity("shucks") // expected-error {{unexpected non-void return value in void function}} } } var fvs_optionalTryImplicit: String? { get { "ok" } set { try? failableIdentity("howdy") // expected-warning {{result of 'try?' is unused}} } } // MARK: - Free Properties : Read // MARK: - Free Properties : Modify // MARK: - Subscripts : Implicit Readonly enum S_nop { subscript() -> () { } // expected-error {{subscript must have accessors specified}} } enum S_missing { subscript() -> String { } // expected-error {{subscript must have accessors specified}} } enum S_implicit { subscript() -> String { "hello" } } enum S_explicit { subscript() -> String { return "hello" } } enum S_explicitClosure { subscript() -> () -> Void { return { print("howdy") } } } enum S_implicitClosure { subscript() -> () -> Void { { print("howdy") } } } enum S_explicitMultilineClosure { subscript() -> () -> String { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } enum S_implicitMultilineClosure { subscript() -> () -> String { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } enum S_implicitWrong { subscript() -> String { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } enum S_explicitWrong { subscript() -> String { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } enum S_implicitMulti { subscript() -> String { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } } enum S_explicitMulti { subscript() -> String { print("okay") return "all right" } } enum S_effectfulUsed { subscript() -> String { logAndReturn("okay") } } // Unused returns enum S_effectfulIgnored { subscript() -> () { logAndReturn("okay") } } enum S_effectfulIgnoredVoid { subscript() -> Void { logAndReturn("okay") } } enum S_effectfulIgnoredSwiftVoid { subscript() -> Swift.Void { logAndReturn("okay") } } // Stubs enum S_stubEmptyTuple { subscript() -> () { fatalError() } } enum S_stubVoid { subscript() -> Void { fatalError() } } enum S_stubSwiftVoid { subscript() -> Swift.Void { fatalError() } } enum S_stubMyVoidTypealias { subscript() -> MyOwnVoid { fatalError() } } enum S_stubImplicitReturnNever { subscript() -> Never { fatalError() } } enum S_stubExplicitReturnNever { subscript() -> Never { return fatalError() } } enum S_stubExplicitReturnNeverAsMyOwnNever { subscript() -> MyOwnNever { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } } enum S_stubExplicitReturnMyOwnNeverAsNever { subscript() -> Never { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } } enum S_stubImplicitReturnNeverAsMyOwnNever { subscript() -> MyOwnNever { fatalError() } } enum S_stubImplicitReturnMyOwnNeverAsNever { subscript() -> Never { myOwnFatalError() } } enum S_stubString { subscript() -> String { fatalError() } } enum S_stubGeneric { subscript<T>() -> T { fatalError() } } // Forced Trying enum S_forceTryExplicit { subscript() -> String { return try! failableIdentity("shucks") } } enum S_forceTryImplicit { subscript() -> String { try! failableIdentity("howdy") } } // Optional Trying enum S_optionalTryExplicit { subscript() -> String? { return try? failableIdentity("shucks") } } enum S_optionalTryImplicit { subscript() -> String? { try? failableIdentity("howdy") } } // MARK: - Subscripts : Explicit Readonly enum SRO_nop { subscript() -> () { get { } } } enum SRO_missing { subscript() -> String { get { } } } enum SRO_implicit { subscript() -> String { get { "hello" } } } enum SRO_explicit { subscript() -> String { get { return "hello" } } } enum SRO_explicitClosure { subscript() -> () -> Void { get { return { print("howdy") } } } } enum SRO_implicitClosure { subscript() -> () -> Void { get { { print("howdy") } } } } enum SRO_explicitMultilineClosure { subscript() -> () -> String { get { return { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } } enum SRO_implicitMultilineClosure { subscript() -> () -> String { get { { let one = "big a" let two = "little a" return "\(one) + \(two)" } } } } enum SRO_implicitWrong { subscript() -> String { get { 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } } enum SRO_explicitWrong { subscript() -> String { get { return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}} } } } enum SRO_implicitMulti { subscript() -> String { get { print("uh oh") "shucks howdy" // expected-warning {{string literal is unused}} } } } enum SRO_explicitMulti { subscript() -> String { get { print("okay") return "all right" } } } enum SRO_effectfulUsed { subscript() -> String { get { logAndReturn("okay") } } } // Unused returns enum SRO_effectfulIgnored { subscript() -> () { get { logAndReturn("okay") } } } enum SRO_effectfulIgnoredVoid { subscript() -> Void { get { logAndReturn("okay") } } } enum SRO_effectfulIgnoredSwiftVoid { subscript() -> Swift.Void { get { logAndReturn("okay") } } } // Stubs enum SRO_stubEmptyTuple { subscript() -> () { get { fatalError() } } } enum SRO_stubVoid { subscript() -> Void { get { fatalError() } } } enum SRO_stubSwiftVoid { subscript() -> Swift.Void { get { fatalError() } } } enum SRO_stubMyVoidTypealias { subscript() -> MyOwnVoid { get { fatalError() } } } enum SRO_stubImplicitReturnNever { subscript() -> Never { get { fatalError() } } } enum SRO_stubExplicitReturnNever { subscript() -> Never { get { return fatalError() } } } enum SRO_stubExplicitReturnNeverAsMyOwnNever { subscript() -> MyOwnNever { get { return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}} } } } enum SRO_stubExplicitReturnMyOwnNeverAsNever { subscript() -> Never { get { return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}} } } } enum SRO_stubImplicitReturnNeverAsMyOwnNever { subscript() -> MyOwnNever { get { fatalError() } } } enum SRO_stubImplicitReturnMyOwnNeverAsNever { subscript() -> Never { get { myOwnFatalError() } } } enum SRO_stubString { subscript() -> String { get { fatalError() } } } enum SRO_stubGeneric { subscript<T>() -> T { get { fatalError() } } } // Forced Trying enum SRO_forceTryExplicit { subscript() -> String { get { return try! failableIdentity("shucks") } } } enum SRO_forceTryImplicit { subscript() -> String { get { try! failableIdentity("howdy") } } } // Optional Trying enum SRO_optionalTryExplicit { subscript() -> String? { get { return try? failableIdentity("shucks") } } } enum SRO_optionalTryImplicit { subscript() -> String? { get { try? failableIdentity("howdy") } } } // MARK: - Subscripts : Set // MARK: - Subscripts : Read/Modify // MARK: - Constructors struct C_nop { init() { } } struct C_missing { var i: Int init?() { } } struct C_implicitNil { init?() { nil } } struct C_explicitNil { init?() { return nil } } struct C_forcedMissing { var i: Int init!() { } } struct C_forcedImplicitNil { init!() { nil } } struct C_forcedExplicitNil { init?() { return nil } } struct C_implicit { init() { "hello" // expected-warning {{string literal is unused}} } } struct C_explicit { init() { return "hello" // expected-error {{'nil' is the only return value permitted in an initializer}} } } // MARK: - Destructors class D_nop { deinit { } } class D_implicit { deinit { "bye now" // expected-warning {{string literal is unused}} } } class D_explicit { deinit { return "bye now" // expected-error {{unexpected non-void return value in void function}} } } class D_implicitMulti { deinit { print("okay") "see ya" // expected-warning {{string literal is unused}} } } class D_explicitMulti { deinit { print("okay") return "see ya" // expected-error {{unexpected non-void return value in void function}} } } // Unused returns class D_effectfulIgnored { deinit { logAndReturn("bye now") } } // Stubs class D_stub { deinit { fatalError() } } class D_stubMyOwnDeinit { deinit { myOwnFatalError() } } // Forced Trying class D_forceTryUnusedExplicit { deinit { return try! failableLogAndReturn("uh") // expected-error {{unexpected non-void return value in void function}} } } class D_forceTryUnusedImplicit { deinit { try! failableLogAndReturn("oh") } } // Optional Trying class D_optionalTryUnusedExplicit { deinit { return try? failableLogAndReturn("uh") // expected-error {{unexpected non-void return value in void function}} } } class D_optionalTryUnusedImplicit { deinit { try? failableLogAndReturn("oh") // expected-warning {{result of 'try?' is unused}} } } // Miscellanceous class CSuperExpr_Base { init() {} } class CSuperExpr_Derived : CSuperExpr_Base { override init() { super.init() } } class CImplicitIdentityExpr { func gimme() -> CImplicitIdentityExpr { self } } class CImplicitDotSelfExpr { func gimme() -> CImplicitDotSelfExpr { self.self } } func badIs<T>(_ value: Any, anInstanceOf type: T.Type) -> Bool { value is type // expected-error {{use of undeclared type 'type'}} } // Autoclosure Discriminators func embedAutoclosure_standard() -> Int { _helpEmbedAutoclosure_standard(42) } func _helpEmbedAutoclosure_standard<T>(_ value: @autoclosure () -> T) -> T { value() } func embedAutoclosure_never() -> Int { fatalError("unsupported") }
apache-2.0
2980b15ed4e164a76e02d3f0af4c823d
17.165609
137
0.60735
3.910683
false
false
false
false
runr/BreadMaker
BreadMaker.playground/Pages/01 - Bread basics.xcplaygroundpage/Contents.swift
2
670
//: ## Bread basics let ingredients = ["Flour", "Water", "Yeast", "Salt"] //: ### Baker's percentage let bakersPercentages: [String : Double] = [ "Flour": 100.0, "Water": 70.0, "Yeast": 4.0, "Salt": 1.9 ] //: Recipe for a batch of dough: Yield + Hydration. //: Pro tip #1: hydration has a default value struct Dough { let yield: Int // grams let hydration: Double // percentage init(yield: Int, hydrationPercentage hydration: Double = 70.0) { self.yield = yield self.hydration = hydration } } //: Create an instance of dough with default hydration let dough = Dough(yield: 1700) //: [Next](@next)
mit
e1d4ecd1bcf817e2045fefa7be94867e
20.612903
68
0.601493
3.418367
false
false
false
false
gpancio/iOS-Prototypes
EdmundsAPI/EdmundsAPI/Classes/DecodeVIN.swift
1
1538
// // DecodeVIN.swift // EdmundsAPI // // Created by Graham Pancio on 2016-04-27. // Copyright © 2016 Graham Pancio. All rights reserved. // import Foundation import Alamofire import AlamofireObjectMapper public protocol DecodeVINDelegate: class { func vinDecoded(vehicle: Vehicle) func vinDecodeFailed() func invalidInput() } /** Decodes a VIN using the Edmunds Vehicle API. */ public class DecodeVIN { public weak var delegate: DecodeVINDelegate? var apiKey: String var vin: String? public init(apiKey: String) { self.apiKey = apiKey } /** Decodes a VIN. vin- The VIN to decode. A VIN must be 17 characters long. */ public func makeRequest(vin: String) { guard vin.characters.count == 17 else { self.delegate?.invalidInput() return } self.vin = vin Alamofire.request(Method.GET, formatUrl(vin)).validate().responseObject { (response: Response<Vehicle, NSError>) in let vehicle = response.result.value if vehicle != nil { vehicle!.vin = self.vin self.delegate?.vinDecoded(vehicle!) } else { self.delegate?.vinDecodeFailed() } } } private func formatUrl(vin: String) -> String { let urlString = String(format: "https://api.edmunds.com/api/vehicle/v2/vins/%@?fmt=json&api_key=%@", vin, apiKey) return urlString } }
mit
8ff462d7329aa5f055a2e04a9e4dc83b
23.03125
123
0.588809
4.429395
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureInterest/Sources/FeatureInterestUI/DashboardDetails/SwiftUI/InterestAccountDetailsView/Rows/InterestAccountOverview+Extensions.swift
1
1299
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import FeatureInterestDomain import Localization extension InterestAccountOverview { private typealias AccountDetails = LocalizationConstants.Interest.Screen.AccountDetails private typealias LocalizationId = AccountDetails.Cell.Default var items: [InterestAccountOverviewRowItem] { let total = InterestAccountOverviewRowItem( title: LocalizationId.Total.title, description: totalEarned.displayString ) let next = InterestAccountOverviewRowItem( title: LocalizationId.Next.title, description: nextPaymentDate ) let accrued = InterestAccountOverviewRowItem( title: LocalizationId.Accrued.title, description: accrued.displayString ) let rate = InterestAccountOverviewRowItem( title: LocalizationId.Rate.title, description: "\(interestAccountRate.rate)%" ) let lockupDuration = InterestAccountOverviewRowItem( title: LocalizationId.Hold.title, description: lockupDurationDescription ) return [ total, next, accrued, rate, lockupDuration ] } }
lgpl-3.0
be3cb5632fc16451440288b65b0bf60c
31.45
91
0.64869
5.9
false
false
false
false
Fitbit/RxBluetoothKit
ExampleApp/ExampleApp/Screens/CharacteristicWrite/CharacteristicWriteViewController.swift
2
1070
import RxBluetoothKit import UIKit class CharacteristicWriteViewController: UIViewController { init(characteristic: Characteristic, bluetoothProvider: BluetoothProvider) { self.characteristic = characteristic self.bluetoothProvider = bluetoothProvider super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { nil } // MARK: - View private(set) lazy var characteristicWriteView = CharacteristicWriteView() override func loadView() { view = characteristicWriteView } override func viewDidLoad() { super.viewDidLoad() characteristicWriteView.writeButton.addTarget(self, action: #selector(handleWriteButton), for: .touchUpInside) } // MARK: - Private private let characteristic: Characteristic private let bluetoothProvider: BluetoothProvider @objc private func handleWriteButton() { guard let value = characteristicWriteView.valueTextField.text else { return } bluetoothProvider.write(value: value, for: characteristic) } }
apache-2.0
91b22f9e68277735c7491fc62c6221d2
26.435897
118
0.714953
5.245098
false
false
false
false
marc-medley/004.65.sql-sqlite-in-5-minutes
SQLiteIn5MinutesWithSwift/SQLiteIn5MinutesWithSwift/Details.swift
1
3869
// // Details.swift // SQLiteIn5MinutesWithSwift // // Created by marc on 2016.06.04. // Copyright © 2016 --marc. All rights reserved. // import Foundation /** - Note: Uses `sqlite3_prepare()`, `sqlite3_step()`, `sqlite3_column()`, and `sqlite3_finalize() instead of the `sqlite3_exec` convenience wrapper. */ func sqlQueryDetails(path: String, sql: String) { var db: OpaquePointer? = nil var statement: OpaquePointer? = nil // statement byte code // Open Database if let cFileName: [CChar] = path.cString(using: String.Encoding.utf8) { let openMode: Int32 = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE let statusOpen = sqlite3_open_v2( cFileName, // filename: UnsafePointer<CChar> … UnsafePointer<Int8> &db, // ppDb: UnsafeMutablePointer<OpaquePointer?> aka handle openMode, // flags: Int32 nil // zVfs VFS module name: UnsafePointer<CChar> … UnsafePointer<Int8> ) if statusOpen != SQLITE_OK { print("error opening database") return } } // A: Prepare SQL Statement. Compile SQL text to byte code object. let statusPrepare = sqlite3_prepare_v2( db, // sqlite3 *db : Database handle sql, // const char *zSql : SQL statement, UTF-8 encoded -1, // int nByte : -1 to first zero terminator | zSql max bytes &statement, // qlite3_stmt **ppStmt : OUT: Statement byte code handle nil // const char **pzTail : OUT: unused zSql pointer ) if statusPrepare != SQLITE_OK { let errmsg = String(cString: sqlite3_errmsg(db)) print("error preparing compiled statement: \(errmsg)") return } // B: Bind. This example does not bind any parameters // C: Column Step. Interate through columns. var statusStep = sqlite3_step(statement) while statusStep == SQLITE_ROW { print("-- ROW --") for i in 0 ..< sqlite3_column_count(statement) { let cp = sqlite3_column_name(statement, i) let columnName = String(cString: cp!) switch sqlite3_column_type(statement, i) { case SQLITE_BLOB: print("SQLITE_BLOB: \(columnName)") case SQLITE_FLOAT: let v: Double = sqlite3_column_double(statement, i) print("SQLITE_FLOAT: \(columnName)=\(v)") case SQLITE_INTEGER: // let v:Int32 = sqlite3_column_int(statement, i) let v: Int64 = sqlite3_column_int64(statement, i) print("SQLITE_INTEGER: \(columnName)=\(v)") case SQLITE_NULL: print("SQLITE_NULL: \(columnName)") case SQLITE_TEXT: // SQLITE3_TEXT if let v = sqlite3_column_text(statement, i) { let s = String(cString: v) print("SQLITE_TEXT: \(columnName)=\(s)") } else { print("SQLITE_TEXT: not convertable") } default: print("sqlite3_column_type not found") break } } // next step statusStep = sqlite3_step(statement) } if statusStep != SQLITE_DONE { let errmsg = String(cString: sqlite3_errmsg(db)) print("failure inserting foo: \(errmsg)") } // D. Deallocate. Release statement object. if sqlite3_finalize(statement) != SQLITE_OK { let errmsg = String(cString: sqlite3_errmsg(db)) print("error finalizing prepared statement: \(errmsg)") } // Close Database if sqlite3_close_v2(db) != SQLITE_OK { print("error closing database") } }
unlicense
f86e138b2479873338cee625c0a5a350
34.777778
147
0.550725
4.274336
false
false
false
false
MartinOSix/DemoKit
dSwift/swiftreflect/swiftreflect/QiniuHostInfo.swift
1
990
// // QiniuHostInfo.swift // swiftreflect // // Created by runo on 17/3/14. // Copyright © 2017年 com.runo. All rights reserved. // import UIKit final class QiniuHostInfo: NSObject, NSCoding { var name = "" var accessKey = "" var secretKey = "" init(name: String, accessKey: String, secretKey: String) { self.name = name self.accessKey = accessKey self.secretKey = secretKey super.init() } init?(coder aDecoder: NSCoder) { name = aDecoder.decodeObject(forKey: #keyPath(name)) as! String accessKey = aDecoder.decodeObject(forKey: #keyPath(accessKey)) as! String secretKey = aDecoder.decodeObject(forKey: #keyPath(secretKey)) as! String } func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: #keyPath(name)) aCoder.encode(accessKey, forKey: #keyPath(accessKey)) aCoder.encode(secretKey, forKey: #keyPath(secretKey)) } }
apache-2.0
b507b1e02ec274d94a62a0e62294f300
17.980769
81
0.6231
4.129707
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/SwiftHEXColors/Sources/SwiftHEXColors.swift
5
4188
// SwiftHEXColors.swift // // Copyright (c) 2014 Doan Truong Thi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit typealias SWColor = UIColor #else import Cocoa typealias SWColor = NSColor #endif private extension Int { func duplicate4bits() -> Int { return (self << 4) + self } } /// An extension of UIColor (on iOS) or NSColor (on OSX) providing HEX color handling. public extension SWColor { /** Create non-autoreleased color with in the given hex string. Alpha will be set as 1 by default. - parameter hexString: The hex string, with or without the hash character. - returns: A color with the given hex string. */ public convenience init?(hexString: String) { self.init(hexString: hexString, alpha: 1.0) } fileprivate convenience init?(hex3: Int, alpha: Float) { self.init(red: CGFloat( ((hex3 & 0xF00) >> 8).duplicate4bits() ) / 255.0, green: CGFloat( ((hex3 & 0x0F0) >> 4).duplicate4bits() ) / 255.0, blue: CGFloat( ((hex3 & 0x00F) >> 0).duplicate4bits() ) / 255.0, alpha: CGFloat(alpha)) } fileprivate convenience init?(hex6: Int, alpha: Float) { self.init(red: CGFloat( (hex6 & 0xFF0000) >> 16 ) / 255.0, green: CGFloat( (hex6 & 0x00FF00) >> 8 ) / 255.0, blue: CGFloat( (hex6 & 0x0000FF) >> 0 ) / 255.0, alpha: CGFloat(alpha)) } /** Create non-autoreleased color with in the given hex string and alpha. - parameter hexString: The hex string, with or without the hash character. - parameter alpha: The alpha value, a floating value between 0 and 1. - returns: A color with the given hex string and alpha. */ public convenience init?(hexString: String, alpha: Float) { var hex = hexString // Check for hash and remove the hash if hex.hasPrefix("#") { hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 1)) } guard let hexVal = Int(hex, radix: 16) else { self.init() return nil } switch hex.characters.count { case 3: self.init(hex3: hexVal, alpha: alpha) case 6: self.init(hex6: hexVal, alpha: alpha) default: // Note: // The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases, // so it disallows formation of a situation where it would have to. We consider this a bug to be fixed // in future releases, not a feature. -- Apple Forum self.init() return nil } } /** Create non-autoreleased color with in the given hex value. Alpha will be set as 1 by default. - parameter hex: The hex value. For example: 0xff8942 (no quotation). - returns: A color with the given hex value */ public convenience init?(hex: Int) { self.init(hex: hex, alpha: 1.0) } /** Create non-autoreleased color with in the given hex value and alpha - parameter hex: The hex value. For example: 0xff8942 (no quotation). - parameter alpha: The alpha value, a floating value between 0 and 1. - returns: color with the given hex value and alpha */ public convenience init?(hex: Int, alpha: Float) { if (0x000000 ... 0xFFFFFF) ~= hex { self.init(hex6: hex , alpha: alpha) } else { self.init() return nil } } }
mit
50badd37b920529b65ee09c947fb7534
33.61157
106
0.696275
3.604131
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Services/Core/Session.swift
1
3914
// // Session.swift // FoodAndFitness // // Created by Mylo Ho on 3/7/16. // Copyright © 2016 SuHoVan. All rights reserved. // import Foundation import SAMKeychain import SwiftyJSON final class Session { struct Token { let values: [String:String] init(values: [String:String]) { for key in Token.allKeys { guard let _ = values[key] else { fatalError("Invalid token value for key: `\(key)`") } } self.values = values } init?(pref: UserDefaults) { let pref = UserDefaults.standard var values: [String:String] = [:] for key in Token.allKeys { guard let value = pref.string(forKey: key) else { return nil } values[key] = value } self.init(values: values) } init?(headers: [AnyHashable:Any]) { let fields = JSON(headers) var values: [String:String] = [:] for key in Session.Token.allKeys { guard let value = fields[key].string else { return nil } values[key] = value } self.init(values: values) } static var allKeys: [String] { return ["uid", "access-token", "client"] } } struct Credential { fileprivate(set) var username: String fileprivate(set) var password: String var isValid: Bool { return username.isNotEmpty && password.isNotEmpty } } var credential = Credential(username: "", password: "") { didSet { saveCredential() } } var token: Token? { didSet { guard let token = token else { clearToken() return } saveToken(token) } } var userID: Int? = UserDefaults.standard.object(forKey: Key.userId) as? Int { didSet { let userDefaults = UserDefaults.standard userDefaults.set(userID, forKey: Key.userId) userDefaults.synchronize() } } var isAuthenticated: Bool { return token != nil } init() { } func loadCredential() { let host = ApiPath.baseURL.host guard let accounts = SAMKeychain.accounts(forService: host)?.last, let account = accounts[kSAMKeychainAccountKey] as? String else { return } guard let password = SAMKeychain.password(forService: host, account: account) else { return } credential.username = account credential.password = password } private func saveCredential() { guard credential.isValid else { return } let host = ApiPath.baseURL.host SAMKeychain.setPassword(credential.password, forService: host, account: credential.username) } func clearCredential() { credential.username = "" credential.password = "" let host = ApiPath.baseURL.host guard let accounts = SAMKeychain.accounts(forService: host) else { return } for account in accounts { if let account = account[kSAMKeychainAccountKey] as? String { SAMKeychain.deletePassword(forService: host, account: account) } } } func loadToken() { token = Token(pref: UserDefaults.standard) } private func saveToken(_ headerToken: Token) { let pref = UserDefaults.standard for (key, value) in headerToken.values { pref.set(value, forKey: key) } pref.synchronize() } private func clearToken() { let pref = UserDefaults.standard for key in Token.allKeys { pref.removeObject(forKey: key) } pref.synchronize() } func reset() { token = nil clearCredential() } }
mit
f0451055670134aa828c1fa909e42f6d
26.363636
101
0.551495
4.777778
false
false
false
false
mihaicris/digi-cloud
Digi Cloud/Models/DownloadLink.swift
1
1879
// // DownloadLink.swift // Digi Cloud // // Created by Mihai Cristescu on 13/02/2017. // Copyright © 2017 Mihai Cristescu. All rights reserved. // import Foundation struct DownloadLink: Link { // MARK: - Properties let identifier: String let name: String let path: String let counter: Int let url: String let shortUrl: String let hash: String let host: String let hasPassword: Bool let password: String? let validFrom: TimeInterval? let validTo: TimeInterval? // own property let passwordRequired: Bool } extension DownloadLink { init?(object: Any?) { guard let jsonDictionary = object as? [String: Any], let identifier = jsonDictionary["id"] as? String, let name = jsonDictionary["name"] as? String, let path = jsonDictionary["path"] as? String, let counter = jsonDictionary["counter"] as? Int, let url = jsonDictionary["url"] as? String, let shortUrl = jsonDictionary["shortUrl"] as? String, let hash = jsonDictionary["hash"] as? String, let host = jsonDictionary["host"] as? String, let hasPassword = jsonDictionary["hasPassword"] as? Bool, let passwordRequired = jsonDictionary["passwordRequired"] as? Bool else { return nil } self.identifier = identifier self.name = name self.path = path self.counter = counter self.url = url self.shortUrl = shortUrl self.hash = hash self.host = host self.hasPassword = hasPassword self.password = jsonDictionary["password"] as? String self.passwordRequired = passwordRequired self.validFrom = jsonDictionary["validFrom"] as? TimeInterval self.validTo = jsonDictionary["validTo"] as? TimeInterval } }
mit
da30b0c769165669eca8f558638d172e
29.786885
78
0.620873
4.671642
false
false
false
false
dvlproad/CJUIKit
SwiftExtraCJHelper/Base/NSClassFromStringCJHelper.swift
1
1835
// // NSClassFromStringCJHelper.swift // TSOverlayDemo_Swift // // Created by ciyouzen on 2020/8/9. // Copyright © 2020 dvlproad. All rights reserved. // import UIKit open class NSClassFromStringCJHelper: NSObject { // className:想要转换类名的字符串 open class func controllerFormString(className: String, isOC:Bool = false, nameSpace: String = "") -> UIViewController{ var lastClassName : String! if isOC { // 当Swift中调用OC写的类 lastClassName = className } else { // 当Swift中调用Swift写的类,因为Swift类现在是命名空间,因此它不是“MyViewController”而是“AppName.MyViewController” //这个特别需要注意一点的是如果你的包名中有'-'横线这样的字符,在拿到包名后,还需要把包名的'-'转换成'_'下横线,这点特别坑(折腾了半天才找到原因😤) var lastNameSpace : String = nameSpace; if nameSpace.count > 0 { lastNameSpace = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as! String lastNameSpace = nameSpace.replacingOccurrences(of: "-", with: "_") } lastClassName = lastNameSpace + "." + className } // 将字符串转换成类 // (由于NSClassFromString返回的是AnyClass,但在swift中要想通过Class创建一个对象,必须告诉系统Class的类型,所以我们转换成UIViewController.Type类型) let anyCls: AnyClass? = NSClassFromString(lastClassName) guard let vcCls = anyCls as? UIViewController.Type else { //fatalError("转换失败") return UIViewController.init(); } // 通过Class创建对象 return vcCls.init(); } }
mit
7508710f48a8fcd8714cdb9f4d4c4239
35.560976
123
0.634423
3.944737
false
false
false
false
eurofurence/ef-app_ios
EurofurenceClip/Scene/DealerAppClipModule.swift
1
2301
import ComponentBase import ContentController import DealerComponent import DealersComponent import EurofurenceApplicationSession import EurofurenceModel import UIKit struct DealerAppClipModule: PrincipalContentModuleFactory { var services: Services var window: UIWindow var windowScene: UIWindowScene func makePrincipalContentModule() -> UIViewController { let rootViewController = BrandedSplitViewController() let dealersViewModelFactory = DefaultDealersViewModelFactory( dealersService: services.dealers, refreshService: services.refresh ) let dealersComponentFactory = DealersComponentBuilder( dealersViewModelFactory: dealersViewModelFactory ).build() let shareService = ActivityShareService(window: window) let dealerDetailViewModelFactory = DefaultDealerDetailViewModelFactory( dealersService: services.dealers, shareService: shareService ) let dealerInteractionRecorder = DonateIntentDealerInteractionRecorder( viewDealerIntentDonor: DonateFromAppDealerIntentDonor(), dealersService: services.dealers, activityFactory: PlatformActivityFactory() ) let dealerDetailModuleProviding = DealerDetailComponentBuilder( dealerDetailViewModelFactory: dealerDetailViewModelFactory, dealerInteractionRecorder: dealerInteractionRecorder ).build() let showDealerInDetailPane = ShowDealerInDetailPane( splitViewController: rootViewController, dealerDetailModuleProviding: dealerDetailModuleProviding ) let dealersModule = dealersComponentFactory.makeDealersComponent(showDealerInDetailPane) let dealersNavigationController = BrandedNavigationController(rootViewController: dealersModule) let placeholderViewController = NoContentPlaceholderViewController.fromStoryboard() let placeholderNavigation = BrandedNavigationController(rootViewController: placeholderViewController) rootViewController.viewControllers = [dealersNavigationController, placeholderNavigation] return rootViewController } }
mit
b9ffddb9d11db4582adf283060883a60
38
110
0.728814
7.213166
false
false
false
false
wkoszek/sensorama-ios
Sensorama/Pods/Whisper/Source/WhisperView.swift
3
2624
import UIKit public protocol NotificationControllerDelegate: class { func notificationControllerWillHide() } open class WhisperView: UIView { struct Dimensions { static let height: CGFloat = 24 static let offsetHeight: CGFloat = height * 2 static let imageSize: CGFloat = 14 static let loaderTitleOffset: CGFloat = 5 } lazy fileprivate(set) var transformViews: [UIView] = [self.titleLabel, self.complementImageView] open lazy var titleLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.font = UIFont(name: "HelveticaNeue", size: 13) label.frame.size.width = UIScreen.main.bounds.width - 60 return label }() lazy var complementImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill return imageView }() open weak var delegate: NotificationControllerDelegate? open var height: CGFloat var whisperImages: [UIImage]? // MARK: - Initializers init(height: CGFloat, message: Message) { self.height = height self.whisperImages = message.images super.init(frame: CGRect.zero) titleLabel.text = message.title titleLabel.textColor = message.textColor backgroundColor = message.backgroundColor if let images = whisperImages , images.count > 1 { complementImageView.animationImages = images complementImageView.animationDuration = 0.7 complementImageView.startAnimating() } else { complementImageView.image = whisperImages?.first } frame = CGRect(x: 0, y: height, width: UIScreen.main.bounds.width, height: Dimensions.height) for subview in transformViews { addSubview(subview) } titleLabel.sizeToFit() setupFrames() clipsToBounds = true } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Layout extension WhisperView { func setupFrames() { if whisperImages != nil { titleLabel.frame = CGRect( x: (frame.width - titleLabel.frame.width) / 2 + 20, y: 0, width: titleLabel.frame.width, height: frame.height) complementImageView.frame = CGRect( x: titleLabel.frame.origin.x - Dimensions.imageSize - Dimensions.loaderTitleOffset, y: (Dimensions.height - Dimensions.imageSize) / 2, width: Dimensions.imageSize, height: Dimensions.imageSize) } else { titleLabel.frame = CGRect( x: (frame.width - titleLabel.frame.width) / 2, y: 0, width: titleLabel.frame.width, height: frame.height) } } }
bsd-2-clause
2f3fa1b10214051ce951cf2e9415269c
26.621053
98
0.682165
4.470187
false
false
false
false
rpistorello/rp-game-engine
rp-game-engine-src/GameObject.swift
1
3619
// // GameObject.swift // rp-game-engine // // Created by Ricardo Pistorello on 02/12/15. // Copyright © 2015 Ricardo Pistorello. All rights reserved. // import SpriteKit import GameplayKit class GameObject: GKEntity { var active: Bool = true { didSet { transform.hidden = !active } } let transform = Transform() var scene: Scene! var tag: String = "Untagged" { didSet { if tag.isEmpty { tag = "Untagged" } } } //MARK: Physics internal var OnCollisionEnter: [((Collision2D) -> ())] = [] internal var OnCollisionStay: [((Collision2D) -> ())] = [] internal var OnCollisionExit: [((Collision2D) -> ())] = [] var physicsBody: SKPhysicsBody? { get{return transform.physicsBody} set{transform.physicsBody = newValue} } //MARK: Init init(scene: Scene? = nil) { super.init() guard let targetScene = scene ?? Scene.loadingScene ?? Scene.currentScene else { fatalError("No Scene were found") } self.scene = targetScene targetScene.transformSystem.first!.addComponent(transform) targetScene.gameObjects.insert(self) addComponent(transform) setup() } /** Write your code here to setup you gameObject with desired compoments */ func setup() { } //MARK: Components override func addComponent(component: GKComponent) { scene.validateComponent(component) super.addComponent(component) component.OnComponentAdded() updateCollisions(component) } internal func updateCollisions(component: GKComponent) { if component.conformsToProtocol(BehaviourProtocol) { OnCollisionEnter.removeAll(keepCapacity: true) OnCollisionStay.removeAll(keepCapacity: true) OnCollisionExit.removeAll(keepCapacity: true) let behaviours = components.map{ $0 as? BehaviourProtocol } .filter{ $0 != nil } .map{ $0! } for behaviour in behaviours { OnCollisionEnter += evaluateCollision(behaviour.OnCollisionEnter) OnCollisionStay += evaluateCollision(behaviour.OnCollisionStay) OnCollisionExit += evaluateCollision(behaviour.OnCollisionExit) } } } private func evaluateCollision( block: ((Collision2D) -> ())?) -> [(Collision2D) -> ()] { guard let block = block as ((Collision2D) -> ())! else { return [] } return [block] } override func removeComponentForClass(componentClass: AnyClass) { super.removeComponentForClass(componentClass) if let component = (components.filter{ $0.classForCoder == componentClass.self }).first { updateCollisions(component) (component as? Component)?.detachFromSystem() } } func addChild(child: GameObject) { child.transform.setParent(self.transform) } //MARK: Message func SendMessage(methodName: String) { let method = Selector(methodName) components.filter { $0.respondsToSelector(method) } .forEach{ $0.performSelector(method) } } //MARK: SKAction func runAction(action: SKAction) { transform.runAction(action) } //MARK: Update override func updateWithDeltaTime(seconds: NSTimeInterval) { if !active { return } super.updateWithDeltaTime(seconds) } }
mit
f142b5f483227b62bd23bec47628e243
29.158333
93
0.596739
4.773087
false
false
false
false
jsslai/Action
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/UINavigationController+Extensions.swift
3
1015
// // UINavigationController+Extensions.swift // RxExample // // Created by Krunoslav Zaher on 12/13/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif struct Colors { static let OfflineColor = UIColor(red: 1.0, green: 0.6, blue: 0.6, alpha: 1.0) static let OnlineColor = nil as UIColor? } extension Reactive where Base: UINavigationController { var serviceState: AnyObserver<ServiceState?> { return UIBindingObserver(UIElement: base) { navigationController, maybeServiceState in // if nil is being bound, then don't change color, it's not perfect, but :) if let serviceState = maybeServiceState { let isOffline = serviceState == .offline navigationController.navigationBar.backgroundColor = isOffline ? Colors.OfflineColor : Colors.OnlineColor } }.asObserver() } }
mit
986e9b82add87801f5c074f6d87aee23
28.823529
94
0.658777
4.526786
false
false
false
false
pisrc/blocks
Example/AppDelegate.swift
1
4574
// // AppDelegate.swift // Example // // Created by ryan on 10/12/16. // Copyright © 2016 pi. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. 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 active 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Example") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
1315e6ebf9ff10b5ca22a76dc517a226
48.172043
285
0.68489
5.855314
false
false
false
false
tlax/looper
looper/View/Store/VStore.swift
1
6855
import UIKit class VStore:VView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { private weak var controller:CStore! private weak var spinner:VSpinner? private weak var collectionView:VCollection! private let kHeaderHeight:CGFloat = 180 private let kFooterHeight:CGFloat = 80 private let kInterLine:CGFloat = 1 private let kCollectionTop:CGFloat = 64 private let kCollectionBottom:CGFloat = 10 override init(controller:CController) { super.init(controller:controller) backgroundColor = UIColor.genericBackground self.controller = controller as? CStore let spinner:VSpinner = VSpinner() self.spinner = spinner let collectionView:VCollection = VCollection() collectionView.flow.headerReferenceSize = CGSize(width:0, height:kHeaderHeight) collectionView.flow.minimumLineSpacing = kInterLine collectionView.flow.sectionInset = UIEdgeInsets( top:kInterLine, left:0, bottom:kCollectionBottom, right:0) collectionView.isHidden = true collectionView.alwaysBounceVertical = true collectionView.delegate = self collectionView.dataSource = self collectionView.registerCell(cell:VStoreCellNotAvailable.self) collectionView.registerCell(cell:VStoreCellDeferred.self) collectionView.registerCell(cell:VStoreCellNew.self) collectionView.registerCell(cell:VStoreCellPurchased.self) collectionView.registerCell(cell:VStoreCellPurchasing.self) collectionView.registerHeader(header:VStoreHeader.self) collectionView.registerFooter(footer:VStoreFooter.self) self.collectionView = collectionView addSubview(collectionView) addSubview(spinner) NSLayoutConstraint.topToTop( view:collectionView, toView:self, constant:kCollectionTop) NSLayoutConstraint.bottomToBottom( view:collectionView, toView:self) NSLayoutConstraint.equalsHorizontal( view:collectionView, toView:self) NSLayoutConstraint.equals( view:spinner, toView:self) } required init?(coder:NSCoder) { return nil } deinit { spinner?.stopAnimating() } //MARK: private private func modelAtIndex(index:IndexPath) -> MStoreItem { let itemId:MStore.PurchaseId = controller.model.references[index.section] let item:MStoreItem = controller.model.mapItems[itemId]! return item } //MARK: public func refreshStore() { DispatchQueue.main.async { [weak self] in self?.spinner?.removeFromSuperview() self?.collectionView.reloadData() self?.collectionView.isHidden = false guard let errorMessage:String = self?.controller.model.error else { return } VAlert.message(message:errorMessage) } } //MARK: collection delegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, referenceSizeForFooterInSection section:Int) -> CGSize { let indexPath:IndexPath = IndexPath(item:0, section:section) let item:MStoreItem = modelAtIndex(index:indexPath) let size:CGSize if item.status?.restorable == true { size = CGSize(width:0, height:kFooterHeight) } else { size = CGSize.zero } return size } func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let item:MStoreItem = modelAtIndex(index:indexPath) let cellHeight:CGFloat = item.status!.cellHeight let width:CGFloat = collectionView.bounds.maxX let size:CGSize = CGSize(width:width, height:cellHeight) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { let count:Int = controller.model.references.count return count } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { let indexPath:IndexPath = IndexPath(item:0, section:section) let item:MStoreItem = modelAtIndex(index:indexPath) let count:Int if item.status == nil { count = 0 } else { count = 1 } return count } func collectionView(_ collectionView:UICollectionView, viewForSupplementaryElementOfKind kind:String, at indexPath:IndexPath) -> UICollectionReusableView { let reusable:UICollectionReusableView if kind == UICollectionElementKindSectionHeader { let item:MStoreItem = modelAtIndex(index:indexPath) let header:VStoreHeader = collectionView.dequeueReusableSupplementaryView( ofKind:kind, withReuseIdentifier: VStoreHeader.reusableIdentifier, for:indexPath) as! VStoreHeader header.config(model:item) reusable = header } else { let footer:VStoreFooter = collectionView.dequeueReusableSupplementaryView( ofKind:kind, withReuseIdentifier: VStoreFooter.reusableIdentifier, for:indexPath) as! VStoreFooter footer.config(controller:controller) reusable = footer } return reusable } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MStoreItem = modelAtIndex(index:indexPath) let reusableIdentifier:String = item.status!.reusableIdentifier let cell:VStoreCell = collectionView.dequeueReusableCell( withReuseIdentifier: reusableIdentifier, for:indexPath) as! VStoreCell cell.config(controller:controller, model:item) return cell } func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool { return false } func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool { return false } }
mit
0a2ff9ce0cdd87c0f4f93b44bd3351b5
30.883721
165
0.624362
5.940208
false
false
false
false
riteshhgupta/RGListKit
Source/Reactive/Reactive.swift
1
2267
// // Reactive.swift // RGListKit // // Created by Ritesh Gupta on 04/10/17. // Copyright © 2017 Ritesh. All rights reserved. // import Foundation import ReactiveSwift import ReactiveCocoa import ProtoKit public protocol ReactiveListViewItemModelInjectable { var itemModel: MutableProperty<ListViewItemModel?> { get } } public protocol ReactiveStackViewItemModelInjectable { var itemModel: MutableProperty<StackViewItemModel?> { get } } public extension Reactive where Base: ReactiveDiffableListViewHolder { var sections: BindingTarget<[SectionModel]> { return makeBindingTarget { $0.sections = $1 } } } public extension Reactive where Base: ReactiveStackViewHolder { var itemModels: BindingTarget<[StackViewItemModel]> { return makeBindingTarget { $0.itemModels = $1 } } } open class ReactiveDiffableListViewHolder: DiffableListViewHolder { override open func listableView<Item: ReusableView>(_ listableView: ListableView, itemForItemAt indexPath: IndexPath) -> Item { let data: (Item, ListViewItemModel) = itemData(at: indexPath) let (item, model) = data guard let cell = item as? ReactiveListViewItemModelInjectable else { return item } cell.itemModel.value = model return item } override open func listableView<Item: ReusableView>(_ listableView: ListableView, viewForHeaderFooterAt indexPath: IndexPath, of kind: String) -> Item? { let data: (Item, ListViewItemModel)? = headerFooterItemData(at: indexPath, of: kind) guard let (item, model) = data else { return nil } guard let view = item as? ReactiveListViewItemModelInjectable else { return item } view.itemModel.value = model return item } } open class ReactiveStackViewHolder: StackViewHolder { override open func listableView<Item: ReusableView>(_ listableView: ListableView, itemForItemAt indexPath: IndexPath) -> Item { let model = itemModels[indexPath.row] let item: Item = listableView.reusableItem(withIdentifier: holderType.typeName, for: indexPath) guard let holder = item as? StackViewItemHolder else { return item } let contentView = holder.attach(itemType: model.itemType) guard let stackItem = contentView as? ReactiveStackViewItemModelInjectable else { return item } stackItem.itemModel.value = model return item } }
mit
173ccef5c0309f88dc9416d6ae47e324
31.84058
154
0.767432
4.243446
false
false
false
false
zhangjk4859/MyWeiBoProject
sinaWeibo/sinaWeibo/Classes/Home/图片控制器/JKPhotoBrowserCell.swift
1
4881
// // JKPhotoBrowserCell.swift // sinaWeibo // // Created by 张俊凯 on 16/7/25. // Copyright © 2016年 张俊凯. All rights reserved. // import UIKit import SDWebImage protocol PhotoBrowserCellDelegate : NSObjectProtocol { func photoBrowserCellDidClose(cell: JKPhotoBrowserCell) } class JKPhotoBrowserCell: UICollectionViewCell { //代理设置弱属性 weak var photoBrowserCellDelegate : PhotoBrowserCellDelegate? //图片链接 var imageURL: NSURL? { didSet{ // 重置属性 reset() // 显示菊花 activity.startAnimating() // 设置图片 iconView.sd_setImageWithURL(imageURL) { (image, _, _, _) -> Void in // 隐藏菊花 self.activity.stopAnimating() // 调整图片的尺寸和位置 self.setImageViewPostion() } } } //重置scrollview和imageview的属性 private func reset() { // 重置scrollview scrollview.contentInset = UIEdgeInsetsZero scrollview.contentOffset = CGPointZero scrollview.contentSize = CGSizeZero // 重置imageview iconView.transform = CGAffineTransformIdentity } //调整图片显示的位置 private func setImageViewPostion() { // 拿到按照宽高比计算之后的图片大小 let size = self.displaySize(iconView.image!) // 判断图片的高度, 是否大于屏幕的高度 if size.height < UIScreen.mainScreen().bounds.height { //图片居中显示 iconView.frame = CGRect(origin: CGPointZero, size: size) //处理居中显示 let y = (UIScreen.mainScreen().bounds.height - size.height) * 0.5 self.scrollview.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0) }else { //设置scrollview的滚动范围为图片的大小 iconView.frame = CGRect(origin: CGPointZero, size: size) scrollview.contentSize = size } } //按照图片的宽高比计算图片显示的大小 private func displaySize(image: UIImage) -> CGSize { // 拿到图片的宽高比 let scale = image.size.height / image.size.width // 根据宽高比计算高度 let width = UIScreen.mainScreen().bounds.width let height = width * scale return CGSize(width: width, height: height) } override init(frame: CGRect) { super.init(frame: frame) // 初始化UI setupUI() } private func setupUI() { // 添加子控件 contentView.addSubview(scrollview) scrollview.addSubview(iconView) contentView.addSubview(activity) // 布局子控件 scrollview.frame = UIScreen.mainScreen().bounds activity.center = contentView.center // 处理缩放 scrollview.delegate = self scrollview.maximumZoomScale = 2.0 scrollview.minimumZoomScale = 0.5 // 监听图片的点击 let tap = UITapGestureRecognizer(target: self, action: #selector(JKPhotoBrowserCell.close)) iconView.addGestureRecognizer(tap) iconView.userInteractionEnabled = true } //关闭浏览器 func close() { print("close") photoBrowserCellDelegate?.photoBrowserCellDidClose(self) } // MARK: - 懒加载 private lazy var scrollview: UIScrollView = UIScrollView() lazy var iconView: UIImageView = UIImageView() private lazy var activity: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension JKPhotoBrowserCell: UIScrollViewDelegate { // 告诉系统需要缩放哪个控件 func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return iconView } // 重新调整配图的位置 // view: 被缩放的视图 func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { print("scrollViewDidEndZooming") var offsetX = (UIScreen.mainScreen().bounds.width - view!.frame.width) * 0.5 var offsetY = (UIScreen.mainScreen().bounds.height - view!.frame.height) * 0.5 offsetX = offsetX < 0 ? 0 : offsetX offsetY = offsetY < 0 ? 0 : offsetY scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX) } }
mit
72dee670efdd9b4cbd5682a06773af0a
26.493827
146
0.59295
5.027088
false
false
false
false
luckymore0520/GreenTea
Loyalty/Main/ViewController/LocationSearchTableViewController.swift
1
2543
// // LocationSearchTableViewController.swift // Loyalty // // Created by WangKun on 16/4/23. // Copyright © 2016年 WangKun. All rights reserved. // import UIKit class LocationSearchTableViewController: UITableViewController { var searchResult:[AMapPOI] = [] var mapSearch = AMapSearchAPI() var selectionHandler:((poi:AMapPOI) -> ())? override func viewDidLoad() { super.viewDidLoad() mapSearch.delegate = self self.tableView.registerReusableCell(PointInfoTableViewCell.self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.tableView.frame = CGRectMake(0, -44, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.searchResult.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(indexPath: indexPath) as PointInfoTableViewCell let poi = self.searchResult[indexPath.row] let pointViewModel = PointInfoTableViewCellViewModel(poi: poi, isChecked: false) cell.render(pointViewModel) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard let selectionHandler = self.selectionHandler else { return } selectionHandler(poi: self.searchResult[indexPath.row]) } } extension LocationSearchTableViewController { func searchLocation(keyword:String?){ guard let keyword = keyword else { return } let request = AMapPOIKeywordsSearchRequest() request.sortrule = 0; request.keywords = keyword request.city = UserDefaultTool.stringForKey(cityKey)?.stringByReplacingOccurrencesOfString("市", withString: "") self.mapSearch?.AMapPOIKeywordsSearch(request) } } extension LocationSearchTableViewController:AMapSearchDelegate { func onPOISearchDone(request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) { if response.pois.count == 0 { return } self.searchResult = response.pois as! [AMapPOI] self.tableView?.reloadData() } }
mit
4df2c0ef0dd59714136f09b13d32af6e
34.25
127
0.705674
5.055777
false
false
false
false
apple/swift-atomics
Sources/Atomics/AtomicOptional.swift
1
1118
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Atomics open source project // // Copyright (c) 2020 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 // //===----------------------------------------------------------------------===// /// An atomic value that also supports atomic operations when wrapped /// in an `Optional`. Atomic optional wrappable types come with a /// standalone atomic representation for their optional-wrapped /// variants. public protocol AtomicOptionalWrappable: AtomicValue { /// The atomic storage representation for `Optional<Self>`. associatedtype AtomicOptionalRepresentation: AtomicStorage where AtomicOptionalRepresentation.Value == Self? } extension Optional: AtomicValue where Wrapped: AtomicOptionalWrappable { public typealias AtomicRepresentation = Wrapped.AtomicOptionalRepresentation }
apache-2.0
4155203ef4bed8507bd004e1f7bbe49b
43.72
80
0.675313
5.507389
false
false
false
false
alexmiragall/Gourmet-iOS
gourmet/gourmet/viewcontrollers/FirstViewController.swift
1
4301
// // FirstViewController.swift // gourmet // // Created by Alejandro Miragall Arnal on 15/3/16. // Copyright © 2016 Alejandro Miragall Arnal. All rights reserved. // import UIKit import MapKit import Firebase import AlamofireImage class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MKMapViewDelegate, CLLocationManagerDelegate, GIDSignInUIDelegate { @IBOutlet var mapView: MKMapView! @IBOutlet var tableView: UITableView! let locationManager = CLLocationManager() var restaurantRepository: RestaurantsRepository! var items: [Restaurant] = [] var userManager = UserManager.instance @IBAction func viewChanged(sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { tableView.hidden = true mapView.hidden = false } else { tableView.hidden = false mapView.hidden = true } } override func viewDidLoad() { super.viewDidLoad() userManager.signIn(self, callback: { (error, errorType) in if (error) { print("Error login: \(errorType)") } else { print("Success login") } }) restaurantRepository = RestaurantsRepository() let nib = UINib(nibName: "RestaurantTableViewCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: RestaurantTableViewCell.name) locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() mapView.delegate = self getRestaurants() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueToRestaurantDetail" { let viewController = segue.destinationViewController as! RestaurantDetailViewController viewController.hidesBottomBarWhenPushed = true viewController.restaurant = sender as? Restaurant } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case .Authorized, .AuthorizedWhenInUse: manager.startUpdatingLocation() self.mapView.showsUserLocation = true default: break } } func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { let region = MKCoordinateRegionMakeWithDistance ( userLocation.location!.coordinate, 10000, 10000) mapView.setRegion(region, animated: true) } override func viewDidAppear(animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:RestaurantTableViewCell = self.tableView.dequeueReusableCellWithIdentifier(RestaurantTableViewCell.name) as! RestaurantTableViewCell let restaurant:Restaurant = self.items[indexPath.row] cell.loadItem(title: restaurant.name, image: restaurant.photo, completion: { cell.setNeedsLayout() }) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) performSegueWithIdentifier("segueToRestaurantDetail", sender: self.items[indexPath.row]) print("You selected cell #\(indexPath.row)!") } func getRestaurants() { restaurantRepository.getItems({ self.items.appendContentsOf($0) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() self.updateMap() }) }) } func updateMap() { for rest in items { mapView.addAnnotation(RestaurantItem(title: rest.name, coordinate: CLLocationCoordinate2D(latitude: rest.lat!, longitude: rest.lon!), info: rest.description)) } } }
mit
1e28f56db5b0d9345391da4d6f5062b0
33.677419
170
0.665116
5.710491
false
false
false
false
alblue/swift
stdlib/public/core/StringCreate.swift
1
5322
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// // String Creation Helpers //===----------------------------------------------------------------------===// internal func _allASCII(_ input: UnsafeBufferPointer<UInt8>) -> Bool { // NOTE: Avoiding for-in syntax to avoid bounds checks // // TODO(String performance): Vectorize and/or incorporate into validity // checking, perhaps both. // let ptr = input.baseAddress._unsafelyUnwrappedUnchecked var i = 0 while i < input.count { guard ptr[i] <= 0x7F else { return false } i &+= 1 } return true } extension String { @usableFromInline internal static func _fromASCII( _ input: UnsafeBufferPointer<UInt8> ) -> String { _sanityCheck(_allASCII(input), "not actually ASCII") if let smol = _SmallString(input) { return String(_StringGuts(smol)) } let storage = _StringStorage.create(initializingFrom: input, isASCII: true) return storage.asString } @usableFromInline internal static func _tryFromUTF8( _ input: UnsafeBufferPointer<UInt8> ) -> String? { guard case .success(let extraInfo) = validateUTF8(input) else { return nil } return String._uncheckedFromUTF8(input, isASCII: extraInfo.isASCII) } @usableFromInline internal static func _fromUTF8Repairing( _ input: UnsafeBufferPointer<UInt8> ) -> (result: String, repairsMade: Bool) { switch validateUTF8(input) { case .success(let extraInfo): return (String._uncheckedFromUTF8( input, asciiPreScanResult: extraInfo.isASCII ), false) case .error(let initialRange): return (repairUTF8(input, firstKnownBrokenRange: initialRange), true) } } @usableFromInline internal static func _uncheckedFromUTF8( _ input: UnsafeBufferPointer<UInt8> ) -> String { return _uncheckedFromUTF8(input, isASCII: _allASCII(input)) } @usableFromInline internal static func _uncheckedFromUTF8( _ input: UnsafeBufferPointer<UInt8>, isASCII: Bool ) -> String { if let smol = _SmallString(input) { return String(_StringGuts(smol)) } let storage = _StringStorage.create( initializingFrom: input, isASCII: isASCII) return storage.asString } // If we've already pre-scanned for ASCII, just supply the result @usableFromInline internal static func _uncheckedFromUTF8( _ input: UnsafeBufferPointer<UInt8>, asciiPreScanResult: Bool ) -> String { if let smol = _SmallString(input) { return String(_StringGuts(smol)) } let isASCII = asciiPreScanResult let storage = _StringStorage.create( initializingFrom: input, isASCII: isASCII) return storage.asString } @usableFromInline internal static func _uncheckedFromUTF16( _ input: UnsafeBufferPointer<UInt16> ) -> String { // TODO(String Performance): Attempt to form smol strings // TODO(String performance): Skip intermediary array, transcode directly // into a StringStorage space. var contents: [UInt8] = [] contents.reserveCapacity(input.count) let repaired = transcode( input.makeIterator(), from: UTF16.self, to: UTF8.self, stoppingOnError: false, into: { contents.append($0) }) _sanityCheck(!repaired, "Error present") return contents.withUnsafeBufferPointer { String._uncheckedFromUTF8($0) } } internal func _withUnsafeBufferPointerToUTF8<R>( _ body: (UnsafeBufferPointer<UTF8.CodeUnit>) throws -> R ) rethrows -> R { return try self.withUnsafeBytes { rawBufPtr in let rawPtr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked return try body(UnsafeBufferPointer( start: rawPtr.assumingMemoryBound(to: UInt8.self), count: rawBufPtr.count)) } } @usableFromInline @inline(never) // slow-path internal static func _fromCodeUnits< Input: Collection, Encoding: Unicode.Encoding >( _ input: Input, encoding: Encoding.Type, repair: Bool ) -> (String, repairsMade: Bool)? where Input.Element == Encoding.CodeUnit { // TODO(String Performance): Attempt to form smol strings // TODO(String performance): Skip intermediary array, transcode directly // into a StringStorage space. var contents: [UInt8] = [] contents.reserveCapacity(input.underestimatedCount) let repaired = transcode( input.makeIterator(), from: Encoding.self, to: UTF8.self, stoppingOnError: false, into: { contents.append($0) }) guard repair || !repaired else { return nil } let str = contents.withUnsafeBufferPointer { String._uncheckedFromUTF8($0) } return (str, repaired) } public // @testable static func _fromInvalidUTF16( _ utf16: UnsafeBufferPointer<UInt16> ) -> String { return String._fromCodeUnits(utf16, encoding: UTF16.self, repair: true)!.0 } }
apache-2.0
ca368f2587217edb25b8f3cd06e3140c
29.763006
80
0.65652
4.513995
false
false
false
false
Den-Ree/InstagramAPI
src/InstagramAPI/Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift
2
17731
// // UIImageView+AlamofireImage.swift // // Copyright (c) 2015-2016 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 Alamofire import Foundation #if os(iOS) || os(tvOS) import UIKit extension UIImageView { // MARK: - ImageTransition /// Used to wrap all `UIView` animation transition options alongside a duration. public enum ImageTransition { case noTransition case crossDissolve(TimeInterval) case curlDown(TimeInterval) case curlUp(TimeInterval) case flipFromBottom(TimeInterval) case flipFromLeft(TimeInterval) case flipFromRight(TimeInterval) case flipFromTop(TimeInterval) case custom( duration: TimeInterval, animationOptions: UIViewAnimationOptions, animations: (UIImageView, Image) -> Void, completion: ((Bool) -> Void)? ) /// The duration of the image transition in seconds. public var duration: TimeInterval { switch self { case .noTransition: return 0.0 case .crossDissolve(let duration): return duration case .curlDown(let duration): return duration case .curlUp(let duration): return duration case .flipFromBottom(let duration): return duration case .flipFromLeft(let duration): return duration case .flipFromRight(let duration): return duration case .flipFromTop(let duration): return duration case .custom(let duration, _, _, _): return duration } } /// The animation options of the image transition. public var animationOptions: UIViewAnimationOptions { switch self { case .noTransition: return UIViewAnimationOptions() case .crossDissolve: return .transitionCrossDissolve case .curlDown: return .transitionCurlDown case .curlUp: return .transitionCurlUp case .flipFromBottom: return .transitionFlipFromBottom case .flipFromLeft: return .transitionFlipFromLeft case .flipFromRight: return .transitionFlipFromRight case .flipFromTop: return .transitionFlipFromTop case .custom(_, let animationOptions, _, _): return animationOptions } } /// The animation options of the image transition. public var animations: ((UIImageView, Image) -> Void) { switch self { case .custom(_, _, let animations, _): return animations default: return { $0.image = $1 } } } /// The completion closure associated with the image transition. public var completion: ((Bool) -> Void)? { switch self { case .custom(_, _, _, let completion): return completion default: return nil } } } // MARK: - Private - AssociatedKeys private struct AssociatedKey { static var imageDownloader = "af_UIImageView.ImageDownloader" static var sharedImageDownloader = "af_UIImageView.SharedImageDownloader" static var activeRequestReceipt = "af_UIImageView.ActiveRequestReceipt" } // MARK: - Associated Properties /// The instance image downloader used to download all images. If this property is `nil`, the `UIImageView` will /// fallback on the `af_sharedImageDownloader` for all downloads. The most common use case for needing to use a /// custom instance image downloader is when images are behind different basic auth credentials. public var af_imageDownloader: ImageDownloader? { get { return objc_getAssociatedObject(self, &AssociatedKey.imageDownloader) as? ImageDownloader } set(downloader) { objc_setAssociatedObject(self, &AssociatedKey.imageDownloader, downloader, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// The shared image downloader used to download all images. By default, this is the default `ImageDownloader` /// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory /// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the /// `af_imageDownloader` is `nil`. public class var af_sharedImageDownloader: ImageDownloader { get { if let downloader = objc_getAssociatedObject(self, &AssociatedKey.sharedImageDownloader) as? ImageDownloader { return downloader } else { return ImageDownloader.default } } set { objc_setAssociatedObject(self, &AssociatedKey.sharedImageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var af_activeRequestReceipt: RequestReceipt? { get { return objc_getAssociatedObject(self, &AssociatedKey.activeRequestReceipt) as? RequestReceipt } set { objc_setAssociatedObject(self, &AssociatedKey.activeRequestReceipt, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Image Download /// Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded /// image and sets it once finished while executing the image transition. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// The `completion` closure is called after the image download and filtering are complete, but before the start of /// the image transition. Please note it is no longer the responsibility of the `completion` closure to set the /// image. It will be set automatically. If you require a second notification after the image transition completes, /// use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when /// the image transition is finished. /// /// - parameter url: The URL used for the image request. /// - parameter placeholderImage: The image to be set initially until the image request finished. If /// `nil`, the image view will not change its image until the image /// request finishes. Defaults to `nil`. /// - parameter filter: The image filter applied to the image after the image request is /// finished. Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the /// request. Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the /// main queue. /// - parameter imageTransition: The image transition animation applied to the image when set. /// Defaults to `.None`. /// - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults /// to `false`. /// - parameter completion: A closure to be executed when the image request finishes. The closure /// has no return value and takes three arguments: the original request, /// the response from the server and the result containing either the /// image or the error that occurred. If the image was returned from the /// image cache, the response will be `nil`. Defaults to `nil`. public func af_setImage( withURL url: URL, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, imageTransition: ImageTransition = .noTransition, runImageTransitionIfCached: Bool = false, completion: ((DataResponse<UIImage>) -> Void)? = nil) { af_setImage( withURLRequest: urlRequest(with: url), placeholderImage: placeholderImage, filter: filter, progress: progress, progressQueue: progressQueue, imageTransition: imageTransition, runImageTransitionIfCached: runImageTransitionIfCached, completion: completion ) } /// Asynchronously downloads an image from the specified URL Request, applies the specified image filter to the downloaded /// image and sets it once finished while executing the image transition. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// The `completion` closure is called after the image download and filtering are complete, but before the start of /// the image transition. Please note it is no longer the responsibility of the `completion` closure to set the /// image. It will be set automatically. If you require a second notification after the image transition completes, /// use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when /// the image transition is finished. /// /// - parameter urlRequest: The URL request. /// - parameter placeholderImage: The image to be set initially until the image request finished. If /// `nil`, the image view will not change its image until the image /// request finishes. Defaults to `nil`. /// - parameter filter: The image filter applied to the image after the image request is /// finished. Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the /// request. Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the /// main queue. /// - parameter imageTransition: The image transition animation applied to the image when set. /// Defaults to `.None`. /// - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults /// to `false`. /// - parameter completion: A closure to be executed when the image request finishes. The closure /// has no return value and takes three arguments: the original request, /// the response from the server and the result containing either the /// image or the error that occurred. If the image was returned from the /// image cache, the response will be `nil`. Defaults to `nil`. public func af_setImage( withURLRequest urlRequest: URLRequestConvertible, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, imageTransition: ImageTransition = .noTransition, runImageTransitionIfCached: Bool = false, completion: ((DataResponse<UIImage>) -> Void)? = nil) { guard !isURLRequestURLEqualToActiveRequestURL(urlRequest) else { return } af_cancelImageRequest() let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader let imageCache = imageDownloader.imageCache // Use the image from the image cache if it exists if let request = urlRequest.urlRequest, let image = imageCache?.image(for: request, withIdentifier: filter?.identifier) { let response = DataResponse<UIImage>(request: request, response: nil, data: nil, result: .success(image)) completion?(response) if runImageTransitionIfCached { let tinyDelay = DispatchTime.now() + Double(Int64(0.001 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) // Need to let the runloop cycle for the placeholder image to take affect DispatchQueue.main.asyncAfter(deadline: tinyDelay) { self.run(imageTransition, with: image) } } else { self.image = image } return } // Set the placeholder since we're going to have to download if let placeholderImage = placeholderImage { self.image = placeholderImage } // Generate a unique download id to check whether the active request has changed while downloading let downloadID = UUID().uuidString // Download the image, then run the image transition or completion handler let requestReceipt = imageDownloader.download( urlRequest, receiptID: downloadID, filter: filter, progress: progress, progressQueue: progressQueue, completion: { [weak self] response in guard let strongSelf = self else { return } completion?(response) guard strongSelf.isURLRequestURLEqualToActiveRequestURL(response.request) && strongSelf.af_activeRequestReceipt?.receiptID == downloadID else { return } if let image = response.result.value { strongSelf.run(imageTransition, with: image) } strongSelf.af_activeRequestReceipt = nil } ) af_activeRequestReceipt = requestReceipt } // MARK: - Image Download Cancellation /// Cancels the active download request, if one exists. public func af_cancelImageRequest() { guard let activeRequestReceipt = af_activeRequestReceipt else { return } let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader imageDownloader.cancelRequest(with: activeRequestReceipt) af_activeRequestReceipt = nil } // MARK: - Image Transition /// Runs the image transition on the image view with the specified image. /// /// - parameter imageTransition: The image transition to ran on the image view. /// - parameter image: The image to use for the image transition. public func run(_ imageTransition: ImageTransition, with image: Image) { UIView.transition( with: self, duration: imageTransition.duration, options: imageTransition.animationOptions, animations: { imageTransition.animations(self, image) }, completion: imageTransition.completion ) } // MARK: - Private - URL Request Helper Methods private func urlRequest(with url: URL) -> URLRequest { var urlRequest = URLRequest(url: url) for mimeType in DataRequest.acceptableImageContentTypes { urlRequest.addValue(mimeType, forHTTPHeaderField: "Accept") } return urlRequest } private func isURLRequestURLEqualToActiveRequestURL(_ urlRequest: URLRequestConvertible?) -> Bool { if let currentRequestURL = af_activeRequestReceipt?.request.task?.originalRequest?.url, let requestURL = urlRequest?.urlRequest?.url, currentRequestURL == requestURL { return true } return false } } #endif
mit
5b2a091edc2014807068a049c28dfd0d
45.783641
126
0.613502
5.783105
false
false
false
false
niklasberglund/SwiftChinese
SwiftChinese/Pods/SwiftyHash/Source/FileHashContext.swift
2
8375
// // FileHashCotext.swift // SwiftyHash // // Created by 刘栋 on 2016/7/28. // Copyright © 2016年 anotheren.com. All rights reserved. // import Foundation import CommonCrypto internal struct FileHashContext { /// The Bytes length of the data to read each time private let sizeForReadingData: Int = 4096 /// Calculate the file hash string /// /// - parameter type: HashType /// - parameter filePath: file path /// /// - returns: hash string internal func string(_ type: HashType, path filePath: String) -> String? { guard let array: Array<UInt8> = digest(type, path: filePath) else { return nil } return type.string(array) } /// Calculate the file hash object /// /// - parameter type: HashType /// - parameter filePath: file path /// /// - returns: hash object internal func digest(_ type: HashType, path filePath: String) -> Array<UInt8>? { guard FileManager.default.fileExists(atPath: filePath), let fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, filePath as CFString, .cfurlposixPathStyle, false), let readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, fileURL), CFReadStreamOpen(readStream) else { return nil } var digest = Array<UInt8>(repeating: 0, count: type.digestLength) let didSuccess: Bool switch type { case .md5: didSuccess = hashOfFileMD5(pointer: &digest, stream: readStream) case .sha1: didSuccess = hashOfFileSHA1(pointer: &digest, stream: readStream) case .sha224: didSuccess = hashOfFileSHA224(pointer: &digest, stream: readStream) case .sha256: didSuccess = hashOfFileSHA256(pointer: &digest, stream: readStream) case .sha384: didSuccess = hashOfFileSHA384(pointer: &digest, stream: readStream) case .sha512: didSuccess = hashOfFileSHA512(pointer: &digest, stream: readStream) } CFReadStreamClose(readStream) return didSuccess ? digest : nil } /// Calculate the file‘s md5 /// /// - parameter digestPointer: hash pointer /// - parameter readStream: readable stream object /// /// - returns: true if success private func hashOfFileMD5(pointer digestPointer: UnsafeMutablePointer<UInt8>, stream readStream: CFReadStream) -> Bool { var hashObject = CC_MD5_CTX() CC_MD5_Init(&hashObject) var hasMoreData = true while hasMoreData { var buffer = Array<UInt8>(repeating: 0, count: sizeForReadingData) let readBytesCount = CFReadStreamRead(readStream, &buffer, sizeForReadingData) if readBytesCount == -1 { break } else if readBytesCount == 0 { hasMoreData = false } else { CC_MD5_Update(&hashObject, &buffer, CC_LONG(readBytesCount)) } } if hasMoreData { return false } CC_MD5_Final(digestPointer, &hashObject) return true } /// Calculate the file‘s sha1 /// /// - parameter digestPointer: hash pointer /// - parameter readStream: readable stream object /// /// - returns: true if success private func hashOfFileSHA1(pointer digestPointer: UnsafeMutablePointer<UInt8>, stream readStream: CFReadStream) -> Bool { var hashObject = CC_SHA1_CTX() CC_SHA1_Init(&hashObject) var hasMoreData = true while hasMoreData { var buffer = Array<UInt8>(repeating: 0, count: sizeForReadingData) let readBytesCount = CFReadStreamRead(readStream, &buffer, sizeForReadingData) if readBytesCount == -1 { break } else if readBytesCount == 0 { hasMoreData = false } else { CC_SHA1_Update(&hashObject, &buffer, CC_LONG(readBytesCount)) } } if hasMoreData { return false } CC_SHA1_Final(digestPointer, &hashObject) return true } /// Calculate the file‘s sha224 /// /// - parameter digestPointer: hash pointer /// - parameter readStream: readable stream object /// /// - returns: true if success private func hashOfFileSHA224(pointer digestPointer: UnsafeMutablePointer<UInt8>, stream readStream: CFReadStream) -> Bool { var hashObject = CC_SHA256_CTX() // same context struct is used for SHA224 and SHA256 CC_SHA224_Init(&hashObject) var hasMoreData = true while hasMoreData { var buffer = Array<UInt8>(repeating: 0, count: sizeForReadingData) let readBytesCount = CFReadStreamRead(readStream, &buffer, sizeForReadingData) if readBytesCount == -1 { break } else if readBytesCount == 0 { hasMoreData = false } else { CC_SHA224_Update(&hashObject, &buffer, CC_LONG(readBytesCount)) } } if hasMoreData { return false } CC_SHA224_Final(digestPointer, &hashObject) return true } /// Calculate the file‘s sha256 /// /// - parameter digestPointer: hash pointer /// - parameter readStream: readable stream object /// /// - returns: true if success private func hashOfFileSHA256(pointer digestPointer: UnsafeMutablePointer<UInt8>, stream readStream: CFReadStream) -> Bool { var hashObject = CC_SHA256_CTX() CC_SHA256_Init(&hashObject) var hasMoreData = true while hasMoreData { var buffer = Array<UInt8>(repeating: 0, count: sizeForReadingData) let readBytesCount = CFReadStreamRead(readStream, &buffer, sizeForReadingData) if readBytesCount == -1 { break } else if readBytesCount == 0 { hasMoreData = false } else { CC_SHA256_Update(&hashObject, &buffer, CC_LONG(readBytesCount)) } } if hasMoreData { return false } CC_SHA256_Final(digestPointer, &hashObject) return true } /// Calculate the file‘s sha384 /// /// - parameter digestPointer: hash pointer /// - parameter readStream: readable stream object /// /// - returns: true if success private func hashOfFileSHA384(pointer digestPointer: UnsafeMutablePointer<UInt8>, stream readStream: CFReadStream) -> Bool { var hashObject = CC_SHA512_CTX() // same context struct is used for SHA384 and SHA512 CC_SHA384_Init(&hashObject) var hasMoreData = true while hasMoreData { var buffer = Array<UInt8>(repeating: 0, count: sizeForReadingData) let readBytesCount = CFReadStreamRead(readStream, &buffer, sizeForReadingData) if readBytesCount == -1 { break } else if readBytesCount == 0 { hasMoreData = false } else { CC_SHA384_Update(&hashObject, &buffer, CC_LONG(readBytesCount)) } } if hasMoreData { return false } CC_SHA384_Final(digestPointer, &hashObject) return true } /// Calculate the file‘s sha512 /// /// - parameter digestPointer: hash pointer /// - parameter readStream: readable stream object /// /// - returns: true if success private func hashOfFileSHA512(pointer digestPointer: UnsafeMutablePointer<UInt8>, stream readStream: CFReadStream) -> Bool { var hashObject = CC_SHA512_CTX() CC_SHA512_Init(&hashObject) var hasMoreData = true while hasMoreData { var buffer = Array<UInt8>(repeating: 0, count: sizeForReadingData) let readBytesCount = CFReadStreamRead(readStream, &buffer, sizeForReadingData) if readBytesCount == -1 { break } else if readBytesCount == 0 { hasMoreData = false } else { CC_SHA512_Update(&hashObject, &buffer, CC_LONG(readBytesCount)) } } if hasMoreData { return false } CC_SHA512_Final(digestPointer, &hashObject) return true } }
mit
11d84ecf4b5b2552c2ef8be2f2ea5c5f
36.981818
128
0.600048
5.070388
false
false
false
false
semiroot/SwiftyConstraints
Examples/iOS/iOS/AnimationViewController.swift
1
2451
// // AnimationViewController.swift // iOS // // Created by Hansmartin Geiser on 16/04/17. // Copyright © 2017 Hansmartin Geiser. All rights reserved. // import UIKit import SwiftyConstraints class AnimationViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "Animation" view.backgroundColor = .white navigationController?.navigationBar.isTranslucent = false let box1 = SCView(); box1.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) let box2 = SCView(); box2.backgroundColor = UIColor(red: 0.05, green: 0.05, blue: 0.05, alpha: 1) let box3 = SCView(); box3.backgroundColor = UIColor(red: 0.94, green: 0.94, blue: 0.94, alpha: 1) let box4 = SCView(); box4.backgroundColor = UIColor(red: 0.94, green: 0.94, blue: 0.94, alpha: 1) // Store SwiftyConstraints if you need it again (the mothod on the View/ViewController does not store an instance) let swiftyConstraints = self.swiftyConstraints() // Set constraints as usual swiftyConstraints .attach(box1) .top().left().right().height(1) .attach(box2) .width(10).height(10).center().middle() .attach(box3) .top(20).left().height(40).width(0) .attach(box4) .bottom(20).right().height(40).width(0) // Layout constraints (equal to LayoutIfNeeded) .updateConstraints() UIView.animate(withDuration: 1, delay: 0, options: .curveEaseOut, animations: { // Change the constraints swiftyConstraints .use(box1) .removeHeight() .heightOfSuperview(0.5) .execute({ (view) in // You can use 'execute' to modify the current view within the method chain view.backgroundColor = UIColor(red: 0.05, green: 0.05, blue: 0.05, alpha: 1) }) .use(box2) .removeWidth() .width(150) .removeHeight() .height(150) .execute({ (view) in view.backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1) view.layer.cornerRadius = 75 }) .use(box3) .removeWidth() .widthOfSuperview(0.8) .use(box4) .removeWidth() .widthOfSuperview(0.8) // Layout constraints again (equal to LayoutIfNeeded) .updateConstraints() }, completion: nil) } }
mit
60c0bc41948fceb9b75eef8e03e995dd
29.246914
118
0.601633
4.003268
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/Networking/RequestAuthenticator.swift
1
14685
import AutomatticTracks import Foundation /// Authenticator for requests to self-hosted sites, wp.com sites, including private /// sites and atomic sites. /// /// - Note: at some point I considered moving this module to the WordPressAuthenticator pod. /// Unfortunately the effort required for this makes it unfeasible for me to focus on it /// right now, as it involves also moving at least CookieJar, AuthenticationService and AtomicAuthenticationService over there as well. - @diegoreymendez /// class RequestAuthenticator: NSObject { enum Error: Swift.Error { case atomicSiteWithoutDotComID(blog: Blog) } enum DotComAuthenticationType { case regular case regularMapped(siteID: Int) case atomic(loginURL: String) case privateAtomic(blogID: Int) } enum WPNavigationActionType { case reload case allow } enum Credentials { case dotCom(username: String, authToken: String, authenticationType: DotComAuthenticationType) case siteLogin(loginURL: URL, username: String, password: String) } fileprivate let credentials: Credentials // MARK: - Services private let authenticationService: AuthenticationService // MARK: - Initializers init(credentials: Credentials, authenticationService: AuthenticationService = AuthenticationService()) { self.credentials = credentials self.authenticationService = authenticationService } @objc convenience init?(account: WPAccount, blog: Blog? = nil) { guard let username = account.username, let token = account.authToken else { return nil } var authenticationType: DotComAuthenticationType = .regular if let blog = blog, let dotComID = blog.dotComID as? Int { if blog.isAtomic() { authenticationType = blog.isPrivate() ? .privateAtomic(blogID: dotComID) : .atomic(loginURL: blog.loginUrl()) } else if blog.hasMappedDomain() { authenticationType = .regularMapped(siteID: dotComID) } } self.init(credentials: .dotCom(username: username, authToken: token, authenticationType: authenticationType)) } @objc convenience init?(blog: Blog) { if let account = blog.account { self.init(account: account, blog: blog) } else if let username = blog.usernameForSite, let password = blog.password, let loginURL = URL(string: blog.loginUrl()) { self.init(credentials: .siteLogin(loginURL: loginURL, username: username, password: password)) } else { DDLogError("Can't authenticate blog \(String(describing: blog.displayURL)) yet") return nil } } /// Potentially rewrites a request for authentication. /// /// This method will call the completion block with the request to be used. /// /// - Warning: On WordPress.com, this uses a special redirect system. It /// requires the web view to call `interceptRedirect(request:)` before /// loading any request. /// /// - Parameters: /// - url: the URL to be loaded. /// - cookieJar: a CookieJar object where the authenticator will look /// for existing cookies. /// - completion: this will be called with either the request for /// authentication, or a request for the original URL. /// @objc func request(url: URL, cookieJar: CookieJar, completion: @escaping (URLRequest) -> Void) { switch self.credentials { case .dotCom(let username, let authToken, let authenticationType): requestForWPCom( url: url, cookieJar: cookieJar, username: username, authToken: authToken, authenticationType: authenticationType, completion: completion) case .siteLogin(let loginURL, let username, let password): requestForSelfHosted( url: url, loginURL: loginURL, cookieJar: cookieJar, username: username, password: password, completion: completion) } } private func requestForWPCom(url: URL, cookieJar: CookieJar, username: String, authToken: String, authenticationType: DotComAuthenticationType, completion: @escaping (URLRequest) -> Void) { switch authenticationType { case .regular: requestForWPCom( url: url, cookieJar: cookieJar, username: username, authToken: authToken, completion: completion) case .regularMapped(let siteID): requestForMappedWPCom(url: url, cookieJar: cookieJar, username: username, authToken: authToken, siteID: siteID, completion: completion) case .privateAtomic(let siteID): requestForPrivateAtomicWPCom( url: url, cookieJar: cookieJar, username: username, siteID: siteID, completion: completion) case .atomic(let loginURL): requestForAtomicWPCom( url: url, loginURL: loginURL, cookieJar: cookieJar, username: username, authToken: authToken, completion: completion) } } private func requestForSelfHosted(url: URL, loginURL: URL, cookieJar: CookieJar, username: String, password: String, completion: @escaping (URLRequest) -> Void) { func done() { let request = URLRequest(url: url) completion(request) } authenticationService.loadAuthCookiesForSelfHosted(into: cookieJar, loginURL: loginURL, username: username, password: password, success: { done() }) { [weak self] error in // Make sure this error scenario isn't silently ignored. self?.logErrorIfNeeded(error) // Even if getting the auth cookies fail, we'll still try to load the URL // so that the user sees a reasonable error situation on screen. // We could opt to create a special screen but for now I'd rather users report // the issue when it happens. done() } } private func requestForPrivateAtomicWPCom(url: URL, cookieJar: CookieJar, username: String, siteID: Int, completion: @escaping (URLRequest) -> Void) { func done() { let request = URLRequest(url: url) completion(request) } // We should really consider refactoring how we retrieve the default account since it doesn't really use // a context at all... let context = ContextManager.shared.mainContext guard let account = try? WPAccount.lookupDefaultWordPressComAccount(in: context) else { WordPressAppDelegate.crashLogging?.logMessage("It shouldn't be possible to reach this point without an account.", properties: nil, level: .error) return } let authenticationService = AtomicAuthenticationService(account: account) authenticationService.loadAuthCookies(into: cookieJar, username: username, siteID: siteID, success: { done() }) { [weak self] error in // Make sure this error scenario isn't silently ignored. self?.logErrorIfNeeded(error) // Even if getting the auth cookies fail, we'll still try to load the URL // so that the user sees a reasonable error situation on screen. // We could opt to create a special screen but for now I'd rather users report // the issue when it happens. done() } } private func requestForAtomicWPCom(url: URL, loginURL: String, cookieJar: CookieJar, username: String, authToken: String, completion: @escaping (URLRequest) -> Void) { func done() { // For non-private Atomic sites, proxy the request through wp-login like Calypso does. // If the site has SSO enabled auth should happen and we get redirected to our preview. // If SSO is not enabled wp-admin prompts for credentials, then redirected. var components = URLComponents(string: loginURL) var queryItems = components?.queryItems ?? [] queryItems.append(URLQueryItem(name: "redirect_to", value: url.absoluteString)) components?.queryItems = queryItems let requestURL = components?.url ?? url let request = URLRequest(url: requestURL) completion(request) } authenticationService.loadAuthCookiesForWPCom(into: cookieJar, username: username, authToken: authToken, success: { done() }) { [weak self] error in // Make sure this error scenario isn't silently ignored. self?.logErrorIfNeeded(error) // Even if getting the auth cookies fail, we'll still try to load the URL // so that the user sees a reasonable error situation on screen. // We could opt to create a special screen but for now I'd rather users report // the issue when it happens. done() } } private func requestForMappedWPCom(url: URL, cookieJar: CookieJar, username: String, authToken: String, siteID: Int, completion: @escaping (URLRequest) -> Void) { func done() { guard let host = url.host, !host.contains(WPComDomain) else { // The requested URL is to the unmapped version of the domain, // so skip proxying the request through r-login. completion(URLRequest(url: url)) return } let rlogin = "https://r-login.wordpress.com/remote-login.php?action=auth" guard var components = URLComponents(string: rlogin) else { // Safety net in case something unexpected changes in the future. DDLogError("There was an unexpected problem initializing URLComponents via the rlogin string.") completion(URLRequest(url: url)) return } var queryItems = components.queryItems ?? [] queryItems.append(contentsOf: [ URLQueryItem(name: "host", value: host), URLQueryItem(name: "id", value: String(siteID)), URLQueryItem(name: "back", value: url.absoluteString) ]) components.queryItems = queryItems let requestURL = components.url ?? url let request = URLRequest(url: requestURL) completion(request) } authenticationService.loadAuthCookiesForWPCom(into: cookieJar, username: username, authToken: authToken, success: { done() }) { [weak self] error in // Make sure this error scenario isn't silently ignored. self?.logErrorIfNeeded(error) // Even if getting the auth cookies fail, we'll still try to load the URL // so that the user sees a reasonable error situation on screen. // We could opt to create a special screen but for now I'd rather users report // the issue when it happens. done() } } private func requestForWPCom(url: URL, cookieJar: CookieJar, username: String, authToken: String, completion: @escaping (URLRequest) -> Void) { func done() { let request = URLRequest(url: url) completion(request) } authenticationService.loadAuthCookiesForWPCom(into: cookieJar, username: username, authToken: authToken, success: { done() }) { [weak self] error in // Make sure this error scenario isn't silently ignored. self?.logErrorIfNeeded(error) // Even if getting the auth cookies fail, we'll still try to load the URL // so that the user sees a reasonable error situation on screen. // We could opt to create a special screen but for now I'd rather users report // the issue when it happens. done() } } private func logErrorIfNeeded(_ error: Swift.Error) { let nsError = error as NSError switch nsError.code { case NSURLErrorTimedOut, NSURLErrorNotConnectedToInternet: return default: WordPressAppDelegate.crashLogging?.logError(error) } } } private extension RequestAuthenticator { static let wordPressComLoginUrl = URL(string: "https://wordpress.com/wp-login.php")! } extension RequestAuthenticator { func isLogin(url: URL) -> Bool { var components = URLComponents(url: url, resolvingAgainstBaseURL: false) components?.queryItems = nil return components?.url == RequestAuthenticator.wordPressComLoginUrl } } // MARK: Navigation Validator extension RequestAuthenticator { /// Validates that the navigation worked as expected then provides a recommendation on if the screen should reload or not. func decideActionFor(response: URLResponse, cookieJar: CookieJar, completion: @escaping (WPNavigationActionType) -> Void) { switch self.credentials { case .dotCom(let username, _, let authenticationType): decideActionForWPCom(response: response, cookieJar: cookieJar, username: username, authenticationType: authenticationType, completion: completion) case .siteLogin: completion(.allow) } } private func decideActionForWPCom(response: URLResponse, cookieJar: CookieJar, username: String, authenticationType: DotComAuthenticationType, completion: @escaping (WPNavigationActionType) -> Void) { guard didEncouterRecoverableChallenge(response) else { completion(.allow) return } cookieJar.removeWordPressComCookies { completion(.reload) } } private func didEncouterRecoverableChallenge(_ response: URLResponse) -> Bool { guard let url = response.url?.absoluteString else { return false } if url.contains("r-login.wordpress.com") || url.contains("wordpress.com/log-in?") { return true } guard let statusCode = (response as? HTTPURLResponse)?.statusCode else { return false } return 400 <= statusCode && statusCode < 500 } }
gpl-2.0
94c36683d48a881547bce3c98243afa9
39.343407
204
0.621246
5.390969
false
false
false
false
ragnar/VindsidenApp
watchkitapp Extension/RHCGraphInterfaceController.swift
1
2603
// // RHCGraphInterfaceController.swift // VindsidenApp // // Created by Ragnar Henriksen on 12.05.15. // Copyright (c) 2015 RHC. All rights reserved. // import WatchKit import WatchConnectivity import Foundation import CoreData import VindsidenWatchKit class RHCGraphInterfaceController: WKInterfaceController { @IBOutlet weak var graphImage: WKInterfaceImage! @IBOutlet weak var stationName: WKInterfaceLabel! override func awake(withContext context: Any?) { super.awake(withContext: context) if let station = context as? CDStation { stationName.setText(station.stationName) guard let stationId = station.stationId else { DLOG("Missing stationId") return; } let screenScale = WKInterfaceDevice.current().screenScale let imageData = generateGraphImage(stationId.intValue, screenSize: WKInterfaceDevice.current().screenBounds, scale: screenScale) let image = UIImage(data: imageData, scale: screenScale) graphImage.setImage(image) } } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } func generateGraphImage( _ stationId: Int, screenSize: CGRect, scale: CGFloat ) -> Data { let graphImage: GraphImage let imageSize = CGSize( width: screenSize.width, height: screenSize.height - 40.0) let gregorian = Calendar(identifier: Calendar.Identifier.gregorian) let inDate = Date().addingTimeInterval(-1*4*3600) let inputComponents = (gregorian as NSCalendar).components([.year, .month, .day, .hour], from: inDate) let outDate = gregorian.date(from: inputComponents)! let fetchRequest: NSFetchRequest<CDPlot> = CDPlot.fetchRequest() fetchRequest.predicate = NSPredicate(format: "station.stationId = %ld AND plotTime >= %@", stationId, outDate as NSDate) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "plotTime", ascending: false)] do { let result = try DataManager.shared.viewContext().fetch(fetchRequest) graphImage = GraphImage(size: imageSize, scale: scale, plots: result) } catch { graphImage = GraphImage(size: imageSize, scale: scale) } let image = graphImage.drawImage() return image.pngData()! } }
bsd-2-clause
57b235ed4e01c7c213084df411335882
33.706667
140
0.669996
4.977055
false
false
false
false
djnivek/Fillio-ios
Fillio/Fillio/network/Network.swift
1
1159
// // FIONetwork.swift // Fillio // // Created by Kévin MACHADO on 23/03/2015. // Copyright (c) 2015 Kévin MACHADO. All rights reserved. // import Foundation public class FIONetwork { private class var DEFAULT_CLIENT_ID: String { return "-the-default-client-2201" } private class var instance: FIONetwork { struct Singleton { static var instance = FIONetwork() } return Singleton.instance } var clients = [String:FIONetworkClient]() private init() { clients[FIONetwork.DEFAULT_CLIENT_ID] = FIONetworkClient() } /// This method create/get a client with a root url public class func clientWithRootUrl(rootUrl: String) -> FIONetworkClient { if let client = FIONetwork.instance.clients[rootUrl] { return client } else { FIONetwork.instance.clients[rootUrl] = FIONetworkClient(rootUrl: rootUrl) return FIONetwork.instance.clients[rootUrl]! } } public class var defaultClient: FIONetworkClient { return FIONetwork.instance.clients[DEFAULT_CLIENT_ID]! } }
gpl-2.0
cecb364b0b3bda5bb922448318f35fa8
25.318182
85
0.630942
4.484496
false
false
false
false
jjz/agora-swift
agora/ChatCell.swift
1
637
import Foundation class ChatCell: UICollectionViewCell { public var agora :AgoraRtcEngineKit! @IBOutlet weak var videoView: UIView! @IBOutlet weak var labelUser: UILabel! private var uid :UInt! func setUid(uid:UInt,localUid:UInt){ labelUser.text=String(uid) let videoCanvas = AgoraRtcVideoCanvas() videoCanvas.uid=uid videoCanvas.view=videoView videoCanvas.renderMode = .render_Fit if(uid != localUid){ agora.setupRemoteVideo(videoCanvas) }else{ agora.setupLocalVideo(videoCanvas) } } }
apache-2.0
357b62682d113fc86362fc75a74817cb
20.965517
47
0.616954
4.333333
false
false
false
false
PiXeL16/BudgetShare
BudgetShare/Modules/Login/Wireframe/LoginWireframeProvider.swift
1
2774
// // Created by Chris Jimenez on 3/5/17. // Copyright (c) 2017 Chris Jimenez. All rights reserved. // import Foundation import UIKit internal class LoginWireframeProvider: Wireframe, LoginWireframe { var root: RootWireframeInterface? // Inits and starts all the wiring required init(root: RootWireframeInterface?, view: LoginView) { self.root = root let service = FirebaseAuthenticationServiceProvider() let interactor = LoginInteractorProvider(service: service) let presenter = LoginPresenterProvider() // Sets the presenter, view and interactors view.presenter = presenter interactor.output = presenter presenter.view = view presenter.interactor = interactor presenter.wireframe = self } // Show the view controller in the window func attachRoot(with controller: UIViewController, in window: UIWindow) { root?.showRoot(with: controller, in: window) } // Show an error Alert func showErrorAlert(title: String, message: String, from controller: UIViewController?) { guard let viewController = controller else { return } // Use the dialog util provider let alert = AlertDialogUtilProvider() alert.showErrorAlert(message: message, title: title, with: viewController) } } extension LoginWireframeProvider { class func createViewController() -> LoginViewController { let sb = UIStoryboard(name: "LoginModule", bundle: Bundle.main) let vc = sb.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController return vc } func pushSignUp(from controller: UIViewController?) { guard controller != nil else { return } let vc = SignUpWireframeProvider.createViewController() let wireframe = SignUpWireframeProvider(root: root, view: vc) wireframe.push(controller: vc, from: controller!) } func pushCreateBudget(from controller: UIViewController?) { guard let fromController = controller else { return } let vc = BudgetCreateWireframeProvider.createViewController() let wireframe = BudgetCreateWireframeProvider(root: root) wireframe.show(controller: vc, from: fromController) } func pushBudgetDetail(from controller: UIViewController?) { guard let fromController = controller else { return } let vc = BudgetDetailListWireframeProvider.createViewController() let wireframe = BudgetDetailListWireframeProvider(root: root, view: vc) wireframe.show(controller: vc, from: fromController) } }
mit
3f793b5780eb119da767b80cfe4e0faf
28.827957
108
0.664744
5.407407
false
false
false
false
bukoli/bukoli-ios
Bukoli/Classes/Extensions/Device.swift
1
2639
// // Device.swift // Pods // // Created by Utku Yildirim on 02/11/2016. // // import Foundation public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro" case "AppleTV5,3": return "Apple TV" case "i386", "x86_64": return "Simulator" default: return identifier } } }
mit
2a7928b7e5eb8dbe5e52650118e0c782
49.75
91
0.461917
3.863836
false
false
false
false
Jaelene/PhotoBroswer
PhotoBroswer/PhotoBroswer/Controller/PhotoBroswer+ZoomAnim.swift
2
4225
// // PhotoBroswer+ZoomAnim.swift // PhotoBroswer // // Created by 冯成林 on 15/8/11. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit /** 力求用最简单的方式实现 */ extension PhotoBroswer{ /** 展示动画: 妈妈,这里好复杂~~ */ func zoomInWithAnim(page: Int){ let photoModel = photoModels[page] let propImgV = UIImageView(frame: photoModel.sourceView.convertRect(photoModel.sourceView.bounds, toView: vc.view)) propImgV.contentMode = UIViewContentMode.ScaleAspectFill propImgV.clipsToBounds = true vc.view.addSubview(propImgV) self.view.alpha = 0 self.collectionView.alpha = 0 if photoType == PhotoType.Local { propImgV.image = photoModel.localImg handleShowAnim(propImgV, thumbNailSize: nil) }else{ /** 服务器图片模式 */ let url = NSURL(string: photoModel.hostHDImgURL)! let cache = Shared.imageCache cache.fetch(key: photoModel.hostHDImgURL).onSuccess {[unowned self] image in propImgV.image = image self.handleShowAnim(propImgV, thumbNailSize: nil) }.onFailure{[unowned self] error in let size = CGSizeMake(CFPBThumbNailWH, CFPBThumbNailWH) if photoModel.hostThumbnailImg != nil { propImgV.image = photoModel.hostThumbnailImg self.handleShowAnim(propImgV, thumbNailSize: size) }else{ /** 这里需要大量修改 */ let img = UIImage.imageWithColor(size: CGSizeMake(CFPBThumbNailWH, CFPBThumbNailWH)) propImgV.image = img self.handleShowAnim(propImgV, thumbNailSize: size) } } } } func handleShowAnim(propImgV: UIImageView,thumbNailSize: CGSize?){ let showSize = thumbNailSize ?? CGSize.decisionShowSize(propImgV.image!.size, contentSize: vc.view.bounds.size) UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 20, options: UIViewAnimationOptions.CurveEaseOut, animations: {[unowned self] () -> Void in propImgV.bounds = CGRectMake(0, 0, showSize.width, showSize.height) propImgV.center = self.vc.view.center self.view.alpha = 1 }) { (complete) -> Void in propImgV.removeFromSuperview() self.collectionView.alpha = 1 } } /** 关闭动画 */ func zoomOutWithAnim(page: Int){ let photoModel = photoModels[page] let cell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: page, inSection: 0)) as! ItemCell let cellImageView = cell.imageV let propImgV = UIImageView(frame: cellImageView.frame) propImgV.contentMode = UIViewContentMode.ScaleAspectFill propImgV.clipsToBounds = true propImgV.image = cellImageView.image propImgV.frame = cellImageView.frame vc.view.addSubview(propImgV) cellImageView.hidden = true photoModel.sourceView.hidden = true UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 20, options: UIViewAnimationOptions.CurveEaseOut, animations: {[unowned self] () -> Void in self.view.alpha = 0 propImgV.frame = photoModel.sourceView.convertRect(photoModel.sourceView.bounds, toView: self.vc.view) }) { (complete) -> Void in photoModel.sourceView.hidden = false propImgV.removeFromSuperview() self.view.removeFromSuperview() self.removeFromParentViewController() } } }
mit
89f59dd9053b2bf3742f793ab27a4bf7
33.115702
193
0.561425
5.332041
false
false
false
false
argent-os/argent-ios
app-ios/IdentityVerificationSplashViewController.swift
1
4267
// // IdentityVerificationSplashViewController.swift // app-ios // // Created by Sinan Ulkuatam on 7/21/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import Foundation import Alamofire import CWStatusBarNotification import SwiftyJSON import KeychainSwift class IdentityVerificationSplashViewController: UIViewController { //@IBOutlet weak var enableRiskProfileButton: UIButton! @IBOutlet weak var goToVerifyButton: UIButton! private var pageIcon = UIImageView() private var pageHeader = UILabel() private var pageDescription = UILabel() override func viewDidLoad() { super.viewDidLoad() configure() } override func prefersStatusBarHidden() -> Bool { return false } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .Default } override func viewDidAppear(animated: Bool) { self.navigationController?.navigationBar.tintColor = UIColor.darkBlue() } func configure() { let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let screenHeight = screen.size.height pageIcon.image = UIImage(named: "IconCustomIdentity") pageIcon.contentMode = .ScaleAspectFit pageIcon.frame = CGRect(x: screenWidth/2-60, y: 125, width: 120, height: 120) self.view.addSubview(pageIcon) let headerAttributedString = adjustAttributedString("Identity Verification", spacing: 0, fontName: "SFUIText-Regular", fontSize: 24, fontColor: UIColor.lightBlue(), lineSpacing: 0.0, alignment: .Center) pageHeader.attributedText = headerAttributedString pageHeader.textAlignment = .Center pageHeader.frame = CGRect(x: 0, y: 260, width: screenWidth, height: 30) self.view.addSubview(pageHeader) let descriptionAttributedString = adjustAttributedString("In order to mitigate end-user risk, \nwe require one identity document\n and social security information. \nWe do not store this information\n on our servers.", spacing: 0, fontName: "SFUIText-Regular", fontSize: 15, fontColor: UIColor.lightBlue(), lineSpacing: 0.0, alignment: .Center) pageDescription.attributedText = descriptionAttributedString pageDescription.numberOfLines = 0 pageDescription.lineBreakMode = .ByWordWrapping pageDescription.textAlignment = .Center pageDescription.frame = CGRect(x: 0, y: 265, width: screenWidth, height: 160) self.view.addSubview(pageDescription) goToVerifyButton.layer.cornerRadius = 0 goToVerifyButton.frame = CGRect(x: 0, y: screenHeight-100, width: screenWidth, height: 50) goToVerifyButton.layer.borderColor = UIColor.oceanBlue().colorWithAlphaComponent(0.5).CGColor goToVerifyButton.layer.borderWidth = 0 goToVerifyButton.clipsToBounds = true goToVerifyButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) goToVerifyButton.setTitleColor(UIColor.offWhite(), forState: .Highlighted) goToVerifyButton.setBackgroundColor(UIColor.oceanBlue(), forState: .Normal) goToVerifyButton.setBackgroundColor(UIColor.oceanBlue().lighterColor(), forState: .Highlighted) var attribs: [String: AnyObject] = [:] attribs[NSFontAttributeName] = UIFont(name: "SFUIText-Regular", size: 14)! attribs[NSForegroundColorAttributeName] = UIColor.whiteColor() let str = NSAttributedString(string: "Verify Identity", attributes: attribs) goToVerifyButton.setAttributedTitle(str, forState: .Normal) self.navigationItem.title = "Identity Verification" self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 17)!, NSForegroundColorAttributeName: UIColor.darkBlue() ] if(screenHeight < 500) { pageIcon.frame = CGRect(x: screenWidth/2-50, y: 100, width: 100, height: 100) pageHeader.frame = CGRect(x: 0, y: 185, width: screenWidth, height: 30) pageDescription.frame = CGRect(x: 0, y: 210, width: screenWidth, height: 50) } } }
mit
2dd4d053cf5347b1fc5b95fae427eae8
42.989691
352
0.691749
5.183475
false
false
false
false
joelpowers/swift-pipes
swift-pipes/GameViewController.swift
1
5472
// // GameViewController.swift // swift-pipes // // Created by Joel Powers on 10/28/15. // Copyright (c) 2015 Joel Powers. All rights reserved. // import UIKit import QuartzCore import SceneKit class GameViewController: UIViewController { var sceneView: SCNView! var camera: SCNNode! var ground: SCNNode! var light: SCNNode! var button: SCNNode! var sphere1: SCNNode! var sphere2: SCNNode! override func viewDidLoad() { super.viewDidLoad() sceneView = SCNView(frame: self.view.frame) sceneView.scene = SCNScene() self.view.addSubview(sceneView) let tapRecognizer = UITapGestureRecognizer() tapRecognizer.numberOfTapsRequired = 1 tapRecognizer.numberOfTouchesRequired = 1 tapRecognizer.addTarget(self, action: "sceneTapped:") sceneView.gestureRecognizers = [tapRecognizer] let groundGeometry = SCNFloor() groundGeometry.reflectivity = 0 let groundMaterial = SCNMaterial() groundMaterial.diffuse.contents = UIColor.blueColor() groundGeometry.materials = [groundMaterial] ground = SCNNode(geometry: groundGeometry) let camera = SCNCamera() camera.zFar = 10000 self.camera = SCNNode() self.camera.camera = camera self.camera.position = SCNVector3(x: -20, y: 15, z: 20) let constraint = SCNLookAtConstraint(target: ground) constraint.gimbalLockEnabled = true self.camera.constraints = [constraint] let ambientLight = SCNLight() ambientLight.color = UIColor.darkGrayColor() ambientLight.type = SCNLightTypeAmbient self.camera.light = ambientLight let spotLight = SCNLight() spotLight.type = SCNLightTypeSpot spotLight.castsShadow = true spotLight.spotInnerAngle = 70.0 spotLight.spotOuterAngle = 90.0 spotLight.zFar = 500 light = SCNNode() light.light = spotLight light.position = SCNVector3(x: 0, y: 25, z: 25) light.constraints = [constraint] let sphereGeometry = SCNSphere(radius: 1.5) let sphereMaterial = SCNMaterial() sphereMaterial.diffuse.contents = UIColor.greenColor() sphereGeometry.materials = [sphereMaterial] sphere1 = SCNNode(geometry: sphereGeometry) sphere1.position = SCNVector3(x: -15, y: 1.5, z: 0) sceneView.scene?.rootNode.addChildNode(sphere1) sphere2 = SCNNode(geometry: sphereGeometry) sphere2.position = SCNVector3(x: 15, y: 1.5, z: 0) sceneView.scene?.rootNode.addChildNode(sphere2) let buttonGeometry = SCNBox(width: 4, height: 1, length: 4, chamferRadius: 0) let buttonMaterial = SCNMaterial() buttonMaterial.diffuse.contents = UIColor.redColor() buttonGeometry.materials = [buttonMaterial] button = SCNNode(geometry: buttonGeometry) button.position = SCNVector3(x: 8, y: 0.5, z: 0) sceneView.scene?.rootNode.addChildNode(self.camera) sceneView.scene?.rootNode.addChildNode(ground) sceneView.scene?.rootNode.addChildNode(light) sceneView.scene?.rootNode.addChildNode(button) } func handleTap(gestureRecognize: UIGestureRecognizer) { // retrieve the SCNView let scnView = self.view as! SCNView // check what nodes are tapped let p = gestureRecognize.locationInView(scnView) let hitResults = scnView.hitTest(p, options: nil) // check that we clicked on at least one object if hitResults.count > 0 { // retrieved the first clicked object let result: AnyObject! = hitResults[0] // get its material let material = result.node!.geometry!.firstMaterial! // highlight it SCNTransaction.begin() SCNTransaction.setAnimationDuration(0.5) // on completion - unhighlight SCNTransaction.setCompletionBlock { SCNTransaction.begin() SCNTransaction.setAnimationDuration(0.5) material.emission.contents = UIColor.blackColor() SCNTransaction.commit() } material.emission.contents = UIColor.redColor() SCNTransaction.commit() } } func sceneTapped(recognizer: UITapGestureRecognizer) { let location = recognizer.locationInView(sceneView) let hitResults = sceneView.hitTest(location, options: nil) if hitResults.count > 0 { let result = hitResults[0] let node = result.node node.removeFromParentNode() } } override func shouldAutorotate() -> Bool { return true } override func prefersStatusBarHidden() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } }
apache-2.0
5f4055181ad6a1a105260a94b9f0eb50
32.987578
85
0.613304
5.172023
false
false
false
false
mrdepth/EVEUniverse
Neocom/Neocom/Utility/DataLoaders/AssetsData.swift
2
13784
// // AssetsData.swift // Neocom // // Created by Artem Shimanski on 2/5/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import Foundation import EVEAPI import CoreData import Combine import Alamofire import Expressible class AssetsData: ObservableObject { @Published var locations: Result<[LocationGroup], AFError>? @Published var categories: Result<[Category], AFError>? var categoriesPublisher: AnyPublisher<[Category], AFError> { $categories.compactMap{$0}.tryGet().eraseToAnyPublisher() } struct LocationGroup { var location: EVELocation var assets: [Asset] var count: Int { return assets.map{$0.count}.reduce(0, +) } } struct Category: Identifiable { struct AssetType { var typeID: Int32 var typeName: String var locations: [LocationGroup] var count: Int { locations.map{$0.assets.count}.reduce(0, +) } } var categoryName: String var id: Int32 var types: [AssetType] var count: Int { types.map{$0.count}.reduce(0, +) } } struct Asset { var nested: [Asset] var underlyingAsset: ESI.Assets.Element var assetName: String? var typeName: String var groupName: String var categoryName: String var categoryID: Int32 var count: Int { return nested.map{$0.count}.reduce(1, +) } } fileprivate struct PartialResult { var locations: [LocationGroup] = [] var categories: [Category] = [] } private static func getNames(of assets: ESI.Assets, managedObjectContext: NSManagedObjectContext, character: ESI.Characters.CharacterID, corporation: ESI.Corporations.CorporationID?, cache: [Int64: String?]) -> AnyPublisher<[Int64: String?], Never> { return Future<Set<Int64>, Never> { promise in managedObjectContext.perform { let typeIDs = assets.map{Int32($0.typeID)} let namedTypeIDs = typeIDs.isEmpty ? Set() : Set( (try? managedObjectContext.from(SDEInvType.self) .filter((/\SDEInvType.typeID).in(typeIDs) && /\SDEInvType.group?.category?.categoryID == SDECategoryID.ship.rawValue) .select(/\SDEInvType.typeID) .fetch().compactMap{$0}) ?? []) let namedAssetIDs = Set(assets.filter {namedTypeIDs.contains(Int32($0.typeID))}.map{$0.itemID}).subtracting(cache.keys) promise(.success(namedAssetIDs)) } }.flatMap { namedAssetIDs -> AnyPublisher<[Int64: String?], Never> in let names: AnyPublisher<[Int64: String?], Never> if !namedAssetIDs.isEmpty { names = (corporation?.assets().names().post(itemIds: Array(namedAssetIDs)) ?? character.assets().names().post(itemIds: Array(namedAssetIDs))) .map{$0.value} .replaceError(with: []) .map { names in Dictionary(names.map{($0.itemID, $0.name)}, uniquingKeysWith: {a, _ in a}) .merging(namedAssetIDs.map{($0, nil)}, uniquingKeysWith: {a, b in a ?? b}) } .eraseToAnyPublisher() } else { names = Just([:]).eraseToAnyPublisher() } return names.map { names -> [Int64: String?] in cache.merging(names, uniquingKeysWith: {a, b in a ?? b}) }.eraseToAnyPublisher() }.eraseToAnyPublisher() } private static func getLocations(of assets: ESI.Assets, managedObjectContext: NSManagedObjectContext, esi: ESI, cache: [Int64: EVELocation?]) -> AnyPublisher<[Int64: EVELocation?], Never> { let locationIDs = Set(assets.map{$0.locationID}).subtracting(assets.map{$0.itemID}).subtracting(cache.keys) return EVELocation.locations(with: locationIDs, esi: esi, managedObjectContext: managedObjectContext).map { result in result.mapValues{$0 as Optional}.merging(locationIDs.map{($0, nil)}, uniquingKeysWith: {a, b in a ?? b}) }.map { locations -> [Int64: EVELocation?] in cache.merging(locations, uniquingKeysWith: {a, b in a ?? b}) }.eraseToAnyPublisher() } ///Group assets by location private static func regroup(assets: ESI.Assets, names: [Int64: String?], locations: [Int64: EVELocation?], managedObjectContext: NSManagedObjectContext) -> PartialResult { let locationGroup = Dictionary(grouping: assets, by: {$0.locationID}) let items = Dictionary(assets.map{($0.itemID, $0)}, uniquingKeysWith: {a, _ in a}) let typeIDs = Set(assets.map{Int32($0.typeID)}) let invTypes = try? managedObjectContext.from(SDEInvType.self) .filter((/\SDEInvType.typeID).in(typeIDs)) .fetch() let typesMap = Dictionary(invTypes?.map{(Int($0.typeID), $0)} ?? [], uniquingKeysWith: {a, _ in a}) let locationIDs = Set(locationGroup.keys).subtracting(items.keys) var assetIDsMap = [Int64: Asset]() //Process single asset func makeAsset(underlying asset: ESI.Assets.Element) -> Asset { let type = typesMap[asset.typeID] let result = Asset(nested: extract(locationGroup[asset.itemID] ?? []).sorted{$0.typeName < $1.typeName}, underlyingAsset: asset, assetName: names[asset.itemID] ?? nil, typeName: type?.typeName ?? "", groupName: type?.group?.groupName ?? "", categoryName: type?.group?.category?.categoryName ?? "", categoryID: type?.group?.category?.categoryID ?? 0) assetIDsMap[asset.itemID] = result return result } func extract(_ assets: ESI.Assets) -> [Asset] { assets.map { asset -> Asset in makeAsset(underlying: asset) } } func getRootLocation(from asset: ESI.Assets.Element) -> Int64 { return items[asset.locationID].map{getRootLocation(from: $0)} ?? asset.locationID } var unknownLocation = LocationGroup(location: .unknown(0), assets: []) var byLocations = [LocationGroup]() for locationID in locationIDs { let assets = extract(locationGroup[locationID] ?? []) if let location = locations[locationID] ?? nil { byLocations.append(LocationGroup(location: location, assets: assets)) } else { unknownLocation.assets.append(contentsOf: assets) } } for i in byLocations.indices { byLocations[i].assets.sort{$0.typeName < $1.typeName} } byLocations.sort{$0.location.name < $1.location.name} if !unknownLocation.assets.isEmpty { byLocations.append(unknownLocation) } var categories = [String: [Int: Category.AssetType]]() for location in byLocations { var types = [Int: [Asset]]() func process(_ assets: [Asset]) { for asset in assets { types[asset.underlyingAsset.typeID, default: []].append(asset) process(asset.nested) } } process(location.assets) for i in types.values { let typeName = i[0].typeName let categoryName = i[0].categoryName let typeID = i[0].underlyingAsset.typeID categories[categoryName, default: [:]][typeID, default: Category.AssetType(typeID: Int32(typeID), typeName: typeName, locations: [])].locations.append(LocationGroup(location: location.location, assets: i)) } } let byCategories = categories.sorted{$0.key < $1.key}.map { i in Category(categoryName: i.key, id: i.value.first?.value.locations.first?.assets.first?.categoryID ?? 0, types: i.value.values.sorted{$0.typeName < $1.typeName}) } return PartialResult(locations: byLocations, categories: byCategories) } @Published var isLoading = false var progress = Progress(totalUnitCount: 3) private var esi: ESI private var characterID: Int64 private var corporate: Bool private var managedObjectContext: NSManagedObjectContext init(esi: ESI, characterID: Int64, corporate: Bool, managedObjectContext: NSManagedObjectContext) { self.esi = esi self.characterID = characterID self.corporate = corporate self.managedObjectContext = managedObjectContext update(cachePolicy: .useProtocolCachePolicy) } func update(cachePolicy: URLRequest.CachePolicy) { isLoading = true subscriptions.removeAll() let managedObjectContext = self.managedObjectContext let esi = self.esi let characterID = self.characterID self.progress = Progress(totalUnitCount: 3) let character = esi.characters.characterID(Int(characterID)) let progress = self.progress let initialProgress = Progress(totalUnitCount: 100, parent: progress, pendingUnitCount: 1) func getXPages<T>(from response: ESIResponse<T>) -> Range<Int> { guard let header = response.httpHeaders?["x-pages"], let pages = Int(header) else {return 1..<1} return 1..<max(min(pages, 20), 1) } var assetNames = [Int64: String?]() var locations = [Int64: EVELocation?]() func process(assets: ESI.Assets, corporation: ESI.Corporations.CorporationID?) -> AnyPublisher<PartialResult, Never> { let a = AssetsData.getNames(of: assets, managedObjectContext: managedObjectContext, character: character, corporation: corporation, cache: assetNames).map { i -> [Int64: String?] in assetNames = i return i } let b = AssetsData.getLocations(of: assets, managedObjectContext: managedObjectContext, esi: esi, cache: locations).map { i -> [Int64: EVELocation?] in locations = i return i } return Publishers.Zip(a, b) .receive(on: managedObjectContext) .map { (names, locations) in AssetsData.regroup(assets: assets, names: names, locations: locations, managedObjectContext: managedObjectContext) }.eraseToAnyPublisher() } func download(_ pages: Range<Int>, _ corporation: ESI.Corporations.CorporationID?) -> AnyPublisher<ESI.Assets, AFError> { progress.performAsCurrent(withPendingUnitCount: 2, totalUnitCount: Int64(pages.count)) { p in pages.publisher.setFailureType(to: AFError.self) .flatMap { page in p.performAsCurrent(withPendingUnitCount: 1, totalUnitCount: 100) { p in corporation?.assets() .get(page: page, cachePolicy: cachePolicy) { p.completedUnitCount = Int64($0.fractionCompleted * 100) } .map{$0.value.map{$0 as AssetProtocol}} .eraseToAnyPublisher() ?? character.assets() .get(page: page, cachePolicy: cachePolicy) { p.completedUnitCount = Int64($0.fractionCompleted * 100) } .map{$0.value.map{$0 as AssetProtocol}} .eraseToAnyPublisher() } } .eraseToAnyPublisher() } } let loader: AnyPublisher<Result<AssetsData.PartialResult, AFError>, Never> if corporate { loader = character.get().map{esi.corporations.corporationID($0.value.corporationID)} .flatMap { corporation in corporation.assets().get(cachePolicy: cachePolicy) { initialProgress.completedUnitCount = Int64($0.fractionCompleted * 100) } .flatMap { result in Just(result.value).setFailureType(to: AFError.self) .merge(with: download(getXPages(from: result).dropFirst(), corporation)) } .reduce([], +) .flatMap { process(assets: $0, corporation: corporation).setFailureType(to: AFError.self) } }.asResult().eraseToAnyPublisher() } else { loader = character.assets().get(cachePolicy: cachePolicy) { initialProgress.completedUnitCount = Int64($0.fractionCompleted * 100) } .flatMap { result in Just(result.value).setFailureType(to: AFError.self) .merge(with: download(getXPages(from: result).dropFirst(), nil)) }.reduce([], +).flatMap { process(assets: $0, corporation: nil).setFailureType(to: AFError.self) }.asResult().eraseToAnyPublisher() } loader.receive(on: RunLoop.main) .sink { [weak self] result in self?.locations = result.map{$0.locations} self?.categories = result.map{$0.categories} self?.isLoading = false }.store(in: &subscriptions) } var subscriptions = Set<AnyCancellable>() }
lgpl-2.1
8ac685f3da44037e0b721c6486c85a27
43.75
254
0.572517
4.933071
false
false
false
false
tottakai/Thongs
Example/Thongs/ViewController.swift
1
2618
// // ViewController.swift // Thongs_Example // // Created by Tomi Koskinen on 17/10/15. // Copyright © 2015 CocoaPods. All rights reserved. // import UIKit import Thongs class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let titleLabel = UILabel(frame: CGRect(x: 20, y: 44, width: view.bounds.size.width-2*20, height: 40)) let textBox = UITextView(frame: CGRect(x: titleLabel.frame.minX , y: titleLabel.frame.maxY + 20, width: titleLabel.frame.size.width, height: view.bounds.size.height - titleLabel.frame.maxY - 2*20)) view.addSubview(titleLabel) view.addSubview(textBox) // Attributed string to both text boxes created with Thongs let red = Thongs.color(UIColor(red: 231/255, green: 76/255, blue: 60/255, alpha: 1)) let large = Thongs.font(UIFont(name: "Avenir-Black", size: 28)!) let kerning = Thongs.kerning(1.4) let titleFormatter = red <*> large <*> kerning titleLabel.attributedText = titleFormatter(Thongs.string("This thing right here")) // format the first part of Sisqo's Thong song let bodyTextFontStyle1 = Thongs.font(UIFont(name: "Baskerville-SemiBoldItalic", size: 24)!) let bodyTextFontStyle2 = Thongs.font(UIFont(name: "BradleyHandITCTT-Bold", size: 16)!) let formatter1 = bodyTextFontStyle1 <*> Thongs.color(UIColor(red: 46/255, green: 204/255, blue: 113/255, alpha: 1)) let formatter2 = bodyTextFontStyle2 <*> Thongs.color(UIColor(red: 34/255, green: 167/255, blue: 240/255, alpha: 1)) let formatter3 = bodyTextFontStyle1 <*> Thongs.color(UIColor(red: 232/255, green: 126/255, blue: 4/255, alpha: 1)) let formatter4 = bodyTextFontStyle2 <*> Thongs.color(UIColor(red: 191/255, green: 85/255, blue: 236/255, alpha: 1)) let formatter5 = bodyTextFontStyle1 <*> Thongs.color(UIColor(red: 245/255, green: 215/255, blue: 110/255, alpha: 1)) let formattedLine = Thongs.font(UIFont(name: "Courier", size: 16)!) <*> Thongs.color(UIColor(red: 103/255, green: 65/255, blue: 114/255, alpha: 1)) ~~> "Check it out\n" textBox.attributedText = formatter1 ~~> "Is lettin all the ladies know\n" <+> formatter2 ~~> "What guys talk about\n" <+> formatter3 ~~> "You know\n" <+> formatter4 ~~> "The finer things in life\n" <+> formatter5 ~~> "Hahaha\n" <+> formattedLine } }
mit
3e5a0c0d7415aa79b2d69660c12cec3a
51.34
205
0.615208
3.971168
false
false
false
false
Connecthings/sdk-tutorial
ios/ObjectiveC/Zone/3-InApp-Action/Complete/InAppAction/TimeConditions.swift
1
2065
// // TimeConditions.swift // InAppAction // // Created by Connecthings on 14/11/2017. // Copyright © 2017 Connecthings. All rights reserved. // import Foundation import ConnectPlaceActions import ConnectPlaceCommon @objc public class TimeConditions: InAppActionConditionsDefault { @objc let delayBeforeCreation: Double @objc public init(maxTimeBeforeReset: Double, delayBeforeCreation: Double) { self.delayBeforeCreation = delayBeforeCreation super.init(maxTimeBeforeReset: maxTimeBeforeReset) } public override func getApplicationNamespace() -> String { return String(reflecting: TimeConditions.self).split(separator: ".")[0].description } public override func getConditionsKey() -> String { return "inAppActionTimeConditions" } public override func getInAppActionParameterClass() -> String { return "TimeConditionsParameter" } public override func updateInAppActionConditionsParameter(_ conditionsParameter: InAppActionConditionsParameter) { if let strategyParameter = conditionsParameter as? TimeConditionsParameter { let currentTime: Double = CFAbsoluteTimeGetCurrent() if strategyParameter.lastDetectionTime + 3 < currentTime { GlobalLogger.shared.debug("delay before creating " , delayBeforeCreation) strategyParameter.timeToShowAlert = currentTime + delayBeforeCreation } strategyParameter.lastDetectionTime = currentTime + 0 } super.updateInAppActionConditionsParameter(conditionsParameter) } public override func isConditionValid(_ conditionsParameter: InAppActionConditionsParameter) -> Bool { if let strategyParameter = conditionsParameter as? TimeConditionsParameter { GlobalLogger.shared.debug("delay remaining " , ( CFAbsoluteTimeGetCurrent() - strategyParameter.timeToShowAlert)) return strategyParameter.timeToShowAlert < CFAbsoluteTimeGetCurrent() } return true } }
apache-2.0
6c72596e5bf2a66a6b8c0d555a887b06
38.692308
125
0.717054
5.608696
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureOpenBanking/Sources/FeatureOpenBankingUI/View/BankView.UI.swift
1
5825
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainUI import FeatureOpenBankingDomain import UIComponentsKit extension BankState.UI { static func communicating(to institution: String) -> Self { Self( info: .init( media: .blockchainLogo, overlay: .init(progress: true), title: Localization.Bank.Communicating.title.interpolating(institution), subtitle: Localization.Bank.Communicating.subtitle ), action: [.retry(label: Localization.Bank.Action.retry, action: .retry)] ) } static func waiting(for institution: String) -> Self { Self( info: .init( media: .blockchainLogo, overlay: .init(progress: true), title: Localization.Bank.Waiting.title.interpolating(institution), subtitle: Localization.Bank.Waiting.subtitle ), action: [.retry(label: Localization.Bank.Action.retry, action: .retry)] ) } static let updatingWallet: Self = .init( info: .init( media: .blockchainLogo, overlay: .init(progress: true), title: Localization.Bank.Updating.title, subtitle: Localization.Bank.Updating.subtitle ), action: .none ) static func linked(institution: String) -> Self { Self( info: .init( media: .bankIcon, overlay: .init(media: .success), title: Localization.Bank.Linked.title, subtitle: Localization.Bank.Linked.subtitle.interpolating(institution) ), action: [.next] ) } private static var formatter = ( iso8601: ISO8601DateFormatter(), date: with(DateFormatter()) { formatter in formatter.dateStyle = .medium formatter.timeStyle = .none } ) static func deposit(success payment: OpenBanking.Payment.Details, in environment: OpenBankingEnvironment) -> Self { guard let fiat = environment.fiatCurrencyFormatter.displayString( amountMinor: payment.amountMinor, currency: payment.amount.symbol ) else { return .errorMessage(Localization.Bank.Payment.error.interpolating(payment.amount.symbol)) } var formatted = ( amount: fiat, currency: payment.amount.symbol, date: "" ) if let date = formatter.iso8601.date(from: payment.insertedAt) { formatted.date = formatter.date.string(from: date) } let resource = environment.fiatCurrencyFormatter.displayImage(currency: payment.amount.symbol) let media: UIComponentsKit.Media switch resource { case .remote(url: let url): media = .image(at: url) default: media = .bankIcon } return Self( info: .init( media: media, overlay: .init(progress: true), title: Localization.Bank.Payment.title .interpolating(formatted.amount), subtitle: Localization.Bank.Payment.subtitle .interpolating(formatted.amount, formatted.currency, formatted.date) ), action: [.ok] ) } static func buy(pending order: OpenBanking.Order, in environment: OpenBankingEnvironment) -> Self { guard let crypto = environment.cryptoCurrencyFormatter.displayString( amountMinor: order.outputQuantity, currency: order.outputCurrency ) else { return .errorMessage(Localization.Error.title) } let resource = environment.cryptoCurrencyFormatter.displayImage(currency: order.outputCurrency) let media: UIComponentsKit.Media switch resource { case .remote(url: let url): media = .image(at: url) default: media = .blockchainLogo } return Self( info: .init( media: media, overlay: .init(progress: true), title: Localization.Bank.Buying.title .interpolating(crypto), subtitle: Localization.Bank.Buying.subtitle ), action: [.ok] ) } static func buy(finished order: OpenBanking.Order, in environment: OpenBankingEnvironment) -> Self { guard let crypto = environment.cryptoCurrencyFormatter.displayString( amountMinor: order.outputQuantity, currency: order.outputCurrency ) else { return .errorMessage(Localization.Error.title) } let resource = environment.cryptoCurrencyFormatter.displayImage(currency: order.outputCurrency) let media: UIComponentsKit.Media switch resource { case .remote(url: let url): media = .image(at: url) default: media = .blockchainLogo } return Self( info: .init( media: media, overlay: .init(media: .success), title: Localization.Bank.Buy.title .interpolating(crypto), subtitle: Localization.Bank.Buy.subtitle ), action: [.ok] ) } static func pending() -> Self { Self( info: .init( media: .blockchainLogo, overlay: .init(progress: true), title: Localization.Bank.Pending.title, subtitle: Localization.Bank.Pending.subtitle ), action: [.ok] ) } }
lgpl-3.0
41c53ce625349448ad6c5add5276baf7
31.536313
119
0.559409
5.095363
false
false
false
false
KevinCoble/AIToolbox
Package/Linux_Accelerate_Wrapper.swift
1
7395
// // Linux_Accelerate_Wrapper.swift // AIToolbox // // Created by Kevin Coble on 3/20/17. // Copyright © 2017 Kevin Coble. All rights reserved. // // This file emulates the Accelerate routines used by AIToolbox. // It would be better if vector routines were used in place #if os(Linux) typealias vDSP_Length = UInt typealias vDSP_Stride = Int // Double-precision real vector-scalar multiply func vDSP_vsmulD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Double>, _ __C: UnsafeMutablePointer<Double>, _ __IC: vDSP_Stride, _ __N: vDSP_Length) { var A_Offset = 0 var C_Offset = 0 for _ in 0..<__N { __C[C_Offset] = __A[A_Offset] * __B.pointee A_Offset += __IA C_Offset += __IC } } // Vector multiply and add; double precision. func vDSP_vmaD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Double>, _ __IB: vDSP_Stride, _ __C: UnsafePointer<Double>, _ __IC: vDSP_Stride, _ __D: UnsafeMutablePointer<Double>, _ __ID: vDSP_Stride, _ __N: vDSP_Length){ var A_Offset = 0 var B_Offset = 0 var C_Offset = 0 var D_Offset = 0 for _ in 0..<__N { __D[D_Offset] = __A[A_Offset] * __B[B_Offset] + __C[C_Offset] A_Offset += __IA B_Offset += __IB C_Offset += __IC D_Offset += __ID } } // Double-precision real vector-scalar multiply and vector add func vDSP_vsmaD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Double>, _ __C: UnsafePointer<Double>, _ __IC: vDSP_Stride, _ __D: UnsafeMutablePointer<Double>, _ __ID: vDSP_Stride, _ __N: vDSP_Length){ var A_Offset = 0 var C_Offset = 0 var D_Offset = 0 for _ in 0..<__N { __D[D_Offset] = __A[A_Offset] * __B.pointee + __C[C_Offset] A_Offset += __IA C_Offset += __IC D_Offset += __ID } } // Adds two vectors; double precision func vDSP_vaddD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Double>, _ __IB: vDSP_Stride, _ __C: UnsafeMutablePointer<Double>, _ __IC: vDSP_Stride, _ __N: vDSP_Length) { var A_Offset = 0 var B_Offset = 0 var C_Offset = 0 for _ in 0..<__N { __C[C_Offset] = __A[A_Offset] + __B[B_Offset] A_Offset += __IA B_Offset += __IB C_Offset += __IC } } // Vector subtract; double precision func vDSP_vsubD(_ __B: UnsafePointer<Double>, _ __IB: vDSP_Stride, _ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __C: UnsafeMutablePointer<Double>, _ __IC: vDSP_Stride, _ __N: vDSP_Length) { var A_Offset = 0 var B_Offset = 0 var C_Offset = 0 for _ in 0..<__N { __C[C_Offset] = __A[A_Offset] - __B[B_Offset] A_Offset += __IA B_Offset += __IB C_Offset += __IC } } // Vector multiplication; double precision func vDSP_vmulD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Double>, _ __IB: vDSP_Stride, _ __C: UnsafeMutablePointer<Double>, _ __IC: vDSP_Stride, _ __N: vDSP_Length) { var A_Offset = 0 var B_Offset = 0 var C_Offset = 0 for _ in 0..<__N { __C[C_Offset] = __A[A_Offset] * __B[B_Offset] A_Offset += __IA B_Offset += __IB C_Offset += __IC } } // Divide scalar by vector; double precision. func vDSP_svdivD(_ __A: UnsafePointer<Double>, _ __B: UnsafePointer<Double>, _ __IB: vDSP_Stride, _ __C: UnsafeMutablePointer<Double>, _ __IC: vDSP_Stride, _ __N: vDSP_Length) { var B_Offset = 0 var C_Offset = 0 for _ in 0..<__N { __C[C_Offset] = __A.pointee / __B[B_Offset] B_Offset += __IB C_Offset += __IC } } // Vector-scalar add; double precision. func vDSP_vsaddD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Double>, _ __C: UnsafeMutablePointer<Double>, _ __IC: vDSP_Stride, _ __N: vDSP_Length) { var A_Offset = 0 var C_Offset = 0 for _ in 0..<__N { __C[C_Offset] = __A[A_Offset] + __B.pointee A_Offset += __IA C_Offset += __IC } } // Computes the squared values of vector A and leaves the result in vector C; double precision. func vDSP_vsqD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __C: UnsafeMutablePointer<Double>, _ __IC: vDSP_Stride, _ __N: vDSP_Length) { var A_Offset = 0 var C_Offset = 0 for _ in 0..<__N { __C[C_Offset] = __A[A_Offset] * __A[A_Offset] A_Offset += __IA C_Offset += __IC } } // Computes the dot or scalar product of vectors A and B and leaves the result in scalar *C; double precision func vDSP_dotprD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Double>, _ __IB: vDSP_Stride, _ __C: UnsafeMutablePointer<Double>, _ __N: vDSP_Length) { var A_Offset = 0 var B_Offset = 0 var sum = 0.0 for _ in 0..<__N { sum += __A[A_Offset] * __B[B_Offset] A_Offset += __IA B_Offset += __IB } __C.pointee = sum } // Square of the Euclidean distance between two points in N-dimensional space, each defined by a real vector; double precision func vDSP_distancesqD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Double>, _ __IB: vDSP_Stride, _ __C: UnsafeMutablePointer<Double>, _ __N: vDSP_Length) { var A_Offset = 0 var B_Offset = 0 var sum = 0.0 for _ in 0..<__N { let diff = __A[A_Offset] - __B[B_Offset] sum += diff * diff A_Offset += __IA B_Offset += __IB } __C.pointee = sum } // Performs an out-of-place multiplication of two matrices; double precision func vDSP_mmulD(_ __A: UnsafePointer<Double>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Double>, _ __IB: vDSP_Stride, _ __C: UnsafeMutablePointer<Double>, _ __IC: vDSP_Stride, _ __M: vDSP_Length, _ __N: vDSP_Length, _ __P: vDSP_Length) { var A_Offset = 0 for m in 0..<__M { var C_Offset = Int(m * __N) * __IC for n in 0..<__N { __C[C_Offset] = 0.0 A_Offset = Int(m * __P) * __IA for p in 0..<__P { __C[C_Offset] += __A[A_Offset] * __B[Int((p * __N) + n) * __IB] A_Offset += __IA } C_Offset += __IC } } } #endif
apache-2.0
88b9f28057b6aef4bd107fc172f96ba5
28.814516
177
0.467812
3.649556
false
false
false
false
minimoog/filters
filters/ImageView.swift
1
3048
// // ImageView.swift // CoreImageHelpers // // Created by Simon Gladman on 09/01/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // import GLKit import UIKit import MetalKit import QuartzCore /// `MetalImageView` extends an `MTKView` and exposes an `image` property of type `CIImage` to /// simplify Metal based rendering of Core Image filters. class MetalImageView: MTKView { let colorSpace = CGColorSpaceCreateDeviceRGB() lazy var commandQueue: MTLCommandQueue = { [unowned self] in return self.device!.makeCommandQueue() }() lazy var ciContext: CIContext = { [unowned self] in return CIContext(mtlDevice: self.device!) }() override init(frame frameRect: CGRect, device: MTLDevice?) { super.init(frame: frameRect, device: device ?? MTLCreateSystemDefaultDevice()) if super.device == nil { fatalError("Device doesn't support Metal") } isPaused = true enableSetNeedsDisplay = false framebufferOnly = false } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// The image to display var image: CIImage? { didSet { draw() } } override func draw(_ rect: CGRect) { guard let image = image, let targetTexture = currentDrawable?.texture else { return } let commandBuffer = commandQueue.makeCommandBuffer() let bounds = CGRect(origin: CGPoint.zero, size: drawableSize) let originX = image.extent.origin.x let originY = image.extent.origin.y let scaleX = drawableSize.width / image.extent.width let scaleY = drawableSize.height / image.extent.height let scale = min(scaleX, scaleY) let scaledImage = image .applying(CGAffineTransform(translationX: -originX, y: -originY)) .applying(CGAffineTransform(scaleX: scale, y: scale)) ciContext.render(scaledImage, to: targetTexture, commandBuffer: commandBuffer, bounds: bounds, colorSpace: colorSpace) commandBuffer.present(currentDrawable!) commandBuffer.commit() } } extension CGRect { func aspectFitInRect(target: CGRect) -> CGRect { let scale: CGFloat = { let scale = target.width / self.width return self.height * scale <= target.height ? scale : target.height / self.height }() let width = self.width * scale let height = self.height * scale let x = target.midX - width / 2 let y = target.midY - height / 2 return CGRect(x: x, y: y, width: width, height: height) } }
mit
492fc9025de592d01345c6209196a120
26.205357
94
0.560223
5.121008
false
false
false
false
dcaunt/ios-snapshot-test-case
FBSnapshotTestCase/SwiftSupport.swift
73
2966
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ public extension FBSnapshotTestCase { public func FBSnapshotVerifyView(view: UIView, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), file: String = __FILE__, line: UInt = __LINE__) { let envReferenceImageDirectory = NSProcessInfo.processInfo().environment["FB_REFERENCE_IMAGE_DIR"] as? String var error: NSError? if let envReferenceImageDirectory = envReferenceImageDirectory { for suffix in suffixes { let referenceImagesDirectory = "\(envReferenceImageDirectory)\(suffix)" let comparisonSuccess = compareSnapshotOfView(view, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance: 0, error: &error) if comparisonSuccess || recordMode { break } assert(comparisonSuccess, message: "Snapshot comparison failed: \(error)", file: file, line: line) assert(recordMode == false, message: "Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!", file: file, line: line) } } else { assert(false, message: "Missing value for referenceImagesDirectory - Set FB_REFERENCE_IMAGE_DIR as Environment variable in your scheme.", file: file, line: line) } } public func FBSnapshotVerifyLayer(layer: CALayer, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), file: String = __FILE__, line: UInt = __LINE__) { let envReferenceImageDirectory = NSProcessInfo.processInfo().environment["FB_REFERENCE_IMAGE_DIR"] as? String var error: NSError? var comparisonSuccess = false if let envReferenceImageDirectory = envReferenceImageDirectory { for suffix in suffixes { let referenceImagesDirectory = "\(envReferenceImageDirectory)\(suffix)" comparisonSuccess = compareSnapshotOfLayer(layer, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance: 0, error: &error) if comparisonSuccess || recordMode { break } assert(comparisonSuccess, message: "Snapshot comparison failed: \(error)", file: file, line: line) assert(recordMode == false, message: "Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!", file: file, line: line) } } else { XCTFail("Missing value for referenceImagesDirectory - Set FB_REFERENCE_IMAGE_DIR as Environment variable in your scheme.") } } func assert(assertion: Bool, message: String, file: String, line: UInt) { if !assertion { XCTFail(message, file: file, line: line) } } }
bsd-3-clause
10ca713d69b923ac7e71a0a2e3e51c3f
50.137931
188
0.716453
5.044218
false
true
false
false
rlacaze/LAB-iOS-T9-L210
LOG210-App-iOS-2.0/cueil_validate.swift
1
5369
// // cueil_validate.swift // LOG210-App-iOS-2.0 // // Created by Romain LACAZE on 2016-03-09. // Copyright © 2016 Romain LACAZE. All rights reserved. // import UIKit class cueil_validate: UIViewController { var idUser: String? var id: Int? var dataTitle: [String] = [] var dataIdExmplaireLivre: [String] = [] var studentName: [String] = [] var etat: [String] = [] var dataIdReservation: [String] = [] @IBOutlet weak var reservedBy: UILabel! @IBOutlet weak var idLivre: UILabel! @IBOutlet weak var titreLivre: UILabel! @IBOutlet weak var idReservationLabel: UILabel! @IBOutlet weak var etatLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //titre nav bar self.title = "Cueillir" titreLivre.text = self.dataTitle[id!] reservedBy.text = "Réservé par \(self.studentName[id!])" idLivre.text = "Numéro d'enregistrement du livre \(cleanData(dataIdExmplaireLivre[id!]))" idReservationLabel.text = "Numéro de réservation \(cleanData(dataIdReservation[id!]))" etatLabel.text = "Livre dans un état \(typeEtatString(cleanData(etat[id!])))" print("etat: \(etat[id!])") print("idReservation: \(dataIdReservation[id!])") } func typeEtatString(id: String) -> String { var result: String if (id == "1") { result = "comme neuf" } else { if (id == "2") { result = "correct" } else { result = "usagé" } } return result } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func cleanData(databrut: String) -> String { var dataclean: String dataclean = databrut.stringByReplacingOccurrencesOfString(":", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) dataclean = dataclean.stringByReplacingOccurrencesOfString(" ", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) dataclean = dataclean.stringByReplacingOccurrencesOfString(",", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) dataclean = dataclean.stringByReplacingOccurrencesOfString("{", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) dataclean = dataclean.stringByReplacingOccurrencesOfString("}", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) dataclean = dataclean.stringByReplacingOccurrencesOfString("]", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) return dataclean } @IBAction func acceptButton(sender: AnyObject) { checkingApi("Post_ValiderExemplaire/?idReservation=\(cleanData(dataIdReservation[id!]))") let finalGestionnaire = storyboard!.instantiateViewControllerWithIdentifier("finalGestionnaireViewID") as! finalGestionnaireView finalGestionnaire.fonction = "cueillette" finalGestionnaire.statut = "validé" finalGestionnaire.titre = self.dataTitle[id!] self.navigationController?.pushViewController(finalGestionnaire, animated: true) } @IBAction func cancelButton(sender: AnyObject) { checkingApi("Post_RefuserExemplaire/?IdReservation=\(cleanData(dataIdReservation[id!]))") let finalGestionnaire = storyboard!.instantiateViewControllerWithIdentifier("finalGestionnaireViewID") as! finalGestionnaireView finalGestionnaire.fonction = "cueillette" finalGestionnaire.statut = "refusé" finalGestionnaire.titre = self.dataTitle[id!] self.navigationController?.pushViewController(finalGestionnaire, animated: true) } func checkingApi(param: String) -> NSString{ var result: NSString = "" let headers = [ "cache-control": "no-cache", "postman-token": "6b9b9816-6dae-aade-504a-9545ec1baef2" ] //idUser = idUser!.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) let url: NSURL = NSURL(string: "http://livreechangerest20160318115916.azurewebsites.net/api/tbl_exemplaireLivre/\(param)")! print(url) let request:NSMutableURLRequest = NSMutableURLRequest(URL:url) request.HTTPMethod = "POST" request.allHTTPHeaderFields = headers let session = NSURLSession.sharedSession() let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { //let httpResponse = response as? NSHTTPURLResponse let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)! print("strData: \(strData)") result = strData } }) dataTask.resume() sleep(1) return result } }
gpl-3.0
caa1f9d6fd1283b535516c31e3fc2000
37.285714
146
0.634074
4.871818
false
false
false
false
AugustRush/Stellar
StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/AnimationSequence.swift
2
3406
//Copyright (c) 2016 // //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 protocol AnimationSequenceDelegate: class { func animationSequenceDidComplete(_ sequence: AnimationSequence); } internal class AnimationSequence: NSObject, UIDynamicAnimatorDelegate { var steps: [AnimationStep] = Array() weak var view: DriveAnimateBehaviors! weak var delegate: AnimationSequenceDelegate? var isRuning = false lazy var animator: UIDynamicAnimator = { let animator = UIDynamicAnimator() animator.delegate = self return animator }() //MARK: init method init(object: DriveAnimateBehaviors) { self.view = object } //MARK: internal method func addStep(_ step: AnimationStep) { steps.append(step) } func last() -> AnimationStep? { return steps.last } func start() { if !isRuning { isRuning = true excuteFirstStepIfExist() } } func removeAllSteps() { steps.removeAll() } fileprivate func excuteFirstStepIfExist() { if self.view == nil { return } let step = steps.first if let step = step { //if step has no animation types it must be the last temple step if step.types.count == 0 { steps.removeFirst() popFirstStepIfExsist() return } for type in step.types { let behavior = view.behavior(forType: type, step: step) animator.addBehavior(behavior) } } else { popFirstStepIfExsist() } } fileprivate func popFirstStepIfExsist() { if !steps.isEmpty { let step = steps.first! //excute completion step.completion?() steps.removeFirst() } else { // all steps has completion self.delegate?.animationSequenceDidComplete(self) } } //MARK: UIDynamicAnimatorDelegate methods func dynamicAnimatorDidPause(_ animator: UIDynamicAnimator) { animator.removeAllBehaviors() popFirstStepIfExsist() excuteFirstStepIfExist() } func dynamicAnimatorWillResume(_ animator: UIDynamicAnimator) { } }
mit
4e10d627b76b7e64e2c9a7541adbebfd
33.06
462
0.632707
5.192073
false
false
false
false
cloudant/swift-cloudant
Tests/SwiftCloudantTests/ReadAttachmentTests.swift
1
3635
// // ReadAttachmentTests.swift // SwiftCloudant // // Created by Rhys Short on 02/06/2016. // Copyright © 2016 IBM. 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 import XCTest @testable import SwiftCloudant class ReadAttachmentTests: XCTestCase { static var allTests = { return [ ("testReadAttachment", testReadAttachment), ("testReadAttachmentProperties", testReadAttachmentProperties)] }() var dbName: String? = nil var client: CouchDBClient? = nil let docId: String = "PutAttachmentTests" var revId: String? let attachment = "This is my awesome essay attachment for my document" let attachmentName = "myAwesomeAttachment" override func setUp() { super.setUp() dbName = generateDBName() client = CouchDBClient(url: URL(string: url)!, username: username, password: password) createDatabase(databaseName: dbName!, client: client!) let createDoc = PutDocumentOperation(id: docId, body: createTestDocuments(count: 1).first!, databaseName: dbName!) {[weak self] (response, info, error) in self?.revId = response?["rev"] as? String } client?.add(operation: createDoc).waitUntilFinished() let put = PutAttachmentOperation(name: attachmentName, contentType: "text/plain", data: attachment.data(using: String.Encoding.utf8, allowLossyConversion: false)!, documentID: docId, revision: revId!, databaseName: dbName! ) {[weak self] (response, info, error) in self?.revId = response?["rev"] as? String } client?.add(operation: put).waitUntilFinished() } override func tearDown() { deleteDatabase(databaseName: dbName!, client: client!) super.tearDown() } func testReadAttachment() { let expectation = self.expectation(description: "read attachment") let read = ReadAttachmentOperation(name: attachmentName, documentID: docId, databaseName: dbName!) {[weak self] (data, info, error) in XCTAssertNil(error) XCTAssertNotNil(info) if let info = info { XCTAssert(info.statusCode / 100 == 2) } XCTAssertNotNil(data) if let data = data { let attxt = String(data: data, encoding: .utf8) XCTAssertEqual(self?.attachment, attxt) } expectation.fulfill() } client?.add(operation: read) self.waitForExpectations(timeout: 10.0, handler: nil) } func testReadAttachmentProperties() { let read = ReadAttachmentOperation(name: attachmentName, documentID: docId, revision: revId, databaseName: dbName!) XCTAssert(read.validate()) XCTAssertEqual("GET", read.method) XCTAssertEqual("/\(dbName!)/\(docId)/\(attachmentName)", read.endpoint) XCTAssertEqual(["rev": revId!], read.parameters) XCTAssertNil(read.data) } }
apache-2.0
38964dae1ac8e4c39e70e5c8a528f151
36.854167
171
0.636489
4.701164
false
true
false
false
ZoranPandovski/al-go-rithms
math/armstrong_number/Swift/ArmstrongNumber.swift
1
702
import Foundation func checkArmstrongNumber(_ num: Int) -> Bool { var sum = 0 var tempNum = num var reminder = 0 let digits = String(num).count while tempNum != 0 { reminder = tempNum % 10 sum = sum + Int(pow(Double(reminder), Double(digits))) tempNum /= 10 if sum > num { break } } if sum == num { return true } return false } print("Pick a number to check: ", terminator: "") let input = readLine() print() if let input = input { if let num = Int(input) { let result = checkArmstrongNumber(num) let text = result ? "is" : "is not" print("\(input) \(text) an Armstrong Number") } else { print("Please enter a number") } } else { print("Please enter a value") }
cc0-1.0
52cf638e0f7ed459b0bbc6fb3e843318
18.5
56
0.633903
2.94958
false
false
false
false
Polidea/RxBluetoothKit
Tests/Autogenerated/_PeripheralManager.generated.swift
1
18210
import Foundation import CoreBluetooth @testable import RxBluetoothKit import RxSwift /// _PeripheralManager is a class implementing ReactiveX API which wraps all the Core Bluetooth _Peripheral's functions, that allow to /// advertise, to publish L2CAP channels and more. /// You can start using this class by adding services and starting advertising. /// Before calling any public `_PeripheralManager`'s functions you should make sure that Bluetooth is turned on and powered on. It can be done /// by `observeStateWithInitialValue()`, observing it's value and then chaining it with `add(_:)` and `startAdvertising(_:)`: /// ``` /// let disposable = centralManager.observeStateWithInitialValue() /// .filter { $0 == .poweredOn } /// .take(1) /// .flatMap { centralManager.add(myService) } /// .flatMap { centralManager.startAdvertising(myAdvertisementData) } /// ``` /// As a result, your peripheral will start advertising. To stop advertising simply dispose it: /// ``` /// disposable.dispose() /// ``` class _PeripheralManager: _ManagerType { /// Implementation of CBPeripheralManagerMock let manager: CBPeripheralManagerMock let delegateWrapper: CBPeripheralManagerDelegateWrapperMock /// Lock for checking advertising state private let advertisingLock = NSLock() /// Is there ongoing advertising var isAdvertisingOngoing = false var restoredAdvertisementData: RestoredAdvertisementData? // MARK: Initialization /// Creates new `_PeripheralManager` /// - parameter peripheralManager: `CBPeripheralManagerMock` instance which is used to perform all of the necessary operations /// - parameter delegateWrapper: Wrapper on CoreBluetooth's peripheral manager callbacks. init(peripheralManager: CBPeripheralManagerMock, delegateWrapper: CBPeripheralManagerDelegateWrapperMock) { self.manager = peripheralManager self.delegateWrapper = delegateWrapper peripheralManager.delegate = delegateWrapper } /// Creates new `_PeripheralManager` instance. By default all operations and events are executed and received on main thread. /// - warning: If you pass background queue to the method make sure to observe results on main thread for UI related code. /// - parameter queue: Queue on which bluetooth callbacks are received. By default main thread is used. /// - parameter options: An optional dictionary containing initialization options for a peripheral manager. /// For more info about it please refer to [_Peripheral Manager initialization options](https://developer.apple.com/documentation/corebluetooth/cbperipheralmanager/peripheral_manager_initialization_options) /// - parameter cbPeripheralManager: Optional instance of `CBPeripheralManagerMock` to be used as a `manager`. If you /// skip this parameter, there will be created an instance of `CBPeripheralManagerMock` using given queue and options. convenience init(queue: DispatchQueue = .main, options: [String: AnyObject]? = nil, cbPeripheralManager: CBPeripheralManagerMock? = nil) { let delegateWrapper = CBPeripheralManagerDelegateWrapperMock() #if os(iOS) || os(macOS) let peripheralManager = cbPeripheralManager ?? CBPeripheralManagerMock(delegate: delegateWrapper, queue: queue, options: options) #else let peripheralManager = CBPeripheralManagerMock() peripheralManager.delegate = delegateWrapper #endif self.init(peripheralManager: peripheralManager, delegateWrapper: delegateWrapper) } /// Returns the app’s authorization status for sharing data while in the background state. /// Wrapper of `CBPeripheralManagerMock.authorizationStatus()` method. static var authorizationStatus: CBPeripheralManagerAuthorizationStatus { return CBPeripheralManagerMock.authorizationStatus() } // MARK: State var state: BluetoothState { return BluetoothState(rawValue: manager.state.rawValue) ?? .unknown } func observeState() -> Observable<BluetoothState> { return self.delegateWrapper.didUpdateState.asObservable() } func observeStateWithInitialValue() -> Observable<BluetoothState> { return Observable.deferred { [weak self] in guard let self = self else { RxBluetoothKitLog.w("observeState - _PeripheralManager deallocated") return .never() } return self.delegateWrapper.didUpdateState.asObservable() .startWith(self.state) } } // MARK: Advertising /// Starts peripheral advertising on subscription. It create inifinite observable /// which emits only one next value, of enum type `StartAdvertisingResult`, just /// after advertising start succeeds. /// For more info of what specific `StartAdvertisingResult` enum cases means please /// refer to ``StartAdvertisingResult` documentation. /// /// There can be only one ongoing advertising (CoreBluetooth limit). /// It will return `advertisingInProgress` error if this method is called when /// it is already advertising. /// /// Advertising is automatically stopped just after disposing of the subscription. /// /// It can return `_BluetoothError.advertisingStartFailed` error, when start advertisement failed /// /// - parameter advertisementData: Services of peripherals to search for. Nil value will accept all peripherals. /// - returns: Infinite observable which emit `StartAdvertisingResult` when advertisement started. /// /// Observable can ends with following errors: /// * `_BluetoothError.advertisingInProgress` /// * `_BluetoothError.advertisingStartFailed` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func startAdvertising(_ advertisementData: [String: Any]?) -> Observable<StartAdvertisingResult> { let observable: Observable<StartAdvertisingResult> = Observable.create { [weak self] observer in guard let strongSelf = self else { observer.onError(_BluetoothError.destroyed) return Disposables.create() } strongSelf.advertisingLock.lock(); defer { strongSelf.advertisingLock.unlock() } if strongSelf.isAdvertisingOngoing { observer.onError(_BluetoothError.advertisingInProgress) return Disposables.create() } strongSelf.isAdvertisingOngoing = true var disposable: Disposable? if strongSelf.manager.isAdvertising { observer.onNext(.attachedToExternalAdvertising(strongSelf.restoredAdvertisementData)) strongSelf.restoredAdvertisementData = nil } else { disposable = strongSelf.delegateWrapper.didStartAdvertising .take(1) .map { error in if let error = error { throw _BluetoothError.advertisingStartFailed(error) } return .started } .subscribe(onNext: { observer.onNext($0) }, onError: { observer.onError($0)}) strongSelf.manager.startAdvertising(advertisementData) } return Disposables.create { [weak self] in guard let strongSelf = self else { return } disposable?.dispose() strongSelf.manager.stopAdvertising() do { strongSelf.advertisingLock.lock(); defer { strongSelf.advertisingLock.unlock() } strongSelf.isAdvertisingOngoing = false } } } return ensure(.poweredOn, observable: observable) } // MARK: Services /// Function that triggers `CBPeripheralManagerMock.add(_:)` and waits for /// delegate `CBPeripheralManagerDelegate.peripheralManager(_:didAdd:error:)` result. /// If it receives a non nil in the result, it will emit `_BluetoothError.addingServiceFailed` error. /// Add method is called after subscription to `Observable` is made. /// - Parameter service: `_Characteristic` to read value from /// - Returns: `Single` which emits `next` with given characteristic when value is ready to read. /// /// Observable can ends with following errors: /// * `_BluetoothError.addingServiceFailed` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func add(_ service: CBMutableService) -> Single<CBServiceMock> { let observable = delegateWrapper .didAddService .filter { $0.0.uuid == service.uuid } .take(1) .map { (cbService, error) -> (CBServiceMock) in if let error = error { throw _BluetoothError.addingServiceFailed(cbService, error) } return cbService } return ensureValidStateAndCallIfSucceeded(for: observable) { [weak self] in self?.manager.add(service) }.asSingle() } /// Wrapper for `CBPeripheralManagerMock.remove(_:)` method func remove(_ service: CBMutableService) { manager.remove(service) } /// Wrapper for `CBPeripheralManagerMock.removeAllServices()` method func removeAllServices() { manager.removeAllServices() } // MARK: Read & Write /// Continuous observer for `CBPeripheralManagerDelegate.peripheralManager(_:didReceiveRead:)` results /// - returns: Observable that emits `next` event whenever didReceiveRead occurs. /// /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeDidReceiveRead() -> Observable<CBATTRequestMock> { return ensure(.poweredOn, observable: delegateWrapper.didReceiveRead) } /// Continuous observer for `CBPeripheralManagerDelegate.peripheralManager(_:didReceiveWrite:)` results /// - returns: Observable that emits `next` event whenever didReceiveWrite occurs. /// /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeDidReceiveWrite() -> Observable<[CBATTRequestMock]> { return ensure(.poweredOn, observable: delegateWrapper.didReceiveWrite) } /// Wrapper for `CBPeripheralManagerMock.respond(to:withResult:)` method func respond(to request: CBATTRequestMock, withResult result: CBATTError.Code) { manager.respond(to: request, withResult: result) } // MARK: Updating value /// Wrapper for `CBPeripheralManagerMock.updateValue(_:for:onSubscribedCentrals:)` method func updateValue( _ value: Data, for characteristic: CBMutableCharacteristic, onSubscribedCentrals centrals: [CBCentralMock]?) -> Bool { return manager.updateValue(value, for: characteristic, onSubscribedCentrals: centrals) } /// Continuous observer for `CBPeripheralManagerDelegate.peripheralManagerIsReady(toUpdateSubscribers:)` results /// - returns: Observable that emits `next` event whenever isReadyToUpdateSubscribers occurs. /// /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeIsReadyToUpdateSubscribers() -> Observable<Void> { return ensure(.poweredOn, observable: delegateWrapper.isReady) } // MARK: Subscribing /// Continuous observer for `CBPeripheralManagerDelegate.peripheralManager(_:central:didSubscribeTo:)` results /// - returns: Observable that emits `next` event whenever didSubscribeTo occurs. /// /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeOnSubscribe() -> Observable<(CBCentralMock, CBCharacteristicMock)> { return ensure(.poweredOn, observable: delegateWrapper.didSubscribeTo) } /// Continuous observer for `CBPeripheralManagerDelegate.peripheralManager(_:central:didUnsubscribeFrom:)` results /// - returns: Observable that emits `next` event whenever didUnsubscribeFrom occurs. /// /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeOnUnsubscribe() -> Observable<(CBCentralMock, CBCharacteristicMock)> { return ensure(.poweredOn, observable: delegateWrapper.didUnsubscribeFrom) } // MARK: L2CAP #if os(iOS) || os(tvOS) || os(watchOS) /// Starts publishing L2CAP channel on a subscription. It creates an infinite observable /// which emits only one next value, of `CBL2CAPPSM` type, just /// after L2CAP channel has been published. /// /// Channel is automatically unpublished just after disposing of the subscription. /// /// It can return `publishingL2CAPChannelFailed` error when publishing channel failed /// /// - parameter encryptionRequired: Publishing channel with or without encryption. /// - returns: Infinite observable which emit `CBL2CAPPSM` when channel published. /// /// Observable can ends with following errors: /// * `_BluetoothError.publishingL2CAPChannelFailed` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` @available(iOS 11, tvOS 11, watchOS 4, *) func publishL2CAPChannel(withEncryption encryptionRequired: Bool) -> Observable<CBL2CAPPSM> { let observable: Observable<CBL2CAPPSM> = Observable.create { [weak self] observer in guard let strongSelf = self else { observer.onError(_BluetoothError.destroyed) return Disposables.create() } var result: CBL2CAPPSM? let disposable = strongSelf.delegateWrapper.didPublishL2CAPChannel .take(1) .map { (cbl2cappSm, error) -> (CBL2CAPPSM) in if let error = error { throw _BluetoothError.publishingL2CAPChannelFailed(cbl2cappSm, error) } result = cbl2cappSm return cbl2cappSm } .subscribe(onNext: { observer.onNext($0) }, onError: { observer.onError($0)}) strongSelf.manager.publishL2CAPChannel(withEncryption: encryptionRequired) return Disposables.create { [weak self] in guard let strongSelf = self else { return } disposable.dispose() if let result = result { strongSelf.manager.unpublishL2CAPChannel(result) } } } return self.ensure(.poweredOn, observable: observable) } /// Continuous observer for `CBPeripheralManagerDelegate.peripheralManager(_:didOpen:error:)` results /// - returns: Observable that emits `next` event whenever didOpen occurs. /// /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` @available(iOS 11, tvOS 11, watchOS 4, *) func observeDidOpenL2CAPChannel() -> Observable<(CBL2CAPChannelMock?, Error?)> { return ensure(.poweredOn, observable: delegateWrapper.didOpenChannel) } #endif // MARK: Internal functions func ensureValidStateAndCallIfSucceeded<T>(for observable: Observable<T>, postSubscriptionCall call: @escaping () -> Void ) -> Observable<T> { let operation = Observable<T>.deferred { call() return .empty() } return ensure(.poweredOn, observable: Observable.merge([observable, operation])) } }
apache-2.0
2ed836915deae9804d7fffb5f9148c73
45.44898
210
0.669376
5.578431
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/TextFormattingCustomViewTableViewCell.swift
4
1005
class TextFormattingCustomViewTableViewCell: TextFormattingTableViewCell { private var customView: (UIView & Themeable)? func configure(with customView: UIView & Themeable) { customView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(customView) let topConstraint = customView.topAnchor.constraint(equalTo: topSeparator.bottomAnchor) let trailingConstraint = customView.trailingAnchor.constraint(equalTo: trailingAnchor) let bottomConstraint = customView.bottomAnchor.constraint(equalTo: bottomAnchor) let leadingConstraint = customView.leadingAnchor.constraint(equalTo: leadingAnchor) NSLayoutConstraint.activate([ topConstraint, trailingConstraint, bottomConstraint, leadingConstraint ]) self.customView = customView } override func apply(theme: Theme) { super.apply(theme: theme) customView?.apply(theme: theme) } }
mit
1d53887c40a7ce34a106893ac705195c
36.222222
95
0.710448
6.28125
false
false
false
false
gaurav1981/eidolon
Kiosk/App/AppSetup.swift
6
851
import UIKit class AppSetup { var auctionID = "los-angeles-modern-auctions-march-2015" lazy var useStaging = true lazy var showDebugButtons = false lazy var disableCardReader = false var isTesting = false class var sharedState : AppSetup { struct Static { static let instance = AppSetup() } return Static.instance } init() { let defaults = NSUserDefaults.standardUserDefaults() if let auction = defaults.stringForKey("KioskAuctionID") { auctionID = auction } useStaging = defaults.boolForKey("KioskUseStaging") showDebugButtons = defaults.boolForKey("KioskShowDebugButtons") disableCardReader = defaults.boolForKey("KioskDisableCardReader") if let _ = NSClassFromString("XCTest") { isTesting = true } } }
mit
1f21bbad4b86c5c8291d8f0092c40acd
27.366667
73
0.652174
4.947674
false
true
false
false
mrarronz/RegionCN
TestRegionCN/TestRegionCN/RegionPickerView.swift
1
11416
// // RegionPickerView.swift // TestRegionCN // // Copyright © 2017年 mrarronz. All rights reserved. // import UIKit import RegionCN public class PickerViewStyle: NSObject { public var toolBarHeight: CGFloat? public var contentHeight: CGFloat? public var pickerHeight: CGFloat? public var buttonWidth: CGFloat? public var pickerTextColor: UIColor? public var doneTitleColor: UIColor? public var cancelTitleColor: UIColor? } @objc public protocol RegionPickerDelegate : class { @objc optional func picker(picker: RegionPickerView, didSelectRegion region: String?) } open class RegionPickerView: UIView, UIPickerViewDataSource, UIPickerViewDelegate { open var style: PickerViewStyle? let pickerWidth = UIScreen.main.bounds.size.width var delegate: RegionPickerDelegate? private var provinceList: NSArray { let items = RegionHelper.shared.provincesXMLArray return items } private var cityList: NSArray? private var districtList: NSArray? private var selectedProvince: NSDictionary? private var selectedCity: NSDictionary? private var selectedDistrict: NSDictionary? // MARK: - Init UI var pickerView: UIPickerView { let pickerView = UIPickerView.init(frame: CGRect.init(x: 0, y: (style?.toolBarHeight)!, width: pickerWidth, height: (style?.pickerHeight)!)) pickerView.dataSource = self pickerView.delegate = self pickerView.showsSelectionIndicator = true return pickerView } var contentView: UIView { let contentView = UIView.init(frame: CGRect.init(x: 0, y: self.bounds.size.height - (style?.contentHeight)!, width: pickerWidth, height: (style?.contentHeight)!)) contentView.backgroundColor = UIColor.white contentView.addSubview(toolbar) contentView.addSubview(pickerView) return contentView } var toolbar: UIToolbar { let toolBar = UIToolbar.init(frame: CGRect.init(x: 0, y: 0, width: pickerWidth, height: (style?.toolBarHeight)!)) toolBar.barTintColor = UIColor.init(red: 244/255, green: 244/255, blue: 244/255, alpha: 1.0) let cancelBtn = UIButton.init(type: .system) cancelBtn.setTitle("取消", for: .normal) cancelBtn.setTitleColor(style?.cancelTitleColor, for: .normal) cancelBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) cancelBtn.addTarget(self, action: #selector(cancelButtonClicked), for: .touchUpInside) cancelBtn.isExclusiveTouch = true toolBar.addSubview(cancelBtn) let doneBtn = UIButton.init(type: .system) doneBtn.setTitle("完成", for: .normal) doneBtn.setTitleColor(style?.doneTitleColor, for: .normal) doneBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15) doneBtn.addTarget(self, action: #selector(doneButtonClicked), for: .touchUpInside) doneBtn.isExclusiveTouch = true toolBar.addSubview(doneBtn) cancelBtn.frame = CGRect.init(x: 0, y: 0, width: (style?.buttonWidth)!, height: (style?.toolBarHeight)!) doneBtn.frame = CGRect.init(x: pickerWidth-(style?.buttonWidth)!, y: 0, width: (style?.buttonWidth)!, height: (style?.toolBarHeight)!) return toolBar } // MARK: - Init public init(delegate: RegionPickerDelegate) { super.init(frame: UIScreen.main.bounds) if self.style == nil { style = PickerViewStyle.init() style?.toolBarHeight = 44 style?.contentHeight = 264 style?.pickerHeight = 220 style?.buttonWidth = 70 style?.pickerTextColor = UIColor.blue style?.cancelTitleColor = UIColor.red style?.doneTitleColor = UIColor.orange } self.delegate = delegate initData() } init(style:PickerViewStyle, delegate: RegionPickerDelegate) { super.init(frame: UIScreen.main.bounds) self.style = style self.delegate = delegate initData() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initData() { self.backgroundColor = UIColor.init(white: 0, alpha: 0) self.addSubview(contentView) // init default data let province = provinceList.firstObject as! NSDictionary self.cityList = province.object(forKey: "city") as? NSArray let city = self.cityList?.firstObject as? NSDictionary self.districtList = RegionHelper.shared.districtList(inCityList: self.cityList, atIndex: 0) self.selectedProvince = province self.selectedCity = city self.selectedDistrict = self.districtList?.firstObject as? NSDictionary } // MARK: - UIPickerViewDataSource public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 3 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { var count: Int? switch component { case 0: count = provinceList.count break case 1: count = (cityList == nil) ? 0 : cityList?.count break case 2: count = (districtList == nil) ? 0 : districtList?.count break default: count = 0 break } return count! } // MARK: - UIPickerViewDelegate public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 40 } public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var titleLabel: UILabel? = view as? UILabel if titleLabel == nil { titleLabel = UILabel.init() titleLabel?.font = UIFont.systemFont(ofSize: 16) titleLabel?.textColor = (style?.pickerTextColor)! titleLabel?.textAlignment = .center titleLabel?.adjustsFontSizeToFitWidth = true } switch component { case 0: let province = provinceList.object(at: row) as! NSDictionary titleLabel?.text = province.object(forKey: "_name") as? String break case 1: if (cityList?.count)! > 0 { let city = cityList?.object(at: row) as! NSDictionary titleLabel?.text = city.object(forKey: "_name") as? String } break case 2: if (districtList?.count)! > 0 { let dict = districtList?.object(at: row) as? NSDictionary titleLabel?.text = dict?.object(forKey: "_name") as? String } break default: break } return titleLabel! } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch component { case 0: let province = provinceList.object(at: row) as! NSDictionary self.cityList = province.object(forKey: "city") as? NSArray pickerView.reloadComponent(1) selectFirstRowInComponent(component: 1, forItems: self.cityList) if self.cityList != nil && (self.cityList?.count)! > 0 { let city = self.cityList?.firstObject as? NSDictionary self.districtList = RegionHelper.shared.districtList(inCityList: self.cityList, atIndex: 0) pickerView.reloadComponent(2) selectFirstRowInComponent(component: 2, forItems: self.districtList) self.selectedCity = city self.selectedDistrict = self.districtList?.firstObject as? NSDictionary } else { self.districtList = nil pickerView.reloadComponent(2) self.selectedCity = nil self.selectedDistrict = nil } self.selectedProvince = province break case 1: if self.cityList != nil && (self.cityList?.count)! > 0 { let city = self.cityList?.object(at: row) as! NSDictionary self.districtList = RegionHelper.shared.districtList(inCityList: self.cityList, atIndex: row) pickerView.reloadComponent(2) selectFirstRowInComponent(component: 2, forItems: self.districtList) self.selectedCity = city self.selectedDistrict = self.districtList?.firstObject as? NSDictionary } break case 2: if self.districtList != nil && (self.districtList?.count)! > 0 { self.selectedDistrict = self.districtList?.object(at: row) as? NSDictionary } break default: break } } func selectFirstRowInComponent(component: Int, forItems items: NSArray?) { if items != nil && (items?.count)! > 0 { self.pickerView.selectRow(0, inComponent: component, animated: true) } } // MARK: - Button events func cancelButtonClicked() { dismiss() } func doneButtonClicked() { dismiss() let provinceName: String = selectedProvince?.object(forKey: "_name") as! String var cityName: String? = selectedCity?.object(forKey: "_name") as? String if cityName == "市辖区" || cityName == "县" || cityName == nil { cityName = "" } let districtName: String = (selectedDistrict?.object(forKey: "_name") == nil) ? "" : (selectedDistrict?.object(forKey: "_name") as! String) let region = String.init(format: "%@%@%@", provinceName, cityName!, districtName) self.delegate?.picker?(picker: self, didSelectRegion: region) } // MARK: - Show & Dismiss func show() { let keyWindow = UIApplication.shared.keyWindow keyWindow?.addSubview(self) UIView.animate(withDuration: 0.25) { self.backgroundColor = UIColor.init(white: 0, alpha: 0.5) self.contentView.frame = CGRect.init(x: 0, y: self.bounds.size.height - (self.style?.contentHeight)!, width: self.pickerWidth, height: (self.style?.contentHeight)!) } } func dismiss() { UIView.animate(withDuration: 0.25, animations: { self.backgroundColor = UIColor.init(white: 0, alpha: 0) self.contentView.frame = CGRect.init(x: 0, y: self.bounds.size.height, width: self.pickerWidth, height: (self.style?.contentHeight)!) }) { (finished) in self.removeFromSuperview() } } }
mit
5ea1101d2b8211f3d767681f477e6a0c
36.613861
148
0.580504
5.108472
false
false
false
false
edouardjamin/30daysSwift
Day 12 - SpotifyLoginScreen/Day 12 - SpotifyLoginScreen/LoginController.swift
1
2554
// // LoginController.swift // Day 12 - SpotifyLoginScreen // // Created by Edouard Jamin on 05/03/16. // Copyright © 2016 Edouard Jamin. All rights reserved. // import UIKit class LoginController: UIViewController { // Interface @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var loginButton: UIButton! // AutoLayout @IBOutlet weak var usernameCenter: NSLayoutConstraint! @IBOutlet weak var passwordCenter: NSLayoutConstraint! @IBOutlet weak var loginCenter: NSLayoutConstraint! // IBAction @IBAction func loginButtonToucher(sender :AnyObject) { // get current bounds let bounds = self.loginButton.bounds // Animate UIView.animateWithDuration(1.0, delay: 0.00, usingSpringWithDamping: 0.2, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveLinear, animations: { self.loginButton.bounds = CGRect(x: bounds.origin.x - 20, y: bounds.origin.y, width: bounds.size.width + 60, height: bounds.size.height) self.loginButton.enabled = false }, completion: { finished in self.loginButton.enabled = true }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) usernameCenter.constant -= view.bounds.width passwordCenter.constant -= view.bounds.width loginButton.alpha = 0.00 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(0.5, delay: 0.00, options: .CurveEaseOut, animations: { self.usernameCenter.constant += self.view.bounds.width self.view.layoutIfNeeded() }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.2, options: .CurveEaseOut, animations: { self.passwordCenter.constant += self.view.bounds.width self.view.layoutIfNeeded() }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.4, options: .CurveEaseOut, animations: { self.loginButton.alpha = 1.00 }, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.loginButton.layer.cornerRadius = 5 var usernameFrame = self.usernameField.frame usernameFrame.size.height = 50 self.usernameField.frame = usernameFrame // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Status bar override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
mit
05fb86572a0b8046dbbd28698ee66fd1
26.75
161
0.726204
4.045959
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Playgrounds/Filters.playground/Pages/Korg Low Pass Filter Operation.xcplaygroundpage/Contents.swift
2
1144
//: ## Low Pass Filter Operation //: import XCPlayground import AudioKit //: Noise Example // Bring down the amplitude so that when it is mixed it is not so loud let whiteNoise = AKWhiteNoise(amplitude: 0.1) let filteredNoise = AKOperationEffect(whiteNoise) { whiteNoise, _ in let cutoff = AKOperation.sineWave(frequency: 0.2).scale(minimum: 12000, maximum: 100) return whiteNoise.korgLowPassFilter(cutoffFrequency: cutoff, resonance: 1, saturation: 1) } //: Music Example let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true let filteredPlayer = AKOperationEffect(player) { player, _ in let cutoff = AKOperation.sineWave(frequency: 0.2).scale(minimum: 12000, maximum: 100) return player.korgLowPassFilter(cutoffFrequency: cutoff, resonance: 1, saturation: 1) } //: Mixdown and playback let mixer = AKDryWetMixer(filteredNoise, filteredPlayer, balance: 0.5) AudioKit.output = mixer AudioKit.start() whiteNoise.start() player.play() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
mit
39dfb2be7996414aa5310b29f29abd00
32.647059
93
0.749126
4.190476
false
false
false
false
benlangmuir/swift
test/SILGen/back_deploy_attribute_struct_method.swift
7
3317
// RUN: %target-swift-emit-sil -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 -verify // RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s | %FileCheck %s // RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 | %FileCheck %s // RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.60 | %FileCheck %s // REQUIRES: OS=macosx @available(macOS 10.50, *) public struct TopLevelStruct { // -- Fallback definition for TopLevelStruct.trivialMethod() // CHECK-LABEL: sil non_abi [serialized] [available 10.51] [ossa] @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwB : $@convention(method) (TopLevelStruct) -> () // CHECK: bb0({{%.*}} : $TopLevelStruct): // CHECK: [[RESULT:%.*]] = tuple () // CHECK: return [[RESULT]] : $() // -- Back deployment thunk for TopLevelStruct.trivialMethod() // CHECK-LABEL: sil non_abi [serialized] [thunk] [available 10.51] [ossa] @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwb : $@convention(method) (TopLevelStruct) -> () // CHECK: bb0([[BB0_ARG:%.*]] : $TopLevelStruct): // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[OSVFN:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[AVAIL:%.*]] = apply [[OSVFN]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: cond_br [[AVAIL]], [[AVAIL_BB:bb[0-9]+]], [[UNAVAIL_BB:bb[0-9]+]] // // CHECK: [[UNAVAIL_BB]]: // CHECK: [[FALLBACKFN:%.*]] = function_ref @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwB : $@convention(method) (TopLevelStruct) -> () // CHECK: {{%.*}} = apply [[FALLBACKFN]]([[BB0_ARG]]) : $@convention(method) (TopLevelStruct) -> () // CHECK: br [[RETURN_BB:bb[0-9]+]] // // CHECK: [[AVAIL_BB]]: // CHECK: [[ORIGFN:%.*]] = function_ref @$s11back_deploy14TopLevelStructV13trivialMethodyyF : $@convention(method) (TopLevelStruct) -> () // CHECK: {{%.*}} = apply [[ORIGFN]]([[BB0_ARG]]) : $@convention(method) (TopLevelStruct) -> () // CHECK: br [[RETURN_BB]] // // CHECK: [[RETURN_BB]] // CHECK: [[RESULT:%.*]] = tuple () // CHECK: return [[RESULT]] : $() // -- Original definition of TopLevelStruct.trivialMethod() // CHECK-LABEL: sil [available 10.51] [ossa] @$s11back_deploy14TopLevelStructV13trivialMethodyyF : $@convention(method) (TopLevelStruct) -> () @available(macOS 10.51, *) @_backDeploy(before: macOS 10.52) public func trivialMethod() {} } // CHECK-LABEL: sil hidden [available 10.51] [ossa] @$s11back_deploy6calleryyAA14TopLevelStructVF : $@convention(thin) (TopLevelStruct) -> () // CHECK: bb0([[STRUCT_ARG:%.*]] : $TopLevelStruct): @available(macOS 10.51, *) func caller(_ s: TopLevelStruct) { // -- Verify the thunk is called // CHECK: {{%.*}} = function_ref @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwb : $@convention(method) (TopLevelStruct) -> () s.trivialMethod() }
apache-2.0
719d8a6bfb534f939a2a4eac42844c5b
60.425926
176
0.655713
3.458811
false
false
false
false
zmeyc/xgaf
Sources/xgaf/Entity.swift
1
1803
// XGAF file format parser for Swift. // (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information. import Foundation class Entity { private var lastAddedIndex = 0 // Key is "structure name"."field name"[index]: // struct.name[0] // Index should be omitted for top level fields. private var values = [String: Value]() private(set) var orderedNames = [String]() var lastStructureIndex = [String: Int]() var startLine = 0 // name is struct.field[index] func add(name: String, value: Value) -> Bool { guard values[name] == nil else { return false } values[name] = value orderedNames.append(name) return true } // name is struct.field[index] func replace(name: String, value: Value) { guard values[name] == nil else { values[name] = value return } values[name] = value orderedNames.append(name) } // name is struct.field[index] func value(named name: String) -> Value? { return values[name] } // name is struct.field WITHOUT [index] suffix func hasRequiredField(named name: String) -> Bool { if let structureName = structureName(fromFieldName: name) { guard let lastIndex = lastStructureIndex[structureName] else { // This is a structure field, but no structures were created return true } // Every structure should have required field: for i in 0...lastIndex { let nameWithIndex = appendIndex(toName: name, index: i) guard values[nameWithIndex] != nil else { return false } } return true } return values[name] != nil } }
mit
0fc922528c4efc67d9201f866e63d4da
30.086207
76
0.580699
4.419118
false
false
false
false
presence-insights/pi-sample-ios-DeviceRegistration
pi-sample-ios-DeviceRegistration/ViewController.swift
1
9963
// © Copyright 2015 IBM Corp. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import PresenceInsightsSDK class ViewController: UIViewController, UITextFieldDelegate { //hard coding the tenantID, orgID, username, password, baseURL //This information can be found in your Presence Insights UI/Dashboard let tenantID = "" let orgID = "" let username = "" let passwd = "" let baseURL = "" override func viewDidLoad() { super.viewDidLoad() self.deviceName.delegate = self self.deviceType.delegate = self self.unencryptedDataValue.delegate = self self.unencryptedDataKey.delegate = self self.datakey.delegate = self self.datavalue.delegate = self //creating a PIAdapter object with bm information piAdapter = PIAdapter(tenant: tenantID, org: orgID, baseURL: baseURL, username: username, password: passwd) //piAdapter.enableLogging() deviceType.userInteractionEnabled = false //initializing device to see if it's registered when the app is loaded. //if regsitered switch the registered switch to on. // note: i do not pull the encrypted data and unecnrypted data in the fields when the device is populated. device = PIDevice(name: " ") piAdapter.getDeviceByDescriptor(device.descriptor) { (rdevice, NSError) -> () in if((rdevice.name?.isEmpty) == nil){ } else{ //using UI thread to make teh necessary changes. dispatch_async(dispatch_get_main_queue(), { () -> Void in self.RegisterSwitch.setOn(true, animated: true) self.deviceName.text = rdevice.name self.deviceType.text = rdevice.type self.alert("Status", messageInput: "The Device is currently registered. Device Name and Type will popular based on PI information") }) print("Device is already registered") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //initializing piAdapter object and PIdevice var piAdapter : PIAdapter! var device : PIDevice! @IBOutlet weak var deviceName: UITextField! @IBOutlet weak var datakey: UITextField! @IBOutlet weak var datavalue: UITextField! @IBOutlet weak var unencryptedDataKey: UITextField! @IBOutlet weak var unencryptedDataValue: UITextField! @IBOutlet weak var deviceType: UITextField! //pop up alert and display BM information @IBAction func bmAction(sender: UIButton) { alert("BM Information", messageInput: "Username: \(username) \n Password: \(passwd) \n Tenant ID: \(tenantID) \n Org ID: \(orgID)") } //UI selection for which device Type exist in the user's PI @IBAction func DeviceTypeAction() { //gets org information piAdapter.getOrg { (org, NSError) -> () in print(org.registrationTypes); //grab the different device types let Types = org.registrationTypes print("TEST") print(Types.count) //need this dispatch to change from backend thread to UI thread dispatch_async(dispatch_get_main_queue(), { () -> Void in let alert = UIAlertController(title: "Select Device Type", message: "", preferredStyle: UIAlertControllerStyle.Alert) for Type in Types{ alert.addAction(UIAlertAction(title: "\(Type)", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction) in self.deviceType.text = Type print(Type) })) } alert.addAction(UIAlertAction(title: "cancel", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) }) } } //Update action @IBAction func Action(sender: UIButton) { //adding device name to the device object device = PIDevice(name: deviceName.text!) device.type = deviceType.text //adding device type to the device object. //NOTE: the type has to exist in the Presence Insights. Default types are : "Internal" and "External" //method to add encrypted data // ("VALUE", key: "KEY_NAME") //checks to see if key or value is empty and throw error as necessary if( MissingText(datavalue, key: datakey) == false){ device.addToDataObject(datavalue.text!, key: datakey.text!) } //checks to see if key or value is empty and throw error as necessary for unencrypted data if( MissingText(unencryptedDataValue, key: unencryptedDataKey) == false){ device.addToUnencryptedDataObject(unencryptedDataValue.text!, key: unencryptedDataKey.text!) } //when the user flicks the switch to green //checking to see if the device is registered before updating the device. if RegisterSwitch.on { //set device register to true if the light is on device.registered=true //device is registered and will update. piAdapter.updateDevice(device, callback: { (newDevice, NSError) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in if(NSError == nil){ self.alert("Success", messageInput: "Successfully Updated the Device Information") } else{ self.alert("Error", messageInput: "\(NSError)") } }) }) } else { //if the device is not registered, will alert saying must register device alert("Error", messageInput: "Must Register Device Before Updating") } } //function to make keyboard disappear when pressing return. func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return false } @IBOutlet weak var RegisterSwitch: UISwitch! //Register Switch Action @IBAction func switchAction(sender: AnyObject) { //adding device name to the device object device = PIDevice(name: deviceName.text!) device.type = deviceType.text //adding device type to the device object. //NOTE: the type has to exist in the Presence Insights. Default types are : "Internal" and "External" //checks to see if key or value is empty if( MissingText(datavalue, key: datakey) == false){ device.addToDataObject(datavalue.text!, key: datakey.text!) } // checks to see if key or value is empty if( MissingText(unencryptedDataValue, key: unencryptedDataKey) == false){ device.addToUnencryptedDataObject(unencryptedDataValue.text!, key: unencryptedDataKey.text!) } if RegisterSwitch.on { //PI Device Register SDK call piAdapter.registerDevice(device, callback: { (newDevice, NSError) -> () in // newDevice is of type PIDevice. dispatch_async(dispatch_get_main_queue(), { () -> Void in if(NSError == nil){ self.alert("Success", messageInput: "Successfully Registered the Device") } else{ self.alert("Error", messageInput: "\(NSError)") } }) }) } else { //PI Device unregister SDK call piAdapter.unregisterDevice(device, callback: { (newDevice, NSError) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in if(NSError == nil){ self.alert("Success", messageInput: "Successfully Unregistered the Device") } else{ self.alert("Error", messageInput: "\(NSError)") } }) }) } } //function to easily create alert messages func alert(titleInput : String , messageInput : String){ let alert = UIAlertController(title: titleInput, message: messageInput, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } //function to check if both or none of the data value and key exist. func MissingText (value: UITextField, key : UITextField) -> Bool{ if ( (key.text! == "" && value.text! == "")){ print("here") return true } else{ print("test") return false } } }
apache-2.0
3f4358adca5e44abec0de4078ac55a13
36.310861
151
0.576691
5.218439
false
false
false
false
justinyaoqi/CYFastImage
CYFastImage/CYFastImage/CYImageDownloader.swift
3
1731
// // CYImageDownloader.swift // CYFastImage // // Created by jason on 14-6-19. // Copyright (c) 2014 chenyang. All rights reserved. // import Foundation import UIKit extension CYFastImage { class CYImageDownloader { var operationQueue: NSOperationQueue! var concurrentCount: Int init(concurrentCount: Int) { self.concurrentCount = concurrentCount operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = concurrentCount } convenience init() { self.init(concurrentCount: 1) } // MARK: public func downloadImage(url: String, callback: DownloadCallback) { var operation = CYDownloadOperation() operation.urlString = url operation.finishCallback = callback operationQueue.addOperation(operation) } func cancel(url: String!) { for operation : AnyObject in operationQueue.operations { if let downloadOperation = operation as? CYDownloadOperation { if url == downloadOperation.urlString && downloadOperation.executing { downloadOperation.cancel() } } } } func isDownloadingImage(url: String!) -> Bool { for operation : AnyObject in operationQueue.operations { if let downloadOperation = operation as? CYDownloadOperation { if url == downloadOperation.urlString { return true } } } return false } } }
mit
4b09522c1c2dfdd145c99f06f2ff6fbc
29.910714
90
0.554015
5.989619
false
false
false
false
keithbhunter/KBHAnimatedLabels
KBHAnimatedLabels/KBHSpinningLabel.swift
1
2243
// // KBHSpinningLabel.swift // KBHAnimatedLabels // // Created by Keith Hunter on 11/2/15. // Copyright © 2015 Keith Hunter. All rights reserved. // import UIKit public class KBHSpinningLabel: KBHLabel, KBHAnimatable { public enum SpinDirection { case Left, Right } /// True if the label is animating; false otherwise. public var isAnimating: Bool { return _isAnimating } private var _isAnimating = false /// The direction that the text will spin when animated. Defaults to Right. public var spinDirection: SpinDirection = .Right /// A timing function for the animation to use. Defaults to kCAMediaTimingFunctionEaseOut. public var timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) /// Total time the spin animation will take. Defaults to 1 second. public var duration: CFTimeInterval = 1 /// The number of times each letter will spin during the duration. This number must be greater than 0. Defaults to 1. public var numberOfSpins: Int = 1 private let spinKey = "spin" // MARK: Animate public func animate() { guard numberOfSpins > 0 && !_isAnimating else { return } _isAnimating = true for i in 0..<text.characters.count { let toValue = Double(numberOfSpins) * 2 * M_PI let spin = CABasicAnimation(keyPath: "transform.rotation.z") spin.fromValue = 0 spin.toValue = spinDirection == .Right ? toValue : -(toValue) spin.duration = duration spin.timingFunction = timingFunction spin.beginTime = CACurrentMediaTime() + (CFTimeInterval(i) / 10) // stagger animations so they don't all start at once spin.setValue(i, forKey: animationKey + spinKey) spin.delegate = self labels[i].layer.addAnimation(spin, forKey: nil) } } public override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if let i = anim.valueForKey(animationKey + spinKey) as? Int where i == labels.count - 1 { // the animation on the last label finished _isAnimating = false } } }
mit
1ca0a83f3e4713e3d67191285bb58d62
34.03125
131
0.638715
4.800857
false
false
false
false
semonchan/LearningSwift
Project/Project - 09 - MusicPlayer/Project - 09 - MusicPlayer/ViewController.swift
1
3456
// // ViewController.swift // Project - 09 - MusicPlayer // // Created by 程超 on 2017/12/3. // Copyright © 2017年 程超. All rights reserved. // import UIKit import AVFoundation import SnapKit class ViewController: UIViewController { fileprivate lazy var pictureImageView: UIImageView = { let temp = UIImageView(image: UIImage(named: "Picture")) return temp }() fileprivate lazy var titleLabel: UILabel = { let temp = UILabel() temp.numberOfLines = 0 temp.text = "All Alone \n\n Fun." temp.textColor = UIColor.white return temp }() fileprivate lazy var musicButton: UIButton = { let temp = UIButton(type: .custom) temp.setImage(UIImage(named: "Play"), for: .normal) temp.setImage(UIImage(named: "Pause"), for: .selected) temp.isSelected = true temp.addTarget(self, action: #selector(clickMusicButton(_:)), for: .touchUpInside) return temp }() fileprivate lazy var audioPlayer: AVAudioPlayer = { var temp = AVAudioPlayer() return temp }() fileprivate var isPlaying = true override func loadView() { // 如果想加载自定义的view, 不需要调用父类方法, 否则需要 // super.loadView() let imageView = UIImageView(image: UIImage(named: "VAN")) let blurEffect = UIBlurEffect(style: .light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = imageView.bounds imageView.addSubview(blurEffectView) imageView.isUserInteractionEnabled = true view = imageView } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } override func viewDidLoad() { super.viewDidLoad() view.addSubview(pictureImageView) view.addSubview(titleLabel) view.addSubview(musicButton) setupLayouSubviews() playMusic() } fileprivate func setupLayouSubviews() { pictureImageView.snp.makeConstraints { (make) in make.centerX.equalTo(view) make.top.equalTo(view.safeAreaLayoutGuide).offset(100) make.size.equalTo(CGSize(width: 200, height: 200)) } titleLabel.snp.makeConstraints { (make) in make.centerX.equalTo(view) make.top.equalTo(pictureImageView.snp.bottom).offset(100) } musicButton.snp.makeConstraints { (make) in make.centerX.equalTo(view) make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-100) make.size.equalTo(CGSize(width: 80, height: 80)) } } fileprivate func playMusic() { let url = URL(fileURLWithPath: Bundle.main.path(forResource: "Fun. - All Alone", ofType: "mp3")!) do { try audioPlayer = AVAudioPlayer(contentsOf: url) audioPlayer.numberOfLoops = -1 audioPlayer.prepareToPlay() audioPlayer.play() } catch let playError as NSError { print(playError) } } @objc func clickMusicButton(_ button: UIButton) { if isPlaying { button.isSelected = false isPlaying = false audioPlayer.stop() } else { button.isSelected = true isPlaying = true audioPlayer.play() } } }
mit
5fdebcd07e882fc07d74dd0cf94b6435
29.918182
105
0.607762
4.844729
false
false
false
false
neonichu/UXCatalog
UICatalog/AlertControllerViewController.swift
1
12535
/* Copyright (C) 2014 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The view controller that demonstrates how to use UIAlertController. */ import UIKit class AlertControllerViewController : UITableViewController { // MARK: Properties weak var secureTextAlertAction: UIAlertAction? // A matrix of closures that should be invoked based on which table view cell is // tapped (index by section, row). var actionMap: [[(selectedIndexPath: NSIndexPath) -> Void]] { return [ // Alert style alerts. [ self.showSimpleAlert, self.showOkayCancelAlert, self.showOtherAlert, self.showTextEntryAlert, self.showSecureTextEntryAlert ], // Action sheet style alerts. [ self.showOkayCancelActionSheet, self.showOtherActionSheet ] ] } // MARK: UIAlertControllerStyleAlert Style Alerts /// Show an alert with an "Okay" button. func showSimpleAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Create the action. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The simple alert's cancel action occured.") } // Add the action. alertController.addAction(cancelAction) presentViewController(alertController, animated: true, completion: nil) } /// Show an alert with an "Okay" and "Cancel" button. func showOkayCancelAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitle = NSLocalizedString("OK", comment: "") let alertCotroller = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Okay/Cancel\" alert's cancel action occured.") } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Okay/Cancel\" alert's other action occured.") } // Add the actions. alertCotroller.addAction(cancelAction) alertCotroller.addAction(otherAction) presentViewController(alertCotroller, animated: true, completion: nil) } /// Show an alert with two custom buttons. func showOtherAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitleOne = NSLocalizedString("Choice One", comment: "") let otherButtonTitleTwo = NSLocalizedString("Choice Two", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Other\" alert's cancel action occured.") } let otherButtonOneAction = UIAlertAction(title: otherButtonTitleOne, style: .Default) { action in NSLog("The \"Other\" alert's other button one action occured.") } let otherButtonTwoAction = UIAlertAction(title: otherButtonTitleTwo, style: .Default) { action in NSLog("The \"Other\" alert's other button two action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherButtonOneAction) alertController.addAction(otherButtonTwoAction) presentViewController(alertController, animated: true, completion: nil) } /// Show a text entry alert with two custom buttons. func showTextEntryAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Add the text field for text entry. alertController.addTextFieldWithConfigurationHandler { textField in // If you need to customize the text field, you can do so here. } // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Text Entry\" alert's cancel action occured.") } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Text Entry\" alert's other action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherAction) presentViewController(alertController, animated: true, completion: nil) } /// Show a secure text entry alert with two custom buttons. func showSecureTextEntryAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Add the text field for the secure text entry. alertController.addTextFieldWithConfigurationHandler { textField in // Listen for changes to the text field's text so that we can toggle the current // action's enabled property based on whether the user has entered a sufficiently // secure entry. NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTextFieldTextDidChangeNotification:", name: UITextFieldTextDidChangeNotification, object: textField) textField.secureTextEntry = true } // Stop listening for text change notifications on the text field. This closure will be called in the two action handlers. let removeTextFieldObserver: Void -> Void = { NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields!.first) } // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Secure Text Entry\" alert's cancel action occured.") removeTextFieldObserver() } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Secure Text Entry\" alert's other action occured.") removeTextFieldObserver() } // The text field initially has no text in the text field, so we'll disable it. otherAction.enabled = false // Hold onto the secure text alert action to toggle the enabled/disabled state when the text changed. secureTextAlertAction = otherAction // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherAction) presentViewController(alertController, animated: true, completion: nil) } // MARK: UIAlertControllerStyleActionSheet Style Alerts /// Show a dialog with an "Okay" and "Cancel" button. func showOkayCancelActionSheet(selectedIndexPath: NSIndexPath) { let cancelButtonTitle = NSLocalizedString("Cancel", comment: "OK") let destructiveButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Okay/Cancel\" alert action sheet's cancel action occured.") } let destructiveAction = UIAlertAction(title: destructiveButtonTitle, style: .Destructive) { action in NSLog("The \"Okay/Cancel\" alert action sheet's destructive action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(destructiveAction) // Configure the alert controller's popover presentation controller if it has one. if let popoverPresentationController = alertController.popoverPresentationController { // This method expects a valid cell to display from. let selectedCell = tableView.cellForRowAtIndexPath(selectedIndexPath)! popoverPresentationController.sourceRect = selectedCell.frame popoverPresentationController.sourceView = view popoverPresentationController.permittedArrowDirections = .Up } presentViewController(alertController, animated: true, completion: nil) } /// Show a dialog with two custom buttons. func showOtherActionSheet(selectedIndexPath: NSIndexPath) { let destructiveButtonTitle = NSLocalizedString("Destructive Choice", comment: "") let otherButtonTitle = NSLocalizedString("Safe Choice", comment: "") let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) // Create the actions. let destructiveAction = UIAlertAction(title: destructiveButtonTitle, style: .Destructive) { action in NSLog("The \"Other\" alert action sheet's destructive action occured.") } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Other\" alert action sheet's other action occured.") } // Add the actions. alertController.addAction(destructiveAction) alertController.addAction(otherAction) // Configure the alert controller's popover presentation controller if it has one. if let popoverPresentationController = alertController.popoverPresentationController { // This method expects a valid cell to display from. let selectedCell = tableView.cellForRowAtIndexPath(selectedIndexPath)! popoverPresentationController.sourceRect = selectedCell.frame popoverPresentationController.sourceView = view popoverPresentationController.permittedArrowDirections = .Up } presentViewController(alertController, animated: true, completion: nil) } // MARK: UITextFieldTextDidChangeNotification func handleTextFieldTextDidChangeNotification(notification: NSNotification) { let textField = notification.object as UITextField // Enforce a minimum length of >= 5 characters for secure text alerts. secureTextAlertAction!.enabled = countElements(textField.text) >= 5 } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let action = actionMap[indexPath.section][indexPath.row] action(selectedIndexPath: indexPath) tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
f1bec6a7fd18d8d6b9f0c12dd561918e
43.760714
184
0.657863
5.917375
false
false
false
false