repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
bromas/ActivityViewController
ApplicationVCSample/GeneratedController.swift
1
1239
// // GeneratedController.swift // ApplicationVCSample // // Created by Brian Thomas on 5/4/15. // Copyright (c) 2015 Brian Thomas. All rights reserved. // import Foundation import UIKit import ActivityViewController class GeneratedController: UIViewController { @IBAction func buttonTap() { actionOnButtonTap() } var actionOnButtonTap : () -> Void = { let operation = ActivityOperation(rule: .any, identifier: "Launch", animator: CircleTransitionAnimator(direction: .outward, duration: 0.5)) ActivityViewController.rootController?.performActivityOperation(operation) } override func viewDidLoad() { super.viewDidLoad() self.view.translatesAutoresizingMaskIntoConstraints = false let label = UILabel(frame: CGRect(x: 100, y: 100, width: 200, height: 100)) self.view.addSubview(label) label.text = "Hi from the generator" self.view.backgroundColor = .red let button: UIButton = UIButton(type: UIButtonType.system) button.setTitle("Back", for: UIControlState()) button.frame = CGRect(x: 100, y: 180, width: 200, height: 100) button.addTarget(self, action: #selector(GeneratedController.buttonTap), for: .touchUpInside) self.view.addSubview(button) } }
mit
Ezfen/iOS.Apprentice.1-4
Checklists/Checklists/ListDetailViewController.swift
1
3626
// // ListDetailViewController.swift // Checklists // // Created by ezfen on 16/8/11. // Copyright © 2016年 Ezfen lnc. All rights reserved. // import UIKit protocol ListDetailViewControllerDelegate: class { func listDetailViewControllerDidCancel(controller: ListDetailViewController) func listDetailViewController(controller: ListDetailViewController, didFinishAddingChecklist checklist: Checklist) func listDetailViewController(controller: ListDetailViewController,didFinishEditingChecklist checklist: Checklist) } class ListDetailViewController: UITableViewController, UITextFieldDelegate, IconPickerViewControllerDelegate { @IBOutlet weak var textField: UITextField! @IBOutlet weak var doneBarButton: UIBarButtonItem! @IBOutlet weak var iconImageView: UIImageView! var iconName = "Folder" weak var delegate: ListDetailViewControllerDelegate? var checklistToEdit: Checklist? 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() if let checklist = checklistToEdit { title = "Edit Checklist" textField.text = checklist.name doneBarButton.enabled = true iconName = checklist.iconName } iconImageView.image = UIImage(named: iconName) } override func viewWillAppear(animated: Bool) { super.viewDidAppear(animated) textField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancel() { delegate?.listDetailViewControllerDidCancel(self) } @IBAction func done() { if let checklist = checklistToEdit { checklist.name = textField.text! checklist.iconName = iconName delegate?.listDetailViewController(self, didFinishEditingChecklist: checklist) } else { let checklist = Checklist(name: textField.text!) checklist.iconName = iconName delegate?.listDetailViewController(self, didFinishAddingChecklist: checklist) } } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.section == 1 { return indexPath } else { return nil } } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let oldText: NSString = textField.text! let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string) doneBarButton.enabled = (newText.length > 0) return true } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PickIcon" { let controller = segue.destinationViewController as! IconPickerViewController controller.delegate = self } } func iconPicker(picker: IconPickerViewController, didPickIcon iconName: String) { self.iconName = iconName iconImageView.image = UIImage(named: iconName) navigationController?.popViewControllerAnimated(true) } }
mit
insidegui/WWDC
WWDC/ActionLabel.swift
1
1154
// // ActionLabel.swift // WWDC // // Created by Guilherme Rambo on 28/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa final class ActionLabel: NSTextField { private var cursorTrackingArea: NSTrackingArea! override func updateTrackingAreas() { super.updateTrackingAreas() if cursorTrackingArea != nil { removeTrackingArea(cursorTrackingArea) } cursorTrackingArea = NSTrackingArea(rect: bounds, options: [.cursorUpdate, .inVisibleRect, .activeInActiveApp], owner: self, userInfo: nil) addTrackingArea(cursorTrackingArea) } override func cursorUpdate(with event: NSEvent) { if event.trackingArea == cursorTrackingArea { NSCursor.pointingHand.push() } else { super.cursorUpdate(with: event) } } override func mouseDown(with event: NSEvent) { if let action = action { NSApp.sendAction(action, to: target, from: self) } } }
bsd-2-clause
karstengresch/rw_studies
StackReview/StackReview/PancakeHouse.swift
1
4216
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import CoreLocation enum PriceGuide : Int { case Unknown = 0 case Low = 1 case Medium = 2 case High = 3 } extension PriceGuide : CustomStringConvertible { var description : String { switch self { case .Unknown: return "?" case .Low: return "$" case .Medium: return "$$" case .High: return "$$$" } } } enum PancakeRating { case Unknown case Rating(Int) } extension PancakeRating { init?(value: Int) { if value > 0 && value <= 5 { self = .Rating(value) } else { self = .Unknown } } } extension PancakeRating { var ratingImage : UIImage? { guard let baseName = ratingImageName else { return nil } return UIImage(named: baseName) } var smallRatingImage : UIImage? { guard let baseName = ratingImageName else { return nil } return UIImage(named: "\(baseName)_small") } private var ratingImageName : String? { switch self { case .Unknown: return nil case .Rating(let value): return "pancake_rate_\(value)" } } } struct PancakeHouse { let name: String let photo: UIImage? let thumbnail: UIImage? let priceGuide: PriceGuide let location: CLLocationCoordinate2D? let details: String let rating: PancakeRating } extension PancakeHouse { init?(dict: [String : AnyObject]) { guard let name = dict["name"] as? String, let priceGuideRaw = dict["priceGuide"] as? Int, let priceGuide = PriceGuide(rawValue: priceGuideRaw), let details = dict["details"] as? String, let ratingRaw = dict["rating"] as? Int, let rating = PancakeRating(value: ratingRaw) else { return nil } self.name = name self.priceGuide = priceGuide self.details = details self.rating = rating if let imageName = dict["imageName"] as? String where !imageName.isEmpty { photo = UIImage(named: imageName) } else { photo = nil } if let thumbnailName = dict["thumbnailName"] as? String where !thumbnailName.isEmpty { thumbnail = UIImage(named: thumbnailName) } else { thumbnail = nil } if let latitude = dict["latitude"] as? Double, let longitude = dict["longitude"] as? Double { location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } else { location = nil } } } extension PancakeHouse { static func loadDefaultPancakeHouses() -> [PancakeHouse]? { return self.loadPancakeHousesFromPlistNamed("pancake_houses") } static func loadPancakeHousesFromPlistNamed(plistName: String) -> [PancakeHouse]? { guard let path = NSBundle.mainBundle().pathForResource(plistName, ofType: "plist"), let array = NSArray(contentsOfFile: path) as? [[String : AnyObject]] else { return nil } return array.map { PancakeHouse(dict: $0) } .filter { $0 != nil } .map { $0! } } } extension PancakeHouse : CustomStringConvertible { var description : String { return "\(name) :: \(details)" } }
unlicense
sebastiangrail/PriorityScheduler
Pod/Classes/ArrayExtension.swift
1
932
// // ArrayExtension.swift // Pods // // Created by Sebastian Grail on 15/02/15. // // extension Array { /// Finds the first element that satisfies the predicate `p` /// Returns nil if no element satisifies `p` func find (p: T -> Bool) -> T? { for x in self { if p(x) { return x } } return nil } /// Finds the index of the first element that satisfies the predicate `p` /// Returns nil, if no element satisifies `p`, returns nil func findIndex (p: T -> Bool) -> Int? { for idx in 0..<self.count { if p(self[idx]) { return idx } } return nil } /// Removes the first element that satisfies the predicate mutating func remove (p: T -> Bool) -> () { if let idx = self.findIndex(p) { self.removeAtIndex(idx) } } /// Swaps items at the given indexes mutating func swapItemAtIndex(n: Int, withItemAtIndex m: Int) { let tmp = self[n] self[n] = self[m] self[m] = tmp } }
mit
joerocca/GitHawk
Pods/Pageboy/Sources/Pageboy/Utilities/ViewUtilities/UIView+AutoLayout.swift
1
1302
// // UIView+AutoLayout.swift // Pageboy // // Created by Merrick Sapsford on 15/02/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit internal extension UIView { @discardableResult func pinToSuperviewEdges() -> [NSLayoutConstraint]? { guard self.superview != nil else { fatalError("superview can not be nil") } self.translatesAutoresizingMaskIntoConstraints = false let views = ["view" : self] var constraints = [NSLayoutConstraint]() let xConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views: views) let yConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views: views) constraints.append(contentsOf: xConstraints) constraints.append(contentsOf: yConstraints) self.superview?.addConstraints(constraints) return constraints } }
mit
glassonion1/RxStoreKit
Example/Example/ViewController.swift
1
534
// // ViewController.swift // Example // // Created by taisuke fujita on 2017/06/21. // Copyright © 2017年 Taisuke Fujita. All rights reserved. // import UIKit import RxStoreKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
coffee-cup/solis
SunriseSunset/SunType.swift
1
5747
// // SunType.swift // SunriseSunset // // Created by Jake Runzer on 2016-07-17. // Copyright © 2016 Puddllee. All rights reserved. // import Foundation import UIKit enum SunType { case astronomicalDawn case nauticalDawn case civilDawn case sunrise case sunset case civilDusk case nauticalDusk case astronomicalDusk case middleNight var description: String { switch self { case .astronomicalDawn: return "Astronomical Dawn"; case .nauticalDawn: return "Nautical Dawn"; case .civilDawn: return "Civil Dawn"; case .sunrise: return "Sunrise"; case .sunset: return "Sunset"; case .civilDusk: return "Civil Dusk"; case .nauticalDusk: return "Nautical Dusk"; case .astronomicalDusk: return "Astronomical Dusk"; case .middleNight: return "Middle of Night"; } } var marker: Bool { switch self { case .astronomicalDawn: return true; case .nauticalDawn: return false; case .civilDawn: return false; case .sunrise: return true; case .sunset: return true; case .civilDusk: return false; case .nauticalDusk: return false; case .astronomicalDusk: return true; case .middleNight: return false; } } var colour: CGColor { switch self { case .astronomicalDawn: return astronomicalColour.cgColor as CGColor case .nauticalDawn: return nauticalColour.cgColor as CGColor case .civilDawn: return civilColour.cgColor as CGColor case .sunrise: return risesetColour.cgColor as CGColor case .civilDusk: return civilColour.cgColor as CGColor case .nauticalDusk: return nauticalColour.cgColor as CGColor case .sunset: return risesetColour.cgColor as CGColor case .astronomicalDusk: return astronomicalColour.cgColor as CGColor case .middleNight: return astronomicalColour.cgColor as CGColor } } var lineColour: UIColor { switch self { case .astronomicalDawn: return lightLineColour; case .nauticalDawn: return lightLineColour; case .civilDawn: return lightLineColour; case .sunrise: return lightLineColour; case .sunset: return darkLineColour; case .civilDusk: return darkLineColour; case .nauticalDusk: return darkLineColour; case .astronomicalDusk: return darkLineColour; case .middleNight: return middleLineColour; } } var message: String { var message = "" if self == .astronomicalDawn || self == .nauticalDawn || self == .civilDawn { message = "The sun is awake now ☀️ Have a good day" } else if self == .sunrise { message = "The sun has risen 🌄" } else if self == .sunset { message = "The sun has set 🌇" } else if self == .civilDusk || self == .nauticalDusk || self == .astronomicalDusk { message = "The sun has gone to sleep for the night 🌚 Goodnight" } return message } var event: String { var message = "" if self == .astronomicalDawn || self == .nauticalDawn || self == .civilDawn { message = "First Light" } else if self == .sunrise { message = "Sunrise" } else if self == .sunset { message = "Sunset" } else if self == .civilDusk || self == .nauticalDusk || self == .astronomicalDusk { message = "Last Light" } return message } var twilightDawn: Bool { switch self { case .astronomicalDawn: return true; case .nauticalDawn: return true; case .civilDawn: return true; case .sunrise: return false; case .sunset: return false; case .civilDusk: return false; case .nauticalDusk: return false; case .astronomicalDusk: return false; case .middleNight: return false; } } var twilightDusk: Bool { switch self { case .astronomicalDawn: return false; case .nauticalDawn: return false; case .civilDawn: return false; case .sunrise: return false; case .sunset: return false; case .civilDusk: return true; case .nauticalDusk: return true; case .astronomicalDusk: return true; case .middleNight: return false; } } var morning: Bool { switch self { case .astronomicalDawn: return true; case .nauticalDawn: return true; case .civilDawn: return true; case .sunrise: return true; case .sunset: return false; case .civilDusk: return false; case .nauticalDusk: return false; case .astronomicalDusk: return false; case .middleNight: return false; } } var night: Bool { switch self { case .astronomicalDawn: return false; case .nauticalDawn: return false; case .civilDawn: return false; case .sunrise: return false; case .sunset: return true; case .civilDusk: return true; case .nauticalDusk: return true; case .astronomicalDusk: return true; case .middleNight: return false; } } var degrees: Float { switch self { case .astronomicalDawn: return 18; case .nauticalDawn: return 12; case .civilDawn: return 6; case .sunrise: return 0; case .sunset: return 0; case .civilDusk: return 6; case .nauticalDusk: return 12; case .astronomicalDusk: return 18; case .middleNight: return 270; } } }
mit
FredrikSjoberg/SnapStack
SnapStack/Fetch/Protocols/ToManyRelationType.swift
1
860
// // ToManyRelationType.swift // SnapStack // // Created by Fredrik Sjöberg on 22/09/15. // Copyright © 2015 Fredrik Sjöberg. All rights reserved. // import Foundation public protocol ToManyRelationType : RelationType { } public extension ToManyRelationType { func count() -> Attribute<Int> { return Attribute(keys: [key, "@count"]) } /* func min<Int>(inner: (Entity.Type) -> Attribute<Int>) -> Attribute<Int> { }*/ } public extension ToManyRelationType { func isIn(values: [Entity]?) -> Predicate { let predicate = NSComparisonPredicate(leftExpression: self.nsExpression, rightExpression: Array.nsExpression(values), modifier: .DirectPredicateModifier, type: .InPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0)) return Predicate(predicate: predicate) } }
mit
J3D1-WARR10R/WikiRaces
Mac Utils/WKRRaceLiveViewer/WKRRaceLiveViewer/Model.swift
2
1405
// // Model.swift // WKRRaceLiveViewer // // Created by Andrew Finke on 7/2/20. // import CloudKit import WKRKitCore class Model: ObservableObject { // MARK: - Properties - private let raceCode: String @Published var host: String? @Published var state: WKRGameState? @Published var resultsInfo: WKRResultsInfo? // MARK: - Initalization - init(raceCode: String) { self.raceCode = raceCode update() Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in self.update() } } // MARK: - Helpers - func update() { let predicate = NSPredicate(format: "Code == %@", raceCode) let sort = NSSortDescriptor(key: "modificationDate", ascending: false) let query = CKQuery(recordType: "RaceActive", predicate: predicate) query.sortDescriptors = [sort] let operation = CKQueryOperation(query: query) operation.resultsLimit = 1 operation.recordFetchedBlock = { record in let wrapper = WKRRaceActiveRecordWrapper(record: record) DispatchQueue.main.async { self.host = wrapper.host() self.state = wrapper.state() self.resultsInfo = wrapper.resultsInfo() } } CKContainer(identifier: "iCloud.com.andrewfinke.wikiraces").publicCloudDatabase.add(operation) } }
mit
Crowdmix/Buildasaur
BuildaKit/StorageManager.swift
1
10956
// // StorageManager.swift // Buildasaur // // Created by Honza Dvorsky on 14/02/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaGitServer import BuildaUtils import XcodeServerSDK public class StorageManager { public static let sharedInstance = StorageManager() private(set) public var syncers: [HDGitHubXCBotSyncer] = [] private(set) public var servers: [XcodeServerConfig] = [] private(set) public var projects: [Project] = [] private(set) public var buildTemplates: [BuildTemplate] = [] init() { //initialize all stored Syncers self.loadAllFromPersistence() } deinit { self.stop() } public func addProjectAtURL(url: NSURL) throws { _ = try Project.attemptToParseFromUrl(url) if let project = Project(url: url) { self.projects.append(project) } else { assertionFailure("Attempt to parse succeeded but Project still wasn't created") } } public func addServerConfig(host host: String, user: String?, password: String?) { let config = try! XcodeServerConfig(host: host, user: user, password: password) self.servers.append(config) } public func addSyncer(syncInterval: NSTimeInterval, waitForLttm: Bool, postStatusComments: Bool, project: Project, serverConfig: XcodeServerConfig, watchedBranchNames: [String]) -> HDGitHubXCBotSyncer? { if syncInterval <= 0 { Log.error("Sync interval must be > 0 seconds.") return nil } let xcodeServer = XcodeServerFactory.server(serverConfig) let github = GitHubFactory.server(project.githubToken) let syncer = HDGitHubXCBotSyncer( integrationServer: xcodeServer, sourceServer: github, project: project, syncInterval: syncInterval, waitForLttm: waitForLttm, postStatusComments: postStatusComments, watchedBranchNames: watchedBranchNames) self.syncers.append(syncer) return syncer } public func saveBuildTemplate(buildTemplate: BuildTemplate) { //in case we have a duplicate, replace var duplicateFound = false for (idx, temp) in self.buildTemplates.enumerate() { if temp.uniqueId == buildTemplate.uniqueId { self.buildTemplates[idx] = buildTemplate duplicateFound = true break } } if !duplicateFound { self.buildTemplates.append(buildTemplate) } //now save all self.saveBuildTemplates() } public func removeBuildTemplate(buildTemplate: BuildTemplate) { //remove from the memory storage for (idx, temp) in self.buildTemplates.enumerate() { if temp.uniqueId == buildTemplate.uniqueId { self.buildTemplates.removeAtIndex(idx) break } } //also delete the file let templatesFolderUrl = Persistence.getFileInAppSupportWithName("BuildTemplates", isDirectory: true) let id = buildTemplate.uniqueId let templateUrl = templatesFolderUrl.URLByAppendingPathComponent("\(id).json") do { try NSFileManager.defaultManager().removeItemAtURL(templateUrl) } catch {} //save self.saveBuildTemplates() } public func removeProject(project: Project) { for (idx, p) in self.projects.enumerate() { if project.url == p.url { self.projects.removeAtIndex(idx) return } } } public func removeServer(serverConfig: XcodeServerConfig) { for (idx, p) in self.servers.enumerate() { if serverConfig.host == p.host { self.servers.removeAtIndex(idx) return } } } public func removeSyncer(syncer: HDGitHubXCBotSyncer) { //don't know how to compare syncers yet self.syncers.removeAll(keepCapacity: true) } public func loadAllFromPersistence() { self.loadProjects() self.loadServers() self.loadSyncers() self.loadBuildTemplates() } func loadServers() { self.servers.removeAll(keepCapacity: true) let serversUrl = Persistence.getFileInAppSupportWithName("ServerConfigs.json", isDirectory: false) do { let json = try Persistence.loadJSONFromUrl(serversUrl) if let json = json as? [NSDictionary] { let allConfigs = json.map { (item) -> XcodeServerConfig? in do { return try XcodeServerConfig(json: item) } catch { return nil } } let parsedConfigs = allConfigs.filter { $0 != nil }.map { $0! } if allConfigs.count != parsedConfigs.count { Log.error("Some configs failed to parse, will be ignored.") //maybe show a popup } parsedConfigs.forEach { self.servers.append($0) } return } } catch { //file not found if (error as NSError).code != 260 { Log.error("Failed to read ServerConfigs, error \(error). Will be ignored. Please don't play with the persistence :(") } } } func loadProjects() { self.projects.removeAll(keepCapacity: true) let projectsUrl = Persistence.getFileInAppSupportWithName("Projects.json", isDirectory: false) do { let json = try Persistence.loadJSONFromUrl(projectsUrl) if let json = json as? [NSDictionary] { let allProjects = json.map { Project(json: $0) } let parsedProjects = allProjects.filter { $0 != nil }.map { $0! } if allProjects.count != parsedProjects.count { Log.error("Some projects failed to parse, will be ignored.") //maybe show a popup } parsedProjects.forEach { self.projects.append($0) } return } } catch { //file not found if (error as NSError).code != 260 { Log.error("Failed to read Projects, error \(error). Will be ignored. Please don't play with the persistence :(") } } } func loadSyncers() { self.syncers.removeAll(keepCapacity: true) let syncersUrl = Persistence.getFileInAppSupportWithName("Syncers.json", isDirectory: false) do { let json = try Persistence.loadJSONFromUrl(syncersUrl) if let json = json as? [NSDictionary] { let allSyncers = json.map { HDGitHubXCBotSyncer(json: $0, storageManager: self) } let parsedSyncers = allSyncers.filter { $0 != nil }.map { $0! } if allSyncers.count != parsedSyncers.count { Log.error("Some syncers failed to parse, will be ignored.") //maybe show a popup } parsedSyncers.forEach { self.syncers.append($0) } return } } catch { //file not found if (error as NSError).code != 260 { Log.error("Failed to read Syncers, error \(error). Will be ignored. Please don't play with the persistence :(") } } } func loadBuildTemplates() { self.buildTemplates.removeAll(keepCapacity: true) let templatesFolderUrl = Persistence.getFileInAppSupportWithName("BuildTemplates", isDirectory: true) Persistence.iterateThroughFilesInFolder(templatesFolderUrl, visit: { (url) -> () in do { let json = try Persistence.loadJSONFromUrl(url) if let json = json as? NSDictionary { if let template = BuildTemplate(json: json) { //we have a template self.buildTemplates.append(template) return } } } catch { Log.error("Couldn't parse Build Template at url \(url), error \(error)") } }) } public func saveProjects() { let projectsUrl = Persistence.getFileInAppSupportWithName("Projects.json", isDirectory: false) let jsons = self.projects.map { $0.jsonify() } do { try Persistence.saveJSONToUrl(jsons, url: projectsUrl) } catch { assert(false, "Failed to save Projects, \(error)") } } public func saveServers() { let serversUrl = Persistence.getFileInAppSupportWithName("ServerConfigs.json", isDirectory: false) let jsons = self.servers.map { $0.jsonify() } do { try Persistence.saveJSONToUrl(jsons, url: serversUrl) } catch { assert(false, "Failed to save ServerConfigs, \(error)") } } public func saveSyncers() { let syncersUrl = Persistence.getFileInAppSupportWithName("Syncers.json", isDirectory: false) let jsons = self.syncers.map { $0.jsonify() } do { try Persistence.saveJSONToUrl(jsons, url: syncersUrl) } catch { assert(false, "Failed to save Syncers, \(error)") } } public func saveBuildTemplates() { let templatesFolderUrl = Persistence.getFileInAppSupportWithName("BuildTemplates", isDirectory: true) self.buildTemplates.forEach { (template: BuildTemplate) -> () in let json = template.jsonify() let id = template.uniqueId let templateUrl = templatesFolderUrl.URLByAppendingPathComponent("\(id).json") do { try Persistence.saveJSONToUrl(json, url: templateUrl) } catch { assert(false, "Failed to save a Build Template, \(error)") } } } public func stop() { self.saveAll() self.stopSyncers() } public func saveAll() { //save to persistence self.saveProjects() self.saveServers() self.saveBuildTemplates() self.saveSyncers() } public func stopSyncers() { for syncer in self.syncers { syncer.active = false } } public func startSyncers() { //start all syncers in memory for syncer in self.syncers { syncer.active = true } } }
mit
nnianhou-/M-Vapor
Sources/App/Models/Video.swift
1
6239
// // Video.swift // App // // Created by N年後 on 2017/10/20. // import Vapor import FluentProvider import HTTP final class Video:Model{ static let idKey = "id" static let videoHallIdKey = "videoHallId" static let titleKey = "title" static let coverKey = "cover" static let coverIdKey = "coverId" static let createdAtKey = "createdAt" static let videoIdKey = "videoId" static let durationKey = "duration" static let playUrlKey = "playUrl" static let statusKey = "status" static let sourceKey = "source" var videoHallId: String var title: String var cover: String var coverId: String var createdAt: String var videoId: String var duration: String var playUrl: String var status : String var source : String let storage = Storage() /// 常规的构造器 init(videoHallId: String,title:String,cover:String,coverId:String,createdAt:String,videoId:String,duration:String,playUrl:String,status:String,source:String) { self.videoHallId = videoHallId self.title = title self.cover = cover self.coverId = coverId self.createdAt = createdAt self.videoId = videoId self.duration = duration self.playUrl = playUrl self.status = status self.source = source } // MARK: Fluent 序列化构造器 /// 通过这个构造器你可以使用数据库中的一行生成一个对应的对象 init(row: Row) throws { videoHallId = try row.get(Video.videoHallIdKey) title = try row.get(Video.titleKey) cover = try row.get(Video.coverKey) coverId = try row.get(Video.coverIdKey) createdAt = try row.get(Video.createdAtKey) videoId = try row.get(Video.videoIdKey) duration = try row.get(Video.durationKey) playUrl = try row.get(Video.playUrlKey) status = try row.get(Video.statusKey) source = try row.get(Video.sourceKey) } // 把一个对象存储到数据库当中 func makeRow() throws -> Row { var row = Row() try row.set(Video.videoHallIdKey, videoHallId) try row.set(Video.titleKey, title) try row.set(Video.coverKey, cover) try row.set(Video.coverIdKey, coverId) try row.set(Video.createdAtKey, createdAt) try row.set(Video.videoIdKey, videoId) try row.set(Video.durationKey, duration) try row.set(Video.playUrlKey, playUrl) try row.set(Video.statusKey, status) try row.set(Video.sourceKey, source) return row } } extension Video:Preparation { static func prepare(_ database: Database) throws { try database.create(self, closure: { Videos in Videos.id() Videos.string(Video.videoHallIdKey) Videos.string(Video.titleKey) Videos.string(Video.coverKey) Videos.string(Video.coverIdKey) Videos.string(Video.createdAtKey) Videos.string(Video.videoIdKey) Videos.string(Video.durationKey) Videos.string(Video.playUrlKey) Videos.string(Video.statusKey) Videos.string(Video.sourceKey) }) } static func revert(_ database: Database) throws { try database.delete(self) } } extension Video: JSONRepresentable { convenience init(json: JSON) throws { try self.init( videoHallId:json.get(Video.videoHallIdKey), title:json.get(Video.titleKey), cover:json.get(Video.coverKey), coverId:json.get(Video.coverIdKey), createdAt:json.get(Video.createdAtKey), videoId:json.get(Video.videoIdKey), duration:json.get(Video.durationKey), playUrl:json.get(Video.playUrlKey), status:json.get(Video.statusKey), source:json.get(Video.sourceKey) ) } func makeJSON() throws -> JSON { var json = JSON() try json.set(Video.idKey, id) try json.set(Video.videoHallIdKey, videoHallId) try json.set(Video.titleKey, title) try json.set(Video.coverKey, cover) try json.set(Video.coverIdKey, coverId) try json.set(Video.createdAtKey, createdAt) try json.set(Video.videoIdKey, videoId) try json.set(Video.durationKey, duration) try json.set(Video.playUrlKey, playUrl) try json.set(Video.statusKey, status) try json.set(Video.sourceKey, source) return json } } extension Video: Updateable { public static var updateableKeys: [UpdateableKey<Video>] { return [ UpdateableKey(Video.videoHallIdKey, String.self) { Video, videoHallId in Video.videoHallId = videoHallId }, UpdateableKey(Video.titleKey, String.self) { Video, title in Video.title = title }, UpdateableKey(Video.coverKey, String.self) { Video, cover in Video.cover = cover }, UpdateableKey(Video.coverIdKey, String.self) { Video, coverId in Video.coverId = coverId }, UpdateableKey(Video.createdAtKey, String.self) { Video, createdAt in Video.createdAt = createdAt }, UpdateableKey(Video.videoIdKey, String.self) { Video, videoId in Video.videoId = videoId }, UpdateableKey(Video.durationKey, String.self) { Video, duration in Video.duration = duration }, UpdateableKey(Video.playUrlKey, String.self) { Video, playUrl in Video.playUrl = playUrl }, UpdateableKey(Video.statusKey, String.self) { Video, status in Video.status = status }, UpdateableKey(Video.sourceKey, String.self) { Video, source in Video.source = source } ] } } extension Video: ResponseRepresentable { }
mit
zachmokahn/SUV
Sources/Spec/mocks/Util/Sock/AddrType.swift
1
180
import SUV class MockAddrType: AddrType { typealias Pointer = UnsafeMutablePointer<Void> let pointer: Pointer init() { self.pointer = Pointer.alloc(sizeof(Void)) } }
mit
mightydeveloper/swift
validation-test/compiler_crashers_fixed/0174-swift-scopeinfo-addtoscope.swift
13
383
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var x1 =I Bool !(a) } func prefix(with: Strin) -> <T>(() -> T) in // Disol g func j(d: h) -> <k>(() -> k) -> h { return { n n "\(} c i< typealias k = a<j<n>, l> }
apache-2.0
shu223/TokyoOlympicEmblem-for-iOS
TokyoOlympicEmblemTests/TokyoOlympicEmblemTests.swift
2
949
// // TokyoOlympicEmblemTests.swift // TokyoOlympicEmblemTests // // Created by Shuichi Tsutsumi on 2015/08/06. // Copyright (c) 2015年 Shuichi Tsutsumi. All rights reserved. // import UIKit import XCTest class TokyoOlympicEmblemTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
xiaoxionglaoshi/SwiftProgramming
003 StringsAndCharacters.playground/Contents.swift
1
1227
// 字符串字面量 let someString = "some string literal value" // 初始化空字符串 var emptyString = "" var anotherEmptyString = String() // 字符串可变性 var variableString = "hello" variableString += " swift" // 字符串值类型 for character in variableString.characters { print(character) } // 字符集合转字符串 let strCharacters: [Character] = ["h", "e", "l", "l", "o"] let str = String(strCharacters) // 字符串索引 let greeting = "guten tag" greeting[greeting.startIndex] greeting[greeting.index(after: greeting.startIndex)] greeting[greeting.index(greeting.endIndex, offsetBy: -2)] for index in greeting.characters.indices { print(greeting[index], terminator: ",") } // 插入和删除 var welcome = "hello" welcome.insert("!", at: welcome.endIndex) welcome.insert(contentsOf: " swift".characters, at: welcome.index(before: welcome.endIndex)) welcome.remove(at: welcome.startIndex) let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex welcome.removeSubrange(range) // 前缀/后缀判断 let messageStr = "hello swift" if messageStr.hasPrefix("he") { print("存在he的前缀") } if messageStr.hasSuffix("ft") { print("存在ft的后缀") }
apache-2.0
huangboju/QMUI.swift
QMUI.swift/Demo/Modules/Demos/UIKit/QDNavigationListViewController.swift
1
1861
// // QDNavigationListViewController.swift // QMUI.swift // // Created by qd-hxt on 2018/4/23. // Copyright © 2018年 伯驹 黄. All rights reserved. // import UIKit class QDNavigationListViewController: QDCommonListViewController { override func initDataSource() { super.initDataSource() dataSourceWithDetailText = QMUIOrderedDictionary( dictionaryLiteral: ("拦截系统navBar返回按钮事件", "例如询问已输入的内容要不要保存"), ("感知系统的手势返回", "可感知到是否成功手势返回或者中断了"), ("方便控制界面导航栏样式", "方便控制前后两个界面的导航栏和状态栏样式"), ("优化导航栏在转场时的样式", "优化系统navController只有一个navBar带来的问题")) } override func didSelectCell(_ title: String) { var viewController: UIViewController? if title == "拦截系统navBar返回按钮事件" { viewController = QDInterceptBackButtonEventViewController() } if title == "感知系统的手势返回" { viewController = QDNavigationTransitionViewController() } if title == "方便控制界面导航栏样式" { viewController = QDChangeNavBarStyleViewController() } if title == "优化导航栏在转场时的样式" { viewController = QDChangeNavBarStyleViewController() if let viewController = viewController as? QDChangeNavBarStyleViewController { viewController.customNavBarTransition = true } } if let viewController = viewController { viewController.title = title navigationController?.pushViewController(viewController, animated: true) } } }
mit
niunaruto/DeDaoAppSwift
DeDaoSwift/DeDaoSwiftUITests/DeDaoSwiftUITests.swift
1
1251
// // DeDaoSwiftUITests.swift // DeDaoSwiftUITests // // Created by niuting on 2017/3/1. // Copyright © 2017年 niuNaruto. All rights reserved. // import XCTest class DeDaoSwiftUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/14543-swift-sourcemanager-getmessage.swift
11
226
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a = [ { class for { enum A { struct A { class case ,
mit
cnoon/swift-compiler-crashes
crashes-duplicates/20885-no-stacktrace.swift
11
233
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing ( [ ] { enum S { let P { case { class A { func a { class case ,
mit
kzaher/RxFirebase
RxFirebase/Classes/Extensions.swift
2
2138
// // RxFirebase.swift // Pods // // Created by Krunoslav Zaher on 12/7/16. // // import Foundation import RxSwift public struct UnknownFirebaseError: Error { } func parseFirebaseResponse<T>(_ observer: AnyObserver<T>) -> (T?, Error?) -> () { return { value, error in if let value = value { observer.on(.next(value)) observer.on(.completed) } else if let error = error { observer.on(.error(error)) } else { observer.on(.error(UnknownFirebaseError())) } } } func parseFirebaseResponse<T>(_ observer: AnyObserver<StorageObservableTask<T>>) -> (T?, Error?) -> () { return { value, error in if let value = value { observer.on(.next(StorageObservableTask(result: value))) observer.on(.completed) } else if let error = error { observer.on(.error(error)) } else { observer.on(.error(UnknownFirebaseError())) } } } func parseFirebaseResponse<T>(_ observer: AnyObserver<T>) -> (Error?, T?) -> () { return { error, value in if let value = value { observer.on(.next(value)) observer.on(.completed) } else if let error = error { observer.on(.error(error)) } else { observer.on(.error(UnknownFirebaseError())) } } } func parseFirebaseResponse<T, T2>(_ observer: AnyObserver<(T2, T)>) -> (Error?, T2, T?) -> () { return { error, value2, value in if let value = value { observer.on(.next((value2, value))) observer.on(.completed) } else if let error = error { observer.on(.error(error)) } else { observer.on(.error(UnknownFirebaseError())) } } } func parseFirebaseResponse(_ observer: AnyObserver<()>) -> (Error?) -> () { return { error in if let error = error { observer.on(.error(error)) } else { observer.on(.next()) observer.on(.completed) } } }
mit
2345Team/Design-Pattern-For-Swift
10.AbstractFactoryPattern/10_AbstractFactoryPattern/操作SQLDepartment对象/SqlserverDepartment.swift
1
508
// // SqlserverDepartment.swift // 10_AbstractFactoryPattern // // Created by yangbin on 16/5/12. // Copyright © 2016年 yangbin. All rights reserved. // import Foundation class SqlserverDepartment: NSObject,Department { func getDepartment() -> SQLDepartment { print("新建一个Sqlserver的SQLDepartment对象") return SQLDepartment() } func insertDepartment(department: SQLDepartment) { print("插入一个Sqlserver的SQLDepartment对象") } }
mit
noppoMan/aws-sdk-swift
Sources/Soto/Services/ApplicationDiscoveryService/ApplicationDiscoveryService_Paginator.swift
1
6345
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension ApplicationDiscoveryService { /// Lists exports as specified by ID. All continuous exports associated with your user account can be listed if you call DescribeContinuousExports as is without passing any parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func describeContinuousExportsPaginator<Result>( _ input: DescribeContinuousExportsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, DescribeContinuousExportsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: describeContinuousExports, tokenKey: \DescribeContinuousExportsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func describeContinuousExportsPaginator( _ input: DescribeContinuousExportsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (DescribeContinuousExportsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeContinuousExports, tokenKey: \DescribeContinuousExportsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns an array of import tasks for your account, including status information, times, IDs, the Amazon S3 Object URL for the import file, and more. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func describeImportTasksPaginator<Result>( _ input: DescribeImportTasksRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, DescribeImportTasksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: describeImportTasks, tokenKey: \DescribeImportTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func describeImportTasksPaginator( _ input: DescribeImportTasksRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (DescribeImportTasksResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeImportTasks, tokenKey: \DescribeImportTasksResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension ApplicationDiscoveryService.DescribeContinuousExportsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ApplicationDiscoveryService.DescribeContinuousExportsRequest { return .init( exportIds: self.exportIds, maxResults: self.maxResults, nextToken: token ) } } extension ApplicationDiscoveryService.DescribeImportTasksRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ApplicationDiscoveryService.DescribeImportTasksRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } }
apache-2.0
functionaldude/XLPagerTabStrip
Example/Example/Spotify/SpotifyExampleViewController.swift
2
3463
// SpotifyExampleViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import XLPagerTabStrip class SpotifyExampleViewController: ButtonBarPagerTabStripViewController { @IBOutlet weak var shadowView: UIView! let graySpotifyColor = UIColor(red: 21/255.0, green: 21/255.0, blue: 24/255.0, alpha: 1.0) let darkGraySpotifyColor = UIColor(red: 19/255.0, green: 20/255.0, blue: 20/255.0, alpha: 1.0) override func viewDidLoad() { // change selected bar color settings.style.buttonBarBackgroundColor = graySpotifyColor settings.style.buttonBarItemBackgroundColor = graySpotifyColor settings.style.selectedBarBackgroundColor = UIColor(red: 33/255.0, green: 174/255.0, blue: 67/255.0, alpha: 1.0) settings.style.buttonBarItemFont = UIFont(name: "HelveticaNeue-Light", size:14) ?? UIFont.systemFont(ofSize: 14) settings.style.selectedBarHeight = 3.0 settings.style.buttonBarMinimumLineSpacing = 0 settings.style.buttonBarItemTitleColor = .black settings.style.buttonBarItemsShouldFillAvailableWidth = true settings.style.buttonBarLeftContentInset = 20 settings.style.buttonBarRightContentInset = 20 changeCurrentIndexProgressive = { (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in guard changeCurrentIndex == true else { return } oldCell?.label.textColor = UIColor(red: 138/255.0, green: 138/255.0, blue: 144/255.0, alpha: 1.0) newCell?.label.textColor = .white } super.viewDidLoad() } // MARK: - PagerTabStripDataSource override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { let child_1 = TableChildExampleViewController(style: .plain, itemInfo: IndicatorInfo(title: "FRIENDS")) child_1.blackTheme = true let child_2 = TableChildExampleViewController(style: .plain, itemInfo: IndicatorInfo(title: "FEATURED")) child_2.blackTheme = true return [child_1, child_2] } // MARK: - Actions @IBAction func closeAction(_ sender: UIButton) { dismiss(animated: true, completion: nil) } }
mit
zhangao0086/DrawingBoard
DrawingBoard/Brushes/DashLineBrush.swift
2
530
// // DashLineBrush.swift // DrawingBoard // // Created by ZhangAo on 15-2-16. // Copyright (c) 2015年 zhangao. All rights reserved. // import UIKit class DashLineBrush: BaseBrush { override func drawInContext(context: CGContextRef) { let lengths: [CGFloat] = [self.strokeWidth * 3, self.strokeWidth * 3] CGContextSetLineDash(context, 0, lengths, 2) CGContextMoveToPoint(context, beginPoint.x, beginPoint.y) CGContextAddLineToPoint(context, endPoint.x, endPoint.y) } }
mit
charmaex/JDSegues
JDSegues/JDSegueScaleIn.swift
1
1836
// // JDSegueScaleIn.swift // JDSegues // // Created by Jan Dammshäuser on 28.08.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit /// Segue where the next screen scales in from a point or the center of the screen. @objc public class JDSegueScaleIn: UIStoryboardSegue, JDSegueDelayable, JDSegueOriginable { /// Defines at which point the animation should start /// - parameter Default: center of the screen public var animationOrigin: CGPoint? /// Time the transition animation takes /// - parameter Default: 0.5 seconds public var transitionTime: NSTimeInterval = 0.5 /// Time the transition animation is delayed after calling /// - parameter Default: 0 seconds public var transitionDelay: NSTimeInterval = 0 /// Animation Curve /// - parameter Default: CurveLinear public var animationOption: UIViewAnimationOptions = .CurveLinear public override func perform() { let sourceVC = sourceViewController let destinationVC = destinationViewController let destCenter = sourceVC.view.center setupScreens() destinationVC.view.transform = CGAffineTransformMakeScale(0.05, 0.05) if let center = animationOrigin { destinationVC.view.center = center } delay() { sourceVC.view.addSubview(destinationVC.view) UIView.animateWithDuration(self.transitionTime, delay: 0, options: self.animationOption, animations: { destinationVC.view.transform = CGAffineTransformMakeScale(1, 1) destinationVC.view.center = destCenter }) { finished in self.finishSegue(nil) } } } }
mit
LetItPlay/iOSClient
blockchainapp/scenes/Channels/ChannelsProtocol.swift
1
471
// // ChannelsProtocol.swift // blockchainapp // // Created by Ivan Gorbulin on 31/08/2017. // Copyright © 2017 Ivan Gorbulin. All rights reserved. // import Foundation typealias StationResult = ([Station]) -> Void protocol ChannelsViewProtocol: class { func display(channels: [Station]) func select(rows: [Int]) } protocol ChannelsPresenterProtocol: class { func getData(onComplete: @escaping StationResult) func select(station: Station) }
mit
austinzheng/swift
test/Driver/Dependencies/chained-after.swift
3
1355
/// other ==> main | yet-another /// other ==> main +==> yet-another // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/chained-after/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/chained-after/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST-NOT: Handled // RUN: touch -t 201401240006 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./yet-another.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s // CHECK-THIRD: Handled other.swift // CHECK-THIRD: Handled main.swift // CHECK-THIRD: Handled yet-another.swift
apache-2.0
JaySonGD/SwiftDayToDay
获取通信录2/获取通信录2/ViewController.swift
1
2269
// // ViewController.swift // 获取通信录2 // // Created by czljcb on 16/3/18. // Copyright © 2016年 lQ. All rights reserved. // import UIKit import AddressBook class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if ABAddressBookGetAuthorizationStatus() == ABAuthorizationStatus.NotDetermined{ let book = ABAddressBookCreate().takeRetainedValue() ABAddressBookRequestAccessWithCompletion(book, { (flag: Bool,error: CFError!) -> Void in if flag { print("授权成功") }else{ print("授权失败") } }) } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if ABAddressBookGetAuthorizationStatus() != ABAuthorizationStatus.Authorized{ print("用户没有授权") return } let book = ABAddressBookCreate().takeRetainedValue() let peoples = ABAddressBookCopyArrayOfAllPeople(book).takeRetainedValue() let count = CFArrayGetCount(peoples) for i in 0..<count { let record = unsafeBitCast(CFArrayGetValueAtIndex(peoples, i) , ABRecordRef.self) let name = (ABRecordCopyValue(record, kABPersonFirstNameProperty).takeRetainedValue() as! String) + (ABRecordCopyValue(record, kABPersonLastNameProperty).takeRetainedValue() as! String) print(name) let phones: ABMultiValueRef = ABRecordCopyValue(record, kABPersonPhoneProperty).takeRetainedValue() as ABMultiValueRef let count = ABMultiValueGetCount(phones) for i in 0..<count{ print( ABMultiValueCopyLabelAtIndex(phones, i).takeRetainedValue() ) print( ABMultiValueCopyValueAtIndex(phones, i).takeRetainedValue() ) } } } }
mit
PureSwift/Cacao
Sources/Cacao/UITouchesEvent.swift
1
1218
// // UITouchesEvent.swift // Cacao // // Created by Alsey Coleman Miller on 11/19/17. // import Foundation internal final class UITouchesEvent: UIEvent { public override var type: UIEventType { return .touches } public override var allTouches: Set<UITouch>? { return touches } internal private(set) var touches = Set<UITouch>() internal func addTouch(_ touch: UITouch) { touches.insert(touch) if let view = touch.view { addGestureRecognizers(for: view, to: touch) } } private func invalidateGestureRecognizerForWindowCache() { } private func addGestureRecognizers(for view: UIView, to touch: UITouch) { } internal func views(for window: UIWindow) -> Set<UIView> { let views = self.touches(for: window)?.compactMap { $0.view } ?? [] return Set(views) } internal override func gestureRecognizers(for window: UIWindow) -> Set<UIGestureRecognizer> { let touches = self.touches(for: window) ?? [] return Set(touches.reduce([], { $0 + ($1.gestureRecognizers ?? []) })) } }
mit
stv-ekushida/STV-Extensions
Example/Tests/Tests.swift
1
764
import UIKit import XCTest import STV-Extensions class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
PairOfNewbie/BeautifulDay
BeautifulDay/View/MusicBar/MusicPlayBar.swift
1
8848
// // MusicPlayBar.swift // BeautifulDay // // Created by DaiFengyi on 16/4/11. // Copyright © 2016年 PairOfNewbie. All rights reserved. // import UIKit import DOUAudioStreamer class MusicPlayBar: UIView { var trk: Track? { didSet { if trk?.audioFileURL == BDAudioService.shareManager.trk?.audioFileURL { BDAudioService.shareManager.updateAction = { [unowned self](type) in switch type { case .Status: self.updateStatus() case .Duration: self.updateProgress() case .BufferingRatio: self.updateBufferingStatus() } } if BDAudioService.shareManager.streamer?.status == .Some(.Playing) { rotate() self.updateProgress() } } } } var timer: NSTimer? // var animateProgress : Double = 0 { // didSet { // rotateIcon.layer.timeOffset = animateProgress // } // } var streamer: DOUAudioStreamer? { get { return BDAudioService.shareManager.streamer } } lazy var rotateImages : [UIImage] = { var arr = [UIImage]() for index in 0...126 { arr.append(UIImage(named: "cd_\(index)")!) } return arr }() @IBOutlet weak var rotateIcon: UIImageView! @IBOutlet weak var remainingLabel: UILabel! @IBOutlet weak var artistLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! //MARK:- Initial override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } deinit { timer?.invalidate() } private func commonInit() { let tapGesture = UITapGestureRecognizer(target: self, action: NSSelectorFromString("onTap:")) addGestureRecognizer(tapGesture) } // func setupSubviews() { // let fromPoint = rotateIcon.center // let toPoint = self.center // let movePath = UIBezierPath() // movePath.moveToPoint(fromPoint) // movePath.addLineToPoint(toPoint) // let animation = CAKeyframeAnimation(keyPath: "position") // animation.path = movePath.CGPath // // animation.duration = 1 // // animation.removedOnCompletion = false // // animation.fillMode = kCAFillModeForwards // // animation.autoreverses = false // // let animation1 = CABasicAnimation(keyPath: "transform.scale") // animation1.fromValue = NSValue(CATransform3D: CATransform3DIdentity) // animation1.toValue = NSValue(CATransform3D: CATransform3DMakeScale(3, 3, 1)) // // animation1.removedOnCompletion = false // // animation1.duration = 1 // // animation1.fillMode = kCAFillModeForwards // // animation1.autoreverses = false // // let animationGroup = CAAnimationGroup() // animationGroup.animations = [animation, animation1] // animationGroup.removedOnCompletion = false // animationGroup.duration = 1 // animationGroup.fillMode = kCAFillModeForwards // animationGroup.autoreverses = false // // rotateIcon.layer.addAnimation(animationGroup, forKey: "rotateIcon") // } //MAKR:- Action func onTap(tapGesture: UITapGestureRecognizer) { print("onTap:") if streamer?.status == .Playing {// 正在播放 if trk?.audioFileURL == BDAudioService.shareManager.trk?.audioFileURL {// 当前音乐,则暂停播放 BDAudioService.shareManager.pause() }else {// 非当前音乐,切歌 if let trk = self.trk { BDAudioService.shareManager.resetStreamer(trk, updateAction: { [unowned self](type) in switch type { case .Status: self.updateStatus() case .Duration: self.updateProgress() case .BufferingRatio: self.updateBufferingStatus() } }) } } }else if streamer?.status == .Paused {// 正在暂停 if let trk = self.trk { if trk.audioFileURL != BDAudioService.shareManager.trk?.audioFileURL {// 不是当前音乐,切歌 BDAudioService.shareManager.resetStreamer(trk, updateAction: { [unowned self](type) in switch type { case .Status: self.updateStatus() case .Duration: self.updateProgress() case .BufferingRatio: self.updateBufferingStatus() } }) }else {// 当前音乐,播放 BDAudioService.shareManager.play() } } }else { if let trk = self.trk { BDAudioService.shareManager.resetStreamer(trk, updateAction: { [unowned self](type) in switch type { case .Status: self.updateStatus() case .Duration: self.updateProgress() case .BufferingRatio: self.updateBufferingStatus() } }) } } } //MARK:- Public func updateBufferingStatus() { remainingLabel.text = String(format: "Received %.2f/%.2f MB (%.2f %%), Speed %.2f MB/s", Float(streamer!.receivedLength) / 1024 / 1024, Float(streamer!.expectedLength) / 1024 / 1024, streamer!.bufferingRatio * 100.0, Float(streamer!.downloadSpeed) / 1024 / 1024) } func updateStatus() { //todo /** * switch ([_streamer status]) { case DOUAudioStreamerPlaying: [_statusLabel setText:@"playing"]; [_buttonPlayPause setTitle:@"Pause" forState:UIControlStateNormal]; break; case DOUAudioStreamerPaused: [_statusLabel setText:@"paused"]; [_buttonPlayPause setTitle:@"Play" forState:UIControlStateNormal]; break; case DOUAudioStreamerIdle: [_statusLabel setText:@"idle"]; [_buttonPlayPause setTitle:@"Play" forState:UIControlStateNormal]; break; case DOUAudioStreamerFinished: [_statusLabel setText:@"finished"]; [self _actionNext:nil]; break; case DOUAudioStreamerBuffering: [_statusLabel setText:@"buffering"]; break; case DOUAudioStreamerError: [_statusLabel setText:@"error"]; break; } */ let status = streamer!.status if status == .Playing { if rotateIcon.isAnimating() { resumeLayer(rotateIcon.layer) }else { rotate() } }else if status == .Paused { pauseLayer(rotateIcon.layer) }else if status == .Idle { rotateIcon.stopAnimating() }else if status == .Finished { rotateIcon.stopAnimating() }else if status == .Buffering { }else if status == .Error { rotateIcon.stopAnimating() } } func updateProgress() { if streamer!.duration == 0{ progressView.setProgress(0, animated: false) }else { progressView.setProgress(Float(streamer!.currentTime / streamer!.duration), animated: true) } } //MARK: Animation func rotate() { rotateIcon.animationImages = rotateImages rotateIcon.startAnimating() } func pauseLayer(layer: CALayer) { let pauseTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) layer.speed = 0 layer.timeOffset = pauseTime } func resumeLayer(layer: CALayer) { if layer.speed == 1 { return } let pausedTime = layer.timeOffset layer.speed = 1 layer.timeOffset = 0 layer.beginTime = 0 let timeSicePause = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime layer.beginTime = timeSicePause } }
mit
kreshikhin/scituner
SciTuner/ViewControllers/TunerViewController.swift
1
8336
// // TunerViewController.swift // SciTuner // // Created by Denis Kreshikhin on 25.02.15. // Copyright (c) 2015 Denis Kreshikhin. All rights reserved. // import UIKit import SpriteKit import RealmSwift class TunerViewController: UIViewController { typealias `Self` = TunerViewController let realm = try! Realm() var settingsViewController = SettingsViewController() var instrumentsAlertController = InstrumentsAlertController(title: nil, message: nil, preferredStyle: .actionSheet) var fretsAlertController = FretsAlertController(title: nil, message: nil, preferredStyle: .actionSheet) var filtersAlertController = FiltersAlertController(title: nil, message: nil, preferredStyle: .actionSheet) var tuner = Tuner.sharedInstance var tubeView: SKView? var tubeScene: TubeScene? let processing = Processing(pointCount: Settings.processingPointCount) var microphone: Microphone? let stackView = UIStackView() let tuningView = TuningView() let modebar = ModebarView() let fineTuningView = FineTuningView() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Style.background customizeNavigationBar() addStackView() customizeDelegates() addTubeView() addNoteBar() addTuningView() addModeBar() microphone = Microphone(sampleRate: Settings.sampleRate, sampleCount: Settings.sampleCount) microphone?.delegate = self microphone?.activate() switch tuner.filter { case .on: processing.enableFilter() case .off: processing.disableFilter() } modebar.fret = tuner.fret modebar.filter = tuner.filter } func customizeDelegates() { tuner.delegate = self instrumentsAlertController.parentDelegate = self fretsAlertController.parentDelegate = self filtersAlertController.parentDelegate = self } func customizeNavigationBar() { self.navigationItem.title = "SciTuner".localized() self.navigationItem.leftBarButtonItem = UIBarButtonItem( title: tuner.instrument.localized(), style: UIBarButtonItemStyle.plain, target: self, action: #selector(Self.showInstrumentsAlertController)) self.navigationItem.rightBarButtonItem = UIBarButtonItem( title: "settings".localized(), style: UIBarButtonItemStyle.plain, target: self, action: #selector(Self.showSettingsViewController)) } func addStackView() { stackView.frame = view.bounds stackView.axis = .vertical stackView.distribution = .equalSpacing view.addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true stackView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true stackView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true } func addTubeView() { tubeView = SKView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.width)) tubeView?.translatesAutoresizingMaskIntoConstraints = false tubeView?.heightAnchor.constraint(equalTo: tubeView!.widthAnchor, multiplier: 1.0).isActive = true stackView.addArrangedSubview(tubeView!) if let tb = tubeView { tb.showsFPS = Settings.showFPS tubeScene = TubeScene(size: tb.bounds.size) tb.presentScene(tubeScene) tb.ignoresSiblingOrder = true tubeScene?.customDelegate = self } } func addModeBar() { modebar.fretMode.addTarget(self, action: #selector(TunerViewController.showFrets), for: .touchUpInside) modebar.filterMode.addTarget(self, action: #selector(TunerViewController.showFilters), for: .touchUpInside) stackView.addArrangedSubview(modebar) } func addNoteBar() { stackView.addArrangedSubview(fineTuningView) } func addTuningView() { stackView.addArrangedSubview(tuningView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tuningView.tuning = tuner.tuning } func showSettingsViewController() { navigationController?.pushViewController(settingsViewController, animated: true) } func showInstrumentsAlertController() { present(instrumentsAlertController, animated: true, completion: nil) } func showFrets() { present(fretsAlertController, animated: true, completion: nil) } func showFilters() { present(filtersAlertController, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension TunerViewController: TunerDelegate { func didSettingsUpdate() { switch tuner.filter { case .on: processing.enableFilter() case .off: processing.disableFilter() } } func didFrequencyChange() { //panel?.targetFrequency?.text = String(format: "%.2f %@", tuner.targetFrequency(), "Hz".localized()) } func didStatusChange() { if tuner.isActive { microphone?.activate() } else { microphone?.inactivate() } } } extension TunerViewController: MicrophoneDelegate { func microphone(_ microphone: Microphone?, didReceive data: [Double]?) { if tuner.isPaused { return } if let tf = tuner.targetFrequency() { processing.setTargetFrequency(tf) } guard let micro = microphone else { return } var wavePoints = [Double](repeating: 0, count: Int(processing.pointCount-1)) let band = tuner.band() processing.setBand(fmin: band.fmin, fmax: band.fmax) processing.push(&micro.sample) processing.savePreview(&micro.preview) processing.recalculate() processing.buildSmoothStandingWave2(&wavePoints, length: wavePoints.count) tuner.frequency = processing.getFrequency() tuner.updateTargetFrequency() tubeScene?.draw(wave: wavePoints) //panel?.actualFrequency?.text = String(format: "%.2f %@", tuner.frequency, "Hz".localized()) //panel?.frequencyDeviation!.text = String(format: "%.0fc", tuner.frequencyDeviation()) //self.panel?.notebar?.pointerPosition = self.tuner.stringPosition() fineTuningView.pointerPosition = tuner.noteDeviation() //print("f dev:", tuner.frequencyDeviation()) tuningView.notePosition = CGFloat(tuner.stringPosition()) if processing.pulsation() > 3 { tuningView.showPointer() fineTuningView.showPointer() } else { tuningView.hidePointer() fineTuningView.hidePointer() } } } extension TunerViewController: InstrumentsAlertControllerDelegate { func didChange(instrument: Instrument) { try! realm.write { tuner.instrument = instrument } tuningView.tuning = tuner.tuning navigationItem.leftBarButtonItem?.title = tuner.instrument.localized() } } extension TunerViewController: FretsAlertControllerDelegate { func didChange(fret: Fret) { try! realm.write { tuner.fret = fret } modebar.fret = fret } } extension TunerViewController: FiltersAlertControllerDelegate { func didChange(filter: Filter) { try! realm.write { tuner.filter = filter } modebar.filter = filter } } extension TunerViewController: TubeSceneDelegate { func getNotePosition() -> CGFloat { return CGFloat(tuner.notePosition()) } func getPulsation() -> CGFloat { return CGFloat(processing.pulsation()) } }
mit
googlemaps/last-mile-fleet-solution-samples
ios_driverapp_samples/LMFSDriverSampleApp/ListTab/StopList.swift
1
2515
/* * Copyright 2022 Google LLC. 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 SwiftUI /// This view shows a list of stops that the vehicle will navigate to in order. Each stop is /// represented by a `StopListRow`. struct StopList: View { @EnvironmentObject var modelData: ModelData @State private var editMode = EditMode.inactive var body: some View { NavigationView { VStack(alignment: .leading) { List { ForEach(modelData.stops) { stop in StopListRow(stop: stop) .moveDisabled(stop.taskStatus != .pending) } .onMove { source, destination in modelData.moveStops(source: source, destination: destination) } } .environment(\.editMode, $editMode) VStack(alignment: .leading) { HStack { Text("ID: \(modelData.manifest.vehicle.vehicleId)") Spacer() Button(action: { UIPasteboard.general.string = modelData.manifest.vehicle.vehicleId }) { Image(systemName: "doc.on.doc") } } Text("Total tasks: \(modelData.manifest.tasks.count)") } .foregroundColor(.gray) .padding(EdgeInsets(top: 0, leading: 20, bottom: 10, trailing: 20)) } .navigationTitle("Your itinerary") .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(editMode == .inactive ? "Reorder Stops" : "Done") { editMode = (editMode == .inactive ? .active : .inactive) } } } } .navigationViewStyle(StackNavigationViewStyle()) .navigationBarTitleDisplayMode(.inline) .ignoresSafeArea(edges: .top) } } struct StopList_Previews: PreviewProvider { static var previews: some View { let _ = LMFSDriverSampleApp.googleMapsInited StopList() .environmentObject(ModelData(filename: "test_manifest")) } }
apache-2.0
aleffert/dials
Desktop/Source/FormattingUtilities.swift
1
1470
// // FormattingUtilities.swift // Dials-Desktop // // Created by Akiva Leffert on 3/22/15. // // import Foundation func stringFromNumber(_ value : Float, requireIntegerPart : Bool = false) -> String { return stringFromNumber(NSNumber(value: value as Float), requireIntegerPart : requireIntegerPart) } func stringFromNumber(_ value : CGFloat, requireIntegerPart : Bool = false) -> String { return stringFromNumber(NSNumber(value: Double(value)), requireIntegerPart : requireIntegerPart) } func stringFromNumber(_ value : Double, requireIntegerPart : Bool = false) -> String { return stringFromNumber(NSNumber(value: value as Double), requireIntegerPart : requireIntegerPart) } func stringFromNumber(_ value : NSNumber, requireIntegerPart : Bool = false) -> String { let formatter = NumberFormatter() formatter.maximumFractionDigits = 2 formatter.alwaysShowsDecimalSeparator = false formatter.minimumIntegerDigits = requireIntegerPart ? 1 : 0 return formatter.string(from: value)! } extension String { func formatWithParameters(_ parameters : [String:Any]) -> String { let result = self.mutableCopy() as! NSMutableString for (key, value) in parameters { let range = NSMakeRange(0, result.length) let token = "{\(key)}" result.replaceOccurrences(of: token, with: "\(value)", options: NSString.CompareOptions(), range: range) } return result as String } }
mit
toshiapp/toshi-ios-client
Toshi/Controllers/DisappearingNavBarViewController.swift
1
10020
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import TinyConstraints import SweetUIKit import UIKit /// A base view controller which has a scroll view and a navigation bar whose contents disappear /// when the bar is scrolled. Handles setup of the scroll view and disappearing navigation bar. /// /// Subclasses are required to override: /// - backgroundTriggerView /// - titleTriggerView /// - addScrollableContent(to:) /// /// Note that all conformances are on the main class since methods in extensions cannot be overridden. class DisappearingNavBarViewController: UIViewController, DisappearingBackgroundNavBarDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate { /// If disappearing is enabled at present. var disappearingEnabled: Bool { return true } /// The current height of the disappearing nav bar. var navBarHeight: CGFloat = DisappearingBackgroundNavBar.defaultHeight /// The height of the top spacer which can be scrolled under the nav bar. Defaults to the nav bar height. var topSpacerHeight: CGFloat { return navBarHeight } /// The view to use as the trigger to show or hide the background. var backgroundTriggerView: UIView { fatalError("Must be overridden by subclass") } /// The view to use as the trigger to show or hide the title. var titleTriggerView: UIView { fatalError("Must be overridden by subclass") } /// True if the left button of the nav bar should be set up as a back button, false if not. var leftAsBackButton: Bool { return true } /// The nav bar to adjust lazy var navBar: DisappearingBackgroundNavBar = { let navBar = DisappearingBackgroundNavBar(delegate: self) if leftAsBackButton { navBar.setupLeftAsBackButton() } return navBar }() private lazy var defaultScrollView = UIScrollView() /// Note that by default, this is a vanilla UIScrollView. If this is overridden /// with a UITableView or UICollectionView in a subclass, the methods to set up /// a content view and content within that view will not be called. var scrollingView: UIScrollView { return defaultScrollView } private var navBarTargetHeight: CGFloat { if #available(iOS 11, *) { return view.safeAreaInsets.top + DisappearingBackgroundNavBar.defaultHeight } else { return DisappearingBackgroundNavBar.defaultHeight } } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() setupNavBarAndScrollingContent() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) // Keep the pop gesture recognizer working self.navigationController?.interactivePopGestureRecognizer?.delegate = self } @available(iOS 11.0, *) override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() updateNavBarHeightIfNeeded() } override func viewWillDisappear(_ animated: Bool) { if self.presentedViewController == nil { navigationController?.setNavigationBarHidden(false, animated: animated) } super.viewWillDisappear(animated) } // MARK: - View Setup /// Sets up the navigation bar and all scrolling content. /// NOTE: Should be set up before any other views are added to the Nav + Scroll parent or there's some weirdness with the scroll view offset. func setupNavBarAndScrollingContent() { view.addSubview(scrollingView) scrollingView.delegate = self scrollingView.edgesToSuperview() view.addSubview(navBar) navBar.edgesToSuperview(excluding: .bottom) updateNavBarHeightIfNeeded() navBar.heightConstraint = navBar.height(navBarHeight) if !(scrollingView is UITableView) && !(scrollingView is UICollectionView) { setupContentView(in: scrollingView) } // else, it's something else that we don't want a content view in } private func setupContentView(in scrollView: UIScrollView) { let contentView = UIView(withAutoLayout: false) scrollView.addSubview(contentView) contentView.edgesToSuperview() contentView.width(to: scrollView) addScrollableContent(to: contentView) } /// Called when scrollable content should be programmatically added to the given container view, which /// has already been added to the scrollView. /// /// Use autolayout to add views to the container, making sure to pin the bottom of the bottom view to the bottom /// of the container. Autolayout will then automatically figure out the height of the container, and then use /// the container's size as the scrollable content size. /// /// - Parameter contentView: The content view to add scrollable content to. func addScrollableContent(to contentView: UIView) { fatalError("Subclasses using the content view must override and not call super") } /// Adds and returns a spacer view to the top of the scroll view's content view the same height as the nav bar (so content can scroll under it) /// /// - Parameter contentView: The content view to add the spacer to /// - Returns: The spacer view so other views can be constrained to it. func addTopSpacer(to contentView: UIView) -> UIView { let spacer = UIView(withAutoLayout: false) spacer.backgroundColor = Theme.viewBackgroundColor contentView.addSubview(spacer) spacer.edgesToSuperview(excluding: .bottom) spacer.height(topSpacerHeight) return spacer } // MARK: - Nav Bar Updating /// Updates the height of the nav bar to account for changes to the Safe Area insets. func updateNavBarHeightIfNeeded() { guard navBarHeight != navBarTargetHeight else { /* we're good */ return } guard let heightConstraint = navBar.heightConstraint, heightConstraint.constant != navBarTargetHeight else { return } navBarHeight = navBarTargetHeight heightConstraint.constant = navBarHeight } /// Updates the state of the nav bar based on where the target views are in relation to the bottom of the nav bar. /// NOTE: This should generally be called from `scrollViewDidScroll`. func updateNavBarAppearance() { guard disappearingEnabled else { return } guard !scrollingView.frame.equalTo(.zero) else { /* View hasn't been set up yet. */ return } updateBackgroundAlpha() updateTitleAlpha() } private func updateBackgroundAlpha() { let targetInParentBounds = backgroundTriggerView.convert(backgroundTriggerView.bounds, to: view) let topOfTarget = targetInParentBounds.midY let centerOfTarget = targetInParentBounds.maxY let differenceFromTop = navBarHeight - topOfTarget let differenceFromCenter = navBarHeight - centerOfTarget if differenceFromCenter > 0 { navBar.setBackgroundAlpha(1) } else if differenceFromTop < 0 { navBar.setBackgroundAlpha(0) } else { let betweenTopAndCenter = centerOfTarget - topOfTarget let percentage = differenceFromTop / betweenTopAndCenter navBar.setBackgroundAlpha(percentage) } } private func updateTitleAlpha() { let targetInParentBounds = titleTriggerView.convert(titleTriggerView.bounds, to: view) let centerOfTarget = targetInParentBounds.midY let bottomOfTarget = targetInParentBounds.maxY let threeQuartersOfTarget = (centerOfTarget + bottomOfTarget) / 2 let differenceFromThreeQuarters = navBarHeight - threeQuartersOfTarget let differenceFromBottom = navBarHeight - bottomOfTarget if differenceFromBottom > 0 { navBar.setTitleAlpha(1) navBar.setTitleOffsetPercentage(from: 1) } else if differenceFromThreeQuarters < 0 { navBar.setTitleAlpha(0) navBar.setTitleOffsetPercentage(from: 0) } else { let betweenThreeQuartersAndBottom = bottomOfTarget - threeQuartersOfTarget let percentageComplete = differenceFromThreeQuarters / betweenThreeQuartersAndBottom navBar.setTitleAlpha(percentageComplete) navBar.setTitleOffsetPercentage(from: percentageComplete) } } // MARK: - Disappearing Background Nav Bar Delegate func didTapRightButton(in navBar: DisappearingBackgroundNavBar) { assertionFailure("If you want this to do something, override it in the subclass") } func didTapLeftButton(in navBar: DisappearingBackgroundNavBar) { self.navigationController?.popViewController(animated: true) } // MARK: - Scroll View Delegate func scrollViewDidScroll(_ scrollView: UIScrollView) { updateNavBarAppearance() } // MARK: - Gesture Recognizer Delegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { // Allow the pop gesture to be recognized return true } }
gpl-3.0
slavapestov/swift
validation-test/compiler_crashers_fixed/27687-swift-classtype-get.swift
5
315
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func a{ enum b class a<T{ func a class a class A{ struct d<T,A{ { } enum S<T{class B<T>:a } class a
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/26148-swift-typebase-getmembersubstitutions.swift
11
640
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class B}struct B<T struct S<T{struct S<T let:{<T protocol c struct S<g{class A var:{struct b{} {}<T g enum S<T enum S<T where T:C{enum B<T{ class B struct S<T{enum S:Collection} enum S<B struct B<a enum B<b struct S<T enum S<b struct S<T class B<H
apache-2.0
danielsaidi/iExtra
iExtra/UI/Layout/UICollectionViewFlowLayout+Layouts.swift
1
1201
// // UICollectionViewFlowLayout+Layouts.swift // iExtra // // Created by Daniel Saidi on 2019-02-01. // Copyright © 2019 Daniel Saidi. All rights reserved. // import UIKit public extension UICollectionViewFlowLayout { private static var idiom: UIUserInterfaceIdiom { return UIDevice.current.userInterfaceIdiom } static var isPadLayout: Bool { return isPadLayoutIdiom(idiom) } static var isPhoneLayout: Bool { return isPhoneLayoutIdiom(idiom) } static var isTVLayout: Bool { return isTVLayoutIdiom(idiom) } var idiom: UIUserInterfaceIdiom { return UICollectionViewFlowLayout.idiom } var isPadLayout: Bool { return UICollectionViewFlowLayout.isPadLayout } var isPhoneLayout: Bool { return UICollectionViewFlowLayout.isPhoneLayout } var isTVLayout: Bool { return UICollectionViewFlowLayout.isTVLayout } static func isPadLayoutIdiom(_ idiom: UIUserInterfaceIdiom) -> Bool { return idiom == .pad } static func isPhoneLayoutIdiom(_ idiom: UIUserInterfaceIdiom) -> Bool { return idiom == .phone } static func isTVLayoutIdiom(_ idiom: UIUserInterfaceIdiom) -> Bool { return idiom == .tv } }
mit
troystribling/BlueCap
BlueCapKit/External/FutureLocation/BeaconRegion.swift
1
3617
// // BeaconRegion.swift // BlueCap // // Created by Troy Stribling on 9/14/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation import CoreLocation public class BeaconRegion : Region { internal let beaconPromise: StreamPromise<[Beacon]> internal var _beacons = [Beacon]() internal let clBeaconRegion: CLBeaconRegion public var beacons: [Beacon] { return self._beacons.sorted() {(b1: Beacon, b2: Beacon) -> Bool in switch b1.discoveredAt.compare(b2.discoveredAt as Date) { case .orderedSame: return true case .orderedDescending: return false case .orderedAscending: return true } } } public var proximityUUID: UUID? { return self.clBeaconRegion.proximityUUID } public var major : Int? { if let _major = self.clBeaconRegion.major { return _major.intValue } else { return nil } } public var minor: Int? { if let _minor = self.clBeaconRegion.minor { return _minor.intValue } else { return nil } } public var notifyEntryStateOnDisplay: Bool { get { return self.clBeaconRegion.notifyEntryStateOnDisplay } set { self.clBeaconRegion.notifyEntryStateOnDisplay = newValue } } public init(region: CLBeaconRegion, capacity: Int = Int.max) { self.clBeaconRegion = region self.beaconPromise = StreamPromise<[Beacon]>(capacity: capacity) super.init(region:region, capacity: capacity) self.notifyEntryStateOnDisplay = true } public convenience init(proximityUUID: UUID, identifier: String, capacity: Int = Int.max) { self.init(region:CLBeaconRegion(proximityUUID: proximityUUID, identifier: identifier), capacity: capacity) } public convenience init(proximityUUID: UUID, identifier: String, major: UInt16, capacity: Int = Int.max) { let beaconMajor : CLBeaconMajorValue = major let beaconRegion = CLBeaconRegion(proximityUUID: proximityUUID, major: beaconMajor, identifier: identifier) self.init(region: beaconRegion, capacity: capacity) } public convenience init(proximityUUID: UUID, identifier: String, major: UInt16, minor: UInt16, capacity: Int = Int.max) { let beaconMinor : CLBeaconMinorValue = minor let beaconMajor : CLBeaconMajorValue = major let beaconRegion = CLBeaconRegion(proximityUUID:proximityUUID, major:beaconMajor, minor:beaconMinor, identifier:identifier) self.init(region:beaconRegion, capacity:capacity) } public override class func isMonitoringAvailableForClass() -> Bool { return CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) } public func peripheralDataWithMeasuredPower(_ measuredPower: Int?) -> [String : AnyObject] { let power: [NSObject : AnyObject] if let measuredPower = measuredPower { power = self.clBeaconRegion.peripheralData(withMeasuredPower: NSNumber(value: measuredPower)) as [NSObject:AnyObject] } else { power = self.clBeaconRegion.peripheralData(withMeasuredPower: nil) as [NSObject : AnyObject] } var result = [String : AnyObject]() for key in power.keys { if let keyPower = power[key], let key = key as? String { result[key] = keyPower } } return result } }
mit
hallas/agent
Agent/Agent.swift
1
6541
// // Agent.swift // Agent // // Created by Christoffer Hallas on 6/2/14. // Copyright (c) 2014 Christoffer Hallas. All rights reserved. // import Foundation public class Agent { public typealias Headers = Dictionary<String, String> public typealias Response = (NSHTTPURLResponse?, AnyObject?, NSError?) -> Void public typealias RawResponse = (NSHTTPURLResponse?, NSData?, NSError?) -> Void /** * Members */ var base: NSURL? var headers: Dictionary<String, String>? var request: NSMutableURLRequest? let queue = NSOperationQueue() /** * Initialize */ init(url: String, headers: Dictionary<String, String>?) { self.base = NSURL(string: url) self.headers = headers } convenience init(url: String) { self.init(url: url, headers: nil) } init(method: String, url: String, headers: Dictionary<String, String>?) { self.headers = headers self.request(method, path: url) } convenience init(method: String, url: String) { self.init(method: method, url: url, headers: nil) } /** * Request */ func request(method: String, path: String) -> Agent { var u: NSURL if self.base != nil { u = self.base!.URLByAppendingPathComponent(path) } else { u = NSURL(string: path)! } self.request = NSMutableURLRequest(URL: u) self.request!.HTTPMethod = method if self.headers != nil { self.request!.allHTTPHeaderFields = self.headers } return self } /** * GET */ public class func get(url: String) -> Agent { return Agent(method: "GET", url: url, headers: nil) } public class func get(url: String, headers: Headers) -> Agent { return Agent(method: "GET", url: url, headers: headers) } public class func get(url: String, done: Response) -> Agent { return Agent.get(url).end(done) } public class func get(url: String, headers: Headers, done: Response) -> Agent { return Agent.get(url, headers: headers).end(done) } public func get(url: String, done: Response) -> Agent { return self.request("GET", path: url).end(done) } /** * POST */ public class func post(url: String) -> Agent { return Agent(method: "POST", url: url, headers: nil) } public class func post(url: String, headers: Headers) -> Agent { return Agent(method: "POST", url: url, headers: headers) } public class func post(url: String, done: Response) -> Agent { return Agent.post(url).end(done) } public class func post(url: String, headers: Headers, data: AnyObject) -> Agent { return Agent.post(url, headers: headers).send(data) } public class func post(url: String, data: AnyObject) -> Agent { return Agent.post(url).send(data) } public class func post(url: String, data: AnyObject, done: Response) -> Agent { return Agent.post(url, data: data).send(data).end(done) } public class func post(url: String, headers: Headers, data: AnyObject, done: Response) -> Agent { return Agent.post(url, headers: headers, data: data).send(data).end(done) } public func POST(url: String, data: AnyObject, done: Response) -> Agent { return self.request("POST", path: url).send(data).end(done) } /** * PUT */ public class func put(url: String) -> Agent { return Agent(method: "PUT", url: url, headers: nil) } public class func put(url: String, headers: Headers) -> Agent { return Agent(method: "PUT", url: url, headers: headers) } public class func put(url: String, done: Response) -> Agent { return Agent.put(url).end(done) } public class func put(url: String, headers: Headers, data: AnyObject) -> Agent { return Agent.put(url, headers: headers).send(data) } public class func put(url: String, data: AnyObject) -> Agent { return Agent.put(url).send(data) } public class func put(url: String, data: AnyObject, done: Response) -> Agent { return Agent.put(url, data: data).send(data).end(done) } public class func put(url: String, headers: Headers, data: AnyObject, done: Response) -> Agent { return Agent.put(url, headers: headers, data: data).send(data).end(done) } public func PUT(url: String, data: AnyObject, done: Response) -> Agent { return self.request("PUT", path: url).send(data).end(done) } /** * DELETE */ public class func delete(url: String) -> Agent { return Agent(method: "DELETE", url: url, headers: nil) } public class func delete(url: String, headers: Headers) -> Agent { return Agent(method: "DELETE", url: url, headers: headers) } public class func delete(url: String, done: Response) -> Agent { return Agent.delete(url).end(done) } public class func delete(url: String, headers: Headers, done: Response) -> Agent { return Agent.delete(url, headers: headers).end(done) } public func delete(url: String, done: Response) -> Agent { return self.request("DELETE", path: url).end(done) } /** * Methods */ public func data(data: NSData?, mime: String) -> Agent { self.set("Content-Type", value: mime) self.request!.HTTPBody = data return self } public func send(data: AnyObject) -> Agent { var error: NSError? let json = NSJSONSerialization.dataWithJSONObject(data, options: nil, error: &error) return self.data(json, mime: "application/json") } public func set(header: String, value: String) -> Agent { self.request!.setValue(value, forHTTPHeaderField: header) return self } public func end(done: Response) -> Agent { let completion = { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in if error != .None { done(.None, data, error) return } var error: NSError? var json: AnyObject! if data != .None { json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) } let res = response as! NSHTTPURLResponse done(res, json, error) } NSURLConnection.sendAsynchronousRequest(self.request!, queue: self.queue, completionHandler: completion) return self } public func raw(done: RawResponse) -> Agent { let completion = { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in if error != .None { done(.None, data, error) return } done(response as? NSHTTPURLResponse, data, error) } NSURLConnection.sendAsynchronousRequest(self.request!, queue: self.queue, completionHandler: completion) return self } }
mit
austinzheng/swift
validation-test/compiler_crashers_fixed/26692-swift-astcontext-getloadedmodule.swift
65
457
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class A{class C{class B{func b:T}}}protocol A{func a<T:T.d
apache-2.0
jbrudvik/swift-playgrounds
multiple-optional-unwrapping.playground/Contents.swift
1
186
// Multiple optionals can be unwrapped at once var a: Int? = 1 var b: Int? = 2 var c: Int? = 3 if let a = a, b = b, c = c where c != 0 { println(a) println(b) println(c) }
mit
hooman/swift
test/Index/invalid_code.swift
4
1427
// RUN: %target-swift-ide-test -print-indexed-symbols -include-locals -source-filename %s | %FileCheck %s var _: Int { get { return 1 } } func test() { for o in allObjects { _ = o.something // don't crash } } class CrashTest { var something = 0 func returnSelf(_ h: [AnyHashable: Any?]) -> CrashTest { return self } init() { } } // CHECK: [[@LINE+1]]:13 | instance-method/Swift | returnSelf CrashTest().returnSelf(["": 0]).something class CrashTest2 { // CHECK: [[@LINE+1]]:8 | instance-method/Swift | bar func bar() { someClosure { [weak self] in guard let sSelf = self else { return } let newDataProvider = Foo() newDataProvider.delegate = sSelf } } } public struct BadCollection: Collection { public var startIndex: Index { } public var endIndex: Index { } public func index(after index: Index) -> Index { } public subscript(position: Index) -> Element { } } struct Protector<T> {} extension Protector where T: RangeReplaceableCollection { func append(_ newElement: T.Iterator.Element) { undefined { (foo: T) in // CHECK: [[@LINE-1]]:18 | param(local)/Swift | foo | {{.*}} | Def,RelChild // CHECK: [[@LINE-2]]:18 | function/acc-get(local)/Swift | getter:foo | {{.*}} | Def,Impl,RelChild,RelAcc // CHECK: [[@LINE-3]]:18 | function/acc-set(local)/Swift | setter:foo | {{.*}} | Def,Impl,RelChild,RelAcc _ = newElement } } }
apache-2.0
mdiep/Logician
Sources/State.swift
1
10884
// // State.swift // Logician // // Created by Matt Diephouse on 9/2/16. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Foundation public enum Error: Swift.Error { case UnificationError } /// A partial or complete solution to a logic problem. public struct State { /// Type-erased information about a set of unified variables. private struct Info { /// The value of the variables, if any. var value: Any? /// Mapping from a key to the derived variable. /// /// All variables that share the same basis must be unified. var derived: [AnyVariable.Basis.Key: AnyVariable] = [:] /// Functions that unify variables from bijections. var bijections: [AnyVariable: Bijection] init(_ bijections: [AnyVariable: Bijection] = [:]) { self.bijections = bijections } } /// The data backing the state. private var context = Context<AnyVariable, Info>() /// The constraints on the state. private var constraints: [Constraint] = [] /// Look up the value of a property. /// /// - parameters: /// - property: A property of a variable in the state /// /// - returns: The value of the property, or `nil` if the value is unknown /// or the variable isn't in the `State`. public func value<Value>(of property: Property<Value>) -> Value? { return value(of: property.variable) .map { property.transform($0) as! Value } } /// Look up the value of a variable. /// /// - parameters: /// - variable: A variable in the state /// /// - returns: The value of the variable, or `nil` if the value is unknown /// or the variable isn't in the `State`. internal func value(of variable: AnyVariable) -> Any? { return context[variable]?.value } /// Look up the value of a variable. /// /// - parameters: /// - variable: A variable in the state /// /// - returns: The value of the variable, or `nil` if the value is unknown /// or the variable isn't in the `State`. public func value<Value>(of variable: Variable<Value>) -> Value? { // ! because asking for the value of a variable can't change it return try! bijecting(variable) .value(of: variable.erased) .map { $0 as! Value } } /// Add a constraint to the state. internal mutating func constrain(_ constraint: @escaping Constraint) throws { try constraint(self) constraints.append(constraint) } /// Add a constraint to the state. internal func constraining(_ constraint: @escaping Constraint) throws -> State { var state = self try state.constrain(constraint) return state } /// Add a bijection to the state, unifying the variable it came from if the /// other variable has a value. private func bijecting<Value>(_ variable: Variable<Value>) throws -> State { // We've already gone through this for this variable if context[variable.erased] != nil { return self } // This isn't a bijection. if variable.bijections.isEmpty { return self } var state = self // If the variable doesn't have a basis, then this *must* be a 1-to-1 // bijection. So the source is the variable that isn't passed in. let source = variable.erased.basis?.source ?? variable.bijections.keys.first { $0 != variable.erased }! let unifySource = variable.bijections[source]! // Unify all derived variables that share the same key. They are, by // definition, unified. var info = state.context[source] ?? Info() for (variable, bijection) in variable.bijections { if variable == source { continue } info.bijections[variable] = bijection if let key = variable.basis?.key { if let existing = info.derived[key] { // Since variable is new, it can't have a value. So just // assume the existing variable's info. state.context.merge(existing, variable) { lhs, _ in lhs } } else { info.derived[key] = variable state.context[variable] = Info([source: unifySource]) } } else { state.context[variable] = Info([source: unifySource]) } } state.context[source] = info // Try to unify each bijection for bijection in variable.bijections.values { state = try bijection(state) } try state.verifyConstraints() return state } /// Verify that all the constraints in the state have been maintained, /// throwing if any have been violated. private func verifyConstraints() throws { for constraint in constraints { try constraint(self) } } /// Unify a variable with a value. /// /// - parameters: /// - variable: The variable to unify /// - value: The value to give the variable /// /// - note: `throws` if `variable` already has a different value. public mutating func unify<Value>(_ variable: Variable<Value>, _ value: Value) throws { self = try unifying(variable, value) } /// Unify a variable with a value. /// /// - parameters: /// - variable: The variable to unify /// - value: The value to give the variable /// /// - returns: The unified state. /// /// - note: `throws` if `variable` already has a different value. public func unifying<Value>(_ variable: Variable<Value>, _ value: Value) throws -> State { return try bijecting(variable) .unifying(variable.erased, value) } /// Unify a variable with a value. /// /// - important: `value` must be of the same type as `variable`'s `Value`. /// /// - parameters: /// - variable: The variable to unify /// - value: The value to give the variable /// /// - note: `throws` if `variable` already has a different value. internal mutating func unify(_ variable: AnyVariable, _ value: Any) throws { self = try unifying(variable, value) } /// Unify a variable with a value. /// /// - important: `value` must be of the same type as `variable`'s `Value`. /// /// - parameters: /// - variable: The variable to unify /// - value: The value to give the variable /// /// - returns: The unified state. /// /// - note: `throws` if `variable` already has a different value. internal func unifying(_ variable: AnyVariable, _ value: Any) throws -> State { var state = self var info = state.context[variable] ?? Info() if let oldValue = info.value { if !variable.equal(oldValue, value) { throw Error.UnificationError } } else { info.value = value state.context[variable] = info for unify in info.bijections.values { state = try unify(state) } try state.verifyConstraints() } return state } /// Unify two variables. /// /// - parameters: /// - lhs: The first variable to unify /// - rhs: The second variable to unify /// /// - note: `throws` if the variables have existing, inequal values. public mutating func unify<Value>(_ lhs: Variable<Value>, _ rhs: Variable<Value>) throws { self = try unifying(lhs, rhs) } /// Unify two variables. /// /// - parameters: /// - lhs: The first variable to unify /// - rhs: The second variable to unify /// /// - returns: The unified state. /// /// - note: `throws` if `variable` already has a different value. public func unifying<Value>(_ lhs: Variable<Value>, _ rhs: Variable<Value>) throws -> State { return try self .bijecting(lhs) .bijecting(rhs) .unifying(lhs.erased, rhs.erased) } /// Unify two variables. /// /// - important: The two variables must have the same `Value` type. /// /// - parameters: /// - lhs: The first variable to unify /// - rhs: The second variable to unify /// /// - note: `throws` if the variables have existing, inequal values. internal mutating func unify(_ lhs: AnyVariable, _ rhs: AnyVariable) throws { self = try unifying(lhs, rhs) } /// Unify two variables. /// /// - important: The two variables must have the same `Value` type. /// /// - parameters: /// - lhs: The first variable to unify /// - rhs: The second variable to unify /// /// - returns: The unified state. /// /// - note: `throws` if `variable` already has a different value. internal func unifying(_ lhs: AnyVariable, _ rhs: AnyVariable) throws -> State { func merge<Key, Value>( _ a: [Key: Value]?, _ b: [Key: Value]?, combine: (Value, Value) -> Value ) -> [Key: Value] { var result: [Key: Value] = [:] var allKeys = Set<Key>() if let a = a?.keys { allKeys.formUnion(a) } if let b = b?.keys { allKeys.formUnion(b) } for key in allKeys { let a = a?[key] let b = b?[key] if let a = a, let b = b { result[key] = combine(a, b) } else { result[key] = a ?? b } } return result } let equal = lhs.equal var state = self var unify: [(AnyVariable, AnyVariable)] = [] try state.context.merge(lhs, rhs) { lhs, rhs in if let left = lhs?.value, let right = rhs?.value, !equal(left, right) { throw Error.UnificationError } var info = Info() info.value = lhs?.value ?? rhs?.value info.bijections = merge(lhs?.bijections, rhs?.bijections) { a, _ in a } info.derived = merge(lhs?.derived, rhs?.derived) { a, b in unify.append((a, b)) return a } return info } for (a, b) in unify { try state.unify(a, b) } let info = state.context[lhs]! for bijection in info.bijections.values { state = try bijection(state) } try state.verifyConstraints() return state } }
mit
eKasztany/4ania
ios/Queue/Pods/R.swift.Library/Library/UIKit/UIKit+Migration.swift
2
4753
// // UIKit+Migration.swift // R.swift.Library // // Created by Tom Lokhorst on 2016-09-08. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import UIKit // Renames from Swift 2 to Swift 3 public extension NibResourceType { @available(*, unavailable, renamed: "instantiate(withOwner:options:)") public func instantiateWithOwner(_ ownerOrNil: AnyObject?, options optionsOrNil: [NSObject : AnyObject]? = nil) -> [AnyObject] { fatalError() } } public extension StoryboardResourceWithInitialControllerType { @available(*, unavailable, renamed: "instantiateInitialViewController") public func initialViewController() -> InitialController? { fatalError() } } public extension UICollectionView { @available(*, unavailable, renamed: "dequeueReusableCell(withReuseIdentifier:for:)") public func dequeueReusableCellWithReuseIdentifier<Identifier: ReuseIdentifierType>(_ identifier: Identifier, forIndexPath indexPath: IndexPath) -> Identifier.ReusableType? where Identifier.ReusableType: UICollectionReusableView { fatalError() } @available(*, unavailable, renamed: "dequeueReusableSupplementaryView(ofKind:withReuseIdentifier:for:)") public func dequeueReusableSupplementaryViewOfKind<Identifier: ReuseIdentifierType>(_ elementKind: String, withReuseIdentifier identifier: Identifier, forIndexPath indexPath: IndexPath) -> Identifier.ReusableType? where Identifier.ReusableType: UICollectionReusableView { fatalError() } @available(*, unavailable, renamed: "register") public func registerNibs<Resource: NibResourceType>(_ nibResources: [Resource]) where Resource: ReuseIdentifierType, Resource.ReusableType: UICollectionViewCell { fatalError() } @available(*, unavailable, renamed: "register") public func registerNib<Resource: NibResourceType>(_ nibResource: Resource) where Resource: ReuseIdentifierType, Resource.ReusableType: UICollectionViewCell { fatalError() } @available(*, unavailable, renamed: "register") public func registerNibs<Resource: NibResourceType>(_ nibResources: [Resource], forSupplementaryViewOfKind kind: String) where Resource: ReuseIdentifierType, Resource.ReusableType: UICollectionReusableView { fatalError() } @available(*, unavailable, renamed: "register") public func registerNib<Resource: NibResourceType>(_ nibResource: Resource, forSupplementaryViewOfKind kind: String) where Resource: ReuseIdentifierType, Resource.ReusableType: UICollectionReusableView { fatalError() } } public extension UITableView { @available(*, unavailable, renamed: "dequeueReusableCell(withIdentifier:for:)") public func dequeueReusableCellWithIdentifier<Identifier: ReuseIdentifierType>(_ identifier: Identifier, forIndexPath indexPath: IndexPath) -> Identifier.ReusableType? where Identifier.ReusableType: UITableViewCell { fatalError() } @available(*, unavailable, renamed: "dequeueReusableCell(withIdentifier:)") public func dequeueReusableCellWithIdentifier<Identifier: ReuseIdentifierType>(_ identifier: Identifier) -> Identifier.ReusableType? where Identifier.ReusableType: UITableViewCell { fatalError() } @available(*, unavailable, renamed: "dequeueReusableHeaderFooterView(withIdentifier:)") public func dequeueReusableHeaderFooterViewWithIdentifier<Identifier: ReuseIdentifierType>(_ identifier: Identifier) -> Identifier.ReusableType? where Identifier.ReusableType: UITableViewHeaderFooterView { fatalError() } @available(*, unavailable, renamed: "register") public func registerNibs<Resource: NibResourceType>(_ nibResources: [Resource]) where Resource: ReuseIdentifierType, Resource.ReusableType: UITableViewCell { fatalError() } @available(*, unavailable, renamed: "register") public func registerNib<Resource: NibResourceType>(_ nibResource: Resource) where Resource: ReuseIdentifierType, Resource.ReusableType: UITableViewCell { fatalError() } @available(*, unavailable, renamed: "registerHeaderFooterView") public func registerNibForHeaderFooterView<Resource: NibResourceType>(_ nibResource: Resource) where Resource: ReuseIdentifierType, Resource.ReusableType: UIView { fatalError() } } public extension SeguePerformerType { @available(*, unavailable, renamed: "performSegue(withIdentifier:sender:)") func performSegueWithIdentifier(_ identifier: String, sender: Any?) { fatalError() } } public extension SeguePerformerType { @available(*, unavailable, renamed: "performSegue(withIdentifier:sender:)") public func performSegueWithIdentifier<Segue, Destination>(_ identifier: StoryboardSegueIdentifier<Segue, Self, Destination>, sender: Any?) { fatalError() } }
apache-2.0
Donkey-Tao/SinaWeibo
SinaWeibo/SinaWeibo/Classes/Discover/TFDiscoverViewController.swift
1
2983
// // TFDiscoverViewController.swift // SinaWeibo // // Created by Donkey-Tao on 2016/10/20. // Copyright © 2016年 http://taofei.me All rights reserved. // import UIKit class TFDiscoverViewController: TFBaseViewController { override func viewDidLoad() { super.viewDidLoad() visitorView.setupVisitorViewInfo(iconName: "visitordiscover_image_message", tip: "登录后,别人评论你的微薄,给你发信息,都会在这里收到") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
Off-Piste/Trolley.io-cocoa
Trolley/Core/Networking/Realtime/TRLWebSocketConnection.swift
2
3538
// // TRLWebSocket.swift // Pods // // Created by Harry Wright on 16.06.17. // // import Foundation import Alamofire var kUserAgent: String { let systemVersion = TRLAppEnviroment.current.systemVersion let deviceName = UIDevice.current.model let bundleIdentifier: String? = Bundle.main.bundleIdentifier let ua: String = "Trolley/13/\(systemVersion)/\(deviceName)_\((bundleIdentifier) ?? "unknown")" return ua } public let ServerDown: Notification.Name = Notification.Name(rawValue: "ServerDown") class TRLWebSocketConnection { fileprivate private(set) var webSocket: WebSocket var delegate: TRLWebSocketDelegate? var wasEverConnected: Bool = false var serverDown: Bool = false var attempts: Int = 0 init(url: URLConvertible, protocols: [String]?) throws { self.webSocket = WebSocket( url: try url.asURL(), QOS: .background, protocols: protocols, userAgent: kUserAgent ) self.webSocket.delegate = self } } extension TRLWebSocketConnection { func open() { assert(delegate != nil, "TRLWebSocketDelegate must be set") if self.serverDown { return } attempts += 1 TRLCoreLogger.debug("This is WebSocket attempt #\(attempts)") self.webSocket.connect() self.waitForTimeout(10) } func close() { self.webSocket.disconnect() } func send(_ message: String) { self.webSocket.write(string: message) } func waitForTimeout(_ time: TimeInterval) { TRLTimer(for: time).once { if self.wasEverConnected { return } TRLCoreNetworkingLogger.debug("WebSocket timed out after \(time) seconds") self.webSocket.disconnect() } } } extension TRLWebSocketConnection : WebSocketDelegate { func webSocketDidConnect(_ socket: WebSocket) { self.wasEverConnected = true self.delegate?.webSocketOnConnection(self) } func webSocket(_ socket: WebSocket, didReceiveData data: Data) { self.delegate?.webSocket(self, onMessage: ["Data" : data]) } func webSocket(_ socket: WebSocket, didReceiveMessage message: String) { if message == "0" { self.delegate?.webSocket(self, onTextMessage: message) } else if let data = message.data(using: .utf8, allowLossyConversion: true) { self.delegate?.webSocket(self, onMessage: JSON(data: data)) } else { self.delegate?.webSocket(self, onMessage: JSON(message)) } } func webSocket(_ socket: WebSocket, didDisconnect error: NSError?) { if error != nil, (error!.code == 61 && Trolley.shared.reachability.isReachable) { let errorResponse = "Server is down [(url: \(socket.currentURL)) ( error: \(error!.localizedDescription)) (reachability: \(Trolley.shared.reachability.currentReachabilityString))]" TRLCoreNetworkingLogger.error(errorResponse) // In the TRLUIComponents we will have some view watching // this to display an error NotificationCenter.default.post(name: ServerDown, object: nil) } self.delegate?.webSocketOnDisconnect(self, wasEverConnected: self.wasEverConnected) } } extension TRLWebSocketConnection : CustomStringConvertible { var description: String { return self.webSocket.description } }
mit
AnarchyTools/atbuild
tests/fixtures/dynamic_library/src/bar.swift
1
100
import dynamicFoo public class Bar : Foo { public override init() { super.init() } }
apache-2.0
crazypoo/PTools
Pods/SwifterSwift/Sources/SwifterSwift/SwiftStdlib/ArrayExtensions.swift
1
5471
// // ArrayExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/5/16. // Copyright © 2016 SwifterSwift // // MARK: - Methods public extension Array { /// SwifterSwift: Insert an element at the beginning of array. /// /// [2, 3, 4, 5].prepend(1) -> [1, 2, 3, 4, 5] /// ["e", "l", "l", "o"].prepend("h") -> ["h", "e", "l", "l", "o"] /// /// - Parameter newElement: element to insert. mutating func prepend(_ newElement: Element) { insert(newElement, at: 0) } /// SwifterSwift: Safely swap values at given index positions. /// /// [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -> [4, 2, 3, 1, 5] /// ["h", "e", "l", "l", "o"].safeSwap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"] /// /// - Parameters: /// - index: index of first element. /// - otherIndex: index of other element. mutating func safeSwap(from index: Index, to otherIndex: Index) { guard index != otherIndex else { return } guard startIndex..<endIndex ~= index else { return } guard startIndex..<endIndex ~= otherIndex else { return } swapAt(index, otherIndex) } /// SwifterSwift: Sort an array like another array based on a key path. If the other array doesn't contain a certain value, it will be sorted last. /// /// [MyStruct(x: 3), MyStruct(x: 1), MyStruct(x: 2)].sorted(like: [1, 2, 3], keyPath: \.x) /// -> [MyStruct(x: 1), MyStruct(x: 2), MyStruct(x: 3)] /// /// - Parameters: /// - otherArray: array containing elements in the desired order. /// - keyPath: keyPath indiciating the property that the array should be sorted by /// - Returns: sorted array. func sorted<T: Hashable>(like otherArray: [T], keyPath: KeyPath<Element, T>) -> [Element] { let dict = otherArray.enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset } return sorted { guard let thisIndex = dict[$0[keyPath: keyPath]] else { return false } guard let otherIndex = dict[$1[keyPath: keyPath]] else { return true } return thisIndex < otherIndex } } } // MARK: - Methods (Equatable) public extension Array where Element: Equatable { /// SwifterSwift: Remove all instances of an item from array. /// /// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5] /// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"] /// /// - Parameter item: item to remove. /// - Returns: self after removing all instances of item. @discardableResult mutating func removeAll(_ item: Element) -> [Element] { removeAll(where: { $0 == item }) return self } /// SwifterSwift: Remove all instances contained in items parameter from array. /// /// [1, 2, 2, 3, 4, 5].removeAll([2,5]) -> [1, 3, 4] /// ["h", "e", "l", "l", "o"].removeAll(["l", "h"]) -> ["e", "o"] /// /// - Parameter items: items to remove. /// - Returns: self after removing all instances of all items in given array. @discardableResult mutating func removeAll(_ items: [Element]) -> [Element] { guard !items.isEmpty else { return self } removeAll(where: { items.contains($0) }) return self } /// SwifterSwift: Remove all duplicate elements from Array. /// /// [1, 2, 2, 3, 4, 5].removeDuplicates() -> [1, 2, 3, 4, 5] /// ["h", "e", "l", "l", "o"]. removeDuplicates() -> ["h", "e", "l", "o"] /// /// - Returns: Return array with all duplicate elements removed. @discardableResult mutating func removeDuplicates() -> [Element] { // Thanks to https://github.com/sairamkotha for improving the method self = reduce(into: [Element]()) { if !$0.contains($1) { $0.append($1) } } return self } /// SwifterSwift: Return array with all duplicate elements removed. /// /// [1, 1, 2, 2, 3, 3, 3, 4, 5].withoutDuplicates() -> [1, 2, 3, 4, 5]) /// ["h", "e", "l", "l", "o"].withoutDuplicates() -> ["h", "e", "l", "o"]) /// /// - Returns: an array of unique elements. /// func withoutDuplicates() -> [Element] { // Thanks to https://github.com/sairamkotha for improving the method return reduce(into: [Element]()) { if !$0.contains($1) { $0.append($1) } } } /// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare. /// /// - Parameter path: Key path to compare, the value must be Equatable. /// - Returns: an array of unique elements. func withoutDuplicates<E: Equatable>(keyPath path: KeyPath<Element, E>) -> [Element] { return reduce(into: [Element]()) { (result, element) in if !result.contains(where: { $0[keyPath: path] == element[keyPath: path] }) { result.append(element) } } } /// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare. /// /// - Parameter path: Key path to compare, the value must be Hashable. /// - Returns: an array of unique elements. func withoutDuplicates<E: Hashable>(keyPath path: KeyPath<Element, E>) -> [Element] { var set = Set<E>() return filter { set.insert($0[keyPath: path]).inserted } } }
mit
TermiT/Flycut
Flycut-iOS/ViewController.swift
1
21026
// // ViewController.swift // Flycut-iOS // // Created by Mark Jerde on 7/12/17. // // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, FlycutStoreDelegate, FlycutOperatorDelegate, MJCloudKitUserDefaultsSyncDelegate { let flycut:FlycutOperator = FlycutOperator() var activeUpdates:Int = 0 var tableView:UITableView! var currentAnimation = UITableView.RowAnimation.none var pbCount:Int = -1 var rememberedSyncSettings:Bool = false var rememberedSyncClippings:Bool = false var ignoreCKAccountStatusNoAccount = false let pasteboardInteractionQueue = DispatchQueue(label: "com.Flycut.pasteboardInteractionQueue") let alertHandlingSemaphore = DispatchSemaphore(value: 0) let defaultsChangeHandlingQueue = DispatchQueue(label: "com.Flycut.defaultsChangeHandlingQueue") let isURLDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) // Some buttons we will reuse. var deleteButton:MGSwipeButton? = nil var openURLButton:MGSwipeButton? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Uncomment the following line to load the demo state for screenshots. //UserDefaults.standard.set(NSNumber(value: true), forKey: "demoForAppStoreScreenshots") // Use this command to get screenshots: // while true; do xcrun simctl io booted screenshot;sleep 1;done MJCloudKitUserDefaultsSync.shared()?.setDelegate(self) if ( UserDefaults.standard.bool(forKey: "demoForAppStoreScreenshots") ) { // Ensure we will not load or save clippings in demo mode. let savePref = UserDefaults.standard.integer(forKey: "savePreference") if ( 0 < savePref ) { UserDefaults.standard.set(0, forKey: "savePreference") } } tableView = self.view.subviews.first as! UITableView tableView.delegate = self tableView.dataSource = self tableView.register(MGSwipeTableCell.self, forCellReuseIdentifier: "FlycutCell") deleteButton = MGSwipeButton(title: "Delete", backgroundColor: .red, callback: { (cell) -> Bool in let indexPath = self.tableView.indexPath(for: cell) if ( nil != indexPath ) { let previousAnimation = self.currentAnimation self.currentAnimation = UITableView.RowAnimation.left // Use .left to look better with swiping left to delete. self.flycut.setStackPositionTo( Int32((indexPath?.row)! )) self.flycut.clearItemAtStackPosition() self.currentAnimation = previousAnimation } return true; }) openURLButton = MGSwipeButton(title: "Open", backgroundColor: .blue, callback: { (cell) -> Bool in let indexPath = self.tableView.indexPath(for: cell) if ( nil != indexPath ) { let url = URL(string: self.flycut.clippingString(withCount: Int32((indexPath?.row)!) )! ) if #available(iOS 10.0, *) { UIApplication.shared.open(url!, options: [:], completionHandler: nil) } else { // Fallback on earlier versions UIApplication.shared.openURL(url!) } self.tableView.reloadRows(at: [indexPath!], with: UITableView.RowAnimation.none) } return true; }) // Force sync disable for test if needed. //UserDefaults.standard.set(NSNumber(value: false), forKey: "syncSettingsViaICloud") //UserDefaults.standard.set(NSNumber(value: false), forKey: "syncClippingsViaICloud") // Force to ask to enable sync for test if needed. //UserDefaults.standard.set(false, forKey: "alreadyAskedToEnableSync") // Ensure these are false since there isn't a way to access the saved clippings on iOS as this point. UserDefaults.standard.set(NSNumber(value: false), forKey: "saveForgottenClippings") UserDefaults.standard.set(NSNumber(value: false), forKey: "saveForgottenFavorites") flycut.setClippingsStoreDelegate(self) flycut.delegate = self flycut.awake(fromNibDisplaying: 10, withDisplayLength: 140, withSave: #selector(savePreferences(toDict:)), forTarget: self) // The 10 isn't used in iOS right now and 140 characters seems to be enough to cover the width of the largest screen. NotificationCenter.default.addObserver(self, selector: #selector(self.checkForClippingAddedToClipboard), name: UIPasteboard.changedNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillTerminate), name: UIApplication.willTerminateNotification, object: nil) // Check for clipping whenever we become active. NotificationCenter.default.addObserver(self, selector: #selector(self.checkForClippingAddedToClipboard), name: UIApplication.didBecomeActiveNotification, object: nil) checkForClippingAddedToClipboard() // Since the first-launch notification will occur before we add observer. // Register for notifications for the scenarios in which we should save the engine. [ UIApplication.willResignActiveNotification, UIApplication.didEnterBackgroundNotification, UIApplication.willTerminateNotification ] .forEach { (notification) in NotificationCenter.default.addObserver(self, selector: #selector(self.saveEngine), name: notification, object: nil) } NotificationCenter.default.addObserver(self, selector: #selector(self.defaultsChanged), name: UserDefaults.didChangeNotification, object: nil) if ( UserDefaults.standard.bool(forKey: "demoForAppStoreScreenshots") ) { // Make sure we won't send these change to iCloud. UserDefaults.standard.set(NSNumber(value: false), forKey: "syncSettingsViaICloud") UserDefaults.standard.set(NSNumber(value: false), forKey: "syncClippingsViaICloud") self.flycut.registerOrDeregisterICloudSync() NotificationCenter.default.removeObserver(self) // Load sample content, reverse order. self.flycut.addClipping("https://www.apple.com", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("App Store is a digital distribution platform, developed and maintained by Apple Inc., for mobile apps on its iOS operating system.", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("https://itunesconnect.apple.com/", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("The party is at 123 Main St. 6 PM. Please bring some chips to share.", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("You are going to love this new design I found. It takes half the effort and resonates with today's hottest trends. With our throughput up we can now keep up with demand.", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("http://www.makeuseof.com/tag/5-best-mac-clipboard-manager-apps-improve-workflow/", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("Swipe left to delete", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("Swipe right to open web links", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("Tap to copy", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("Manage your clippings in iOS", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("Flycut has made the leap from macOS to iOS", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) self.flycut.addClipping("Flycut has made the leap from OS X to iOS", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) // Unset the demo setting. UserDefaults.standard.set(NSNumber(value: false), forKey: "demoForAppStoreScreenshots") } } @objc func defaultsChanged() { // This seems to be the only way to respond to Settings changes, though it doesn't inform us what changed so we will have to check each to see if they were the one(s). // Don't use DispatchQueue.main.async since that will still end up blocking the UI draw until the user responds to what hasn't been drawn yet. // Use async on a sequential queue to avoid concurrent response to the same change. This allows enqueuing of defaultsChanged calls in reponse to changes made within the handling, but using sync causes EXC_BAD_ACCESS in this case. defaultsChangeHandlingQueue.async { let newRememberNum = Int32(UserDefaults.standard.integer(forKey: "rememberNum")) if ( UserDefaults.standard.value(forKey: "rememberNum") is String ) { // Reset the value, since TextField will make it a String and CloudKit sync will object to changing the type. Check this independent of value change, since the type could be changed without a change in value and we don't want it left around causing confusion. UserDefaults.standard.set(newRememberNum, forKey: "rememberNum") } if ( self.flycut.rememberNum() != newRememberNum ) { self.flycut.setRememberNum(newRememberNum, forPrimaryStore: true) } let syncSettings = UserDefaults.standard.bool(forKey: "syncSettingsViaICloud") let syncClippings = UserDefaults.standard.bool(forKey: "syncClippingsViaICloud") if ( syncSettings != self.rememberedSyncSettings || syncClippings != self.rememberedSyncClippings ) { self.rememberedSyncSettings = syncSettings self.rememberedSyncClippings = syncClippings if ( self.rememberedSyncClippings ) { if ( 2 > UserDefaults.standard.integer(forKey: "savePreference") ) { UserDefaults.standard.set(2, forKey: "savePreference") } } self.flycut.registerOrDeregisterICloudSync() } } } override func viewDidAppear(_ animated: Bool) { // Ask once to enable Sync. The syntax below will take the else unless alreadyAnswered is non-nil and true. let alreadyAsked = UserDefaults.standard.value(forKey: "alreadyAskedToEnableSync") if let answer = alreadyAsked, answer as! Bool { } else { // Don't use DispatchQueue.main.async since that will still end up blocking the UI draw until the user responds to what hasn't been drawn yet. Just create a queue to get us away from main, since this is a one-time code path. DispatchQueue(label: "com.Flycut.alertHandlingQueue", qos: .userInitiated ).async { let selection = self.alert(withMessageText: "iCloud Sync", informationText: "Would you like to enable Flycut's iCloud Sync for Settings and Clippings?", buttonsTexts: ["Yes", "No"]) let response = (selection == "Yes"); UserDefaults.standard.set(NSNumber(value: response), forKey: "syncSettingsViaICloud") UserDefaults.standard.set(NSNumber(value: response), forKey: "syncClippingsViaICloud") UserDefaults.standard.set(true, forKey: "alreadyAskedToEnableSync") self.flycut.registerOrDeregisterICloudSync() } } // This is a suitable place to prepare to possible eventual display of preferences, resetting values that should reset before each display of preferences. flycut.willShowPreferences() } @objc func savePreferences(toDict: NSMutableDictionary) { } func beginUpdates() { if ( !Thread.isMainThread ) { DispatchQueue.main.sync { beginUpdates() } return } print("Begin updates") print("Num rows: \(tableView.dataSource?.tableView(tableView, numberOfRowsInSection: 0))") if ( 0 == activeUpdates ) { tableView.beginUpdates() } activeUpdates += 1 } func endUpdates() { if ( !Thread.isMainThread ) { DispatchQueue.main.sync { endUpdates() } return } print("End updates"); activeUpdates -= 1; if ( 0 == activeUpdates ) { tableView.endUpdates() } } func insertClipping(at index: Int32) { if ( !Thread.isMainThread ) { DispatchQueue.main.sync { insertClipping(at: index) } return } print("Insert row \(index)") tableView.insertRows(at: [IndexPath(row: Int(index), section: 0)], with: currentAnimation) // We will override the animation for now, because we are the ViewController and should guide the UX. } func deleteClipping(at index: Int32) { if ( !Thread.isMainThread ) { DispatchQueue.main.sync { deleteClipping(at: index) } return } print("Delete row \(index)") tableView.deleteRows(at: [IndexPath(row: Int(index), section: 0)], with: currentAnimation) // We will override the animation for now, because we are the ViewController and should guide the UX. } func reloadClipping(at index: Int32) { if ( !Thread.isMainThread ) { DispatchQueue.main.sync { reloadClipping(at: index) } return } print("Reloading row \(index)") tableView.reloadRows(at: [IndexPath(row: Int(index), section: 0)], with: currentAnimation) // We will override the animation for now, because we are the ViewController and should guide the UX. } func moveClipping(at index: Int32, to newIndex: Int32) { if ( !Thread.isMainThread ) { DispatchQueue.main.sync { moveClipping(at: index, to: newIndex) } return } print("Moving row \(index) to \(newIndex)") tableView.moveRow(at: IndexPath(row: Int(index), section: 0), to: IndexPath(row: Int(newIndex), section: 0)) } func alert(withMessageText message: String!, informationText information: String!, buttonsTexts buttons: [Any]!) -> String! { // Don't use DispatchQueue.main.async since that will still end up blocking the UI draw until the user responds to what hasn't been drawn yet. This isn't a great check, as it is OS-version-limited and results in a EXC_BAD_INSTRUCTION if it fails, but is good enough for development / test. if #available(iOS 10.0, *) { __dispatch_assert_queue_not(DispatchQueue.main) } let alertController = UIAlertController(title: message, message: information, preferredStyle: .alert) var selection:String? = nil for option in buttons { alertController.addAction(UIAlertAction(title: option as? String, style: .default) { action in selection = action.title self.alertHandlingSemaphore.signal() }) } if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } // topController should now be your topmost view controller // Transform the asynchronous UIAlertController into a synchronous alert by waiting, after presenting, on a semaphore that is initialized to zero and only signaled in the selection handler. DispatchQueue.main.async { topController.present(alertController, animated: true) } alertHandlingSemaphore.wait() // To wait for queue to resume. } return selection } @objc func checkForClippingAddedToClipboard() { pasteboardInteractionQueue.async { // This is a suitable place to prepare to possible eventual display of preferences, resetting values that should reset before each display of preferences. self.flycut.willShowPreferences() if ( UIPasteboard.general.changeCount != self.pbCount ) { self.pbCount = UIPasteboard.general.changeCount; if UIPasteboard.general.types.contains("public.utf8-plain-text"), let pasteboard = UIPasteboard.general.value(forPasteboardType: "public.utf8-plain-text") as? String { self.flycut.addClipping(pasteboard, ofType: "public.utf8-plain-text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) } else if UIPasteboard.general.types.contains("public.text"), let pasteboard = UIPasteboard.general.value(forPasteboardType: "public.text") as? String { self.flycut.addClipping(pasteboard, ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil) } } } } @objc func applicationWillTerminate() { saveEngine() } @objc func saveEngine() { flycut.saveEngine() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() saveEngine() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Int(flycut.jcListCount()) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item: MGSwipeTableCell = tableView.dequeueReusableCell(withIdentifier: "FlycutCell", for: indexPath) as! MGSwipeTableCell item.textLabel?.text = flycut.previousDisplayStrings(Int32(indexPath.row + 1), containing: nil).last as! String? //configure left buttons var removeAll:Bool = true if let content = flycut.clippingString(withCount: Int32(indexPath.row) ) { // Detect if something is a URL before passing it to canOpenURL because on iOS 9 and later, if building with an earlier SDK, there is a limit of 50 distinct URL schemes before canOpenURL will just return false. This limit is theorized to prevent apps from detecting what other apps are installed. The limit should be okay, assuming any user encounters fewer than 50 URL schemes, since those that the user actually uses will be allowed through before reaching the limit. For building with an iOS 9 or later SDK a whitelist of schemes in the Info.plist will be used, but filtering before calling canOpenURL decreases the volume of log messages. // NSTextCheckingResult.CheckingType.link.rawValue blocks things like single words that URL() would let in // URL() blocks things like paragraphs of text containing a URL that NSTextCheckingResult.CheckingType.link.rawValue would let in let matches = isURLDetector?.matches(in: content, options: .reportCompletion, range: NSMakeRange(0, content.count)) if let matchesCount = matches?.count { if matchesCount > 0 { if let url = URL(string: content) { if UIApplication.shared.canOpenURL( url ) { if(!item.leftButtons.contains(openURLButton!)) { item.leftButtons.append(openURLButton!) item.leftSwipeSettings.transition = .border item.leftExpansion.buttonIndex=0 removeAll = false } } } } } } if ( removeAll ) { item.leftButtons.removeAll() } //configure right buttons if ( 0 == item.rightButtons.count ) { // Setup the right buttons only if they haven't been before. item.rightButtons.append(deleteButton!) item.rightSwipeSettings.transition = .border item.rightExpansion.buttonIndex = 0 } return item } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if ( MGSwipeState.none == (tableView.cellForRow(at: indexPath) as! MGSwipeTableCell).swipeState ) { tableView.deselectRow(at: indexPath, animated: true) // deselect before getPaste since getPaste may reorder the list let content = flycut.getPasteFrom(Int32(indexPath.row)) print("Select: \(indexPath.row) \(content) OK") pasteboardInteractionQueue.async { // Capture value before setting the pastboard for reasons noted below. self.pbCount = UIPasteboard.general.changeCount // This call will clear all other content types and appears to immediately increment the changeCount. UIPasteboard.general.setValue(content as Any, forPasteboardType: "public.utf8-plain-text") // Apple documents that "UIPasteboard waits until the end of the current event loop before incrementing the change count", but this doesn't seem to be the case for the above call. Handle both scenarios by doing a simple increment if unchanged and an update-to-match if changed. if ( UIPasteboard.general.changeCount == self.pbCount ) { self.pbCount += 1 } else { self.pbCount = UIPasteboard.general.changeCount } } } } func notifyCKAccountStatusNoAccount() { DispatchQueue.main.async { guard !self.ignoreCKAccountStatusNoAccount else { return } let alert = UIAlertController(title: "No iCloud Account", message: "An iCloud account with iCloud Drive enabled is required for iCloud sync.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Preferences", style: .default, handler: { (_) in if #available(iOS 10.0, *) { // Opens iCloud Prefs < iOS 11.0, main Prefs >= iOS 11.0 UIApplication.shared.openURL(URL(string: "App-Prefs:root=CASTLE")!) } else { UIApplication.shared.openURL(URL(string: "prefs:root=CASTLE")!) } })) alert.addAction(UIAlertAction(title: "Ignore", style: .cancel, handler: { (_) in self.ignoreCKAccountStatusNoAccount = true })) self.present(alert, animated: true, completion: nil) } } }
mit
robconrad/fledger-ios
fledger-ios/controllers/type/TypesTableView.swift
1
3791
// // AccountTableView.swift // fledger-ios // // Created by Robert Conrad on 5/2/15. // Copyright (c) 2015 Robert Conrad. All rights reserved. // import UIKit import FledgerCommon class TypesTableView: AppUITableView, UITableViewDataSource, UITableViewDelegate { private var typeId: Int64? private var types: [Type]? private var sections: [String] = [] private var sectionIndices: [String] = [] private var sectionRows: [String: [Type]] = [:] private var selected: NSIndexPath? var selectHandler: SelectIdHandler? override internal func setup() { super.setup() delegate = self dataSource = self sectionIndexBackgroundColor = AppColors.bgHighlight() } func setType(id: Int64) { self.typeId = id selectType() } private func selectType() { if typeId != nil { let type = types!.filter { $0.id == self.typeId }.first! let section = type.group().name let index = sectionRows[section]?.find { $0.id == self.typeId } if let i = index { let indexPath = NSIndexPath(forRow: i, inSection: sections.find { $0 == section }!) selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Middle) } } } override func reloadData() { sections = [] sectionRows = [:] types = TypeSvc().all() for type in types! { let section = type.group().name if sectionRows[section] == nil { sectionRows[section] = [] } sectionRows[section]!.append(type) } for section in sectionRows.keys { sections.append(section) } sections.sortInPlace({ left, right in return left.lowercaseString < right.lowercaseString }) for section in sections { sectionIndices.append(section.substringToIndex(section.startIndex.advancedBy(min(3, section.characters.count)))) } super.reloadData() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sectionRows[sections[section]]!.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section] } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as! UITableViewHeaderFooterView header.textLabel!.textColor = AppColors.text() header.contentView.backgroundColor = AppColors.bgHighlight() } func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]! { return sectionIndices } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var reuseIdentifier = "default" var label = "failure" if let type = sectionRows[sections[indexPath.section]]?[indexPath.row] { if type.id == typeId { reuseIdentifier = "selected" } label = type.name } let cell = dequeueReusableCellWithIdentifier(reuseIdentifier)! cell.textLabel?.text = label return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let handler = selectHandler, typeId = self.sectionRows[sections[indexPath.section]]?[indexPath.row].id { handler(typeId) } } }
mit
swift-lang/swift-k
tests/language-behaviour/arrays/209-closing-return-array.swift
2
127
int[] a; (int[] r) f() { foreach i in [0:9] { r[i] = i; r[i + 10] = i + 10; } } a = f(); foreach v in a { trace(v); }
apache-2.0
RyanTech/AwesomeCache
Example/ViewController.swift
7
700
// // ViewController.swift // Example // // Created by Alexander Schuch on 12/07/14. // Copyright (c) 2014 Alexander Schuch. All rights reserved. // import UIKit import AwesomeCache class ViewController: UIViewController { @IBOutlet var textView: UITextView! let cache = Cache<NSString>(name: "AwesomeCache") override func viewDidLoad() { super.viewDidLoad() textView.text = (cache["myText"] as? String) ?? "" } @IBAction func reloadData(sender: AnyObject?) { textView.text = (cache["myText"] as? String) ?? "" } @IBAction func saveInCache(sender: AnyObject?) { cache["myText"] = textView.text } }
mit
nickqiao/NKBill
NKBill/Third/CVCalendar/CVWeekdaySymbolType.swift
4
269
// // CVWeekdaySymbolType.swift // CVCalendar Demo // // Created by Roy McKenzie on 10/8/15. // Copyright (c) 2015 GameApp. All rights reserved. // import Foundation @objc public enum CVWeekdaySymbolType: Int { case Normal case Short case VeryShort }
apache-2.0
fly2xj/zhihu_xjing
zhihu.study/zhihu.studyTests/zhihu_studyTests.swift
1
900
// // zhihu_studyTests.swift // zhihu.studyTests // // Created by shawn on 22/7/15. // Copyright (c) 2015 shawn. All rights reserved. // import UIKit import XCTest class zhihu_studyTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
octanner/ios-environment-switcher
EnvironmentSwitcher/EnvironmentSwitcherViewController.swift
1
3944
// // EnvironmentSwitcherViewController.swift // EnvironmentSwitcher // // Created by Ben Norris on 2/12/16. // Copyright © 2016 OC Tanner. All rights reserved. // import UIKit import NetworkStack public protocol EnvironmentSwitcherDelegate { func closeEnvironmentSwitcher(appNetworkStateChanged: Bool) } public class EnvironmentSwitcherViewController: UIViewController { // MARK: - Public properties public var delegate: EnvironmentSwitcherDelegate? public var environments = [AppNetworkState]() // MARK: - Internal properties @IBOutlet weak var apiURLField: UITextField! @IBOutlet weak var tokenURLField: UITextField! @IBOutlet weak var picker: UIPickerView! // MARK: - Constants private let customName = "custom" // MARK: - Lifecycle overrides public override func viewDidLoad() { super.viewDidLoad() guard let appEnvironment = AppNetworkState.currentAppState else { fatalError("Must have app environment") } for (index, environment) in environments.enumerate() { if appEnvironment.environmentKey == environment.environmentKey { let custom = environment.environmentKey == customName picker.selectRow(index, inComponent: 0, animated: false) apiURLField.text = environment.apiURLString apiURLField.enabled = custom tokenURLField.text = environment.tokenEndpointURLString tokenURLField.enabled = custom break } } } // MARK: - Internal functions @IBAction func saveSwitch(sender: AnyObject) { view.endEditing(true) let updatedEnvironment = environments[picker.selectedRowInComponent(0)] AppNetworkState.currentAppState = updatedEnvironment delegate?.closeEnvironmentSwitcher(true) } @IBAction func cancelSwitch(sender: AnyObject) { delegate?.closeEnvironmentSwitcher(false) } } // MARK: - Text field delegate extension EnvironmentSwitcherViewController: UITextFieldDelegate { public func textFieldDidEndEditing(textField: UITextField) { let index = picker.selectedRowInComponent(0) let custom = environments[index] if custom.environmentKey != customName { return } let updatedCustom = AppNetworkState(apiURLString: apiURLField.text!, tokenEndpointURLString: tokenURLField.text!, environmentKey: customName) environments[index] = updatedCustom } public func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == apiURLField { tokenURLField.becomeFirstResponder() } else { textField.resignFirstResponder() } return true } } // MARK: - Picker delegate extension EnvironmentSwitcherViewController: UIPickerViewDelegate { public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let environment = environments[row] return environment.environmentKey } public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let environment = environments[row] let custom = environment.environmentKey == customName apiURLField.text = environment.apiURLString apiURLField.enabled = custom tokenURLField.text = environment.tokenEndpointURLString tokenURLField.enabled = custom } } // MARK: - Picker data source extension EnvironmentSwitcherViewController: UIPickerViewDataSource { public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return environments.count } }
mit
fgengine/quickly
Quickly/Analytics/IQAnalytics.swift
1
59
// // Quickly // public protocol IQAnalytics : class { }
mit
MA806P/SwiftDemo
SwiftTestDemo/SwiftTestDemo/ARC.swift
1
6512
// // ARC.swift // SwiftTestDemo // // Created by MA806P on 2018/9/10. // Copyright © 2018年 myz. All rights reserved. // import Foundation /* Automatic Reference Counting 引用计数只适用于实例对象。结构体和枚举是值类型,不是引用类型,并且不通过引用存储和传递的。 解决实例之间的强引用循环 Swift 提供了两种方法解决你在使用类的属性而产生的强引用循环:弱引用( weak )和无主引用( unowned )。 弱引用( weak )和无主引用( unowned )能确保一个实例在循环引用中引用另一个实例, 而不用保持强引用关系。这样实例就可以相互引用且不会产生强引用循环。 //weak class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { print("\(name) is being deinitialized") } } class Apartment { let unit: String init(unit: String) { self.unit = unit } weak var tenant: Person? // <--------------- deinit { print("Apartment \(unit) is being deinitialized") } } //unowned 与弱引用不同的是,无主引用适用于其他实例有相同的生命周期或是更长的生命周期的场景。 无主引用总是有值的。因而,ARC也不会将无主引用的值设置为 nil,这也意味着无主引用要被定义为非可选类型。 只有在确保引用的实例 永远 不会释放,才能使用无主引用。 如果你在无主引用的对象释放之后,视图访问该值,会触发运行时错误 对于需要禁掉运行时安全检查的情况,Swift 也提供了不安全的无主引用--例如,出于性能考虑。 想其他不安全操作一样,你需要负责检查代码的安全性。 unowned(unsafe) 表示这是一个不安全的无主引用。当你试图访问已经释放了的不安全的无主引用实例时, 程序会试图访问该实例指向的内存区域,这是一种不安全的操作。 Person 和 Apartment 的例子展示了两个属性都允许设置为 nil,并会造成潜在的强引用循环。这种场景最适合用弱引用来解决。 Customer 和 CreditCard 的例子展示了一个属性允许设置为 nil,而另一个属性不允许设置为 nil,并会造成潜在的强引用循环。这种场景最适合用无主引用来解决。 然而,还有第三种场景,两个属性 都 必须有值,初始化之后属性都不能为 nil。在这场景下,需要一个类使用无主引用属性,另一个类使用隐式解析可选类型属性。 闭包引起的强引用循环 强引用循环还可能发生在将一个闭包赋值给一个实例的属性,并且这个闭包又捕获到这个实例的时候。捕获的原因可能是在闭包的内部需要访问实例的属性 当你把一个闭包赋值给一个属性时,其实赋值的是这个闭包的引用,和之前的问题一样--都是两个强引用互相持有对方不被释放 Swift 提供了一个优雅的解决方案,称之为 闭包捕获列表(closure capture list)。 解决闭包引起的强引用循环 定义闭包的时候同时定义 捕获列表 ,并作为闭包的一部分,通过这种方式可以解决闭包和实例之间的强引用循环。 捕获列表定义了在闭包内部捕获一个或多个引用类型的规则。像解决两个实例的强引用循环一样, 将每一个捕获类型声明为弱引用(weak)或是无主引用(unowned),而不是声明为强引用。 至于是使用弱引用(weak)还是无主引用(unowned)取决于你代码中的不同部分之间的关系。 Swift强制要求 闭包内部使用 self 的成员,必须要写成 self.someProperty 或 self.someMethod() (而不是仅仅写成 someProperty 或 someMethod())。这提醒你可能会一不小心就捕获了 self。 定义捕获列表 捕获列表中的每一项都是由 weak 或 unowned 关键字和实例的引用(如 self) 或是由其他值初始化的变量(如delegate = self.delegate!)成组构成的。 它们每一组都写在方括号中,组之间用逗号隔开。 lazy var someClosure: (Int, String) -> String = { [unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in // closure body goes here } 如果一个闭包没有指定的参数列表或是返回值,则可以在上下文中推断出来,此时要把捕获列表放在闭包的开始位置,其后跟着关键字 in : lazy var someClosure: () -> String = { [unowned self, weak delegate = self.delegate!] in // closure body goes here } 弱引用和无主引用 当闭包和它捕获的实例始终互相持有对方的时候,将闭包的捕获定义为无主引用,那闭包和它捕获的实例总会同时释放。 相反的,将捕获定义弱引用时,捕获的引用也许会在将来的某一时刻变成 nil。弱引用总是可选类型的, 并且,当引用的实例释放的时候,弱引用自动变成 nil。 这就需要你在闭包内部检查它的值是否存在。 */ class HTMLElement { let name: String let text: String? // lazy var asHTML: () -> String = { // if let text = self.text { // return "<\(self.name)>\(text)</\(self.name)>" // } else { // return "<\(self.name) />" // } // } lazy var asHTML: () -> String = { [unowned self] in if let text = self.text { return "<\(self.name)>\(text)</\(self.name)>" } else { return "<\(self.name) />" } } init(name: String, text: String? = nil) { self.name = name self.text = text } deinit { print("\(name) is being deinitialized") } } //let heading = HTMLElement(name: "h1") //let defaultText = "some default text" //heading.asHTML = { // return "<\(heading.name)>\(heading.text ?? defaultText)</\(heading.name)>" //} //print(heading.asHTML()) //// "<h1>some default text</h1>" //var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world") //print(paragraph!.asHTML()) //// Prints "<p>hello, world</p>" ////置变量 paragraph 为 nil,断开它对 HTMLElement 实例的强引用,但是,HTMLElement 实例和它的闭包都不释放,这是因为强引用循环: //paragraph = nil ////我们注意到 HTMLElement 实例的析构函数中的消息并没有打印
apache-2.0
tidepool-org/nutshell-ios
Nutshell/Resources/NutshellStyles.swift
1
15054
/* * Copyright (c) 2015, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * 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 License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ import Foundation import UIKit extension UIColor { convenience init(hex: UInt, opacity: Float) { self.init( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hex & 0x0000FF) / 255.0, alpha: CGFloat(opacity) ) } convenience init(hex: UInt) { self.init(hex: hex, opacity: 1.0) } } open class Styles: NSObject { // This table determines the background style design to color mapping in the UI. Setting "usage" variables in storyboards will determine color settings via this table; actual colors are defined below and can be changed globally there. static var usageToBackgroundColor = [ // general usage "brightBackground": brightBlueColor, "darkBackground": darkPurpleColor, "lightBackground": veryLightGreyColor, "whiteBackground": whiteColor, // login & signup "brightBackgroundButton": brightBlueColor, "userDataEntry": whiteColor, // menu and account settings "rowSeparator": dimmedDarkGreyColor, "darkBackgroundButton": darkPurpleColor, // add/edit event scenes "addEditViewSaveButton": brightBlueColor, ] // This table is used for mapping usage to font and font color for UI elements including fonts (UITextField, UILabel, UIButton). An entry may appear here as well as in the basic color mapping table above to set both font attributes as well as background coloring. static var usageToFontWithColor = [ // general usage "brightBackgroundButton": (largeRegularFont, whiteColor), "darkBackgroundButton": (largeRegularFont, whiteColor), // login & signup scenes "userDataEntry": (mediumRegularFont, darkPurpleColor), "dataEntryErrorFeedback": (smallSemiboldFont, redErrorColor), "brightLinkText": (mediumRegularFont, brightBlueColor), "networkDisconnectText" : (largeRegularFont, whiteColor), // event list table scene "eventListCellTitle": (mediumSemiboldFont, altDarkGreyColor), "eventListCellLocation": (smallSemiboldFont, altDarkGreyColor), "eventListCellRepeatCount": (mediumSemiboldFont, altDarkGreyColor), "searchPlaceholder": (mediumLightFont, blackColor), "searchText": (largeRegularFont, blackColor), // grouped event list table scene "groupedEventHeaderTitle": (mediumSemiboldFont, whiteColor), "groupedEventHeaderLocation": (smallSemiboldFont, whiteColor), "groupedEventHeaderButton": (mediumVerySmallSemiboldFont, whiteColor), "groupedEventCellTitle": (mediumSmallSemiboldFont, darkGreyColor), "groupedEventCellDate": (smallRegularFont, altDarkGreyColor), // event detail view scene "detailHeaderTitle": (mediumLargeBoldFont, whiteColor), "detailHeaderNotes": (mediumRegularFont, whiteColor), "detailHeaderDate": (smallRegularFont, whiteColor), "detailHeaderLocation": (smallBoldFont, whiteColor), "detailViewButtonText": (mediumSmallBoldFont, whiteColor), "advisoryText": (mediumSemiboldFont, darkGreyColor), "advisorySubtext": (mediumRegularFont, lightDarkGreyColor), "greenLink": (mediumRegularFont, lightGreenColor), // event detail graph area "currentGraphDate" : (smallRegularFont, lightDarkGreyColor), // add/edit event scenes "addEditViewTitle": (mediumLargeBoldFont, whiteColor), "addEditViewNotes": (mediumRegularFont, whiteColor), "addEditViewHint": (smallRegularFont, whiteColor), "addEditViewDate": (smallRegularFont, whiteColor), "addEditViewLocation": (smallRegularFont, whiteColor), "addEditViewSaveButton": (mediumBoldFont, whiteColor), // account configuration scene "sidebarSettingUserName": (mediumLargeBoldFont, blackColor), "sidebarSettingItem": (mediumRegularFont, darkGreyColor), "sidebarSettingItemSmall": (mediumSmallRegularFont, darkGreyColor), "sidebarLogoutButton": (mediumSemiboldFont, darkGreyColor), "sidebarOtherLinks": (mediumVerySmallSemiboldFont, darkGreyColor), "sidebarSettingHKEnable": (mediumLargeBoldFont, darkGreyColor), "sidebarSettingHKMainStatus": (mediumSmallSemiboldFont, darkGreyColor), "sidebarSettingHKMinorStatus": (mediumSmallRegularFont, darkGreyColor), ] class func backgroundImageofSize(_ size: CGSize, style: String) -> UIImage? { if let backColor = Styles.usageToBackgroundColor[style] { UIGraphicsBeginImageContextWithOptions(size, false, 0) // draw background let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: size.width, height: size.height)) backColor.setFill() rectanglePath.fill() let backgroundImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return backgroundImage } else { return nil } } // // MARK: - Fonts // //// Cache fileprivate struct FontCache { static let verySmallRegularFont: UIFont = UIFont(name: "OpenSans", size: 10.0)! static let smallRegularFont: UIFont = UIFont(name: "OpenSans", size: 12.0)! static let mediumRegularFont: UIFont = UIFont(name: "OpenSans", size: 17.0)! static let mediumSmallRegularFont: UIFont = UIFont(name: "OpenSans", size: 15.0)! static let largeRegularFont: UIFont = UIFont(name: "OpenSans", size: 20.0)! static let smallSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 12.0)! static let mediumSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 17.0)! static let mediumSmallSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 15.0)! static let mediumVerySmallSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 14.0)! static let veryLargeSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 25.5)! static let smallBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 12.0)! static let mediumSmallBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 14.0)! static let mediumBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 16.0)! static let mediumLargeBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 17.5)! static let navTitleBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 20.0)! static let smallLightFont: UIFont = UIFont(name: "OpenSans-Light", size: 12.0)! static let mediumLightFont: UIFont = UIFont(name: "OpenSans-Light", size: 17.0)! // Fonts for special graph view static let tinyRegularFont: UIFont = UIFont(name: "OpenSans", size: 8.5)! static let verySmallSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 10.0)! static let veryTinySemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 8.0)! } static let uniformDateFormat: String = "MMM d, yyyy h:mm a" open class var smallRegularFont: UIFont { return FontCache.smallRegularFont } open class var mediumRegularFont: UIFont { return FontCache.mediumRegularFont } open class var mediumSmallRegularFont: UIFont { return FontCache.mediumSmallRegularFont } open class var largeRegularFont: UIFont { return FontCache.largeRegularFont } open class var smallSemiboldFont: UIFont { return FontCache.smallSemiboldFont } open class var mediumSemiboldFont: UIFont { return FontCache.mediumSemiboldFont } open class var mediumSmallSemiboldFont: UIFont { return FontCache.mediumSmallSemiboldFont } open class var mediumVerySmallSemiboldFont: UIFont { return FontCache.mediumVerySmallSemiboldFont } open class var veryLargeSemiboldFont: UIFont { return FontCache.veryLargeSemiboldFont } open class var smallBoldFont: UIFont { return FontCache.smallBoldFont } open class var mediumSmallBoldFont: UIFont { return FontCache.mediumSmallBoldFont } open class var mediumBoldFont: UIFont { return FontCache.mediumBoldFont } open class var mediumLargeBoldFont: UIFont { return FontCache.mediumLargeBoldFont } open class var navTitleBoldFont: UIFont { return FontCache.navTitleBoldFont } open class var smallLightFont: UIFont { return FontCache.smallLightFont } open class var mediumLightFont: UIFont { return FontCache.mediumLightFont } // Fonts for special graph view open class var verySmallRegularFont: UIFont { return FontCache.verySmallRegularFont } open class var tinyRegularFont: UIFont { return FontCache.tinyRegularFont } open class var verySmallSemiboldFont: UIFont { return FontCache.verySmallSemiboldFont } open class var veryTinySemiboldFont: UIFont { return FontCache.veryTinySemiboldFont } // // MARK: - Background Colors // //// Cache fileprivate struct ColorCache { static let darkPurpleColor: UIColor = UIColor(hex: 0x281946) static let brightBlueColor: UIColor = UIColor(hex: 0x627cff) static let lightGreyColor: UIColor = UIColor(hex: 0xeaeff0) static let veryLightGreyColor: UIColor = UIColor(hex: 0xf2f3f5) static let redErrorColor: UIColor = UIColor(hex: 0xff354e) static let pinkColor: UIColor = UIColor(hex: 0xf58fc7, opacity: 0.75) static let purpleColor: UIColor = UIColor(hex: 0xb29ac9) static let darkGreyColor: UIColor = UIColor(hex: 0x4a4a4a) static let lightDarkGreyColor: UIColor = UIColor(hex: 0x5c5c5c) static let altDarkGreyColor: UIColor = UIColor(hex: 0x4d4e4c) static let mediumLightGreyColor: UIColor = UIColor(hex: 0xd0d3d4) static let mediumGreyColor: UIColor = UIColor(hex: 0xb8b8b8) static let whiteColor: UIColor = UIColor(hex: 0xffffff) static let dimmedWhiteColor: UIColor = UIColor(hex: 0xffffff, opacity: 0.30) static let blackColor: UIColor = UIColor(hex: 0x000000) static let peachColor: UIColor = UIColor(hex: 0xf88d79) static let peachDeleteColor: UIColor = UIColor(hex: 0xf66f56) static let greenColor: UIColor = UIColor(hex: 0x98ca63) static let lightGreenColor: UIColor = UIColor(hex: 0x4cd964) static let lightBlueColor: UIColor = UIColor(hex: 0xc5e5f1) static let blueColor: UIColor = UIColor(hex: 0x7aceef) static let mediumBlueColor: UIColor = UIColor(hex: 0x6db7d4) static let goldColor: UIColor = UIColor(hex: 0xffd382) static let lineColor: UIColor = UIColor(hex: 0x281946) static let goldStarColor: UIColor = UIColor(hex: 0xf8ad04) static let greyStarColor: UIColor = UIColor(hex: 0xd0d3d4) static let dimmedDarkGreyColor: UIColor = UIColor(hex: 0x979797, opacity: 0.5) } open class var darkPurpleColor: UIColor { return ColorCache.darkPurpleColor } open class var brightBlueColor: UIColor { return ColorCache.brightBlueColor } open class var lightGreyColor: UIColor { return ColorCache.lightGreyColor } open class var veryLightGreyColor: UIColor { return ColorCache.veryLightGreyColor } // // MARK: - Text Colors // open class var pinkColor: UIColor { return ColorCache.pinkColor } open class var redErrorColor: UIColor { return ColorCache.redErrorColor } open class var darkGreyColor: UIColor { return ColorCache.darkGreyColor } open class var lightDarkGreyColor: UIColor { return ColorCache.lightDarkGreyColor } open class var altDarkGreyColor: UIColor { return ColorCache.altDarkGreyColor } open class var mediumLightGreyColor: UIColor { return ColorCache.mediumLightGreyColor } open class var mediumGreyColor: UIColor { return ColorCache.mediumGreyColor } open class var whiteColor: UIColor { return ColorCache.whiteColor } open class var dimmedWhiteColor: UIColor { return ColorCache.dimmedWhiteColor } open class var blackColor: UIColor { return ColorCache.blackColor } open class var peachColor: UIColor { return ColorCache.peachColor } open class var peachDeleteColor: UIColor { return ColorCache.peachDeleteColor } open class var purpleColor: UIColor { return ColorCache.purpleColor } open class var greenColor: UIColor { return ColorCache.greenColor } open class var lightGreenColor: UIColor { return ColorCache.lightGreenColor } // // MARK: - Graph Colors // // background, left side/right side // public class var lightGreyColor: UIColor { return lightGreyColor } // public class var veryLightGreyColor: UIColor { return veryLightGreyColor } // axis text // public class var darkGreyColor: UIColor { return darkGreyColor } // insulin bar open class var lightBlueColor: UIColor { return ColorCache.lightBlueColor } open class var blueColor: UIColor { return ColorCache.blueColor } // Open Sans Semibold 10: custom graph insulin amount text open class var mediumBlueColor: UIColor { return ColorCache.mediumBlueColor } // blood glucose data // public class var peachColor: UIColor { return peachColor } // public class var purpleColor: UIColor { return purpleColor } // public class var greenColor: UIColor { return greenColor } // event carb amount circle and vertical line open class var goldColor: UIColor { return ColorCache.goldColor } open class var lineColor: UIColor { return ColorCache.lineColor } // // MARK: - Misc Colors // // Icon: favorite star colors open class var goldStarColor: UIColor { return ColorCache.goldStarColor } open class var greyStarColor: UIColor { return ColorCache.greyStarColor } // View: table row line separator open class var dimmedDarkGreyColor: UIColor { return ColorCache.dimmedDarkGreyColor } // // MARK: - Strings // open class var placeholderTitleString: String { return "Meal name" } open class var titleHintString: String { return "Simple and repeatable" } open class var placeholderNotesString: String { return "Notes" } open class var noteHintString: String { return "Sides, dessert, anything else?" } open class var placeholderLocationString: String { return "Location" } }
bsd-2-clause
egorio/devslopes-showcase
devslopes-showcase/Services/DataService.swift
1
1089
// // DataService.swift // devslopes-showcase // // Created by Egorio on 3/15/16. // Copyright © 2016 Egorio. All rights reserved. // import Foundation import Firebase class DataService { static let instance = DataService() private var _firebase = Firebase(url: "https://egorio-showcase.firebaseio.com") private var _users = Firebase(url: "https://egorio-showcase.firebaseio.com/users") private var _posts = Firebase(url: "https://egorio-showcase.firebaseio.com/posts") var firebase: Firebase { return _firebase } var users: Firebase { return _users } var posts: Firebase { return _posts } var currentUser: Firebase { let id = NSUserDefaults.standardUserDefaults().valueForKey(Auth.userKey) as! String return Firebase(url: "\(_users)").childByAppendingPath(id)! } func createUser(id: String, user: [String: String]) { users.childByAppendingPath(id).setValue(user) } func createPost(post: [String: AnyObject]) { posts.childByAutoId().setValue(post) } }
mit
sunweifeng/SWFKit
SWFKit/Classes/Utils/PresentationController/SWFPresentationController.swift
1
1735
// // SWFPresentationController.swift // SWFKit // // Created by 孙伟峰 on 2017/6/19. // Copyright © 2017年 Sun Weifeng. All rights reserved. // import UIKit public class SWFPresentationController: UIPresentationController { lazy var dimmingView: UIView = { let view = UIView(frame: self.containerView!.bounds) view.backgroundColor = UIColor(white: 0, alpha: 0.5) view.alpha = 0.0 return view }() override public func presentationTransitionWillBegin() { guard let containerView = self.containerView, let presentedView = self.presentedView else { return } dimmingView.frame = containerView.bounds containerView.addSubview(dimmingView) dimmingView.addSubview(presentedView) let transitionCoordinator = presentingViewController.transitionCoordinator transitionCoordinator?.animate(alongsideTransition: { (context) in self.dimmingView.alpha = 1.0 }, completion: { (context) in }) } override public func presentationTransitionDidEnd(_ completed: Bool) { if !completed { dimmingView.removeFromSuperview() } } override public func dismissalTransitionWillBegin() { let transitionCoordinator = presentingViewController.transitionCoordinator transitionCoordinator?.animate(alongsideTransition: { (context) in self.dimmingView.alpha = 0.0 }, completion: { (context) in }) } override public func dismissalTransitionDidEnd(_ completed: Bool) { if completed { self.dimmingView.removeFromSuperview() } } }
mit
Blackjacx/StickyHeaderFlowLayout
Demo/DemoTests/DemoTests.swift
1
896
// // DemoTests.swift // DemoTests // // Created by Stefan Herold on 19.02.15. // Copyright (c) 2015 Stefan Herold. All rights reserved. // import UIKit import XCTest class DemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
Fidetro/SwiftFFDB
Sources/Limit.swift
1
679
// // Limit.swift // Swift-FFDB // // Created by Fidetro on 2018/5/29. // Copyright © 2018年 Fidetro. All rights reserved. // import Foundation public struct Limit:STMT { public let stmt: String } // MARK: - internal extension Limit { init(_ stmt : String,format:String?=nil) { if let format = format { self.stmt = stmt + "limit" + " " + format + " " } else { self.stmt = stmt + " " } } } // MARK: - Offset extension Limit { public func offset(_ offset:String) -> Offset { return Offset(stmt, format: offset) } }
apache-2.0
yuhao-ios/DouYuTVForSwift
DouYuTVForSwift/DouYuTVForSwift/Home/Controller/RecommendVC.swift
1
3548
// // RecommendVC.swift // DouYuTVForSwift // // Created by t4 on 17/4/24. // Copyright © 2017年 t4. All rights reserved. // //推荐控制器 import UIKit class RecommendVC: BaseAnchorViewController { //MARK: - 懒加载 //创建ViewModel的属性 lazy var recommandVM : RecommendVM = RecommendVM() //创建轮播图 fileprivate lazy var cycleView : RecommendCycleView = { let cycleView = RecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewHeight+90), width: kMainWidth, height: kCycleViewHeight) return cycleView }() //创建显示游戏名字的视图 fileprivate lazy var gameView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -90, width: kMainWidth, height: 90) return gameView }() } //MARK: - 设置UI界面 extension RecommendVC { //重写父类的布局 override func loadUI() { super.loadUI() collectionView.addSubview(cycleView) collectionView.addSubview(gameView) //设置collectionView内边距 collectionView.contentInset = UIEdgeInsetsMake(kCycleViewHeight + 90, 0, 0, 0) } // 重写父类 请求网络数据 的方法 override func loadData(){ super.loadData() //给父类赋值 baseAnchorVm = recommandVM //加载推荐直播数据 recommandVM.requestData { //1.刷新collectionView self.collectionView .reloadData() //2. var groups = self.recommandVM.anchorGroups //2.1.移除前两组数据 添加一组更多数据 groups.remove(at: 0) groups.remove(at: 0) let moreGroup = AnchorGroupModel() moreGroup.tag_name = "更多" groups.append(moreGroup) //2.2给gameView设置数据 self.gameView.groups = groups //3.数据加载完成 展示内容 self.showContentView() } //加载无限轮播数据 recommandVM.requestCycleData { self.cycleView.cycles = self.recommandVM.cycles } } } //MARK: - UICollectionViewDataSource UICollectionViewDelegateFlowLayout extension RecommendVC : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemWidth, height: kPrettyItemHeight) } return CGSize(width: kItemWidth, height: kNormalItemHeight) } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //section = 1 返回自己的cell if indexPath.section == 1 { let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier:prettyCellID , for: indexPath) as! CollectionPrettyCell // 2.设置数据 prettyCell.anchor = recommandVM.anchorGroups[indexPath.section].anchors[indexPath.item] return prettyCell } //否则返回父类的cell return super.collectionView(collectionView, cellForItemAt: indexPath) } }
mit
sascha/DrawerController
KitchenSink/ExampleFiles/ViewControllers/ExampleSideDrawerViewController.swift
1
13801
// Copyright (c) 2017 evolved.io (http://evolved.io) // // 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 import DrawerController enum DrawerSection: Int { case viewSelection case drawerWidth case shadowToggle case openDrawerGestures case closeDrawerGestures case centerHiddenInteraction case stretchDrawer } class ExampleSideDrawerViewController: ExampleViewController, UITableViewDataSource, UITableViewDelegate { var tableView: UITableView! let drawerWidths: [CGFloat] = [160, 200, 240, 280, 320] override func viewDidLoad() { super.viewDidLoad() self.tableView = UITableView(frame: self.view.bounds, style: .grouped) self.tableView.delegate = self self.tableView.dataSource = self self.view.addSubview(self.tableView) self.tableView.autoresizingMask = [ .flexibleWidth, .flexibleHeight ] self.tableView.backgroundColor = UIColor(red: 110 / 255, green: 113 / 255, blue: 115 / 255, alpha: 1.0) self.tableView.separatorStyle = .none self.navigationController?.navigationBar.barTintColor = UIColor(red: 161 / 255, green: 164 / 255, blue: 166 / 255, alpha: 1.0) self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor(red: 55 / 255, green: 70 / 255, blue: 77 / 255, alpha: 1.0)] self.view.backgroundColor = UIColor.clear } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // See https://github.com/sascha/DrawerController/issues/12 self.navigationController?.view.setNeedsLayout() let integersRange = NSRange(location: 0, length: self.tableView.numberOfSections - 1) self.tableView.reloadSections(IndexSet(integersIn: Range(integersRange) ?? 0..<0), with: .none) } override func contentSizeDidChange(_ size: String) { self.tableView.reloadData() } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 7 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case DrawerSection.viewSelection.rawValue: return 2 case DrawerSection.drawerWidth.rawValue: return self.drawerWidths.count case DrawerSection.shadowToggle.rawValue: return 1 case DrawerSection.openDrawerGestures.rawValue: return 3 case DrawerSection.closeDrawerGestures.rawValue: return 6 case DrawerSection.centerHiddenInteraction.rawValue: return 3 case DrawerSection.stretchDrawer.rawValue: return 1 default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let CellIdentifier = "Cell" var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as UITableViewCell? if cell == nil { cell = SideDrawerTableViewCell(style: .default, reuseIdentifier: CellIdentifier) cell.selectionStyle = .blue } switch (indexPath as NSIndexPath).section { case DrawerSection.viewSelection.rawValue: if (indexPath as NSIndexPath).row == 0 { cell.textLabel?.text = "Quick View Change" } else { cell.textLabel?.text = "Full View Change" } cell.accessoryType = .disclosureIndicator case DrawerSection.drawerWidth.rawValue: // Implement in Subclass break case DrawerSection.shadowToggle.rawValue: cell.textLabel?.text = "Show Shadow" if self.evo_drawerController != nil && self.evo_drawerController!.showsShadows { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case DrawerSection.openDrawerGestures.rawValue: switch (indexPath as NSIndexPath).row { case 0: cell.textLabel?.text = "Pan Nav Bar" if self.evo_drawerController != nil && self.evo_drawerController!.openDrawerGestureModeMask.contains(.panningNavigationBar) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case 1: cell.textLabel?.text = "Pan Center View" if self.evo_drawerController != nil && self.evo_drawerController!.openDrawerGestureModeMask.contains(.panningCenterView) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case 2: cell.textLabel?.text = "Bezel Pan Center View" if self.evo_drawerController != nil && self.evo_drawerController!.openDrawerGestureModeMask.contains(.bezelPanningCenterView) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } default: break } case DrawerSection.closeDrawerGestures.rawValue: switch (indexPath as NSIndexPath).row { case 0: cell.textLabel?.text = "Pan Nav Bar" if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.panningNavigationBar) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case 1: cell.textLabel?.text = "Pan Center View" if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.panningCenterView) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case 2: cell.textLabel?.text = "Bezel Pan Center View" if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.bezelPanningCenterView) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case 3: cell.textLabel?.text = "Tap Nav Bar" if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.tapNavigationBar) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case 4: cell.textLabel?.text = "Tap Center View" if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.tapCenterView) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case 5: cell.textLabel?.text = "Pan Drawer View" if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.panningDrawerView) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } default: break } case DrawerSection.centerHiddenInteraction.rawValue: cell.selectionStyle = .blue switch (indexPath as NSIndexPath).row { case 0: cell.textLabel?.text = "None" if self.evo_drawerController != nil && self.evo_drawerController!.centerHiddenInteractionMode == .none { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case 1: cell.textLabel?.text = "Full" if self.evo_drawerController != nil && self.evo_drawerController!.centerHiddenInteractionMode == .full { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } case 2: cell.textLabel?.text = "Nav Bar Only" if self.evo_drawerController != nil && self.evo_drawerController!.centerHiddenInteractionMode == .navigationBarOnly { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } default: break } case DrawerSection.stretchDrawer.rawValue: cell.textLabel?.text = "Stretch Drawer" if self.evo_drawerController != nil && self.evo_drawerController!.shouldStretchDrawer { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } default: break } return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case DrawerSection.viewSelection.rawValue: return "New Center View" case DrawerSection.drawerWidth.rawValue: return "Drawer Width" case DrawerSection.shadowToggle.rawValue: return "Shadow" case DrawerSection.openDrawerGestures.rawValue: return "Drawer Open Gestures" case DrawerSection.closeDrawerGestures.rawValue: return "Drawer Close Gestures" case DrawerSection.centerHiddenInteraction.rawValue: return "Open Center Interaction Mode" case DrawerSection.stretchDrawer.rawValue: return "Stretch Drawer" default: return nil } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = SideDrawerSectionHeaderView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 56.0)) headerView.autoresizingMask = [ .flexibleHeight, .flexibleWidth ] headerView.title = tableView.dataSource?.tableView?(tableView, titleForHeaderInSection: section) return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 56 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0 } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath as NSIndexPath).section { case DrawerSection.viewSelection.rawValue: let center = ExampleCenterTableViewController() let nav = UINavigationController(rootViewController: center) if (indexPath as NSIndexPath).row % 2 == 0 { self.evo_drawerController?.setCenter(nav, withCloseAnimation: true, completion: nil) } else { self.evo_drawerController?.setCenter(nav, withFullCloseAnimation: true, completion: nil) } case DrawerSection.drawerWidth.rawValue: // Implement in Subclass break case DrawerSection.shadowToggle.rawValue: self.evo_drawerController?.showsShadows = !self.evo_drawerController!.showsShadows tableView.reloadSections(IndexSet(integer: (indexPath as NSIndexPath).section), with: .none) case DrawerSection.openDrawerGestures.rawValue: switch (indexPath as NSIndexPath).row { case 0: self.evo_drawerController?.openDrawerGestureModeMask.formSymmetricDifference(.panningNavigationBar) case 1: self.evo_drawerController?.openDrawerGestureModeMask.formSymmetricDifference(.panningCenterView) case 2: self.evo_drawerController?.openDrawerGestureModeMask.formSymmetricDifference(.bezelPanningCenterView) default: break } tableView.reloadRows(at: [indexPath], with: .none) case DrawerSection.closeDrawerGestures.rawValue: switch (indexPath as NSIndexPath).row { case 0: self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.panningNavigationBar) case 1: self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.panningCenterView) case 2: self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.bezelPanningCenterView) case 3: self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.tapNavigationBar) case 4: self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.tapCenterView) case 5: self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.panningDrawerView) default: break } tableView.reloadRows(at: [indexPath], with: .none) case DrawerSection.centerHiddenInteraction.rawValue: self.evo_drawerController?.centerHiddenInteractionMode = DrawerOpenCenterInteractionMode(rawValue: ((indexPath as NSIndexPath).row))! tableView.reloadSections(IndexSet(integer: (indexPath as NSIndexPath).section), with: .none) case DrawerSection.stretchDrawer.rawValue: self.evo_drawerController?.shouldStretchDrawer = !self.evo_drawerController!.shouldStretchDrawer tableView.reloadRows(at: [indexPath], with: .none) default: break } tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) tableView.deselectRow(at: indexPath, animated: true) } }
mit
sareninden/DataSourceFramework
DataSourceFrameworkDemo/DataSourceFrameworkDemo/InsertingTableViewController.swift
1
2529
import Foundation import UIKit import DataSourceFramework class InsertingTableViewController : BaseTableViewController { // MARK:- Class Variables // MARK:- Variables // MARK:- Init and Dealloc override init() { super.init() title = "Inserting" tableView.editing = true tableController.editingDelegate = self tableController.titleForDeleteConfirmation = "Delete" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- Public Class Methods // MARK:- Internal Instance Methods override func loadData() { for sectionIndex in 0 ..< 3 { let section = sectionWithHeaderTitle("Section \(sectionIndex)") for row in 0 ... 15 { let item = TableItem(text: "Start row \(row)") section.addItem(item) } tableController.addSection(section) } } } extension InsertingTableViewController : TableControllerEditingInterface { func tableController(tableController : TableController, tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return .Insert } func tableController(tableController : TableController, tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { let section = tableController.sectionAtIndex(indexPath.section) switch editingStyle { case .None: break case .Insert: let newIndexPath = NSIndexPath(forItem: indexPath.item + 1, inSection: indexPath.section) let item = TableItem(text: "Inserted at row \(newIndexPath.item)") item.editingStyle = .Delete section.insertItem(item, atIndex: newIndexPath.item) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic) break case .Delete: section.removeItemAtIndex(indexPath.item) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) break } } func tableController(tableController : TableController, tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } }
gpl-3.0
sarvex/SwiftRecepies
Data/Implementing Relationships in Core Data/Implementing Relationships in Core Data/ViewController.swift
1
537
// // ViewController.swift // Implementing Relationships in Core Data // // Created by vandad on 167//14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
isc
CodySchrank/HackingWithSwift
project33/Project33/AppDelegate.swift
25
2904
// // AppDelegate.swift // Project33 // // Created by Hudzilla on 19/09/2015. // Copyright © 2015 Paul Hudson. All rights reserved. // import CloudKit import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) UIApplication.sharedApplication().registerForRemoteNotifications() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { if let pushInfo = userInfo as? [String: NSObject] { let notification = CKNotification(fromRemoteNotificationDictionary: pushInfo) let ac = UIAlertController(title: "What's that Whistle?", message: notification.alertBody, preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) if let nc = window?.rootViewController as? UINavigationController { if let vc = nc.visibleViewController { vc.presentViewController(ac, animated: true, completion: nil) } } } } }
unlicense
Eonil/EditorLegacy
Modules/EditorModel/EditorModel/Editing.swift
1
332
// // Editing.swift // EditorModel // // Created by Hoon H. on 2015/06/02. // Copyright (c) 2015 Eonil. All rights reserved. // import Foundation import SignalGraph public class Editing { public let currentFileURL = ValueStorage<NSURL?>(nil) /// MARK: - internal weak var owner : Workspace? internal init() { } }
mit
liyanhuadev/ObjectMapper-Plugin
Pods/ObjectMapper/Sources/HexColorTransform.swift
15
3339
// // HexColorTransform.swift // ObjectMapper // // Created by Vitaliy Kuzmenko on 10/10/16. // Copyright © 2016 hearst. All rights reserved. // #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #elseif os(macOS) import Cocoa #endif #if os(iOS) || os(tvOS) || os(watchOS) || os(macOS) open class HexColorTransform: TransformType { #if os(iOS) || os(tvOS) || os(watchOS) public typealias Object = UIColor #else public typealias Object = NSColor #endif public typealias JSON = String var prefix: Bool = false var alpha: Bool = false public init(prefixToJSON: Bool = false, alphaToJSON: Bool = false) { alpha = alphaToJSON prefix = prefixToJSON } open func transformFromJSON(_ value: Any?) -> Object? { if let rgba = value as? String { if rgba.hasPrefix("#") { let index = rgba.index(rgba.startIndex, offsetBy: 1) let hex = String(rgba[index...]) return getColor(hex: hex) } else { return getColor(hex: rgba) } } return nil } open func transformToJSON(_ value: Object?) -> JSON? { if let value = value { return hexString(color: value) } return nil } fileprivate func hexString(color: Object) -> String { let comps = color.cgColor.components! let compsCount = color.cgColor.numberOfComponents let r: Int let g: Int var b: Int let a = Int(comps[compsCount - 1] * 255) if compsCount == 4 { // RGBA r = Int(comps[0] * 255) g = Int(comps[1] * 255) b = Int(comps[2] * 255) } else { // Grayscale r = Int(comps[0] * 255) g = Int(comps[0] * 255) b = Int(comps[0] * 255) } var hexString: String = "" if prefix { hexString = "#" } hexString += String(format: "%02X%02X%02X", r, g, b) if alpha { hexString += String(format: "%02X", a) } return hexString } fileprivate func getColor(hex: String) -> Object? { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: // Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8 return nil } } else { // "Scan hex error return nil } #if os(iOS) || os(tvOS) || os(watchOS) return UIColor(red: red, green: green, blue: blue, alpha: alpha) #else return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha) #endif } } #endif
mit
loudnate/Loop
Loop/View Controllers/StatusTableViewController.swift
1
60388
// // StatusTableViewController.swift // Naterade // // Created by Nathan Racklyeft on 9/6/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // import UIKit import HealthKit import Intents import LoopCore import LoopKit import LoopKitUI import LoopUI import SwiftCharts import os.log private extension RefreshContext { static let all: Set<RefreshContext> = [.status, .glucose, .insulin, .carbs, .targets] } final class StatusTableViewController: ChartsTableViewController { private let log = OSLog(category: "StatusTableViewController") lazy var quantityFormatter: QuantityFormatter = QuantityFormatter() override func viewDidLoad() { super.viewDidLoad() statusCharts.glucose.glucoseDisplayRange = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 100)...HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 175) registerPumpManager() let notificationCenter = NotificationCenter.default notificationObservers += [ notificationCenter.addObserver(forName: .LoopDataUpdated, object: deviceManager.loopManager, queue: nil) { [weak self] note in let rawContext = note.userInfo?[LoopDataManager.LoopUpdateContextKey] as! LoopDataManager.LoopUpdateContext.RawValue let context = LoopDataManager.LoopUpdateContext(rawValue: rawContext) DispatchQueue.main.async { switch context { case .none, .bolus?: self?.refreshContext.formUnion([.status, .insulin]) case .preferences?: self?.refreshContext.formUnion([.status, .targets]) case .carbs?: self?.refreshContext.update(with: .carbs) case .glucose?: self?.refreshContext.formUnion([.glucose, .carbs]) case .tempBasal?: self?.refreshContext.update(with: .insulin) } self?.hudView?.loopCompletionHUD.loopInProgress = false self?.log.debug("[reloadData] from notification with context %{public}@", String(describing: context)) self?.reloadData(animated: true) } }, notificationCenter.addObserver(forName: .LoopRunning, object: deviceManager.loopManager, queue: nil) { [weak self] _ in DispatchQueue.main.async { self?.hudView?.loopCompletionHUD.loopInProgress = true } }, notificationCenter.addObserver(forName: .PumpManagerChanged, object: deviceManager, queue: nil) { [weak self] (notification: Notification) in DispatchQueue.main.async { self?.registerPumpManager() self?.configurePumpManagerHUDViews() } }, notificationCenter.addObserver(forName: .PumpEventsAdded, object: deviceManager, queue: nil) { [weak self] (notification: Notification) in DispatchQueue.main.async { self?.refreshContext.update(with: .insulin) self?.reloadData(animated: true) } } ] if let gestureRecognizer = charts.gestureRecognizer { tableView.addGestureRecognizer(gestureRecognizer) } tableView.estimatedRowHeight = 70 // Estimate an initial value landscapeMode = UIScreen.main.bounds.size.width > UIScreen.main.bounds.size.height // Toolbar toolbarItems![0].accessibilityLabel = NSLocalizedString("Add Meal", comment: "The label of the carb entry button") toolbarItems![0].tintColor = UIColor.COBTintColor toolbarItems![4].accessibilityLabel = NSLocalizedString("Bolus", comment: "The label of the bolus entry button") toolbarItems![4].tintColor = UIColor.doseTintColor if #available(iOS 13.0, *) { toolbarItems![8].image = UIImage(systemName: "gear") } toolbarItems![8].accessibilityLabel = NSLocalizedString("Settings", comment: "The label of the settings button") toolbarItems![8].tintColor = UIColor.secondaryLabelColor tableView.register(BolusProgressTableViewCell.nib(), forCellReuseIdentifier: BolusProgressTableViewCell.className) addScenarioStepGestureRecognizers() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() if !visible { refreshContext.formUnion(RefreshContext.all) } } private var appearedOnce = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) updateBolusProgress() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !appearedOnce { appearedOnce = true if deviceManager.loopManager.authorizationRequired { deviceManager.loopManager.authorize { DispatchQueue.main.async { self.log.debug("[reloadData] after HealthKit authorization") self.reloadData() } } } } onscreen = true AnalyticsManager.shared.didDisplayStatusScreen() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) onscreen = false if presentedViewController == nil { navigationController?.setNavigationBarHidden(false, animated: animated) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { refreshContext.update(with: .size(size)) super.viewWillTransition(to: size, with: coordinator) } // MARK: - State override var active: Bool { didSet { hudView?.loopCompletionHUD.assertTimer(active) updateHUDActive() } } // This is similar to the visible property, but is set later, on viewDidAppear, to be // suitable for animations that should be seen in their entirety. var onscreen: Bool = false { didSet { updateHUDActive() } } private var bolusState = PumpManagerStatus.BolusState.none { didSet { if oldValue != bolusState { // Bolus starting if case .inProgress = bolusState { self.bolusProgressReporter = self.deviceManager.pumpManager?.createBolusProgressReporter(reportingOn: DispatchQueue.main) } refreshContext.update(with: .status) self.reloadData(animated: true) } } } private var bolusProgressReporter: DoseProgressReporter? private func updateBolusProgress() { if let cell = tableView.cellForRow(at: IndexPath(row: StatusRow.status.rawValue, section: Section.status.rawValue)) as? BolusProgressTableViewCell { cell.deliveredUnits = bolusProgressReporter?.progress.deliveredUnits } } private func updateHUDActive() { deviceManager.pumpManagerHUDProvider?.visible = active && onscreen } public var basalDeliveryState: PumpManagerStatus.BasalDeliveryState = .active(Date()) { didSet { if oldValue != basalDeliveryState { log.debug("New basalDeliveryState: %@", String(describing: basalDeliveryState)) refreshContext.update(with: .status) self.reloadData(animated: true) } } } // Toggles the display mode based on the screen aspect ratio. Should not be updated outside of reloadData(). private var landscapeMode = false private var lastLoopError: Error? private var reloading = false private var refreshContext = RefreshContext.all private var shouldShowHUD: Bool { return !landscapeMode } private var shouldShowStatus: Bool { return !landscapeMode && statusRowMode.hasRow } override func glucoseUnitDidChange() { refreshContext = RefreshContext.all } private func registerPumpManager() { if let pumpManager = deviceManager.pumpManager { self.basalDeliveryState = pumpManager.status.basalDeliveryState pumpManager.removeStatusObserver(self) pumpManager.addStatusObserver(self, queue: .main) } } private lazy var statusCharts = StatusChartsManager(colors: .default, settings: .default, traitCollection: self.traitCollection) override func createChartsManager() -> ChartsManager { return statusCharts } private func updateChartDateRange() { let settings = deviceManager.loopManager.settings // How far back should we show data? Use the screen size as a guide. let availableWidth = (refreshContext.newSize ?? self.tableView.bounds.size).width - self.charts.fixedHorizontalMargin let totalHours = floor(Double(availableWidth / settings.minimumChartWidthPerHour)) let futureHours = ceil((deviceManager.loopManager.insulinModelSettings?.model.effectDuration ?? .hours(4)).hours) let historyHours = max(settings.statusChartMinimumHistoryDisplay.hours, totalHours - futureHours) let date = Date(timeIntervalSinceNow: -TimeInterval(hours: historyHours)) let chartStartDate = Calendar.current.nextDate(after: date, matching: DateComponents(minute: 0), matchingPolicy: .strict, direction: .backward) ?? date if charts.startDate != chartStartDate { refreshContext.formUnion(RefreshContext.all) } charts.startDate = chartStartDate charts.maxEndDate = chartStartDate.addingTimeInterval(.hours(totalHours)) charts.updateEndDate(charts.maxEndDate) } override func reloadData(animated: Bool = false) { // This should be kept up to date immediately hudView?.loopCompletionHUD.lastLoopCompleted = deviceManager.loopManager.lastLoopCompleted guard !reloading && !deviceManager.loopManager.authorizationRequired else { return } updateChartDateRange() redrawCharts() if case .bolusing = statusRowMode, bolusProgressReporter?.progress.isComplete == true { refreshContext.update(with: .status) } if visible && active { bolusProgressReporter?.addObserver(self) } else { bolusProgressReporter?.removeObserver(self) } guard active && visible && !refreshContext.isEmpty else { return } log.debug("Reloading data with context: %@", String(describing: refreshContext)) let currentContext = refreshContext var retryContext: Set<RefreshContext> = [] self.refreshContext = [] reloading = true let reloadGroup = DispatchGroup() var newRecommendedTempBasal: (recommendation: TempBasalRecommendation, date: Date)? var glucoseValues: [StoredGlucoseSample]? var predictedGlucoseValues: [GlucoseValue]? var iobValues: [InsulinValue]? var doseEntries: [DoseEntry]? var totalDelivery: Double? var cobValues: [CarbValue]? let startDate = charts.startDate let basalDeliveryState = self.basalDeliveryState // TODO: Don't always assume currentContext.contains(.status) reloadGroup.enter() self.deviceManager.loopManager.getLoopState { (manager, state) -> Void in predictedGlucoseValues = state.predictedGlucoseIncludingPendingInsulin ?? [] // Retry this refresh again if predicted glucose isn't available if state.predictedGlucose == nil { retryContext.update(with: .status) } /// Update the status HUDs immediately let lastLoopCompleted = manager.lastLoopCompleted let lastLoopError = state.error // Net basal rate HUD let netBasal: NetBasal? if let basalSchedule = manager.basalRateScheduleApplyingOverrideHistory { netBasal = basalDeliveryState.getNetBasal(basalSchedule: basalSchedule, settings: manager.settings) } else { netBasal = nil } self.log.debug("Update net basal to %{public}@", String(describing: netBasal)) DispatchQueue.main.async { self.hudView?.loopCompletionHUD.dosingEnabled = manager.settings.dosingEnabled self.lastLoopError = lastLoopError if let netBasal = netBasal { self.hudView?.basalRateHUD.setNetBasalRate(netBasal.rate, percent: netBasal.percent, at: netBasal.start) } } // Display a recommended basal change only if we haven't completed recently, or we're in open-loop mode if lastLoopCompleted == nil || lastLoopCompleted! < Date(timeIntervalSinceNow: .minutes(-6)) || !manager.settings.dosingEnabled { newRecommendedTempBasal = state.recommendedTempBasal } if currentContext.contains(.carbs) { reloadGroup.enter() manager.carbStore.getCarbsOnBoardValues(start: startDate, effectVelocities: manager.settings.dynamicCarbAbsorptionEnabled ? state.insulinCounteractionEffects : nil) { (values) in DispatchQueue.main.async { cobValues = values reloadGroup.leave() } } } reloadGroup.leave() } if currentContext.contains(.glucose) { reloadGroup.enter() self.deviceManager.loopManager.glucoseStore.getCachedGlucoseSamples(start: startDate) { (values) -> Void in DispatchQueue.main.async { glucoseValues = values reloadGroup.leave() } } } if currentContext.contains(.insulin) { reloadGroup.enter() deviceManager.loopManager.doseStore.getInsulinOnBoardValues(start: startDate) { (result) -> Void in DispatchQueue.main.async { switch result { case .failure(let error): self.log.error("DoseStore failed to get insulin on board values: %{public}@", String(describing: error)) retryContext.update(with: .insulin) iobValues = [] case .success(let values): iobValues = values } reloadGroup.leave() } } reloadGroup.enter() deviceManager.loopManager.doseStore.getNormalizedDoseEntries(start: startDate) { (result) -> Void in DispatchQueue.main.async { switch result { case .failure(let error): self.log.error("DoseStore failed to get normalized dose entries: %{public}@", String(describing: error)) retryContext.update(with: .insulin) doseEntries = [] case .success(let doses): doseEntries = doses } reloadGroup.leave() } } reloadGroup.enter() deviceManager.loopManager.doseStore.getTotalUnitsDelivered(since: Calendar.current.startOfDay(for: Date())) { (result) in DispatchQueue.main.async { switch result { case .failure: retryContext.update(with: .insulin) totalDelivery = nil case .success(let total): totalDelivery = total.value } reloadGroup.leave() } } } if deviceManager.loopManager.settings.preMealTargetRange == nil { preMealMode = nil } else { preMealMode = deviceManager.loopManager.settings.preMealTargetEnabled() } if !FeatureFlags.sensitivityOverridesEnabled, deviceManager.loopManager.settings.legacyWorkoutTargetRange == nil { workoutMode = nil } else { workoutMode = deviceManager.loopManager.settings.nonPreMealOverrideEnabled() } reloadGroup.notify(queue: .main) { /// Update the chart data // Glucose if let glucoseValues = glucoseValues { self.statusCharts.setGlucoseValues(glucoseValues) } if let predictedGlucoseValues = predictedGlucoseValues { self.statusCharts.setPredictedGlucoseValues(predictedGlucoseValues) } if let lastPoint = self.statusCharts.glucose.predictedGlucosePoints.last?.y { self.eventualGlucoseDescription = String(describing: lastPoint) } else { self.eventualGlucoseDescription = nil } if currentContext.contains(.targets) { self.statusCharts.targetGlucoseSchedule = self.deviceManager.loopManager.settings.glucoseTargetRangeSchedule self.statusCharts.scheduleOverride = self.deviceManager.loopManager.settings.scheduleOverride } if self.statusCharts.scheduleOverride?.hasFinished() == true { self.statusCharts.scheduleOverride = nil } let charts = self.statusCharts // Active Insulin if let iobValues = iobValues { charts.setIOBValues(iobValues) } // Show the larger of the value either before or after the current date if let maxValue = charts.iob.iobPoints.allElementsAdjacent(to: Date()).max(by: { return $0.y.scalar < $1.y.scalar }) { self.currentIOBDescription = String(describing: maxValue.y) } else { self.currentIOBDescription = nil } // Insulin Delivery if let doseEntries = doseEntries { charts.setDoseEntries(doseEntries) } if let totalDelivery = totalDelivery { self.totalDelivery = totalDelivery } // Active Carbohydrates if let cobValues = cobValues { charts.setCOBValues(cobValues) } if let index = charts.cob.cobPoints.closestIndex(priorTo: Date()) { self.currentCOBDescription = String(describing: charts.cob.cobPoints[index].y) } else { self.currentCOBDescription = nil } self.tableView.beginUpdates() if let hudView = self.hudView { // Glucose HUD if let glucose = self.deviceManager.loopManager.glucoseStore.latestGlucose { let unit = self.statusCharts.glucose.glucoseUnit hudView.glucoseHUD.setGlucoseQuantity(glucose.quantity.doubleValue(for: unit), at: glucose.startDate, unit: unit, staleGlucoseAge: self.deviceManager.loopManager.settings.inputDataRecencyInterval, sensor: self.deviceManager.sensorState ) } } // Show/hide the table view rows let statusRowMode = self.determineStatusRowMode(recommendedTempBasal: newRecommendedTempBasal) self.updateHUDandStatusRows(statusRowMode: statusRowMode, newSize: currentContext.newSize, animated: animated) self.redrawCharts() self.tableView.endUpdates() self.reloading = false let reloadNow = !self.refreshContext.isEmpty self.refreshContext.formUnion(retryContext) // Trigger a reload if new context exists. if reloadNow { self.log.debug("[reloadData] due to context change during previous reload") self.reloadData() } } } private enum Section: Int { case hud = 0 case status case charts static let count = 3 } // MARK: - Chart Section Data private enum ChartRow: Int { case glucose = 0 case iob case dose case cob static let count = 4 } // MARK: Glucose private var eventualGlucoseDescription: String? // MARK: IOB private var currentIOBDescription: String? // MARK: Dose private var totalDelivery: Double? // MARK: COB private var currentCOBDescription: String? // MARK: - Loop Status Section Data private enum StatusRow: Int { case status = 0 static let count = 1 } private enum StatusRowMode { case hidden case recommendedTempBasal(tempBasal: TempBasalRecommendation, at: Date, enacting: Bool) case scheduleOverrideEnabled(TemporaryScheduleOverride) case enactingBolus case bolusing(dose: DoseEntry) case cancelingBolus case pumpSuspended(resuming: Bool) var hasRow: Bool { switch self { case .hidden: return false default: return true } } } private var statusRowMode = StatusRowMode.hidden private func determineStatusRowMode(recommendedTempBasal: (recommendation: TempBasalRecommendation, date: Date)? = nil) -> StatusRowMode { let statusRowMode: StatusRowMode if case .initiating = bolusState { statusRowMode = .enactingBolus } else if case .canceling = bolusState { statusRowMode = .cancelingBolus } else if case .suspended = basalDeliveryState { statusRowMode = .pumpSuspended(resuming: false) } else if self.basalDeliveryState == .resuming { statusRowMode = .pumpSuspended(resuming: true) } else if case .inProgress(let dose) = bolusState, dose.endDate.timeIntervalSinceNow > 0 { statusRowMode = .bolusing(dose: dose) } else if let (recommendation: tempBasal, date: date) = recommendedTempBasal { statusRowMode = .recommendedTempBasal(tempBasal: tempBasal, at: date, enacting: false) } else if let scheduleOverride = deviceManager.loopManager.settings.scheduleOverride, scheduleOverride.context != .preMeal && scheduleOverride.context != .legacyWorkout, !scheduleOverride.hasFinished() { statusRowMode = .scheduleOverrideEnabled(scheduleOverride) } else { statusRowMode = .hidden } return statusRowMode } private func updateHUDandStatusRows(statusRowMode: StatusRowMode, newSize: CGSize?, animated: Bool) { let hudWasVisible = self.shouldShowHUD let statusWasVisible = self.shouldShowStatus let oldStatusRowMode = self.statusRowMode self.statusRowMode = statusRowMode if let newSize = newSize { self.landscapeMode = newSize.width > newSize.height } let hudIsVisible = self.shouldShowHUD let statusIsVisible = self.shouldShowStatus tableView.beginUpdates() switch (hudWasVisible, hudIsVisible) { case (false, true): self.tableView.insertRows(at: [IndexPath(row: 0, section: Section.hud.rawValue)], with: animated ? .top : .none) case (true, false): self.tableView.deleteRows(at: [IndexPath(row: 0, section: Section.hud.rawValue)], with: animated ? .top : .none) default: break } let statusIndexPath = IndexPath(row: StatusRow.status.rawValue, section: Section.status.rawValue) switch (statusWasVisible, statusIsVisible) { case (true, true): switch (oldStatusRowMode, self.statusRowMode) { case (.recommendedTempBasal(tempBasal: let oldTempBasal, at: let oldDate, enacting: let wasEnacting), .recommendedTempBasal(tempBasal: let newTempBasal, at: let newDate, enacting: let isEnacting)): // Ensure we have a change guard oldTempBasal != newTempBasal || oldDate != newDate || wasEnacting != isEnacting else { break } // If the rate or date change, reload the row if oldTempBasal != newTempBasal || oldDate != newDate { self.tableView.reloadRows(at: [statusIndexPath], with: animated ? .fade : .none) } else if let cell = tableView.cellForRow(at: statusIndexPath) { // If only the enacting state changed, update the activity indicator if isEnacting { let indicatorView = UIActivityIndicatorView(style: .default) indicatorView.startAnimating() cell.accessoryView = indicatorView } else { cell.accessoryView = nil } } case (.enactingBolus, .enactingBolus): break case (.bolusing(let oldDose), .bolusing(let newDose)): if oldDose != newDose { self.tableView.reloadRows(at: [statusIndexPath], with: animated ? .fade : .none) } case (.pumpSuspended(resuming: let wasResuming), .pumpSuspended(resuming: let isResuming)): if isResuming != wasResuming { self.tableView.reloadRows(at: [statusIndexPath], with: animated ? .fade : .none) } default: self.tableView.reloadRows(at: [statusIndexPath], with: animated ? .fade : .none) } case (false, true): self.tableView.insertRows(at: [statusIndexPath], with: animated ? .top : .none) case (true, false): self.tableView.deleteRows(at: [statusIndexPath], with: animated ? .top : .none) default: break } tableView.endUpdates() } private func redrawCharts() { tableView.beginUpdates() self.charts.prerender() for case let cell as ChartTableViewCell in self.tableView.visibleCells { cell.reloadChart() if let indexPath = self.tableView.indexPath(for: cell) { self.tableView(self.tableView, updateSubtitleFor: cell, at: indexPath) } } tableView.endUpdates() } // MARK: - Toolbar data private var preMealMode: Bool? = nil { didSet { guard oldValue != preMealMode else { return } if let preMealMode = preMealMode { toolbarItems![2] = createPreMealButtonItem(selected: preMealMode) } else { toolbarItems![2].isEnabled = false } } } private var workoutMode: Bool? = nil { didSet { guard oldValue != workoutMode else { return } if let workoutMode = workoutMode { toolbarItems![6] = createWorkoutButtonItem(selected: workoutMode) } else { toolbarItems![6].isEnabled = false } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return Section.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Section(rawValue: section)! { case .hud: return shouldShowHUD ? 1 : 0 case .charts: return ChartRow.count case .status: return shouldShowStatus ? StatusRow.count : 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch Section(rawValue: indexPath.section)! { case .hud: let cell = tableView.dequeueReusableCell(withIdentifier: HUDViewTableViewCell.className, for: indexPath) as! HUDViewTableViewCell self.hudView = cell.hudView return cell case .charts: let cell = tableView.dequeueReusableCell(withIdentifier: ChartTableViewCell.className, for: indexPath) as! ChartTableViewCell switch ChartRow(rawValue: indexPath.row)! { case .glucose: cell.chartContentView.chartGenerator = { [weak self] (frame) in return self?.statusCharts.glucoseChart(withFrame: frame)?.view } cell.titleLabel?.text = NSLocalizedString("Glucose", comment: "The title of the glucose and prediction graph") case .iob: cell.chartContentView.chartGenerator = { [weak self] (frame) in return self?.statusCharts.iobChart(withFrame: frame)?.view } cell.titleLabel?.text = NSLocalizedString("Active Insulin", comment: "The title of the Insulin On-Board graph") case .dose: cell.chartContentView?.chartGenerator = { [weak self] (frame) in return self?.statusCharts.doseChart(withFrame: frame)?.view } cell.titleLabel?.text = NSLocalizedString("Insulin Delivery", comment: "The title of the insulin delivery graph") case .cob: cell.chartContentView?.chartGenerator = { [weak self] (frame) in return self?.statusCharts.cobChart(withFrame: frame)?.view } cell.titleLabel?.text = NSLocalizedString("Active Carbohydrates", comment: "The title of the Carbs On-Board graph") } self.tableView(tableView, updateSubtitleFor: cell, at: indexPath) let alpha: CGFloat = charts.gestureRecognizer?.state == .possible ? 1 : 0 cell.titleLabel?.alpha = alpha cell.subtitleLabel?.alpha = alpha cell.subtitleLabel?.textColor = UIColor.secondaryLabelColor return cell case .status: func getTitleSubtitleCell() -> TitleSubtitleTableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: TitleSubtitleTableViewCell.className, for: indexPath) as! TitleSubtitleTableViewCell cell.selectionStyle = .none return cell } switch StatusRow(rawValue: indexPath.row)! { case .status: switch statusRowMode { case .hidden: let cell = getTitleSubtitleCell() cell.titleLabel.text = nil cell.subtitleLabel?.text = nil cell.accessoryView = nil return cell case .recommendedTempBasal(tempBasal: let tempBasal, at: let date, enacting: let enacting): let cell = getTitleSubtitleCell() let timeFormatter = DateFormatter() timeFormatter.dateStyle = .none timeFormatter.timeStyle = .short cell.titleLabel.text = NSLocalizedString("Recommended Basal", comment: "The title of the cell displaying a recommended temp basal value") cell.subtitleLabel?.text = String(format: NSLocalizedString("%1$@ U/hour @ %2$@", comment: "The format for recommended temp basal rate and time. (1: localized rate number)(2: localized time)"), NumberFormatter.localizedString(from: NSNumber(value: tempBasal.unitsPerHour), number: .decimal), timeFormatter.string(from: date)) cell.selectionStyle = .default if enacting { let indicatorView = UIActivityIndicatorView(style: .default) indicatorView.startAnimating() cell.accessoryView = indicatorView } else { cell.accessoryView = nil } return cell case .scheduleOverrideEnabled(let override): let cell = getTitleSubtitleCell() switch override.context { case .preMeal, .legacyWorkout: assertionFailure("Pre-meal and legacy workout modes should not produce status rows") case .preset(let preset): cell.titleLabel.text = String(format: NSLocalizedString("%@ %@", comment: "The format for an active override preset. (1: preset symbol)(2: preset name)"), preset.symbol, preset.name) case .custom: cell.titleLabel.text = NSLocalizedString("Custom Override", comment: "The title of the cell indicating a generic temporary override is enabled") } if override.isActive() { switch override.duration { case .finite: let endTimeText = DateFormatter.localizedString(from: override.activeInterval.end, dateStyle: .none, timeStyle: .short) cell.subtitleLabel.text = String(format: NSLocalizedString("until %@", comment: "The format for the description of a temporary override end date"), endTimeText) case .indefinite: cell.subtitleLabel.text = nil } } else { let startTimeText = DateFormatter.localizedString(from: override.startDate, dateStyle: .none, timeStyle: .short) cell.subtitleLabel.text = String(format: NSLocalizedString("starting at %@", comment: "The format for the description of a temporary override start date"), startTimeText) } cell.accessoryView = nil return cell case .enactingBolus: let cell = getTitleSubtitleCell() cell.titleLabel.text = NSLocalizedString("Starting Bolus", comment: "The title of the cell indicating a bolus is being sent") cell.subtitleLabel.text = nil let indicatorView = UIActivityIndicatorView(style: .default) indicatorView.startAnimating() cell.accessoryView = indicatorView return cell case .bolusing(let dose): let progressCell = tableView.dequeueReusableCell(withIdentifier: BolusProgressTableViewCell.className, for: indexPath) as! BolusProgressTableViewCell progressCell.selectionStyle = .none progressCell.totalUnits = dose.programmedUnits progressCell.tintColor = .doseTintColor progressCell.unit = HKUnit.internationalUnit() progressCell.deliveredUnits = bolusProgressReporter?.progress.deliveredUnits return progressCell case .cancelingBolus: let cell = getTitleSubtitleCell() cell.titleLabel.text = NSLocalizedString("Canceling Bolus", comment: "The title of the cell indicating a bolus is being canceled") cell.subtitleLabel.text = nil let indicatorView = UIActivityIndicatorView(style: .default) indicatorView.startAnimating() cell.accessoryView = indicatorView return cell case .pumpSuspended(let resuming): let cell = getTitleSubtitleCell() cell.titleLabel.text = NSLocalizedString("Pump Suspended", comment: "The title of the cell indicating the pump is suspended") if resuming { let indicatorView = UIActivityIndicatorView(style: .default) indicatorView.startAnimating() cell.accessoryView = indicatorView cell.subtitleLabel.text = nil } else { cell.accessoryView = nil cell.subtitleLabel.text = NSLocalizedString("Tap to Resume", comment: "The subtitle of the cell displaying an action to resume insulin delivery") } cell.selectionStyle = .default return cell } } } } private func tableView(_ tableView: UITableView, updateSubtitleFor cell: ChartTableViewCell, at indexPath: IndexPath) { switch Section(rawValue: indexPath.section)! { case .charts: switch ChartRow(rawValue: indexPath.row)! { case .glucose: if let eventualGlucose = eventualGlucoseDescription { cell.subtitleLabel?.text = String(format: NSLocalizedString("Eventually %@", comment: "The subtitle format describing eventual glucose. (1: localized glucose value description)"), eventualGlucose) } else { cell.subtitleLabel?.text = nil } case .iob: if let currentIOB = currentIOBDescription { cell.subtitleLabel?.text = currentIOB } else { cell.subtitleLabel?.text = nil } case .dose: let integerFormatter = NumberFormatter() integerFormatter.maximumFractionDigits = 0 if let total = totalDelivery, let totalString = integerFormatter.string(from: total) { cell.subtitleLabel?.text = String(format: NSLocalizedString("%@ U Total", comment: "The subtitle format describing total insulin. (1: localized insulin total)"), totalString) } else { cell.subtitleLabel?.text = nil } case .cob: if let currentCOB = currentCOBDescription { cell.subtitleLabel?.text = currentCOB } else { cell.subtitleLabel?.text = nil } } case .hud, .status: break } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch Section(rawValue: indexPath.section)! { case .charts: // Compute the height of the HUD, defaulting to 70 let hudHeight = ceil(hudView?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height ?? 70) var availableSize = max(tableView.bounds.width, tableView.bounds.height) if #available(iOS 11.0, *) { availableSize -= (tableView.safeAreaInsets.top + tableView.safeAreaInsets.bottom + hudHeight) } else { // 20: Status bar // 44: Toolbar availableSize -= hudHeight + 20 + 44 } switch ChartRow(rawValue: indexPath.row)! { case .glucose: return max(106, 0.37 * availableSize) case .iob, .dose, .cob: return max(106, 0.21 * availableSize) } case .hud, .status: return UITableView.automaticDimension } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch Section(rawValue: indexPath.section)! { case .charts: switch ChartRow(rawValue: indexPath.row)! { case .glucose: performSegue(withIdentifier: PredictionTableViewController.className, sender: indexPath) case .iob, .dose: performSegue(withIdentifier: InsulinDeliveryTableViewController.className, sender: indexPath) case .cob: performSegue(withIdentifier: CarbAbsorptionViewController.className, sender: indexPath) } case .status: switch StatusRow(rawValue: indexPath.row)! { case .status: tableView.deselectRow(at: indexPath, animated: true) switch statusRowMode { case .recommendedTempBasal(tempBasal: let tempBasal, at: let date, enacting: let enacting) where !enacting: self.updateHUDandStatusRows(statusRowMode: .recommendedTempBasal(tempBasal: tempBasal, at: date, enacting: true), newSize: nil, animated: true) self.deviceManager.loopManager.enactRecommendedTempBasal { (error) in DispatchQueue.main.async { self.updateHUDandStatusRows(statusRowMode: .hidden, newSize: nil, animated: true) if let error = error { self.log.error("Failed to enact recommended temp basal: %{public}@", String(describing: error)) self.present(UIAlertController(with: error), animated: true) } else { self.refreshContext.update(with: .status) self.log.debug("[reloadData] after manually enacting temp basal") self.reloadData() } } } case .pumpSuspended(let resuming) where !resuming: self.updateHUDandStatusRows(statusRowMode: .pumpSuspended(resuming: true) , newSize: nil, animated: true) self.deviceManager.pumpManager?.resumeDelivery() { (error) in DispatchQueue.main.async { if let error = error { let alert = UIAlertController(with: error, title: NSLocalizedString("Error Resuming", comment: "The alert title for a resume error")) self.present(alert, animated: true, completion: nil) if case .suspended = self.basalDeliveryState { self.updateHUDandStatusRows(statusRowMode: .pumpSuspended(resuming: false), newSize: nil, animated: true) } } else { self.updateHUDandStatusRows(statusRowMode: self.determineStatusRowMode(), newSize: nil, animated: true) self.refreshContext.update(with: .insulin) self.log.debug("[reloadData] after manually resuming suspend") self.reloadData() } } } case .scheduleOverrideEnabled(let override): let vc = AddEditOverrideTableViewController(glucoseUnit: statusCharts.glucose.glucoseUnit) vc.inputMode = .editOverride(override) vc.delegate = self show(vc, sender: tableView.cellForRow(at: indexPath)) case .bolusing: self.updateHUDandStatusRows(statusRowMode: .cancelingBolus, newSize: nil, animated: true) self.deviceManager.pumpManager?.cancelBolus() { (result) in DispatchQueue.main.async { switch result { case .success: // show user confirmation and actual delivery amount? break case .failure(let error): let alert = UIAlertController(with: error, title: NSLocalizedString("Error Canceling Bolus", comment: "The alert title for an error while canceling a bolus")) self.present(alert, animated: true, completion: nil) if case .inProgress(let dose) = self.bolusState { self.updateHUDandStatusRows(statusRowMode: .bolusing(dose: dose), newSize: nil, animated: true) } else { self.updateHUDandStatusRows(statusRowMode: .hidden, newSize: nil, animated: true) } } } } default: break } } case .hud: break } } // MARK: - Actions override func restoreUserActivityState(_ activity: NSUserActivity) { switch activity.activityType { case NSUserActivity.newCarbEntryActivityType: performSegue(withIdentifier: CarbEntryViewController.className, sender: activity) default: break } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) var targetViewController = segue.destination if let navVC = targetViewController as? UINavigationController, let topViewController = navVC.topViewController { targetViewController = topViewController } switch targetViewController { case let vc as CarbAbsorptionViewController: vc.deviceManager = deviceManager vc.hidesBottomBarWhenPushed = true case let vc as CarbEntryViewController: vc.deviceManager = deviceManager vc.glucoseUnit = statusCharts.glucose.glucoseUnit vc.defaultAbsorptionTimes = deviceManager.loopManager.carbStore.defaultAbsorptionTimes vc.preferredUnit = deviceManager.loopManager.carbStore.preferredUnit if let activity = sender as? NSUserActivity { vc.restoreUserActivityState(activity) } case let vc as InsulinDeliveryTableViewController: vc.doseStore = deviceManager.loopManager.doseStore vc.hidesBottomBarWhenPushed = true case let vc as BolusViewController: vc.deviceManager = deviceManager vc.glucoseUnit = statusCharts.glucose.glucoseUnit vc.configuration = .manualCorrection AnalyticsManager.shared.didDisplayBolusScreen() case let vc as OverrideSelectionViewController: if deviceManager.loopManager.settings.futureOverrideEnabled() { vc.scheduledOverride = deviceManager.loopManager.settings.scheduleOverride } vc.presets = deviceManager.loopManager.settings.overridePresets vc.glucoseUnit = statusCharts.glucose.glucoseUnit vc.delegate = self case let vc as PredictionTableViewController: vc.deviceManager = deviceManager case let vc as SettingsTableViewController: vc.dataManager = deviceManager default: break } } @IBAction func unwindFromEditing(_ segue: UIStoryboardSegue) {} @IBAction func unwindFromBolusViewController(_ segue: UIStoryboardSegue) { guard let bolusViewController = segue.source as? BolusViewController else { return } if let carbEntry = bolusViewController.updatedCarbEntry { if #available(iOS 12.0, *) { let interaction = INInteraction(intent: NewCarbEntryIntent(), response: nil) interaction.donate { [weak self] (error) in if let error = error { self?.log.error("Failed to donate intent: %{public}@", String(describing: error)) } } } deviceManager.loopManager.addCarbEntryAndRecommendBolus(carbEntry) { result in DispatchQueue.main.async { switch result { case .success: // Enact the user-entered bolus if let bolus = bolusViewController.bolus, bolus > 0 { self.deviceManager.enactBolus(units: bolus) { _ in } } case .failure(let error): // Ignore bolus wizard errors if error is CarbStore.CarbStoreError { self.present(UIAlertController(with: error), animated: true) } else { self.log.error("Failed to add carb entry: %{public}@", String(describing: error)) } } } } } else if let bolus = bolusViewController.bolus, bolus > 0 { self.deviceManager.enactBolus(units: bolus) { _ in } } } @IBAction func unwindFromSettings(_ segue: UIStoryboardSegue) { } private func createPreMealButtonItem(selected: Bool) -> UIBarButtonItem { let item = UIBarButtonItem(image: UIImage.preMealImage(selected: selected), style: .plain, target: self, action: #selector(togglePreMealMode(_:))) item.accessibilityLabel = NSLocalizedString("Pre-Meal Targets", comment: "The label of the pre-meal mode toggle button") if selected { item.accessibilityTraits.insert(.selected) item.accessibilityHint = NSLocalizedString("Disables", comment: "The action hint of the workout mode toggle button when enabled") } else { item.accessibilityHint = NSLocalizedString("Enables", comment: "The action hint of the workout mode toggle button when disabled") } item.tintColor = UIColor.COBTintColor return item } private func createWorkoutButtonItem(selected: Bool) -> UIBarButtonItem { let item = UIBarButtonItem(image: UIImage.workoutImage(selected: selected), style: .plain, target: self, action: #selector(toggleWorkoutMode(_:))) item.accessibilityLabel = NSLocalizedString("Workout Targets", comment: "The label of the workout mode toggle button") if selected { item.accessibilityTraits.insert(.selected) item.accessibilityHint = NSLocalizedString("Disables", comment: "The action hint of the workout mode toggle button when enabled") } else { item.accessibilityHint = NSLocalizedString("Enables", comment: "The action hint of the workout mode toggle button when disabled") } item.tintColor = UIColor.glucoseTintColor return item } @IBAction func togglePreMealMode(_ sender: UIBarButtonItem) { if preMealMode == true { deviceManager.loopManager.settings.clearOverride(matching: .preMeal) } else { deviceManager.loopManager.settings.enablePreMealOverride(for: .hours(1)) } } @IBAction func toggleWorkoutMode(_ sender: UIBarButtonItem) { if workoutMode == true { deviceManager.loopManager.settings.clearOverride() } else { if FeatureFlags.sensitivityOverridesEnabled { performSegue(withIdentifier: OverrideSelectionViewController.className, sender: toolbarItems![6]) } else { let vc = UIAlertController(workoutDurationSelectionHandler: { duration in let startDate = Date() self.deviceManager.loopManager.settings.enableLegacyWorkoutOverride(at: startDate, for: duration) }) present(vc, animated: true, completion: nil) } } } // MARK: - HUDs @IBOutlet var hudView: HUDView? { didSet { guard let hudView = hudView, hudView != oldValue else { return } let statusTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showLastError(_:))) hudView.loopCompletionHUD.addGestureRecognizer(statusTapGestureRecognizer) hudView.loopCompletionHUD.accessibilityHint = NSLocalizedString("Shows last loop error", comment: "Loop Completion HUD accessibility hint") let glucoseTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(openCGMApp(_:))) hudView.glucoseHUD.addGestureRecognizer(glucoseTapGestureRecognizer) if deviceManager.cgmManager?.appURL != nil { hudView.glucoseHUD.accessibilityHint = NSLocalizedString("Launches CGM app", comment: "Glucose HUD accessibility hint") } configurePumpManagerHUDViews() hudView.loopCompletionHUD.stateColors = .loopStatus hudView.glucoseHUD.stateColors = .cgmStatus hudView.glucoseHUD.tintColor = .glucoseTintColor hudView.basalRateHUD.tintColor = .doseTintColor refreshContext.update(with: .status) self.log.debug("[reloadData] after hudView loaded") reloadData() } } private func configurePumpManagerHUDViews() { if let hudView = hudView { hudView.removePumpManagerProvidedViews() if let pumpManagerHUDProvider = deviceManager.pumpManagerHUDProvider { let views = pumpManagerHUDProvider.createHUDViews() for view in views { addViewToHUD(view) } pumpManagerHUDProvider.visible = active && onscreen } else { let reservoirView = ReservoirVolumeHUDView.instantiate() let batteryView = BatteryLevelHUDView.instantiate() for view in [reservoirView, batteryView] { addViewToHUD(view) } } } } private func addViewToHUD(_ view: BaseHUDView) { if let hudView = hudView { let hudTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(hudViewTapped(_:))) view.addGestureRecognizer(hudTapGestureRecognizer) view.stateColors = .pumpStatus hudView.addHUDView(view) } } @objc private func showLastError(_: Any) { var error: Error? = nil // First, check whether we have a device error after the most recent completion date if let deviceError = deviceManager.lastError, deviceError.date > (hudView?.loopCompletionHUD.lastLoopCompleted ?? .distantPast) { error = deviceError.error } else if let lastLoopError = lastLoopError { error = lastLoopError } if error != nil { let alertController = UIAlertController(with: error!) let manualLoopAction = UIAlertAction(title: NSLocalizedString("Retry", comment: "The button text for attempting a manual loop"), style: .default, handler: { _ in self.deviceManager.loopManager.loop() }) alertController.addAction(manualLoopAction) present(alertController, animated: true) } } @objc private func openCGMApp(_: Any) { if let url = deviceManager.cgmManager?.appURL, UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } @objc private func hudViewTapped(_ sender: UIGestureRecognizer) { if let hudSubView = sender.view as? BaseHUDView, let pumpManagerHUDProvider = deviceManager.pumpManagerHUDProvider, let action = pumpManagerHUDProvider.didTapOnHUDView(hudSubView) { switch action { case .presentViewController(let vc): var completionNotifyingVC = vc completionNotifyingVC.completionDelegate = self self.present(vc, animated: true, completion: nil) case .openAppURL(let url): UIApplication.shared.open(url) } } } // MARK: - Testing scenarios override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { if let testingScenariosManager = deviceManager.testingScenariosManager, !testingScenariosManager.scenarioURLs.isEmpty { if motion == .motionShake { presentScenarioSelector() } } } private func presentScenarioSelector() { guard let testingScenariosManager = deviceManager.testingScenariosManager else { return } let vc = TestingScenariosTableViewController(scenariosManager: testingScenariosManager) present(UINavigationController(rootViewController: vc), animated: true) } private func addScenarioStepGestureRecognizers() { if debugEnabled { let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(stepActiveScenarioForward)) leftSwipe.direction = .left let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(stepActiveScenarioBackward)) rightSwipe.direction = .right let toolBar = navigationController!.toolbar! toolBar.addGestureRecognizer(leftSwipe) toolBar.addGestureRecognizer(rightSwipe) } } @objc private func stepActiveScenarioForward() { deviceManager.testingScenariosManager?.stepActiveScenarioForward { _ in } } @objc private func stepActiveScenarioBackward() { deviceManager.testingScenariosManager?.stepActiveScenarioBackward { _ in } } } extension StatusTableViewController: CompletionDelegate { func completionNotifyingDidComplete(_ object: CompletionNotifying) { if let vc = object as? UIViewController, presentedViewController === vc { dismiss(animated: true, completion: nil) } } } extension StatusTableViewController: PumpManagerStatusObserver { func pumpManager(_ pumpManager: PumpManager, didUpdate status: PumpManagerStatus, oldStatus: PumpManagerStatus) { dispatchPrecondition(condition: .onQueue(.main)) log.default("PumpManager:%{public}@ did update status", String(describing: type(of: pumpManager))) self.basalDeliveryState = status.basalDeliveryState self.bolusState = status.bolusState } } extension StatusTableViewController: DoseProgressObserver { func doseProgressReporterDidUpdate(_ doseProgressReporter: DoseProgressReporter) { updateBolusProgress() if doseProgressReporter.progress.isComplete { // Bolus ended self.bolusProgressReporter = nil DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { self.bolusState = .none self.reloadData(animated: true) }) } } } extension StatusTableViewController: OverrideSelectionViewControllerDelegate { func overrideSelectionViewController(_ vc: OverrideSelectionViewController, didUpdatePresets presets: [TemporaryScheduleOverridePreset]) { deviceManager.loopManager.settings.overridePresets = presets } func overrideSelectionViewController(_ vc: OverrideSelectionViewController, didConfirmOverride override: TemporaryScheduleOverride) { deviceManager.loopManager.settings.scheduleOverride = override } func overrideSelectionViewController(_ vc: OverrideSelectionViewController, didCancelOverride override: TemporaryScheduleOverride) { deviceManager.loopManager.settings.scheduleOverride = nil } } extension StatusTableViewController: AddEditOverrideTableViewControllerDelegate { func addEditOverrideTableViewController(_ vc: AddEditOverrideTableViewController, didSaveOverride override: TemporaryScheduleOverride) { deviceManager.loopManager.settings.scheduleOverride = override } func addEditOverrideTableViewController(_ vc: AddEditOverrideTableViewController, didCancelOverride override: TemporaryScheduleOverride) { deviceManager.loopManager.settings.scheduleOverride = nil } }
apache-2.0
GuiminChu/HishowZone-iOS
HiShow/General/View/ImageViewingController.swift
1
11807
import UIKit import Kingfisher class ImageViewingController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate { private lazy var scrollView: UIScrollView = { let view = UIScrollView(frame: self.view.bounds) view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.delegate = self view.showsHorizontalScrollIndicator = false view.zoomScale = 1.0 view.maximumZoomScale = 8.0 view.isScrollEnabled = false return view }() private let duration = 0.3 private let zoomScale: CGFloat = 3.0 private let dismissDistance: CGFloat = 100.0 private var image: UIImage! private var imageView: AnimatedImageView! private var imageInfo: ImageInfo! private var startFrame: CGRect! private var snapshotView: UIView! private var originalScrollViewCenter: CGPoint = .zero private var singleTapGestureRecognizer: UITapGestureRecognizer! private var panGestureRecognizer: UIPanGestureRecognizer! private var longPressGestureRecognizer: UILongPressGestureRecognizer! private var doubleTapGestureRecognizer: UITapGestureRecognizer! init(imageInfo: ImageInfo) { super.init(nibName: nil, bundle: nil) self.imageInfo = imageInfo image = imageInfo.image } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(scrollView) let referenceFrameCurrentView = imageInfo.referenceView.convert(imageInfo.referenceRect, to: view) imageView = AnimatedImageView(frame: referenceFrameCurrentView) imageView.isUserInteractionEnabled = true imageView.image = image // imageView.originalData = imageInfo.originalData // used for gif image imageView.contentMode = .scaleAspectFill // reset content mode imageView.backgroundColor = .clear setupGestureRecognizers() view.backgroundColor = .black } func presented(by viewController: UIViewController) { view.isUserInteractionEnabled = false snapshotView = snapshotParentmostViewController(of: viewController) snapshotView.alpha = 0.1 view.insertSubview(snapshotView, at: 0) let referenceFrameInWindow = imageInfo.referenceView.convert(imageInfo.referenceRect, to: nil) view.addSubview(imageView) // will move to scroll view after transition finishes viewController.present(self, animated: false) { self.imageView.frame = referenceFrameInWindow self.startFrame = referenceFrameInWindow UIView.animate(withDuration: self.duration, delay: 0, options: .beginFromCurrentState, animations: { self.imageView.frame = self.resizedFrame(forImageSize: self.image.size) self.imageView.center = CGPoint(x: self.view.bounds.width / 2.0, y: self.view.bounds.height / 2.0) }, completion: { (_) in self.scrollView.addSubview(self.imageView) self.updateScrollViewAndImageView() self.view.isUserInteractionEnabled = true }) } } private func dismiss() { view.isUserInteractionEnabled = false let imageFrame = view.convert(imageView.frame, from: scrollView) imageView.removeFromSuperview() imageView.frame = imageFrame view.addSubview(imageView) scrollView.removeFromSuperview() UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState, animations: { self.imageView.frame = self.startFrame }) { (_) in self.dismiss(animated: false, completion: nil) } } // MARK: - Private private func cancelImageDragging() { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: { self.imageView.center = CGPoint(x: self.scrollView.contentSize.width / 2.0, y: self.scrollView.contentSize.height / 2.0) self.updateScrollViewAndImageView() self.snapshotView.alpha = 0.1 }, completion: nil) } private func setupGestureRecognizers() { doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTap(_:))) doubleTapGestureRecognizer.numberOfTapsRequired = 2 doubleTapGestureRecognizer.delegate = self longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress)) longPressGestureRecognizer.delegate = self singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(singleTap)) singleTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer) singleTapGestureRecognizer.require(toFail: longPressGestureRecognizer) singleTapGestureRecognizer.delegate = self view.addGestureRecognizer(singleTapGestureRecognizer) view.addGestureRecognizer(longPressGestureRecognizer) view.addGestureRecognizer(doubleTapGestureRecognizer) panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan(_:))) panGestureRecognizer.maximumNumberOfTouches = 1 panGestureRecognizer.delegate = self scrollView.addGestureRecognizer(panGestureRecognizer) } private func snapshotParentmostViewController(of viewController: UIViewController) -> UIView { var snapshot = viewController.view if var presentingViewController = viewController.view.window!.rootViewController { while presentingViewController.presentedViewController != nil { presentingViewController = presentingViewController.presentedViewController! } snapshot = presentingViewController.view.snapshotView(afterScreenUpdates: true) } return snapshot ?? UIView() } private func updateScrollViewAndImageView() { scrollView.frame = view.bounds imageView.frame = resizedFrame(forImageSize: image.size) scrollView.contentSize = imageView.frame.size scrollView.contentInset = contentInsetForScrollView(withZoomScale: scrollView.zoomScale) } private func contentInsetForScrollView(withZoomScale zoomScale: CGFloat) -> UIEdgeInsets { let boundsWidth = scrollView.bounds.width let boundsHeight = scrollView.bounds.height let contentWidth = image.size.width let contentHeight = image.size.height var minContentHeight: CGFloat! var minContentWidth: CGFloat! if (contentHeight / contentWidth) < (boundsHeight / boundsWidth) { minContentWidth = boundsWidth minContentHeight = minContentWidth * (contentHeight / contentWidth) } else { minContentHeight = boundsHeight minContentWidth = minContentHeight * (contentWidth / contentHeight) } minContentWidth = minContentWidth * zoomScale minContentHeight = minContentHeight * zoomScale let hDiff = max(boundsWidth - minContentWidth, 0) let vDiff = max(boundsHeight - minContentHeight, 0) let inset = UIEdgeInsets(top: vDiff / 2.0, left: hDiff / 2.0, bottom: vDiff / 2.0, right: hDiff / 2.0) return inset } private func resizedFrame(forImageSize size: CGSize) -> CGRect { guard size.width > 0, size.height > 0 else { return .zero } var frame = view.bounds let nativeWidth = size.width let nativeHeight = size.height var targetWidth = frame.width * scrollView.zoomScale var targetHeight = frame.height * scrollView.zoomScale if (targetHeight / targetWidth) < (nativeHeight / nativeWidth) { targetWidth = targetHeight * (nativeWidth / nativeHeight) } else { targetHeight = targetWidth * (nativeHeight / nativeWidth) } frame = CGRect(x: 0, y: 0, width: targetWidth, height: targetHeight) return frame } // MARK: - Gesture Recognizer Actions @objc private func singleTap() { dismiss() } @objc private func pan(_ sender: UIPanGestureRecognizer) { let translation = sender.translation(in: sender.view) let translationDistance = sqrt(pow(translation.x, 2) + pow(translation.y, 2)) switch sender.state { case .began: originalScrollViewCenter = scrollView.center case .changed: scrollView.center = CGPoint(x: originalScrollViewCenter.x + translation.x, y: originalScrollViewCenter.y + translation.y) snapshotView.alpha = min(max(translationDistance / dismissDistance * 0.5, 0.1), 0.6) default: if translationDistance > dismissDistance { dismiss() } else { cancelImageDragging() } } } @objc private func longPress() { let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil) present(activityViewController, animated: true, completion: nil) } @objc private func doubleTap(_ sender: UITapGestureRecognizer) { let rawLocation = sender.location(in: sender.view) let point = scrollView.convert(rawLocation, from: sender.view) var targetZoomRect: CGRect var targetInsets: UIEdgeInsets if scrollView.zoomScale == 1.0 { let zoomWidth = view.bounds.width / zoomScale let zoomHeight = view.bounds.height / zoomScale targetZoomRect = CGRect(x: point.x - zoomWidth * 0.5, y: point.y - zoomHeight * 0.5, width: zoomWidth, height: zoomHeight) targetInsets = contentInsetForScrollView(withZoomScale: zoomScale) } else { let zoomWidth = view.bounds.width * scrollView.zoomScale let zoomHeight = view.bounds.height * scrollView.zoomScale targetZoomRect = CGRect(x: point.x - zoomWidth * 0.5, y: point.y - zoomHeight * 0.5, width: zoomWidth, height: zoomHeight) targetInsets = contentInsetForScrollView(withZoomScale: 1.0) } view.isUserInteractionEnabled = false CATransaction.begin() CATransaction.setCompletionBlock { self.scrollView.contentInset = targetInsets self.view.isUserInteractionEnabled = true } scrollView.zoom(to: targetZoomRect, animated: true) CATransaction.commit() } // MARK: - UIGestureRecognizerDelegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if gestureRecognizer == panGestureRecognizer, scrollView.zoomScale != 1.0 { return false } return true } // MARK: - UIScrollViewDelegate func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { scrollView.contentInset = contentInsetForScrollView(withZoomScale: scrollView.zoomScale) scrollView.isScrollEnabled = true } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { scrollView.isScrollEnabled = (scale > 1) scrollView.contentInset = contentInsetForScrollView(withZoomScale: scale) } } struct ImageInfo { var image: UIImage! var originalData: Data? var referenceRect: CGRect! var referenceView: UIView! }
mit
cacawai/Tap2Read
tap2read/Pods/SugarRecord/SugarRecord/Source/CoreData/Storages/CoreDataDefaultStorage.swift
1
7929
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 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) }
mit
sachin004/firefox-ios
Client/Frontend/Settings/SettingsTableViewController.swift
1
42628
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Account import Base32 import Shared import UIKit import XCGLogger private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // The following are only here because we use master for L10N and otherwise these strings would disappear from the v1.0 release private let Bug1204635_S1 = NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.") private let Bug1204635_S2 = NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything") private let Bug1204635_S3 = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog") private let Bug1204635_S4 = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog") // A base TableViewCell, to help minimize initialization and allow recycling. class SettingsTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) indentationWidth = 0 layoutMargins = UIEdgeInsetsZero // So that the seperator line goes all the way to the left edge. separatorInset = UIEdgeInsetsZero } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // A base setting class that shows a title. You probably want to subclass this, not use it directly. class Setting { private var _title: NSAttributedString? // The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy. var url: NSURL? { return nil } // The title shown on the pref. var title: NSAttributedString? { return _title } // An optional second line of text shown on the pref. var status: NSAttributedString? { return nil } // Whether or not to show this pref. var hidden: Bool { return false } var style: UITableViewCellStyle { return .Subtitle } var accessoryType: UITableViewCellAccessoryType { return .None } // Called when the cell is setup. Call if you need the default behaviour. func onConfigureCell(cell: UITableViewCell) { cell.detailTextLabel?.attributedText = status cell.textLabel?.attributedText = title cell.accessoryType = accessoryType cell.accessoryView = nil } // Called when the pref is tapped. func onClick(navigationController: UINavigationController?) { return } // Helper method to set up and push a SettingsContentViewController func setUpAndPushSettingsContentViewController(navigationController: UINavigationController?) { if let url = self.url { let viewController = SettingsContentViewController() viewController.settingsTitle = self.title viewController.url = url navigationController?.pushViewController(viewController, animated: true) } } init(title: NSAttributedString? = nil) { self._title = title } } // A setting in the sections panel. Contains a sublist of Settings class SettingSection : Setting { private let children: [Setting] init(title: NSAttributedString? = nil, children: [Setting]) { self.children = children super.init(title: title) } var count: Int { var count = 0 for setting in children { if !setting.hidden { count++ } } return count } subscript(val: Int) -> Setting? { var i = 0 for setting in children { if !setting.hidden { if i == val { return setting } i++ } } return nil } } // A helper class for settings with a UISwitch. // Takes and optional settingsDidChange callback and status text. class BoolSetting: Setting { private let prefKey: String private let prefs: Prefs private let defaultValue: Bool private let settingDidChange: ((Bool) -> Void)? private let statusText: String? init(prefs: Prefs, prefKey: String, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) { self.prefs = prefs self.prefKey = prefKey self.defaultValue = defaultValue self.settingDidChange = settingDidChange self.statusText = statusText super.init(title: NSAttributedString(string: titleText, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var status: NSAttributedString? { if let text = statusText { return NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor]) } else { return nil } } override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged) control.on = prefs.boolForKey(prefKey) ?? defaultValue cell.accessoryView = control } @objc func switchValueChanged(control: UISwitch) { prefs.setBool(control.on, forKey: prefKey) settingDidChange?(control.on) } } // A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to // the fxAccount happen. private class AccountSetting: Setting, FxAContentViewControllerDelegate { unowned var settings: SettingsTableViewController var profile: Profile { return settings.profile } override var title: NSAttributedString? { return nil } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } private override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) if settings.profile.getAccount() != nil { cell.selectionStyle = .None } } override var accessoryType: UITableViewCellAccessoryType { return .None } func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void { if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil { // The /settings endpoint sends a partial "login"; ignore it entirely. NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.") return } // TODO: Error handling. let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)! settings.profile.setAccount(account) // Reload the data to reflect the new Account immediately. settings.tableView.reloadData() // And start advancing the Account state in the background as well. settings.SELrefresh() settings.navigationController?.popToRootViewControllerAnimated(true) } func contentViewControllerDidCancel(viewController: FxAContentViewController) { NSLog("didCancel") settings.navigationController?.popToRootViewControllerAnimated(true) } } private class WithAccountSetting: AccountSetting { override var hidden: Bool { return !profile.hasAccount() } } private class WithoutAccountSetting: AccountSetting { override var hidden: Bool { return profile.hasAccount() } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. private class ConnectSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Sign In", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { let viewController = FxAContentViewController() viewController.delegate = self viewController.url = settings.profile.accountConfiguration.signInURL navigationController?.pushViewController(viewController, animated: true) } } // Sync setting for disconnecting a Firefox Account. Shown when we have an account. private class DisconnectSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .None } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed]) } override func onClick(navigationController: UINavigationController?) { let alertController = UIAlertController( title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"), message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"), preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction( UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button in the 'log out firefox account' alert"), style: .Cancel) { (action) in // Do nothing. }) alertController.addAction( UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in self.settings.profile.removeAccount() // Refresh, to show that we no longer have an Account immediately. self.settings.SELrefresh() }) navigationController?.presentViewController(alertController, animated: true, completion: nil) } } private class SyncNowSetting: WithAccountSetting { private let syncNowTitle = NSAttributedString(string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIConstants.DefaultStandardFont]) private let syncingTitle = NSAttributedString(string: NSLocalizedString("Syncing…", comment: "Syncing Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIConstants.DefaultStandardFontSize, weight: UIFontWeightRegular)]) override var accessoryType: UITableViewCellAccessoryType { return .None } override var style: UITableViewCellStyle { return .Value1 } override var title: NSAttributedString? { return profile.syncManager.isSyncing ? syncingTitle : syncNowTitle } override var status: NSAttributedString? { if let timestamp = profile.prefs.timestampForKey(PrefsKeys.KeyLastSyncFinishTime) { let label = NSLocalizedString("Last synced: %@", comment: "Last synced time label beside Sync Now setting option. Argument is the relative date string.") let formattedLabel = String(format: label, NSDate.fromTimestamp(timestamp).toRelativeTimeString()) let attributedString = NSMutableAttributedString(string: formattedLabel) let attributes = [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12, weight: UIFontWeightRegular)] let range = NSMakeRange(0, attributedString.length) attributedString.setAttributes(attributes, range: range) return attributedString } return nil } override func onConfigureCell(cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.detailTextLabel?.attributedText = status cell.accessoryType = accessoryType cell.accessoryView = nil cell.userInteractionEnabled = !profile.syncManager.isSyncing } override func onClick(navigationController: UINavigationController?) { profile.syncManager.syncEverything() } } // Sync setting that shows the current Firefox Account status. private class AccountStatusSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { if let account = profile.getAccount() { switch account.actionNeeded { case .NeedsVerification: // We link to the resend verification email page. return .DisclosureIndicator case .NeedsPassword: // We link to the re-enter password page. return .DisclosureIndicator case .None, .NeedsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. return .None } } return .DisclosureIndicator } override var title: NSAttributedString? { if let account = profile.getAccount() { return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: UIConstants.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } return nil } override var status: NSAttributedString? { if let account = profile.getAccount() { switch account.actionNeeded { case .None: return nil case .NeedsVerification: return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) case .NeedsPassword: let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: string.characters.count) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs = [NSForegroundColorAttributeName : orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res case .NeedsUpgrade: let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: string.characters.count) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs = [NSForegroundColorAttributeName : orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } } return nil } override func onClick(navigationController: UINavigationController?) { let viewController = FxAContentViewController() viewController.delegate = self if let account = profile.getAccount() { switch account.actionNeeded { case .NeedsVerification: let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .NeedsPassword: let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .None, .NeedsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. return } } navigationController?.pushViewController(viewController, animated: true) } } // For great debugging! private class RequirePasswordDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.makeSeparated() settings.tableView.reloadData() } } // For great debugging! private class RequireUpgradeDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.makeDoghouse() settings.tableView.reloadData() } } // For great debugging! private class ForgetSyncAuthStateDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.syncAuthState.invalidate() settings.tableView.reloadData() } } // For great debugging! private class HiddenSetting: Setting { let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } extension NSFileManager { public func removeItemInDirectory(directory: String, named: String) throws { if let file = NSURL.fileURLWithPath(directory).URLByAppendingPathComponent(named).path { try self.removeItemAtPath(file) } } } private class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] do { try NSFileManager.defaultManager().removeItemInDirectory(documentsPath, named: "browser.db") } catch { print("Couldn't delete exported data: \(error).") } } } private class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] if let browserDB = NSURL.fileURLWithPath(documentsPath).URLByAppendingPathComponent("browser.db").path { do { try self.settings.profile.files.copy("browser.db", toAbsolutePath: browserDB) } catch { print("Couldn't export browser data: \(error).") } } } } // Show the current version of Firefox private class VersionSetting : Setting { let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } private override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .None } override func onClick(navigationController: UINavigationController?) { if AppConstants.BuildChannel != .Aurora { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } } } // Opens the the license page in a new tab private class LicenseAndAcknowledgementsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { return NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens about:rights page in the content view controller private class YourRightsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { return NSURL(string: "https://www.mozilla.org/about/legal/terms/firefox/") } private override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again private class ShowIntroductionSetting: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { navigationController?.dismissViewControllerAnimated(true, completion: { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } private class SendFeedbackSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Show an input.mozilla.org page where people can submit feedback"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String return NSURL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)") } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the the SUMO page in a new tab private class OpenSupportPageSetting: Setting { init() { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { navigationController?.dismissViewControllerAnimated(true, completion: { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { let rootNavigationController = appDelegate.rootViewController rootNavigationController.popViewControllerAnimated(true) if let url = NSURL(string: "https://support.mozilla.org/products/ios") { appDelegate.browserViewController.openURLInNewTab(url) } } }) } } // Opens the search settings pane private class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var style: UITableViewCellStyle { return .Value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines navigationController?.pushViewController(viewController, animated: true) } } private class LoginsSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let loginsTitle = NSLocalizedString("Logins", comment: "Label used as an item in Settings. When touched, the user will be navigated to the Logins/Password manager.") super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { } } private class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = NSLocalizedString("Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.") super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } private class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { return NSURL(string: "https://www.mozilla.org/privacy/firefox/") } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // The base settings view controller. class SettingsTableViewController: UITableViewController { private let Identifier = "CellIdentifier" private let SectionHeaderIdentifier = "SectionHeaderIdentifier" private var settings = [SettingSection]() var profile: Profile! var tabManager: TabManager! override func viewDidLoad() { super.viewDidLoad() let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title") let accountDebugSettings: [Setting] if AppConstants.BuildChannel != .Aurora { accountDebugSettings = [ // Debug settings: RequirePasswordDebugSetting(settings: self), RequireUpgradeDebugSetting(settings: self), ForgetSyncAuthStateDebugSetting(settings: self), ] } else { accountDebugSettings = [] } let prefs = profile.prefs var generalSettings = [ SearchSetting(settings: self), BoolSetting(prefs: prefs, prefKey: "blockPopups", defaultValue: true, titleText: NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")), BoolSetting(prefs: prefs, prefKey: "saveLogins", defaultValue: true, titleText: NSLocalizedString("Save Logins", comment: "Setting to enable the built-in password manager")), ] // There is nothing to show in the Customize section if we don't include the compact tab layout // setting on iPad. When more options are added that work on both device types, this logic can // be changed. if UIDevice.currentDevice().userInterfaceIdiom == .Phone { generalSettings += [ BoolSetting(prefs: prefs, prefKey: "CompactTabLayout", defaultValue: true, titleText: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview")) ] } settings += [ SettingSection(title: nil, children: [ // Without a Firefox Account: ConnectSetting(settings: self), // With a Firefox Account: AccountStatusSetting(settings: self), SyncNowSetting(settings: self) ] + accountDebugSettings), SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings) ] var privacySettings: [Setting] = [LoginsSetting(settings: self), ClearPrivateDataSetting(settings: self)] if #available(iOS 9, *) { privacySettings += [ BoolSetting(prefs: prefs, prefKey: "settings.closePrivateTabs", defaultValue: false, titleText: NSLocalizedString("Close Private Tabs", tableName: "PrivateBrowsing", comment: "Setting for closing private tabs"), statusText: NSLocalizedString("When Leaving Private Browsing", tableName: "PrivateBrowsing", comment: "Will be displayed in Settings under 'Close Private Tabs'")) ] } privacySettings += [ BoolSetting(prefs: prefs, prefKey: "crashreports.send.always", defaultValue: false, titleText: NSLocalizedString("Send Crash Reports", comment: "Setting to enable the sending of crash reports"), settingDidChange: { configureActiveCrashReporter($0) }), PrivacyPolicySetting() ] settings += [ SettingSection(title: NSAttributedString(string: privacyTitle), children: privacySettings), SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [ ShowIntroductionSetting(settings: self), SendFeedbackSetting(), OpenSupportPageSetting() ]), SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [ VersionSetting(settings: self), LicenseAndAcknowledgementsSetting(), YourRightsSetting(), DisconnectSetting(settings: self), ExportBrowserDataSetting(settings: self), DeleteExportedDataSetting(settings: self), ]) ] navigationItem.title = NSLocalizedString("Settings", comment: "Settings") navigationItem.leftBarButtonItem = UIBarButtonItem( title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"), style: UIBarButtonItemStyle.Done, target: navigationController, action: "SELdone") tableView.registerClass(SettingsTableViewCell.self, forCellReuseIdentifier: Identifier) tableView.registerClass(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier) tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128)) tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: ProfileDidStartSyncingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: ProfileDidFinishSyncingNotification, object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) SELrefresh() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidStartSyncingNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidFinishSyncingNotification, object: nil) } @objc private func SELsyncDidChangeState() { dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } @objc private func SELrefresh() { // Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app. if let account = self.profile.getAccount() { account.advance().upon { _ in dispatch_async(dispatch_get_main_queue()) { () -> Void in self.tableView.reloadData() } } } else { self.tableView.reloadData() } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let section = settings[indexPath.section] if let setting = section[indexPath.row] { var cell: UITableViewCell! if let _ = setting.status { // Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell. // I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account. // Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it. cell = SettingsTableViewCell(style: setting.style, reuseIdentifier: nil) } else { cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) } setting.onConfigureCell(cell) return cell } return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return settings.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let section = settings[section] return section.count } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView let sectionSetting = settings[section] if let sectionTitle = sectionSetting.title?.string { headerView.titleLabel.text = sectionTitle } // Hide the top border for the top section to avoid having a double line at the top if section == 0 { headerView.showTopBorder = false } else { headerView.showTopBorder = true } return headerView } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // empty headers should be 13px high, but headers with text should be 44 var height: CGFloat = 13 let section = settings[section] if let sectionTitle = section.title { if sectionTitle.length > 0 { height = 44 } } return height } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { let section = settings[indexPath.section] if let setting = section[indexPath.row] { setting.onClick(navigationController) } return nil } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { //make account/sign-in and close private tabs rows taller, as per design specs if indexPath.section == 0 && indexPath.row == 0 { return 64 } if #available(iOS 9, *) { if indexPath.section == 2 && indexPath.row == 2 { return 64 } } return 44 } } class SettingsTableFooterView: UIView { var logo: UIImageView = { var image = UIImageView(image: UIImage(named: "settingsFlatfox")) image.contentMode = UIViewContentMode.Center return image }() private lazy var topBorder: CALayer = { let topBorder = CALayer() topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor return topBorder }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIConstants.TableViewHeaderBackgroundColor layer.addSublayer(topBorder) addSubview(logo) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5) logo.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2) } } class SettingsTableSectionHeaderFooterView: UITableViewHeaderFooterView { var showTopBorder: Bool = true { didSet { topBorder.hidden = !showTopBorder } } var showBottomBorder: Bool = true { didSet { bottomBorder.hidden = !showBottomBorder } } var titleLabel: UILabel = { var headerLabel = UILabel() var frame = headerLabel.frame frame.origin.x = 15 frame.origin.y = 25 headerLabel.frame = frame headerLabel.textColor = UIConstants.TableViewHeaderTextColor headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular) return headerLabel }() private lazy var topBorder: CALayer = { let topBorder = CALayer() topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor return topBorder }() private lazy var bottomBorder: CALayer = { let bottomBorder = CALayer() bottomBorder.backgroundColor = UIConstants.SeparatorColor.CGColor return bottomBorder }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor addSubview(titleLabel) clipsToBounds = true layer.addSublayer(topBorder) layer.addSublayer(bottomBorder) } override func prepareForReuse() { super.prepareForReuse() showTopBorder = true showBottomBorder = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() bottomBorder.frame = CGRectMake(0.0, frame.size.height - 0.5, frame.size.width, 0.5) topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5) titleLabel.sizeToFit() } }
mpl-2.0
phatblat/realm-cocoa
examples/ios/swift/AppClip/AppClipApp.swift
2
1525
//////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import SwiftUI import RealmSwift @main struct AppClipApp: SwiftUI.App { var body: some Scene { WindowGroup { // This is ContentView.swift shared from AppClipParent ContentView(objects: demoObjects().list) } } private func demoObjects() -> DemoObjects { let config = Realm.Configuration(fileURL: FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.groupId)!.appendingPathComponent("default.realm")) let realm = try! Realm(configuration: config) if let demoObjects = realm.object(ofType: DemoObjects.self, forPrimaryKey: 0) { return demoObjects } else { return try! realm.write { realm.create(DemoObjects.self, value: []) } } } }
apache-2.0
jeanpimentel/HonourBridge
HonourBridge/HonourBridge/Honour/Library/Rules/Roman.swift
3
292
// // Regex.swift // Honour // // Created by Jean Pimentel on 5/18/15. // Copyright (c) 2015 Honour. All rights reserved. // import Foundation public class Roman: Regex { public init() { super.init(regex: "^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$") } }
mit
odemolliens/blockchain-ios-sdk
SDK_SWIFT/ODBlockChainWallet/ODBlockChainWallet/Services/User/ODBCWalletService.swift
1
23369
// //Copyright 2014 Olivier Demolliens - @odemolliens // //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 class ODBCWalletService { /* * Encode all char */ class func encode(toEncode : NSString) -> NSString { return CFURLCreateStringByAddingPercentEscapes( nil, toEncode, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.toRaw() ) } /* Create Wallet Service -> Email & Name : parameters are optionnal Return an ODWallet object with identifier if successfull Knowed Errors case Unknow case PasswordLength case ApiKey case Email case AlphaNumericOnly */ class func createWallet(name : NSString, apiKey : NSString, password : NSString, email : NSString, success :(ODWallet) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void { var url : NSURL; var request : NSMutableURLRequest; var postKeys : NSMutableString = NSMutableString(); var firstCharKeys : NSString = "?"; //Parameters postKeys.appendFormat("%@api_code=%@", firstCharKeys, apiKey); firstCharKeys = "&"; postKeys.appendFormat("%@password=%@", firstCharKeys, encode(password)); //Optionnal keys if(email.length>0){ postKeys.appendFormat("%@email=%@", firstCharKeys, email); } if(name.length>0){ postKeys.appendFormat("%@label=%@", firstCharKeys ,name); } url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlCreateWallet,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)); request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout)); ODBlockChainService.manageRequest(request, success:{(object : AnyObject) -> Void in if(object.isKindOfClass(NSDictionary)){ var dic : NSDictionary = object as NSDictionary; success(ODWallet.instantiateWithDictionnary(dic)); }else{ failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description)); } },failure:{(error : ODBlockChainError) -> Void in failure(error); }); } /* //TODO : untested Making Outgoing Payments Send bitcoin from your wallet to another bitcoin address. All transactions include a 0.0001 BTC miners fee. -> mainPassword : Your Main My wallet password -> secondPassword : Your second My Wallet password if double encryption is enabled (Optional). -> to : Recipient Bitcoin Address. -> amount : Amount to send in satoshi. -> from : Send from a specific Bitcoin Address (Optional) shared "true" or "false" indicating whether the transaction should be sent through a shared wallet. Fees apply. (Optional) -> fee : Transaction fee value in satoshi (Must be greater than default fee) (Optional) -> note : A public note to include with the transaction (Optional) Knowed Errors case Unknow */ class func makePayment(walletIdentifier : NSString, apiKey : NSString, mainPassword : NSString, secondPassword : NSString, amount : NSNumber, to : NSString,from : NSString,shared : NSNumber,fee : NSNumber,note : NSString, success :(ODPaymentResults) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void { var url : NSURL; var request : NSMutableURLRequest; var postKeys : NSMutableString = NSMutableString(); var firstCharKeys : NSString = "?"; //Parameters postKeys.appendFormat("%@/payment", walletIdentifier); postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword)); firstCharKeys = "&"; postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey); postKeys.appendFormat("%@second_password=%@", firstCharKeys, encode(secondPassword)); postKeys.appendFormat("%@amount=%f", firstCharKeys, (amount.floatValue*kBCWalletSatoshi.floatValue)); postKeys.appendFormat("%@to=%@", firstCharKeys, to); if(from.length>0){ postKeys.appendFormat("%@from=%@", firstCharKeys ,from); } if(!(shared.floatValue==(-1.0))){ postKeys.appendFormat("%@shared=%f", firstCharKeys ,shared); } if(fee.floatValue>0){ postKeys.appendFormat("%@fee=%f", firstCharKeys ,(fee.floatValue*kBCWalletSatoshi.floatValue)); } if(note.length>0){ postKeys.appendFormat("%@note=%@", firstCharKeys ,note); } url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)); request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout)); ODBlockChainService.manageRequest(request, success:{(object : AnyObject) -> Void in if(object.isKindOfClass(NSDictionary)){ var dic : NSDictionary = object as NSDictionary; success(ODPaymentResults.instantiateWithDictionnary(dic)); }else{ failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description)); } },failure:{(error : ODBlockChainError) -> Void in failure(error); }); } /* //TODO : untested Send Many Transactions Send a transaction to multiple recipients in the same transaction.. All transactions include a 0.0001 BTC miners fee. -> walletIdentifier : Your Wallet identifier -> mainPassword : Your Main My wallet password -> secondPassword : Your second My Wallet password if double encryption is enabled (Optional). -> from : Send from a specific Bitcoin Address (Optional) -> to : Send an NSDictionnary like this { "1JzSZFs2DQke2B3S4pBxaNaMzzVZaG4Cqh": 100000000, "12Cf6nCcRtKERh9cQm3Z29c9MWvQuFSxvT": 1500000000, "1dice6YgEVBf88erBFra9BHf6ZMoyvG88": 200000000 } shared "true" or "false" indicating whether the transaction should be sent through a shared wallet. Fees apply. (Optional) -> fee : Transaction fee value in satoshi (Must be greater than default fee) (Optional) -> note : A public note to include with the transaction (Optional) Knowed Errors case Unknow */ class func makeManyPayments(walletIdentifier : NSString,apiKey : NSString, mainPassword : NSString, secondPassword : NSString, to : NSDictionary,from : NSString,shared : NSNumber,fee : NSNumber,note : NSString, success :(ODPaymentResults) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void { var url : NSURL; var request : NSMutableURLRequest; var postKeys : NSMutableString = NSMutableString(); var firstCharKeys : NSString = "?"; //Parameters postKeys.appendFormat("%@/payment", walletIdentifier); postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword)); firstCharKeys = "&"; postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey); postKeys.appendFormat("%@second_password=%@", firstCharKeys, encode(secondPassword)); var error : NSError?; var data : NSData; data = NSJSONSerialization.dataWithJSONObject(to, options: NSJSONWritingOptions.PrettyPrinted, error: &error)!; // TODO : can be optimized if((error) != nil){ failure(ODBlockChainError.parseError("NSDictionnary", result: to.description)); }else{ // TODO : can be optimized postKeys.appendFormat("%@recipients=%@", firstCharKeys, NSString(data: data,encoding: NSUTF8StringEncoding)); if(from.length>0){ postKeys.appendFormat("%@from=%@", firstCharKeys ,from); } if(!(shared.floatValue==(-1.0))){ postKeys.appendFormat("%@shared=%f", firstCharKeys ,shared); } if(fee.floatValue>0){ postKeys.appendFormat("%@fee=%f", firstCharKeys ,(fee.floatValue*kBCWalletSatoshi.floatValue)); } if(note.length>0){ postKeys.appendFormat("%@note=%@", firstCharKeys ,note); } url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)); request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout)); ODBlockChainService.manageRequest(request, success:{(object : AnyObject) -> Void in if(object.isKindOfClass(NSDictionary)){ var dic : NSDictionary = object as NSDictionary; success(ODPaymentResults.instantiateWithDictionnary(dic)); }else{ failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description)); } },failure:{(error : ODBlockChainError) -> Void in failure(error); }); } } /* Fetching the wallet balance Fetch the balance of a wallet. This should be used as an estimate only and will include unconfirmed transactions and possibly double spends. -> walletIdentifier : Your Wallet identifier -> mainPassword : Your Main My wallet password Knowed Errors case Unknow */ class func fetchingWalletBalance(walletIdentifier : NSString,apiKey : NSString, mainPassword : NSString, success :(ODBalance) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void { var url : NSURL; var request : NSMutableURLRequest; var postKeys : NSMutableString = NSMutableString(); var firstCharKeys : NSString = "?"; //Parameters postKeys.appendFormat("%@/balance", walletIdentifier); postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey); firstCharKeys = "&"; postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword)); url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)); request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout)); ODBlockChainService.manageRequest(request, success:{(object : AnyObject) -> Void in if(object.isKindOfClass(NSDictionary)){ var dic : NSDictionary = object as NSDictionary; success(ODBalance.instantiateWithDictionnary(dic)); }else{ failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description)); } },failure:{(error : ODBlockChainError) -> Void in failure(error); }); } /* Listing Addresses List all active addresses in a wallet. Also includes a 0 confirmation balance which should be used as an estimate only and will include unconfirmed transactions and possibly double spends. -> walletIdentifier : Your Wallet identifier -> mainPassword : Your Main My wallet password -> confirmations : The minimum number of confirmations transactions must have before being included in balance of addresses (Optional) Knowed Errors case Invalid case DecryptingWallet case Unknow case ApiKey */ class func listingAddresses(walletIdentifier : NSString,apiKey : NSString,mainPassword : NSString,confirmations : NSNumber, success :(NSArray) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void { var url : NSURL; var request : NSMutableURLRequest; var postKeys : NSMutableString = NSMutableString(); var firstCharKeys : NSString = "?"; //Parameters postKeys.appendFormat("%@/list", walletIdentifier); postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword)); firstCharKeys = "&"; postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey); if(!(confirmations.floatValue==(-1.0))){ postKeys.appendFormat("%@confirmations=%i", firstCharKeys ,confirmations.integerValue); } url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)); request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout)); ODBlockChainService.manageRequest(request, success:{(object : AnyObject) -> Void in if(object.isKindOfClass(NSDictionary)){ var dic : NSDictionary = object as NSDictionary; //if(dic.valueForKey("addresses").isKindOfClass(NSArray)){ var resultArray : NSArray = dic.valueForKey("addresses") as NSArray; var mArray : NSMutableArray = NSMutableArray(); for(var i = 0; i < resultArray.count;i++){ var dicAddress : NSDictionary = resultArray.objectAtIndex(i) as NSDictionary; mArray.addObject(ODBalanceDetails.instantiateWithDictionnary(dicAddress)); } success(mArray); /*}else{ failure(ODBlockChainError.parseError(NSArray.description(),result:dic.description)); }*/ }else{ failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description)); } },failure:{(error : ODBlockChainError) -> Void in failure(error); }); } /* //TODO : untested Getting the balance of an address Retrieve the balance of a bitcoin address. Querying the balance of an address by label is depreciated. -> walletIdentifier : Your Wallet identifier -> mainPassword : Your Main My wallet password -> confirmations : The minimum number of confirmations transactions must have before being included in balance of addresses (Optional) -> address : The bitcoin address to lookup Knowed Errors case Invalid case Unknow */ //#define kBCWalletMyAdress class func myAddress(walletIdentifier : NSString,apiKey : NSString,mainPassword : NSString,address : NSString,confirmations : NSNumber, success :(ODBalanceDetails) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void { var url : NSURL; var request : NSMutableURLRequest; var postKeys : NSMutableString = NSMutableString(); var firstCharKeys : NSString = "?"; //Parameters postKeys.appendFormat("%@/address_balance", walletIdentifier); postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword)); firstCharKeys = "&"; postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey); postKeys.appendFormat("%@address=%@", firstCharKeys, address); if(!(confirmations.floatValue==(-1.0))){ postKeys.appendFormat("%@confirmations=%i", firstCharKeys ,confirmations.integerValue); } url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)); request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout)); ODBlockChainService.manageRequest(request, success:{(object : AnyObject) -> Void in if(object.isKindOfClass(NSDictionary)){ var dic : NSDictionary = object as NSDictionary; success(ODBalanceDetails.instantiateWithDictionnary(dic)); }else{ failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description)); } },failure:{(error : ODBlockChainError) -> Void in failure(error); }); } /* Generating a new address -> walletIdentifier : Your Wallet identifier -> mainPassword Your Main My wallet password -> secondPassword : Your second My Wallet password if double encryption is enabled (Optional). -> label : An optional label to attach to this address. It is recommended this is a human readable string e.g. "Order No : 1234". You May use this as a reference to check balance of an order (documented later) Knowed Errors case Unknow */ class func createAddress(walletIdentifier : NSString,apiKey : NSString,mainPassword : NSString,secondPassword : NSString,label : NSString, success :(ODBalanceDetails) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void { var url : NSURL; var request : NSMutableURLRequest; var postKeys : NSMutableString = NSMutableString(); var firstCharKeys : NSString = "?"; //Parameters postKeys.appendFormat("%@/new_address", walletIdentifier); postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword)); firstCharKeys = "&"; postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey); postKeys.appendFormat("%@second_password=%@", firstCharKeys, encode(secondPassword)); postKeys.appendFormat("%@label=%@", firstCharKeys, label); url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)); request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout)); ODBlockChainService.manageRequest(request, success:{(object : AnyObject) -> Void in if(object.isKindOfClass(NSDictionary)){ var dic : NSDictionary = object as NSDictionary; success(ODBalanceDetails.instantiateWithDictionnary(dic)); }else{ failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description)); } },failure:{(error : ODBlockChainError) -> Void in failure(error); }); } /* Archiving an address To improve wallet performance addresses which have not been used recently should be moved to an archived state. They will still be held in the wallet but will no longer be included in the "list" or "list-transactions" calls. For example if an invoice is generated for a user once that invoice is paid the address should be archived. Or if a unique bitcoin address is generated for each user, users who have not logged in recently (~30 days) their addresses should be archived. https://blockchain.info/merchant/$guid/archive_address?password=$main_password&second_password=$second_password&address=$address $main_password Your Main My wallet password $second_password Your second My Wallet password if double encryption is enabled. $address The bitcoin address to archive Response: {"archived" : "18fyqiZzndTxdVo7g9ouRogB4uFj86JJiy"} */ /* Unarchive an address Unarchive an address. Will also restore consolidated addresses (see below). https://blockchain.info/merchant/$guid/unarchive_address?password=$main_password&second_password=$second_password&address=$address $main_password Your Main My wallet password $second_password Your second My Wallet password if double encryption is enabled. $address The bitcoin address to unarchive Response: {"active" : "18fyqiZzndTxdVo7g9ouRogB4uFj86JJiy"} */ /* Consolidating Addresses Queries to wallets with over 10 thousand addresses will become sluggish especially in the web interface. The auto_consolidate command will remove some inactive archived addresses from the wallet and insert them as forwarding addresses (see receive payments API). You will still receive callback notifications for these addresses however they will no longer be part of the main wallet and will be stored server side. If generating a lot of addresses it is a recommended to call this method at least every 48 hours. A good value for days is 60 i.e. addresses which have not received transactions in the last 60 days will be consolidated. https://blockchain.info/merchant/$guid/auto_consolidate?password=$main_password&second_password=$second_password&days=$days $main_password Your Main My wallet password $second_password Your second My Wallet password if double encryption is enabled. $days Addresses which have not received any transactions in at least this many days will be consolidated. Response: { "consolidated" : ["18fyqiZzndTxdVo7g9ouRogB4uFj86JJiy"]} */ }
apache-2.0
gravicle/library
Sources/UIScrollView+RxContentSize.swift
1
300
import UIKit import RxSwift import RxCocoa extension Reactive where Base: UITableView { public var contentSize: Driver<CGSize> { return observe(CGSize.self, #keyPath(UITableView.contentSize)) .replaceNil(with: .zero) .asDriver(onErrorJustReturn: .zero) } }
mit
rymcol/Server-Side-Swift-Benchmarks-Summer-2017
KituraPress/Sources/main.swift
1
2100
import Kitura import SwiftyJSON #if os(Linux) import SwiftGlibc public func arc4random_uniform(_ max: UInt32) -> Int32 { return (SwiftGlibc.rand() % Int32(max-1)) + 1 } #endif // All Web apps need a router to define routes let router = Router() router.get("/") { _, response, next in let header = CommonHandler().getHeader() let footer = CommonHandler().getFooter() let body = IndexHandler().loadPageContent() let homePage = header + body + footer try response.send(homePage).end() } router.get("/blog") { _, response, next in response.headers["Content-Type"] = "text/html; charset=utf-8" let header = CommonHandler().getHeader() let footer = CommonHandler().getFooter() let body = BlogPageHandler().loadPageContent() let blogPage = header + body + footer try response.send(blogPage).end() } router.get("/json") { _, response, next in response.headers["Content-Type"] = "application/json; charset=utf-8" let json = JSON(JSONCreator().generateJSON()) try response.send(json: json).end() } router.get(middleware: StaticFileServer(path: "./public")) // Handles any errors that get set router.error { request, response, next in response.headers["Content-Type"] = "text/plain; charset=utf-8" let errorDescription: String if let error = response.error { errorDescription = "\(error)" } else { errorDescription = "Unknown error" } try response.send("Caught the error: \(errorDescription)").end() } // A custom Not found handler router.all { request, response, next in if response.statusCode == .unknown { // Remove this wrapping if statement, if you want to handle requests to / as well if request.originalURL != "/" && request.originalURL != "" { try response.status(.notFound).send("404! - This page does not exits!").end() } } next() } // Add HTTP Server to listen on port 8090 Kitura.addHTTPServer(onPort: 8090, with: router) // start the framework - the servers added until now will start listening Kitura.run()
apache-2.0
a8b/CoreDataStackFromScratch
CoreDataStack/CoreDataStack/CoreDataManager.swift
1
2460
// // CoreDataManager.swift // CoreDataStack // // Created by Yakiv Kovalsky on 1/4/17. // Copyright © 2017 Yakiv Kovalsky. All rights reserved. // import Foundation import CoreData public class CoreDataManager { private let modelName: String init(modelName: String) { self.modelName = modelName } public private(set) lazy var managedObjectContext: NSManagedObjectContext = { // Initialize Managed Object Context let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) // Configure Managed Object Context managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator return managedObjectContext }() private lazy var managedObjectModel: NSManagedObjectModel? = { // Fetch Model URL guard let modelURL = Bundle.main.url(forResource: self.modelName, withExtension: "momd") else { return nil } // Initialize Managed Object Model let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL) return managedObjectModel }() private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { guard let managedObjectModel = self.managedObjectModel else { return nil } // Helper let persistentStoreURL = self.persistentStoreURL // Initialize Persistent Store Coordinator let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) do { let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ] try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: persistentStoreURL, options: options) } catch { let addPersistentStoreError = error as NSError print("Unable to Add Persistent Store") print("\(addPersistentStoreError.localizedDescription)") } return persistentStoreCoordinator }() private var persistentStoreURL: URL { // Helpers let storeName = "\(modelName).sqlite" let fileManager = FileManager.default let documentsDirectoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] return documentsDirectoryURL.appendingPathComponent(storeName) } }
mit
6ag/AppScreenshots
AppScreenshots/Classes/Module/Home/Model/JFPasterGroup.swift
1
2261
// // JFPasterGroup.swift // AppScreenshots // // Created by zhoujianfeng on 2017/2/12. // Copyright © 2017年 zhoujianfeng. All rights reserved. // import UIKit class JFPasterGroup: NSObject { /// 贴纸组名 var groupName: String /// 贴纸组icon名 var iconName: String /// 贴纸组里的贴纸集合 var pasterList: [JFPaster] /// 初始化贴图组模型 /// /// - Parameters: /// - groupName: 组名 /// - prefix: 前缀 /// - count: 数量 init(groupName: String, prefix: String, count: Int) { self.groupName = groupName self.iconName = "\(prefix)_icon.png" var pasterList = [JFPaster]() for index in 1...count { let paster = JFPaster(iconName: "\(prefix)_compress_\(index).png") pasterList.append(paster) } self.pasterList = pasterList super.init() } /// 获取所有贴纸组 /// /// - Returns: 贴纸组模型集合 class func getPasterGroupList() -> [JFPasterGroup] { var pasterGroupList = [JFPasterGroup]() let shenjjm = JFPasterGroup(groupName: "神经猫", prefix: "shenjjm", count: 110) let HK = JFPasterGroup(groupName: "hello kitty", prefix: "HK", count: 95) let SC = JFPasterGroup(groupName: "蜡笔小新", prefix: "SC", count: 102) let DA = JFPasterGroup(groupName: "多啦A梦", prefix: "DA", count: 123) let Maruko = JFPasterGroup(groupName: "小丸子", prefix: "Maruko", count: 102) let cheesecat = JFPasterGroup(groupName: "奶酪猫", prefix: "cheesecat", count: 36) let COCO = JFPasterGroup(groupName: "小女人", prefix: "COCO", count: 77) let mengmengxiong_christmas = JFPasterGroup(groupName: "萌萌熊", prefix: "mengmengxiong_christmas", count: 32) pasterGroupList.append(shenjjm) pasterGroupList.append(HK) pasterGroupList.append(SC) pasterGroupList.append(DA) pasterGroupList.append(Maruko) pasterGroupList.append(cheesecat) pasterGroupList.append(COCO) pasterGroupList.append(mengmengxiong_christmas) return pasterGroupList } }
mit
SASAbus/SASAbus-ios
SASAbus/Data/Networking/Model/EcoPoints/Badge.swift
1
1020
import Foundation import SwiftyJSON final class Badge: JSONable, JSONCollection { let id: String let title: String let description: String let iconUrl: String let progress: Int let points: Int let users: Int let isNewBadge: Bool let locked: Bool required init(parameter: JSON) { id = parameter["id"].stringValue title = parameter["title"].stringValue description = parameter["description"].stringValue iconUrl = parameter["icon_url"].stringValue progress = parameter["progress"].intValue points = parameter["points"].intValue users = parameter["users"].intValue isNewBadge = parameter["new"].boolValue locked = parameter["locked"].boolValue } static func collection(parameter: JSON) -> [Badge] { var items: [Badge] = [] for itemRepresentation in parameter.arrayValue { items.append(Badge(parameter: itemRepresentation)) } return items } }
gpl-3.0
leoru/Brainstorage
Brainstorage-iOS/Vendor/HTMLParser/HTMLNode.swift
1
8934
/**@file * @brief Swift-HTML-Parser * @author _tid_ */ import Foundation /** * HTMLNode */ public class HTMLNode { public enum HTMLNodeType : String { case HTMLUnkownNode = "" case HTMLHrefNode = "href" case HTMLTextNode = "text" case HTMLCodeNode = "code" case HTMLSpanNode = "span" case HTMLPNode = "p" case HTMLLiNode = "li" case HTMLUiNode = "ui" case HTMLImageNode = "image" case HTMLOlNode = "ol" case HTMLStrongNode = "strong" case HTMLPreNode = "pre" case HTMLBlockQuoteNode = "blockquote" } private var doc : htmlDocPtr private var pointer : xmlNodePtr private var node : xmlNode? private var nodeType : HTMLNodeType = HTMLNodeType.HTMLUnkownNode /** * 親ノード */ private var parent : HTMLNode? { if let p = self.node?.parent { return HTMLNode(doc: self.doc, node: p) } return nil } /** * 次ノード */ private var next : HTMLNode? { if let n : UnsafeMutablePointer<xmlNode> = node?.next { if n != nil { return HTMLNode(doc: doc, node: n) } } return nil } /** * 子ノード */ private var child : HTMLNode? { if let c = node?.children { if c != nil { return HTMLNode(doc: doc, node: c) } } return nil } /** * クラス名 */ public var className : String { return getAttributeNamed("class") } /** * タグ名 */ public var tagName : String { if node != nil { return ConvXmlCharToString(self.node!.name) } return "" } /** * コンテンツ */ public var contents : String { if node != nil { var n = self.node!.children if n != nil { return ConvXmlCharToString(n.memory.content) } } return "" } public var rawContents : String { if node != nil { return rawContentsOfNode(self.node!, self.pointer) } return "" } /** * Initializer * @param[in] doc xmlDoc */ public init(doc: htmlDocPtr = nil) { self.doc = doc var node = xmlDocGetRootElement(doc) self.pointer = node if node != nil { self.node = node.memory } } private init(doc: htmlDocPtr, node: UnsafePointer<xmlNode>) { self.doc = doc self.node = node.memory self.pointer = xmlNodePtr(node) let type = HTMLNodeType(rawValue: tagName) if let type = HTMLNodeType(rawValue: tagName) { self.nodeType = type } } /** * 属性名を取得する * @param[in] name 属性 * @return 属性名 */ public func getAttributeNamed(name: String) -> String { for var attr : xmlAttrPtr = node!.properties; attr != nil; attr = attr.memory.next { var mem = attr.memory if name == ConvXmlCharToString(mem.name) { return ConvXmlCharToString(mem.children.memory.content) } } return "" } /** * タグ名に一致する全ての子ノードを探す * @param[in] tagName タグ名 * @return 子ノードの配列 */ public func findChildTags(tagName: String) -> [HTMLNode] { var nodes : [HTMLNode] = [] return findChildTags(tagName, node: self.child, retAry: &nodes) } private func findChildTags(tagName: String, node: HTMLNode?, inout retAry: [HTMLNode] ) -> [HTMLNode] { if let n = node { for curNode in n { if curNode.tagName == tagName { retAry.append(curNode) } findChildTags(tagName, node: curNode.child, retAry: &retAry) } } return retAry } /** * タグ名で子ノードを探す * @param[in] tagName タグ名 * @return 子ノード。見つからなければnil */ public func findChildTag(tagName: String) -> HTMLNode? { return findChildTag(tagName, node: self) } private func findChildTag(tagName: String, node: HTMLNode?) -> HTMLNode? { if let nd = node { for curNode in nd { if tagName == curNode.tagName { return curNode } if let c = curNode.child { if let n = findChildTag(tagName, node: c) { return n } } } } return nil } //------------------------------------------------------ public func findChildTagsAttr(tagName: String, attrName : String, attrValue : String) -> [HTMLNode] { var nodes : [HTMLNode] = [] return findChildTagsAttr(tagName, attrName : attrName, attrValue : attrValue, node: self.child, retAry: &nodes) } private func findChildTagsAttr(tagName: String, attrName : String, attrValue : String, node: HTMLNode?, inout retAry: [HTMLNode] ) -> [HTMLNode] { if let n = node { for curNode in n { if curNode.tagName == tagName && curNode.getAttributeNamed(attrName) == attrValue { retAry.append(curNode) } findChildTagsAttr(tagName, attrName : attrName, attrValue : attrValue, node: curNode.child, retAry: &retAry) } } return retAry } public func findChildTagAttr(tagName : String, attrName : String, attrValue : String) -> HTMLNode? { return findChildTagAttr(tagName, attrName : attrName, attrValue : attrValue, node: self) } private func findChildTagAttr(tagName : String, attrName : String, attrValue : String, node: HTMLNode?) -> HTMLNode? { if let nd = node { for curNode in nd { if tagName == curNode.tagName && curNode.getAttributeNamed(attrName) == attrValue { return curNode } if let c = curNode.child { if let n = findChildTagAttr(tagName,attrName: attrName,attrValue: attrValue, node: c) { return n } } } } return nil } /** * Find node by id (id has to be used properly it is a uniq attribute) * @param[in] id String * @return HTMLNode */ public func findNodeById(id: String) -> HTMLNode? { return findNodeById(id, node: self) } private func findNodeById(id: String, node: HTMLNode?) -> HTMLNode? { if let nd = node { for curNode in nd { if id == curNode.getAttributeNamed("id") { return curNode } if let c = curNode.child { if let n = findNodeById(id, node: c) { return n } } } } return nil } /** * xpathで子ノードを探す * @param[in] xpath xpath * @return 子ノード。見つからなければnil */ public func xpath(xpath: String) -> [HTMLNode]? { let ctxt = xmlXPathNewContext(self.doc) if ctxt == nil { return nil } let result = xmlXPathEvalExpression(xpath, ctxt) xmlXPathFreeContext(ctxt) if result == nil { return nil } let nodeSet = result.memory.nodesetval if nodeSet == nil || nodeSet.memory.nodeNr == 0 || nodeSet.memory.nodeTab == nil { return nil } var nodes : [HTMLNode] = [] let size = Int(nodeSet.memory.nodeNr) for var i = 0; i < size; ++i { let n = nodeSet.memory let node = nodeSet.memory.nodeTab[i] let htmlNode = HTMLNode(doc: self.doc, node: node) nodes.append(htmlNode) } return nodes } } extension HTMLNode : SequenceType { public func generate() -> HTMLNodeGenerator { return HTMLNodeGenerator(node: self) } } /** * HTMLNodeGenerator */ public class HTMLNodeGenerator : GeneratorType { private var node : HTMLNode? public init(node: HTMLNode?) { self.node = node } public func next() -> HTMLNode? { var temp = node node = node?.next return temp } }
mit
iWeslie/Ant
Ant/Ant/Main/NewsHotModel.swift
2
385
// // NewsHotModel.swift // Ant // // Created by LiuXinQiang on 2017/8/16. // Copyright © 2017年 LiuXinQiang. All rights reserved. // import UIKit class NewsHotModel: NSObject { var id : NSNumber? var title : String? var publish_time : String? var source : String? var picture : String? var url : String? // var user_info : NewsUserInfoModel? }
apache-2.0
vimeo/VimeoUpload
VimeoUpload/Upload/Networking/Old Upload/VimeoSessionManager+OldUpload.swift
1
7652
// // VimeoSessionManager+Upload.swift // VimeoUpload // // Created by Alfred Hanssen on 10/21/15. // Copyright © 2015 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import VimeoNetworking extension VimeoSessionManager { public func myVideosDataTask(completionHandler: @escaping VideosCompletionHandler) throws -> Task? { let request = try self.jsonRequestSerializer.myVideosRequest() as URLRequest return self.request(request) { [jsonResponseSerializer] (sessionManagingResult: SessionManagingResult<JSON>) in // Do model parsing on a background thread DispatchQueue.global(qos: .default).async { switch sessionManagingResult.result { case .failure(let error as NSError): completionHandler(nil, error) case .success(let json): do { let videos = try jsonResponseSerializer.process( myVideosResponse: sessionManagingResult.response, responseObject: json as AnyObject, error: nil ) completionHandler(videos, nil) } catch let error as NSError { completionHandler(nil, error) } } } } } public func createVideoDownloadTask(url: URL) throws -> Task? { let request = try self.jsonRequestSerializer.createVideoRequest(with: url) as URLRequest return self.download(request) { _ in } } func uploadVideoTask(source: URL, destination: String, completionHandler: ErrorBlock?) throws -> Task? { let request = try self.jsonRequestSerializer.uploadVideoRequest(with: source, destination: destination) as URLRequest return self.upload(request, sourceFile: source) { [jsonResponseSerializer] sessionManagingResult in switch sessionManagingResult.result { case .failure(let error): completionHandler?(error as NSError) case .success(let json): do { try jsonResponseSerializer.process( uploadVideoResponse: sessionManagingResult.response, responseObject: json as AnyObject, error: nil ) completionHandler?(nil) } catch let error as NSError { completionHandler?(error) } } } } // For use with background sessions, use session delegate methods for destination and completion func activateVideoDownloadTask(uri activationUri: String) throws -> Task? { let request = try self.jsonRequestSerializer.activateVideoRequest(withURI: activationUri) as URLRequest return self.download(request) { _ in } } // For use with background sessions, use session delegate methods for destination and completion func videoSettingsDownloadTask(videoUri: String, videoSettings: VideoSettings) throws -> Task? { let request = try self.jsonRequestSerializer.videoSettingsRequest(with: videoUri, videoSettings: videoSettings) as URLRequest return self.download(request) { _ in } } public func videoSettingsDataTask(videoUri: String, videoSettings: VideoSettings, completionHandler: @escaping VideoCompletionHandler) throws -> Task? { let request = try self.jsonRequestSerializer.videoSettingsRequest(with: videoUri, videoSettings: videoSettings) as URLRequest return self.request(request) { [jsonResponseSerializer] (sessionManagingResult: SessionManagingResult<JSON>) in // Do model parsing on a background thread DispatchQueue.global(qos: .default).async { switch sessionManagingResult.result { case .failure(let error): completionHandler(nil, error as NSError) case .success(let json): do { let video = try jsonResponseSerializer.process( videoSettingsResponse: sessionManagingResult.response, responseObject: json as AnyObject, error: nil ) completionHandler(video, nil) } catch let error as NSError { completionHandler(nil, error) } } } } } func deleteVideoDataTask(videoUri: String, completionHandler: @escaping ErrorBlock) throws -> Task? { let request = try self.jsonRequestSerializer.deleteVideoRequest(with: videoUri) as URLRequest return self.request(request) { [jsonResponseSerializer] (sessionManagingResult: SessionManagingResult<JSON>) in switch sessionManagingResult.result { case .failure(let error): completionHandler(error as NSError) case .success(let json): do { try jsonResponseSerializer.process( deleteVideoResponse: sessionManagingResult.response, responseObject: json as AnyObject, error: nil ) completionHandler(nil) } catch let error as NSError { completionHandler(error) } } } } func videoDataTask(videoUri: String, completionHandler: @escaping VideoCompletionHandler) throws -> Task? { let request = try self.jsonRequestSerializer.videoRequest(with: videoUri) as URLRequest return self.request(request) { [jsonResponseSerializer] (sessionManagingResult: SessionManagingResult<JSON>) in switch sessionManagingResult.result { case .failure(let error as NSError): completionHandler(nil, error) case .success(let json): do { let video = try jsonResponseSerializer.process( videoResponse: sessionManagingResult.response, responseObject: json as AnyObject, error: nil ) completionHandler(video, nil) } catch let error as NSError { completionHandler(nil, error) } } } } }
mit
anlaital/Swan
Swan/Swan/DateExtensions.swift
1
5031
// // DateExtensions.swift // Swan // // Created by Antti Laitala on 22/05/15. // // import Foundation // MARK: Helpers public extension Date { var nanosecond: Int { return Calendar.mainThreadSharedCalendar().component(.nanosecond, from: self) } var second: Int { return Calendar.mainThreadSharedCalendar().component(.second, from: self) } var minute: Int { return Calendar.mainThreadSharedCalendar().component(.minute, from: self) } var hour: Int { return Calendar.mainThreadSharedCalendar().component(.hour, from: self) } var day: Int { return Calendar.mainThreadSharedCalendar().component(.day, from: self) } var month: Int { return Calendar.mainThreadSharedCalendar().component(.month, from: self) } var year: Int { return Calendar.mainThreadSharedCalendar().component(.year, from: self) } /// Returns a date set to the start of the day (00:00:00) of this date. var startOfDay: Date { let calendar = Calendar.mainThreadSharedCalendar() let comps = calendar.dateComponents([.year, .month, .day], from: self) return calendar.date(from: comps)! } /// Returns a date set to the end of the day (23:59:59) of this date. var endOfDay: Date { let calendar = Calendar.mainThreadSharedCalendar() var comps = calendar.dateComponents([.year, .month, .day], from: self) comps.hour = 23 comps.minute = 59 comps.second = 59 return calendar.date(from: comps)! } /// Returns a date set to the start of the month (1st day, 00:00:00) of this date. var startOfMonth: Date { let calendar = Calendar.mainThreadSharedCalendar() let comps = calendar.dateComponents([.year, .month], from: self) return calendar.date(from: comps)! } /// Returns a date set to the end of the month (last day, 23:59:59) of this date. var endOfMonth: Date { let calendar = Calendar.mainThreadSharedCalendar() let dayRange = calendar.range(of: .day, in: .month, for: self)! var comps = calendar.dateComponents([.year, .month], from: self) comps.day = dayRange.upperBound - dayRange.lowerBound comps.hour = 23 comps.minute = 59 comps.second = 59 return calendar.date(from: comps)! } /// Returns the noon (12:00:00) of this date. var noon: Date { let calendar = Calendar.mainThreadSharedCalendar() var comps = calendar.dateComponents([.year, .month, .day], from: self) comps.hour = 12 return calendar.date(from: comps)! } /// Returns the zero-indexed weekday component of this date starting on monday in range [0, 6]. var zeroIndexedWeekdayStartingOnMonday: Int { let weekday = Calendar.mainThreadSharedCalendar().component(.weekday, from: self) return weekday >= 2 ? weekday - 2 : 6 } /// Returns the number of calendar days between this date and `date`. func calendarDaysToDate(_ date: Date) -> Int { let calendar = Calendar.mainThreadSharedCalendar() var fromDate = Date() var toDate = Date() var interval: TimeInterval = 0 _ = calendar.dateInterval(of: .day, start: &fromDate, interval: &interval, for: self) _ = calendar.dateInterval(of: .day, start: &toDate, interval: &interval, for: date) let comps = calendar.dateComponents([.day], from: fromDate, to: toDate) return comps.day! } /// Returns the number of calendar weeks between this date and `date`. func calendarWeeksToDate(_ date: Date) -> Int { let calendar = Calendar.mainThreadSharedCalendar() var fromDate = Date() var toDate = Date() var interval: TimeInterval = 0 _ = calendar.dateInterval(of: .day, start: &fromDate, interval: &interval, for: self) _ = calendar.dateInterval(of: .day, start: &toDate, interval: &interval, for: date) let comps = calendar.dateComponents([.weekOfYear], from: fromDate, to: toDate) return comps.weekOfYear! } } // MARK: Date Arithmetic public struct TimeUnit { let unit: Calendar.Component let duration: Int init(_ unit: Calendar.Component, duration: Int) { self.unit = unit self.duration = duration } } public func +(lhs: Date, rhs: TimeUnit) -> Date { return Calendar.mainThreadSharedCalendar().date(byAdding: rhs.unit, value: rhs.duration, to: lhs)! } public func +=(lhs: inout Date, rhs: TimeUnit) { lhs = Calendar.mainThreadSharedCalendar().date(byAdding: rhs.unit, value: rhs.duration, to: lhs)! } public func -(lhs: Date, rhs: TimeUnit) -> Date { return Calendar.mainThreadSharedCalendar().date(byAdding: rhs.unit, value: -rhs.duration, to: lhs)! } public func -=(lhs: inout Date, rhs: TimeUnit) { lhs = Calendar.mainThreadSharedCalendar().date(byAdding: rhs.unit, value: -rhs.duration, to: lhs)! }
mit
NunoAlexandre/broccoli_mobile
ios/broccoli/Feedback.swift
1
739
import Foundation import UIKit class Feedback { class func dayAdded() -> UIAlertController { return UIAlertController(title: "Saved!", message: "Well done, broccoli :)", dismissTitle: "Yay!") } class func duplicatedDay() -> UIAlertController { return UIAlertController(title: "Ups!", message: "You have already added this day.", dismissTitle: "Oke") } class func loginRequired(handler : @escaping (UIAlertAction) -> Void) -> UIAlertController { return UIAlertController(title: "Ups!", message: "The time has come: you need to login again!", dismissTitle: "Ok", onDismiss: handler) } }
mit
ahoppen/swift
test/IRGen/eager-class-initialization.swift
17
1453
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -emit-ir -target %target-pre-stable-abi-triple | %FileCheck %s -DINT=i%target-ptrsize --check-prefix=CHECK --check-prefix=CHECK-OLD // REQUIRES: objc_interop // UNSUPPORTED: swift_only_stable_abi // See also eager-class-initialization-stable-abi.swift, for the stable ABI // deployment target test. import Foundation class BaseWithCoding : NSObject, NSCoding { required init(coder: NSCoder) { fatalError() } func encode(coder: NSCoder) { fatalError() } } class Generic<T> : BaseWithCoding {} class GenericAncestry : Generic<Int> {} @objc(custom_name) class GenericAncestryWithCustomName : Generic<Double> {} // CHECK-LABEL: define {{.*}} @_swift_eager_class_initialization // CHECK-NEXT: entry: // CHECK-OLD-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s4main15GenericAncestryCMa"([[INT]] 0) // CHECK-OLD-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0 // CHECK-OLD-NEXT: call void asm sideeffect "", "r"(%swift.type* [[METADATA]]) // CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s4main29GenericAncestryWithCustomNameCMa"([[INT]] 0) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0 // CHECK-NEXT: call void asm sideeffect "", "r"(%swift.type* [[METADATA]]) // CHECK-NEXT: ret
apache-2.0
saturday06/FrameworkBenchmarks
frameworks/Swift/vapor/Sources/vapor-tfb-postgresql/main.swift
10
698
/// We have isolated all of our App's logic into /// the App module because it makes our app /// more testable. /// /// In general, the executable portion of our App /// shouldn't include much more code than is presented /// here. /// /// We simply initialize our Droplet, optionally /// passing in values if necessary /// Then, we pass it to our App's setup function /// this should setup all the routes and special /// features of our app /// /// .run() runs the Droplet's commands, /// if no command is given, it will default to "serve" var config = try Config() try config.set("fluent.driver", "postgresql") try config.setup() let drop = try Droplet(config) try drop.setup() try drop.run()
bsd-3-clause
stevebrambilla/Runes
Tests/Tests/ArraySpec.swift
3
2959
import SwiftCheck import XCTest import Runes class ArraySpec: XCTestCase { func testFunctor() { // fmap id = id property("identity law") <- forAll { (xs: [Int]) in let lhs = id <^> xs let rhs = xs return lhs == rhs } // fmap (f . g) = (fmap f) . (fmap g) property("function composition law") <- forAll { (a: ArrayOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in let xs = a.getArray let f = fa.getArrow let g = fb.getArrow let lhs = compose(f, g) <^> xs let rhs = compose(curry(<^>)(f), curry(<^>)(g))(xs) return lhs == rhs } } func testApplicative() { // pure id <*> x = x property("identity law") <- forAll { (xs: [Int]) in let lhs = pure(id) <*> xs let rhs = xs return lhs == rhs } // pure f <*> pure x = pure (f x) property("homomorphism law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in let f = fa.getArrow let lhs: [Int] = pure(f) <*> pure(x) let rhs: [Int] = pure(f(x)) return rhs == lhs } // f <*> pure x = pure ($ x) <*> f property("interchange law") <- forAll { (x: Int, fa: ArrayOf<ArrowOf<Int, Int>>) in let f = fa.getArray.map { $0.getArrow } let lhs = f <*> pure(x) let rhs = pure({ $0(x) }) <*> f return lhs == rhs } // f <*> (g <*> x) = pure (.) <*> f <*> g <*> x property("composition law") <- forAll { (a: ArrayOf<Int>, fa: ArrayOf<ArrowOf<Int, Int>>, fb: ArrayOf<ArrowOf<Int, Int>>) in let x = a.getArray let f = fa.getArray.map { $0.getArrow } let g = fb.getArray.map { $0.getArrow } let lhs = f <*> (g <*> x) let rhs = pure(curry(compose)) <*> f <*> g <*> x return lhs == rhs } } func testMonad() { // return x >>= f = f x property("left identity law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in let f: Int -> [Int] = compose(pure, fa.getArrow) let lhs = pure(x) >>- f let rhs = f(x) return lhs == rhs } // m >>= return = m property("right identity law") <- forAll { (x: [Int]) in let lhs = x >>- pure let rhs = x return lhs == rhs } // (m >>= f) >>= g = m >>= (\x -> f x >>= g) property("associativity law") <- forAll { (a: ArrayOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in let m = a.getArray let f: Int -> [Int] = compose(pure, fa.getArrow) let g: Int -> [Int] = compose(pure, fb.getArrow) let lhs = (m >>- f) >>- g let rhs = m >>- { x in f(x) >>- g } return lhs == rhs } } }
mit
KeithPiTsui/Pavers
Pavers/Sources/UI/ReactiveCocoa/CocoaTarget.swift
1
1457
import Foundation import PaversFRP /// A target that accepts action messages. internal final class CocoaTarget<Value>: NSObject { private enum State { case idle case sending(queue: [Value]) } private let observer: Signal<Value, Never>.Observer private let transform: (Any?) -> Value private var state: State internal init(_ observer: Signal<Value, Never>.Observer, transform: @escaping (Any?) -> Value) { self.observer = observer self.transform = transform self.state = .idle } /// Broadcast the action message to all observers. /// /// Reentrancy is supported, and the action message would be deferred until the /// delivery of the current message has completed. /// /// - note: It should only be invoked on the main queue. /// /// - parameters: /// - sender: The object which sends the action message. @objc internal func invoke(_ sender: Any?) { switch state { case .idle: state = .sending(queue: []) observer.send(value: transform(sender)) while case let .sending(values) = state { guard !values.isEmpty else { break } state = .sending(queue: Array(values.dropFirst())) observer.send(value: values[0]) } state = .idle case let .sending(values): state = .sending(queue: values + [transform(sender)]) } } } extension CocoaTarget where Value == Void { internal convenience init(_ observer: Signal<(), Never>.Observer) { self.init(observer, transform: { _ in }) } }
mit
ahoppen/swift
test/DebuggerTestingTransform/basic-assignments.swift
36
2647
// RUN: %target-swift-frontend -debugger-testing-transform -Xllvm -sil-full-demangle -emit-sil -module-name M %s | %FileCheck %s -check-prefix=CHECK-SIL // REQUIRES: executable_test // RUN: %target-build-swift -Xfrontend -debugger-testing-transform %s -o %t // RUN: %target-codesign %t // RUN: %target-run %t | %FileCheck %s -check-prefix=CHECK-E2E // RUN: rm -rf %t var a = 1001 a = 1002 // CHECK-SIL-LABEL: sil private @$s1MyyXEfU0_ : {{.*}} () -> () // CHECK-SIL: [[int:%.*]] = integer_literal {{.*}}, 1002 // CHECK-SIL: [[struct:%.*]] = struct $Int ([[int]] : {{.*}}) // CHECK-SIL: store [[struct]] {{.*}} : $*Int // CHECK-SIL: string_literal utf8 "a" // CHECK-SIL: [[PO:%.*]] = function_ref {{.*}}_stringForPrintObjectySSypF // CHECK-SIL: [[PO_result:%.*]] = apply [[PO]] // CHECK-SIL: [[check_expect:%.*]] = function_ref {{.*}}_debuggerTestingCheckExpectyySS_SStF // CHECK-SIL: apply [[check_expect]] print("a = \(a)") // CHECK-E2E: a = 1002 // CHECK-SIL-LABEL: sil private @$s1MyyXEfU_yyXEfU1_ ({ () -> () in a = 1003 // CHECK-SIL: function_ref {{.*}}_debuggerTestingCheckExpectyySS_SStF print("a = \(a)") // CHECK-E2E-NEXT: a = 1003 })() // CHECK-SIL-LABEL: sil private @$s1MyyXEfU2_ // CHECK-SIL: function_ref {{.*}}_debuggerTestingCheckExpectyySS_SStF a = 1004 print("a = \(a)") // CHECK-E2E-NEXT: a = 1004 // CHECK-SIL-LABEL: sil private @$s1M2f1yyFyyXEfU3_ func f1() { var b = 2001 b = 2002 // CHECK-SIL: function_ref {{.*}}_debuggerTestingCheckExpectyySS_SStF print("b = \(b)") // CHECK-E2E-NEXT: b = 2002 } f1() // CHECK-SIL-LABEL: sil private @$s1M2f2yyFyyXEfU_yyXEfU4_ func f2() { var c: Int = 3001 ({ () -> () in c = 3002 // CHECK-SIL: function_ref {{.*}}_debuggerTestingCheckExpectyySS_SStF print("c = \(c)") // CHECK-E2E-NEXT: c = 3002 })() } f2() // CHECK-SIL-LABEL: sil private @$s1M2f3yySaySiGzFyyXEfU5_ func f3(_ d: inout [Int]) { d[0] = 4002 // CHECK-SIL: function_ref {{.*}}_debuggerTestingCheckExpectyySS_SStF print("d[0] = \(d[0])") // CHECK-E2E-NEXT: d[0] = 4002 } var d: [Int] = [4001] f3(&d) // CHECK-SIL-LABEL: sil hidden @$s1M2f4yyF // CHECK-SIL-NOT: _debuggerTestingCheckExpect func f4() { // We don't attempt to instrument in this case because we don't try // to prove that the var decl is definitively initialized. var e: Int e = 5001 print("e = \(e)") // CHECK-E2E-NEXT: e = 5001 } f4() // CHECK-SIL-LABEL: sil private @$s1M2f5yySSzFyyXEfU6_ func f5(_ v: inout String) { v = "Hello world" // CHECK-SIL: function_ref {{.*}}_debuggerTestingCheckExpectyySS_SStF print("v = \(v)") // CHECK-E2E-NEXT: v = Hello world } var v: String = "" f5(&v)
apache-2.0
JGiola/swift
test/expr/unary/async_await.swift
4
7537
// RUN: %target-swift-frontend -typecheck -verify %s -verify-syntax-tree -disable-availability-checking // REQUIRES: concurrency func test1(asyncfp : () async -> Int, fp : () -> Int) async { _ = await asyncfp() _ = await asyncfp() + asyncfp() _ = await asyncfp() + fp() _ = await fp() + 42 // expected-warning {{no 'async' operations occur within 'await' expression}} _ = 32 + asyncfp() + asyncfp() // expected-error {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-1:12{{call is 'async'}} // expected-note@-2:24{{call is 'async'}} } func getInt() async -> Int { return 5 } // Locations where "await" is prohibited. func test2( defaulted: Int = await getInt() // expected-error{{'async' call cannot occur in a default argument}} ) async { defer { _ = await getInt() // expected-error{{'async' call cannot occur in a defer body}} } print("foo") } func test3() { // expected-note{{add 'async' to function 'test3()' to make it asynchronous}} {{13-13= async}} _ = await getInt() // expected-error{{'async' call in a function that does not support concurrency}} } func test4()throws { // expected-note{{add 'async' to function 'test4()' to make it asynchronous}} {{13-19=async throws}} _ = await getInt() // expected-error{{'async' call in a function that does not support concurrency}} } func test5<T>(_ f : () async throws -> T) rethrows->T { // expected-note{{add 'async' to function 'test5' to make it asynchronous}} {{44-52=async rethrows}} return try await f() // expected-error{{'async' call in a function that does not support concurrency}} } enum SomeEnum: Int { case foo = await 5 // expected-error{{raw value for enum case must be a literal}} } struct SomeStruct { var x = await getInt() // expected-error{{'async' call cannot occur in a property initializer}} static var y = await getInt() // expected-error{{'async' call cannot occur in a global variable initializer}} } func acceptAutoclosureNonAsync(_: @autoclosure () -> Int) async { } func acceptAutoclosureAsync(_: @autoclosure () async -> Int) async { } func acceptAutoclosureAsyncThrows(_: @autoclosure () async throws -> Int) async { } func acceptAutoclosureAsyncThrowsRethrows(_: @autoclosure () async throws -> Int) async rethrows { } func acceptAutoclosureNonAsyncBad(_: @autoclosure () async -> Int) -> Int { 0 } // expected-error@-1{{'async' autoclosure parameter in a non-'async' function}} // expected-note@-2{{add 'async' to function 'acceptAutoclosureNonAsyncBad' to make it asynchronous}} {{67-67= async}} struct HasAsyncBad { init(_: @autoclosure () async -> Int) { } // expected-error@-1{{'async' autoclosure parameter in a non-'async' function}} } func testAutoclosure() async { await acceptAutoclosureAsync(await getInt()) await acceptAutoclosureNonAsync(await getInt()) // expected-error{{'async' call in an autoclosure that does not support concurrency}} await acceptAutoclosureAsync(42 + getInt()) // expected-error@-1:32{{expression is 'async' but is not marked with 'await'}}{{32-32=await }} // expected-note@-2:37{{call is 'async' in an autoclosure argument}} await acceptAutoclosureNonAsync(getInt()) // expected-error{{'async' call in an autoclosure that does not support concurrency}} } // Test inference of 'async' from the body of a closure. func testClosure() { let closure = { await getInt() } let _: () -> Int = closure // expected-error{{invalid conversion from 'async' function of type '() async -> Int' to synchronous function type '() -> Int'}} let closure2 = { () async -> Int in print("here") return await getInt() } let _: () -> Int = closure2 // expected-error{{invalid conversion from 'async' function of type '() async -> Int' to synchronous function type '() -> Int'}} } // Nesting async and await together func throwingAndAsync() async throws -> Int { return 0 } enum HomeworkError : Error { case dogAteIt } func testThrowingAndAsync() async throws { _ = try await throwingAndAsync() _ = await try throwingAndAsync() // expected-warning{{'try' must precede 'await'}}{{7-13=}}{{17-17=await }} _ = await (try throwingAndAsync()) _ = try (await throwingAndAsync()) // Errors _ = await throwingAndAsync() // expected-error{{call can throw but is not marked with 'try'}} // expected-note@-1{{did you mean to use 'try'?}}{{7-7=try }} // expected-note@-2{{did you mean to handle error as optional value?}}{{7-7=try? }} // expected-note@-3{{did you mean to disable error propagation?}}{{7-7=try! }} _ = try throwingAndAsync() // expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{11-11=await }} // expected-note@-2{{call is 'async'}} } func testExhaustiveDoCatch() async { do { _ = try await throwingAndAsync() } catch { } do { _ = try await throwingAndAsync() // expected-error@-1{{errors thrown from here are not handled because the enclosing catch is not exhaustive}} } catch let e as HomeworkError { } // Ensure that we infer 'async' through an exhaustive do-catch. let fn = { do { _ = try await throwingAndAsync() } catch { } } let _: Int = fn // expected-error{{cannot convert value of type '() async -> ()'}} // Ensure that we infer 'async' through a non-exhaustive do-catch. let fn2 = { do { _ = try await throwingAndAsync() } catch let e as HomeworkError { } } let _: Int = fn2 // expected-error{{cannot convert value of type '() async throws -> ()'}} } // String interpolation func testStringInterpolation() async throws { // expected-error@+2:30{{expression is 'async' but is not marked with 'await'}}{{30-30=await }} // expected-note@+1:35{{call is 'async'}} _ = "Eventually produces \(32 + getInt())" _ = "Eventually produces \(await getInt())" _ = await "Eventually produces \(getInt())" } func invalidAsyncFunction() async { _ = try await throwingAndAsync() // expected-error {{errors thrown from here are not handled}} } func validAsyncFunction() async throws { _ = try await throwingAndAsync() } // Async let checking func mightThrow() throws { } func getIntUnsafely() throws -> Int { 0 } func getIntUnsafelyAsync() async throws -> Int { 0 } extension Error { var number: Int { 0 } } func testAsyncLet() async throws { async let x = await getInt() print(x) // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1:9{{reference to async let 'x' is 'async'}} print(await x) do { try mightThrow() } catch let e where e.number == x { // expected-error{{async let 'x' cannot be referenced in a catch guard expression}} } catch { } async let x1 = getIntUnsafely() // okay, try is implicit here async let x2 = getInt() // okay, await is implicit here async let x3 = try getIntUnsafely() async let x4 = try! getIntUnsafely() async let x5 = try? getIntUnsafely() _ = await x1 // expected-error{{reading 'async let' can throw but is not marked with 'try'}} _ = await x2 _ = try await x3 _ = await x4 _ = await x5 } // expected-note@+1 3{{add 'async' to function 'testAsyncLetOutOfAsync()' to make it asynchronous}} {{30-30= async}} func testAsyncLetOutOfAsync() { async let x = 1 // expected-error{{'async let' in a function that does not support concurrency}} _ = await x // expected-error{{'async let' in a function that does not support concurrency}} _ = x // expected-error{{'async let' in a function that does not support concurrency}} }
apache-2.0
anhnc55/fantastic-swift-library
Example/Pods/paper-onboarding/Source/PageView/PageContainerView/PageContainer.swift
1
3971
// // PageContaineView.swift // AnimatedPageView // // Created by Alex K. on 13/04/16. // Copyright © 2016 Alex K. All rights reserved. // import UIKit class PageContrainer: UIView { var items: [PageViewItem]? let space: CGFloat // space between items var currentIndex = 0 private let itemRadius: CGFloat private let selectedItemRadius: CGFloat private let itemsCount: Int private let animationKey = "animationKey" init(radius: CGFloat, selectedRadius: CGFloat, space: CGFloat, itemsCount: Int) { self.itemsCount = itemsCount self.space = space self.itemRadius = radius self.selectedItemRadius = selectedRadius super.init(frame: CGRect.zero) items = createItems(itemsCount, radius: radius, selectedRadius: selectedRadius) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: public extension PageContrainer { func currenteIndex(index: Int, duration: Double, animated: Bool) { guard let items = self.items where index != currentIndex else {return} animationItem(items[index], selected: true, duration: duration) let fillColor = index > currentIndex ? true : false animationItem(items[currentIndex], selected: false, duration: duration, fillColor: fillColor) currentIndex = index } } // MARK: animations extension PageContrainer { private func animationItem(item: PageViewItem, selected: Bool, duration: Double, fillColor: Bool = false) { let toValue = selected == true ? selectedItemRadius * 2 : itemRadius * 2 item.constraints .filter{ $0.identifier == "animationKey" } .forEach { $0.constant = toValue } UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) item.animationSelected(selected, duration: duration, fillColor: fillColor) } } // MARK: create extension PageContrainer { private func createItems(count: Int, radius: CGFloat, selectedRadius: CGFloat) -> [PageViewItem] { var items = [PageViewItem]() // create first item var item = createItem(radius, selectedRadius: selectedRadius, isSelect: true) addConstraintsToView(item, radius: selectedRadius) items.append(item) for _ in 1..<count { let nextItem = createItem(radius, selectedRadius: selectedRadius) addConstraintsToView(nextItem, leftItem: item, radius: radius) items.append(nextItem) item = nextItem } return items } private func createItem(radius: CGFloat, selectedRadius: CGFloat, isSelect: Bool = false) -> PageViewItem { let item = Init(PageViewItem(radius: radius, selectedRadius: selectedRadius, isSelect: isSelect)) { $0.translatesAutoresizingMaskIntoConstraints = false $0.backgroundColor = .clearColor() } self.addSubview(item) return item } private func addConstraintsToView(item: UIView, radius: CGFloat) { [NSLayoutAttribute.Left, NSLayoutAttribute.CenterY].forEach { attribute in (self, item) >>>- { $0.attribute = attribute } } [NSLayoutAttribute.Width, NSLayoutAttribute.Height].forEach { attribute in item >>>- { $0.attribute = attribute $0.constant = radius * 2.0 $0.identifier = animationKey } } } private func addConstraintsToView(item: UIView, leftItem: UIView, radius: CGFloat) { (self, item) >>>- { $0.attribute = .CenterY } (self, item, leftItem) >>>- { $0.attribute = .Leading $0.secondAttribute = .Trailing $0.constant = space } [NSLayoutAttribute.Width, NSLayoutAttribute.Height].forEach { attribute in item >>>- { $0.attribute = attribute $0.constant = radius * 2.0 $0.identifier = animationKey } } } }
mit
daniel-barros/TV-Calendar
TV Calendar/LoadingView.swift
1
1385
// // LoadingView.swift // TV Calendar // // Created by Daniel Barros López on 10/22/17. // Copyright © 2017 Daniel Barros. All rights reserved. // import UIKit class LoadingView: UIView { @IBOutlet private weak var visualEffectView: UIVisualEffectView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var label: UILabel! init() { super.init(frame: .zero) let view = Bundle.main.loadNibNamed("LoadingView", owner: self, options: nil)!.first as! UIView view.frame = bounds addSubview(view) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func fadeIn(completion: (() -> ())? = nil) { visualEffectView.effect = nil activityIndicator.alpha = 0 label.alpha = 0 UIView.animate(withDuration: 0.3, animations: { self.visualEffectView.effect = UIBlurEffect(style: .light) self.activityIndicator.alpha = 1 self.label.alpha = 1 }, completion: { _ in completion?() }) } func fadeOut(completion: (() -> ())? = nil) { UIView.animate(withDuration: 0.3, animations: { self.visualEffectView.effect = nil self.activityIndicator.alpha = 0 self.label.alpha = 0 }, completion: { _ in completion?() }) } }
gpl-3.0
STShenZhaoliang/Swift2Guide
Swift2Guide/Swift100Tips/Swift100Tips/ObjcController.swift
1
2192
// // ObjcController.swift // Swift100Tips // // Created by 沈兆良 on 16/5/27. // Copyright © 2016年 ST. All rights reserved. // import UIKit class ObjcController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } /* Objective-C 和 Swift 在底层使用的是两套完全不同的机制,Cocoa 中的 Objective-C 对象是基于运行时的,它从骨子里遵循了 KVC (Key-Value Coding,通过类似字典的方式存储对象信息) 以及动态派发 (Dynamic Dispatch,在运行调用时再决定实际调用的具体实现)。而 Swift 为了追求性能,如果没有特殊需要的话,是不会在运行时再来决定这些的。也就是说,Swift 类型的成员或者方法在编译时就已经决定,而运行时便不再需要经过一次查找,而可以直接使用。 注意这个步骤只需要对那些不是继承自 NSObject 的类型进行,如果你用 Swift 写的 class 是继承自 NSObject 的话,Swift 会默认自动为所有的非 private 的类和成员加上 @objc。这就是说,对一个 NSObject 的子类,你只需要导入相应的头文件就可以在 Objective-C 里使用这个类了。 @objc 修饰符的另一个作用是为 Objective-C 侧重新声明方法或者变量的名字。 需要注意的是,添加 @objc 修饰符并不意味着这个方法或者属性会变成动态派发,Swift 依然可能会将其优化为静态调用。如果你需要和 Objective-C 里动态调用时相同的运行时特性的话,你需要使用的修饰符是 dynamic。 */
mit
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Cells/Chat/ChatMessageDaySeparator.swift
1
687
// // ChatMessageDaySeparator.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 19/12/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import UIKit final class ChatMessageDaySeparator: UICollectionViewCell { static let minimumHeight: CGFloat = 40.0 static let identifier = "ChatMessageDaySeparator" @IBOutlet weak var labelTitle: UILabel! @IBOutlet weak var seperatorLine: UIView! } // MARK: Themeable extension ChatMessageDaySeparator { override func applyTheme() { super.applyTheme() seperatorLine.backgroundColor = #colorLiteral(red: 0.491, green: 0.4938107133, blue: 0.500592351, alpha: 0.1964201627) } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/00917-swift-lexer-leximpl.swift
1
813
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck init() { () -> String { self.c> Self { } func g<d where T! { let t: [c) { } func b(array: Collection where T> U -> { func d<T where B { b) { var d where B : C<Int) { x = a<d where A> ((false)) { func g<d where T> () { print() { typealias d.c(self.d = c<T>((1] c>(e: S) { return [T { func f(x, A, y: Any) { protocol B { } } b("cd"") } } } protocol A { typealias B : b { func a(Any) -> T where S(" typealias b = a"""
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/01069-swift-nominaltypedecl-getprotocols.swift
1
518
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol P { func a(b([Any) let c, let t: B) let b : () { init(i: Int = c>) -> () -> Int { } } protocol B : a { func f:
apache-2.0