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
drewcrawford/DCAKit
DCAKit/Foundation Additions/DCATimer.swift
1
1703
// // DCATimer.swift // DCAKit // // Created by Drew Crawford on 1/16/15. // Copyright (c) 2015 DrewCrawfordApps. // This file is part of DCAKit. It is subject to the license terms in the LICENSE // file found in the top level of this distribution and at // https://github.com/drewcrawford/DCAKit/blob/master/LICENSE. // No part of DCAKit, including this file, may be copied, modified, // propagated, or distributed except according to the terms contained // in the LICENSE file. import Foundation /**A better NSTimer. GCD-based, runloop-indepenedent. */ public class DCATimer { private let source : dispatch_source_t /**Creates and starts the timer. :param: interval the amount of time between fires. The first run will be after this amount, plus/minus leeway :param: leeway the amount of leeway the system has to coalesce timers. Higher values produce power savings. :param: queue the dispatch queue the timer will run on. :param: block the block that will be executed. :note: Some latency is to be expected for all timers, even when a leeway value of zero is specified.*/ public init(interval: NSTimeInterval, leeway: NSTimeInterval, queue: dispatch_queue_t, block:() -> () ) { source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC))) dispatch_source_set_timer(source, DISPATCH_TIME_NOW, UInt64(interval * Double(NSEC_PER_SEC)), UInt64(leeway * Double( NSEC_PER_SEC))) dispatch_source_set_event_handler(source, block) dispatch_resume(source) } public func stop() { dispatch_source_cancel(source) } }
mit
DisappearPing/MRDQRCodeReader
MRDQRCode/AppDelegate.swift
1
2149
// // AppDelegate.swift // MRDQRCode // // Created by disappearping on 2016/1/26. // Copyright © 2016年 disappear. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
muukii/PhotosProvider
PhotosProviderDemo/AssetsViewController.swift
3
881
// // AssetsViewController.swift // PhotosProvider // // Created by Hiroshi Kimura on 8/7/15. // Copyright © 2015 muukii. All rights reserved. // import UIKit class AssetsViewController: 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. } */ }
mit
davidkobilnyk/BNRGuideSolutionsInSwift
11-Camera/HomePwner/HomePwner/BNRItemsViewController.swift
2
5485
// // BNRItemsViewController.swift // HomePwner // // Created by David Kobilnyk on 7/8/14. // Copyright (c) 2014 David Kobilnyk. All rights reserved. // import UIKit class BNRItemsViewController: UITableViewController { // Need to add this init in in Swift, or you get "fatal error: use of unimplemented initializer 'init(nibName:bundle:)' for class" override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override init() { super.init(style: UITableViewStyle.Plain) let navItem = self.navigationItem navItem.title = "Homepwner" // Create a new bar button item that will send // addNewItem: to BNRItemsViewController let bbi = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addNewItem:") // Set this bar button item as the right item in the navigationItem navItem.rightBarButtonItem = bbi navItem.leftBarButtonItem = self.editButtonItem() } override convenience init(style: UITableViewStyle) { self.init() } // Without this, get error: "Class ‘BNRItemsViewController’ does not implement its // superclass’s required members" required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() // Use .self to get the class. It's equivalent to [UITableViewCell class] in Objective-C. tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell") } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int)->Int { return BNRItemStore.sharedStore.allItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Get a new or recycled cell let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell") as UITableViewCell // Set the text on the cell with the description of the item // that is at the nth index of items, where n = row this cell // will appear in on the tableview let item = BNRItemStore.sharedStore.allItems[indexPath.row] cell.textLabel?.text = item.description return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let detailViewController = BNRDetailViewController() let items = BNRItemStore.sharedStore.allItems let selectedItem = items[indexPath.row] // Give detail view controller a pointer to the item object in row detailViewController.item = selectedItem // Push it onto the top of the navigation controller's stack self.navigationController?.pushViewController(detailViewController, animated: true) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // If the table view is asking to commit a delete command... if (editingStyle == .Delete) { var items = BNRItemStore.sharedStore.allItems var item = items[indexPath.row] BNRItemStore.sharedStore.removeItem(item) // Also remove that row from the table view with an animation tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { BNRItemStore.sharedStore.moveItemAtIndex(sourceIndexPath.row, toIndex: destinationIndexPath.row) } @IBAction func addNewItem(sender: UIButton) { // Create a new BNRItem and add it to the store var newItem = BNRItemStore.sharedStore.createItem() // Figure out where that item is in the array var lastRow: Int = 0 for i in 0..<BNRItemStore.sharedStore.allItems.count { if BNRItemStore.sharedStore.allItems[i] === newItem { lastRow = i break } } // I wonder why BNR does it like this -- searching through the array for the new // element instead of just using count-1 for lastRow var indexPath = NSIndexPath(forRow: lastRow, inSection: 0) // Insert this new row into the table. tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Top) } @IBAction func toggleEditingMode(sender: UIButton) { // If you are currently in editing mode... if editing { // Change text of button to inform user of state sender.setTitle("Edit", forState: .Normal) // Turn off editing mode setEditing(false, animated: true) } else { // Change tet of button to inform user of state sender.setTitle("Done", forState: .Normal) // Enter editing mode setEditing(true, animated: true) } } }
mit
FredrikSjoberg/SnapStack
SnapStack/Protocols/CommitType.swift
1
898
// // CommitType.swift // SnapStack // // Created by Fredrik Sjöberg on 19/09/15. // Copyright © 2015 Fredrik Sjöberg. All rights reserved. // import Foundation import CoreData public protocol CommitType : ContextType, LoggingType { func commit() throws } extension CommitType { /// Commits any changes and throws errors public func commit() throws { guard handlerContext.hasChanges else { logger?.deliver(SnapStackInfo.NoChangesToCommit(context: handlerContext)) return } try handlerContext.save() logger?.deliver(SnapStackInfo.CommitedChanges(context: handlerContext)) } /// Tries to commit the changes and logs any errors public func commitAndLog() { do { try commit() } catch let commitError as NSError { logger?.deliver(commitError) } } }
mit
6ag/BaoKanIOS
BaoKanIOS/Classes/Utils/JFSQLiteManager.swift
1
3710
// // JFSQLiteManager.swift // LiuAGeIOS // // Created by zhoujianfeng on 16/6/12. // Copyright © 2016年 六阿哥. All rights reserved. // import UIKit import FMDB let NEWS_LIST_HOME_TOP = "jf_newslist_hometop" // 首页 列表页 的 幻灯片 数据表 let NEWS_LIST_HOME_LIST = "jf_newslist_homelist" // 首页 列表页 的 列表 数据表 let NEWS_LIST_OTHER_TOP = "jf_newslist_othertop" // 其他分类 列表页 的 幻灯片 数据表 let NEWS_LIST_OTHER_LIST = "jf_newslist_otherlist" // 其他分类 列表页 的 列表 数据表 let NEWS_CONTENT = "jf_news_content" // 资讯/图库 正文 数据表 let SEARCH_KEYBOARD = "jf_search_keyboard" // 搜索关键词数据表 class JFSQLiteManager: NSObject { /// FMDB单例 static let shareManager = JFSQLiteManager() /// sqlite数据库名 fileprivate let newsDBName = "news.db" let dbQueue: FMDatabaseQueue override init() { let documentPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! let dbPath = "\(documentPath)/\(newsDBName)" print(dbPath) // 根据路径创建并打开数据库,开启一个串行队列 dbQueue = FMDatabaseQueue(path: dbPath) super.init() // 创建数据表 createNewsListTable(NEWS_LIST_HOME_TOP) createNewsListTable(NEWS_LIST_HOME_LIST) createNewsListTable(NEWS_LIST_OTHER_TOP) createNewsListTable(NEWS_LIST_OTHER_LIST) createNewsContentTable() createSearchKeyboardTable() } /** 创建新闻列表的数据表 - parameter tbname: 表名 */ fileprivate func createNewsListTable(_ tbname: String) { let sql = "CREATE TABLE IF NOT EXISTS \(tbname) ( \n" + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \n" + "classid INTEGER, \n" + "news TEXT, \n" + "createTime VARCHAR(30) DEFAULT (datetime('now', 'localtime')) \n" + ");" dbQueue.inDatabase { (db) in if (db?.executeStatements(sql))! { print("创建 \(tbname) 表成功") } else { print("创建 \(tbname) 表失败") } } } /** 创建资讯内容数据表 */ fileprivate func createNewsContentTable() { let sql = "CREATE TABLE IF NOT EXISTS \(NEWS_CONTENT) ( \n" + "id INTEGER, \n" + "classid INTEGER, \n" + "news TEXT, \n" + "createTime VARCHAR(30) DEFAULT (datetime('now', 'localtime')) \n" + ");" dbQueue.inDatabase { (db) in if (db?.executeStatements(sql))! { print("创建 \(NEWS_CONTENT) 表成功") } else { print("创建 \(NEWS_CONTENT) 表失败") } } } /** 创建搜索关键词数据表 */ fileprivate func createSearchKeyboardTable() { let sql = "CREATE TABLE IF NOT EXISTS \(SEARCH_KEYBOARD) ( \n" + "id INTEGER, \n" + "keyboard VARCHAR(30), \n" + "pinyin VARCHAR(30), \n" + "num INTEGER, \n" + "createTime VARCHAR(30) DEFAULT (datetime('now', 'localtime')) \n" + ");" dbQueue.inDatabase { (db) in if (db?.executeStatements(sql))! { print("创建 \(SEARCH_KEYBOARD) 表成功") } else { print("创建 \(SEARCH_KEYBOARD) 表失败") } } } }
apache-2.0
griff/metaz
Framework/src/String-matches-mimetype-pattern.swift
1
975
// // String-matches-mimetype-pattern.swift // MetaZKit // // Created by Brian Olsen on 22/02/2020. // import Foundation extension String { public func matches(mimeTypePattern pattern: String) -> Bool { if pattern == "*" { return true } var pattern = pattern var range : Range<String.Index> = self.startIndex ..< self.endIndex var length = pattern.endIndex if pattern.hasSuffix("/*") { length = pattern.index(before: length) pattern = String(pattern.prefix(upTo: length)) if length < range.upperBound { range = self.startIndex ..< length } } else if range.upperBound != length { return false } return self.compare(pattern, options: [.caseInsensitive, .literal], range: range, locale: nil) == .orderedSame } }
mit
superk589/DereGuide
DereGuide/LiveSimulator/LSNote.swift
2
2389
// // LSNote.swift // DereGuide // // Created by zzk on 2017/3/31. // Copyright © 2017 zzk. All rights reserved. // import Foundation struct LSNote { var comboFactor: Double var baseScore: Double var sec: Float var rangeType: CGSSBeatmapNote.RangeType var noteType: CGSSBeatmapNote.Style var beatmapNote: CGSSBeatmapNote func lifeLost(in difficulty: CGSSLiveDifficulty, evaluation: LSEvaluationType) -> Int { return lifeLoss[evaluation]?[difficulty]?[rangeType] ?? 0 } } enum LSEvaluationType { case perfect case great case good case bad case miss var modifier: Double { switch self { case .perfect: return 1 case .great: return 0.7 case .good: return 0.4 case .bad: return 0.1 case .miss: return 0 } } } fileprivate let lifeLoss: [LSEvaluationType: [CGSSLiveDifficulty: [CGSSBeatmapNote.RangeType: Int]]] = [ .bad: [ .debut: [ .click: 6, ], .regular: [ .click: 7, ], .light: [ .click: 7, ], .pro: [ .click: 9, .slide: 5, .flick: 5 ], .master: [ .click: 12, .slide: 6, .flick: 6 ], .masterPlus: [ .click: 12, .slide: 6, .flick: 6 ], .legacyMasterPlus: [ .click: 12, .slide: 6, .flick: 6 ], .trick: [ .click: 12, .slide: 6, .flick: 6 ] ], .miss: [ .debut: [ .click: 10, ], .regular: [ .click: 12, ], .light: [ .click: 12, ], .pro: [ .click: 15, .slide: 8, .flick: 8 ], .master: [ .click: 20, .slide: 10, .flick: 10 ], .masterPlus: [ .click: 20, .slide: 10, .flick: 10 ], .legacyMasterPlus: [ .click: 20, .slide: 10, .flick: 10 ], .trick: [ .click: 20, .slide: 10, .flick: 10 ] ] ]
mit
ps2/rileylink_ios
OmniKitUI/ViewModels/DeliveryUncertaintyRecoveryViewModel.swift
1
968
// // DeliveryUncertaintyRecoveryViewModel.swift // OmniKit // // Created by Pete Schwamb on 8/25/20. // Copyright © 2021 LoopKit Authors. All rights reserved. // import Foundation import LoopKit class DeliveryUncertaintyRecoveryViewModel: PumpManagerStatusObserver { let appName: String let uncertaintyStartedAt: Date var respondToRecovery: Bool var onDismiss: (() -> Void)? var didRecover: (() -> Void)? var onDeactivate: (() -> Void)? init(appName: String, uncertaintyStartedAt: Date) { self.appName = appName self.uncertaintyStartedAt = uncertaintyStartedAt respondToRecovery = false } func pumpManager(_ pumpManager: PumpManager, didUpdate status: PumpManagerStatus, oldStatus: PumpManagerStatus) { if !status.deliveryIsUncertain && respondToRecovery { didRecover?() } } func podDeactivationChosen() { self.onDeactivate?() } }
mit
dklinzh/NodeExtension
NodeExtension/Classes/UIKit/String.swift
1
3198
// // String.swift // NodeExtension // // Created by Linzh on 8/20/17. // Copyright (c) 2017 Daniel Lin. All rights reserved. // /// Get localized string for the specified key from a custom table /// /// - Parameters: /// - key: The specified key /// - tableName: The custom table /// - Returns: Localized string from the specified strings table public func DLLocalizedString(_ key: String, tableName: String? = "Localizable") -> String { return NSLocalizedString(key, tableName: tableName, comment: "") } extension NSAttributedString { /// Create a NSAttributedString with some attributes /// /// - Parameters: /// - string: The string for the new attributed string /// - size: The font size of attributed string /// - color: The color of attributed string /// - Returns: A NSAttributedString instance public static func dl_attributedString(string: String, fontSize size: CGFloat, color: UIColor = .black) -> NSAttributedString { return NSAttributedString.dl_attributedString(string: string, fontSize: size, color: color, firstWordColor: nil) } /// Create a NSAttributedString with some attributes /// /// - Parameters: /// - string: The string for the new attributed string /// - size: The font size of attributed string /// - color: The color of attributed string /// - firstWordColor: The color of frist word /// - Returns: A NSAttributedString instance public static func dl_attributedString(string: String, fontSize size: CGFloat, color: UIColor = .black, firstWordColor: UIColor? = nil) -> NSAttributedString { let attributes = [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font: UIFont.systemFont(ofSize: size)] let attributedString = NSMutableAttributedString(string: string, attributes: attributes) if let firstWordColor = firstWordColor { let nsString = string as NSString let firstSpaceRange = nsString.rangeOfCharacter(from: NSCharacterSet.whitespaces) let firstWordRange = NSMakeRange(0, firstSpaceRange.location) attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: firstWordColor, range: firstWordRange) } return attributedString } /// Add attributs of font size and text color to the NSAttributedString /// /// - Parameters: /// - range: The range of characters to which the specified attributes apply /// - font: The font of text /// - color: The text color /// - Returns: A NSAttributedString instance public func dl_stringAddAttribute(range: NSRange, font: UIFont, color: UIColor) -> NSAttributedString { guard range.location != NSNotFound else { return self } let attributedString = self.mutableCopy() as! NSMutableAttributedString let attributes = [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font: font] attributedString.addAttributes(attributes, range: range) return attributedString } }
mit
AppLovin/iOS-SDK-Demo
Swift Demo App/iOS-SDK-Demo/ALEventTrackingViewController.swift
1
8088
// // ALEventTrackingViewController.swift // iOS-SDK-Demo-Swift // // Created by Monica Ong on 6/5/17. // Copyright © 2017 AppLovin. All rights reserved. // import UIKit import StoreKit import AppLovinSDK struct ALDemoEvent { var name: String var purpose: String } class ALEventTrackingViewController : ALDemoBaseTableViewController { private let events = [ALDemoEvent(name: "Began Checkout Event", purpose: "Track when user begins checkout procedure"), ALDemoEvent(name: "Cart Event", purpose: "Track when user adds an item to cart"), ALDemoEvent(name: "Completed Achievement Event", purpose: "Track when user completed an achievement"), ALDemoEvent(name: "Completed Checkout Event", purpose: "Track when user completed checkout"), ALDemoEvent(name: "Completed Level Event", purpose: "Track when user completed level"), ALDemoEvent(name: "Created Reservation Event", purpose: "Track when user created a reservation"), ALDemoEvent(name: "In-App Purchase Event", purpose: "Track when user makes an in-app purchase"), ALDemoEvent(name: "Login Event", purpose: "Track when user logs in"), ALDemoEvent(name: "Payment Info Event", purpose: "Tracks when user inputs their payment information"), ALDemoEvent(name: "Registration Event", purpose: "Track when user registers"), ALDemoEvent(name: "Search Event", purpose: "Track when user makes a search"), ALDemoEvent(name: "Sent Invitation Event", purpose: "Track when user sends invitation"), ALDemoEvent(name: "Shared Link Event", purpose: "Track when user shares a link"), ALDemoEvent(name: "Spent Virtual Currency Event", purpose: "Track when users spends virtual currency"), ALDemoEvent(name: "Tutorial Event", purpose: "Track when users does a tutorial"), ALDemoEvent(name: "Viewed Content Event", purpose: "Track when user views content"), ALDemoEvent(name: "Viewed Product Event", purpose: "Track when user views product"), ALDemoEvent(name: "Wishlist Event", purpose: "Track when user adds an item to their wishlist")] // MARK: Table View Data Source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return events.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "rootPrototype", for: indexPath) cell.textLabel!.text = events[indexPath.row].name cell.detailTextLabel!.text = events[indexPath.row].purpose return cell } // MARK: Table View Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let eventService = ALSdk.shared()!.eventService switch indexPath.row { case 0: eventService.trackEvent(kALEventTypeUserBeganCheckOut, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID", kALEventParameterRevenueAmountKey : "PRICE OF ITEM", kALEventParameterRevenueCurrencyKey : "3-LETTER CURRENCY CODE"]) case 1: eventService.trackEvent(kALEventTypeUserAddedItemToCart, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID"]) case 2: eventService.trackEvent(kALEventTypeUserCompletedAchievement, parameters: [kALEventParameterCompletedAchievementKey : "ACHIEVEMENT NAME OR ID"]) case 3: eventService.trackEvent(kALEventTypeUserCompletedCheckOut, parameters: [kALEventParameterCheckoutTransactionIdentifierKey : "UNIQUE TRANSACTION ID", kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID", kALEventParameterRevenueAmountKey : "AMOUNT OF MONEY SPENT", kALEventParameterRevenueCurrencyKey : "3-LETTER CURRENCY CODE"]) case 4: eventService.trackEvent(kALEventTypeUserCompletedLevel, parameters: [kALEventParameterCompletedLevelKey : "LEVEL NAME OR NUMBER"]) case 5: eventService.trackEvent(kALEventTypeUserCreatedReservation, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID", kALEventParameterReservationStartDateKey : "START NSDATE", kALEventParameterReservationEndDateKey : "END NSDATE"]) case 6: //In-App Purchases // let transaction: SKPaymentTransaction = ... // from paymentQueue:updatedTransactions: //let product: SKProduct = ... // Appropriate product (matching productIdentifier property to SKPaymentTransaction) eventService.trackInAppPurchase(withTransactionIdentifier: "transaction.transactionIdentifier", parameters: [kALEventParameterRevenueAmountKey : "AMOUNT OF MONEY SPENT", kALEventParameterRevenueCurrencyKey : "3-LETTER CURRENCY CODE", kALEventParameterProductIdentifierKey : "product.productIdentifier"]) //product.productIdentifier case 7: eventService.trackEvent(kALEventTypeUserLoggedIn, parameters: [kALEventParameterUserAccountIdentifierKey : "USERNAME"]) case 8: eventService.trackEvent(kALEventTypeUserProvidedPaymentInformation) case 9: eventService.trackEvent(kALEventTypeUserCreatedAccount, parameters: [kALEventParameterUserAccountIdentifierKey : "USERNAME"]) case 10: eventService.trackEvent(kALEventTypeUserExecutedSearch, parameters: [kALEventParameterSearchQueryKey : "USER'S SEARCH STRING"]) case 11: eventService.trackEvent(kALEventTypeUserSentInvitation) case 12: eventService.trackEvent(kALEventTypeUserSharedLink) case 13: eventService.trackEvent(kALEventTypeUserSpentVirtualCurrency, parameters: [kALEventParameterVirtualCurrencyAmountKey : "NUMBER OF COINS SPENT", kALEventParameterVirtualCurrencyNameKey : "CURRENCY NAME"]) case 14: eventService.trackEvent(kALEventTypeUserCompletedTutorial) case 15: eventService.trackEvent(kALEventTypeUserViewedContent, parameters: [kALEventParameterContentIdentifierKey : "SOME ID DESCRIBING CONTENT"]) case 16: eventService.trackEvent(kALEventTypeUserViewedProduct, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID"]) case 17: eventService.trackEvent(kALEventTypeUserAddedItemToWishlist, parameters: [kALEventParameterProductIdentifierKey : "PRODUCT SKU OR ID"]) default: title = "Default event tracking initiated" } } }
mit
omaralbeik/SwifterSwift
Tests/FoundationTests/FileManagerExtensionsTests.swift
1
3674
// // FileManagerExtensionsTests.swift // SwifterSwift // // Created by Jason Jon E. Carreos on 05/02/2018. // Copyright © 2018 SwifterSwift // import XCTest @testable import SwifterSwift #if canImport(Foundation) import Foundation final class FileManagerExtensionsTests: XCTestCase { func testJSONFromFileAtPath() { do { let bundle = Bundle(for: FileManagerExtensionsTests.self) let filePath = bundle.path(forResource: "test", ofType: "json") guard let path = filePath else { XCTFail("File path undefined.") return } let json = try FileManager.default.jsonFromFile(atPath: path) XCTAssertNotNil(json) // Check contents if let dict = json { if let string = dict["title"] as? String, let itemId = dict["id"] as? Int { XCTAssert(string == "Test") XCTAssert(itemId == 1) } else { XCTFail("Does not contain the correct content.") } } else { XCTFail("Opening of file returned nil.") } } catch { XCTFail("Error encountered during opening of file. \(error.localizedDescription)") } } func testJSONFromFileWithFilename() { do { var filename = "test.json" // With extension var json = try FileManager.default.jsonFromFile(withFilename: filename, at: FileManagerExtensionsTests.self) XCTAssertNotNil(json) filename = "test" // Without extension json = try FileManager.default.jsonFromFile(withFilename: filename, at: FileManagerExtensionsTests.self) XCTAssertNotNil(json) // Check contents if let dict = json { if let string = dict["title"] as? String, let itemId = dict["id"] as? Int { XCTAssert(string == "Test") XCTAssert(itemId == 1) } else { XCTFail("Does not contain the correct content.") } } else { XCTFail("Opening of file returned nil.") } } catch { XCTFail("Error encountered during opening of file. \(error.localizedDescription)") } } func testInvalidFile() { let filename = "another_test.not_json" do { let json = try FileManager.default.jsonFromFile(withFilename: filename, at: FileManagerExtensionsTests.self) XCTAssertNil(json) } catch {} } func testCreateTemporaryDirectory() { do { let fileManager = FileManager.default let tempDirectory = try fileManager.createTemporaryDirectory() XCTAssertFalse(tempDirectory.path.isEmpty) var isDirectory = ObjCBool(false) XCTAssert(fileManager.fileExists(atPath: tempDirectory.path, isDirectory: &isDirectory)) XCTAssertTrue(isDirectory.boolValue) XCTAssert(try fileManager.contentsOfDirectory(atPath: tempDirectory.path).isEmpty) let tempFile = tempDirectory.appendingPathComponent(ProcessInfo().globallyUniqueString) XCTAssert(fileManager.createFile(atPath: tempFile.path, contents: Data(), attributes: nil)) XCTAssertFalse(try fileManager.contentsOfDirectory(atPath: tempDirectory.path).isEmpty) XCTAssertNotNil(fileManager.contents(atPath: tempFile.path)) try fileManager.removeItem(at: tempDirectory) } catch { XCTFail("\(error)") } } } #endif
mit
AttilaTheFun/SwaggerParser
Sources/SchemaType.swift
1
4732
/// The discrete type defined by the schema. /// This can be a primitive type (string, float, integer, etc.) or a complex type like a dictionay or array. public enum SchemaType { /// A structure represents a named or aliased type. indirect case structure(Structure<Schema>) /// Defines an anonymous object type with a set of named properties. indirect case object(ObjectSchema) /// Defines an array of heterogenous (but possibly polymorphic) objects. indirect case array(ArraySchema) /// Defines an object with the combined requirements of several subschema. indirect case allOf(AllOfSchema) /// A string type with optional format information (e.g. base64 encoding). case string(StringFormat?) /// A floating point number type with optional format information (e.g. single vs double precision). case number(NumberFormat?) /// An integer type with an optional format (32 vs 64 bit). case integer(IntegerFormat?) /// An enumeration type with explicit acceptable values defined in the metadata. case enumeration /// A boolean type. case boolean /// A file type. case file /// An 'any' type which matches any value. case any /// A void data type. (Void in Swift, None in Python) case null } enum SchemaTypeBuilder: Codable { indirect case pointer(Pointer<SchemaBuilder>) indirect case object(ObjectSchemaBuilder) indirect case array(ArraySchemaBuilder) indirect case allOf(AllOfSchemaBuilder) case string(StringFormat?) case number(NumberFormat?) case integer(IntegerFormat?) case enumeration case boolean case file case any case null enum CodingKeys: String, CodingKey { case format } init(from decoder: Decoder) throws { let dataType = try DataType(from: decoder) let values = try decoder.container(keyedBy: CodingKeys.self) switch dataType { case .pointer: self = .pointer(try Pointer<SchemaBuilder>(from: decoder)) case .object: self = .object(try ObjectSchemaBuilder(from: decoder)) case .array: self = .array(try ArraySchemaBuilder(from: decoder)) case .allOf: self = .allOf(try AllOfSchemaBuilder(from: decoder)) case .string: self = .string(try values.decodeIfPresent(StringFormat.self, forKey: .format)) case .number: self = .number(try values.decodeIfPresent(NumberFormat.self, forKey: .format)) case .integer: self = .integer(try values.decodeIfPresent(IntegerFormat.self, forKey: .format)) case .enumeration: self = .enumeration case .boolean: self = .boolean case .file: self = .file case .any: self = .any case .null: self = .null } } func encode(to encoder: Encoder) throws { switch self { case .pointer(let pointer): try pointer.encode(to: encoder) case .object(let object): try object.encode(to: encoder) case .array(let array): try array.encode(to: encoder) case .allOf(let allOf): try allOf.encode(to: encoder) case .string(let format): try format.encode(to: encoder) case .number(let format): try format.encode(to: encoder) case .integer(let format): try format.encode(to: encoder) case .enumeration, .boolean, .file, .any, .null: // Will be encoded by Schema -> Metadata -> DataType break } } } extension SchemaTypeBuilder: Builder { typealias Building = SchemaType func build(_ swagger: SwaggerBuilder) throws -> SchemaType { switch self { case .pointer(let pointer): let structure = try SchemaBuilder.resolver.resolve(swagger, pointer: pointer) return .structure(structure) case .object(let builder): return .object(try builder.build(swagger)) case .array(let builder): return .array(try builder.build(swagger)) case .allOf(let builder): return .allOf(try builder.build(swagger)) case .string(let format): return .string(format) case .number(let format): return .number(format) case .integer(let format): return .integer(format) case .enumeration: return .enumeration case .boolean: return .boolean case .file: return .file case .any: return .any case .null: return .null } } }
mit
peferron/algo
EPI/Binary Trees/Implement ab inorder traversal with O(1) space/swift/main.swift
1
1273
// swiftlint:disable conditional_binding_cascade public class Node<T> { public let value: T public let left: Node? public let right: Node? public var parent: Node? = nil public init(value: T, left: Node? = nil, right: Node? = nil) { self.value = value self.left = left self.right = right left?.parent = self right?.parent = self } public func inorder() -> [T] { var values = [T]() var current: Node? = self var previous: Node? = nil while let c = current { if let p = previous, let l = c.left, p === l { // Coming back up from the left child. values.append(c.value) current = c.right ?? c.parent } else if let p = previous, let r = c.right, p === r { // Coming back up from the right child. current = c.parent } else { // Coming down from the parent. if let l = c.left { current = l } else { values.append(c.value) current = c.right ?? c.parent } } previous = c } return values } }
mit
SwiftBond/Bond
Tests/BondTests/TreeChangesetDiffAndPatchTest.swift
1
2790
// // CollectionDiff+Array.swift.swift // Bond-iOS // // Created by Srdan Rasic on 26/08/2018. // Copyright © 2018 Swift Bond. All rights reserved. // import XCTest @testable import Bond extension OrderedCollectionOperation where Element == TreeNode<Int>, Index == IndexPath { static func randomOperation(collection: TreeNode<Int>) -> OrderedCollectionOperation<TreeNode<Int>, IndexPath> { let element = TreeNode(Int.random(in: 11..<100)) let indices = collection.indices guard indices.count > 1 else { return .insert(element, at: [0]) } switch [0, 2, 3].randomElement() { case 0: var at = indices.randomElement()! if Bool.random() { at = at.appending(0) } return .insert(element, at: at) case 1: let at = indices.randomElement()! return .delete(at: at) case 2: let at = indices.randomElement()! return .update(at: at, newElement: element) case 3: let from = indices.randomElement()! var collection = collection collection.remove(at: from) let to = collection.indices.randomElement() ?? from return .move(from: from, to: to) default: fatalError() } } } class TreeChangesetDiffAndPatchTest: XCTestCase { let testTree = TreeNode(0, [TreeNode(1, [TreeNode(2), TreeNode(3, [TreeNode(4)])]), TreeNode(5)]) func testRandom() { measure { for _ in 0..<1000 { oneRandomTest() } } } func oneRandomTest() { let initialCollection = testTree var collection = initialCollection var operations: [TreeChangeset<TreeNode<Int>>.Operation] = [] for _ in 0..<Int.random(in: 2..<12) { let operation = TreeChangeset<TreeNode<Int>>.Operation.randomOperation(collection: collection) collection.apply(operation) operations.append(operation) } execTest(operations: operations, initialCollection: initialCollection) } func execTest(operations: [TreeChangeset<TreeNode<Int>>.Operation], initialCollection: TreeNode<Int>) { var collection = initialCollection for operation in operations { collection.apply(operation) } let diff = TreeChangeset<TreeNode<Int>>.Diff(from: operations) let patch = diff.generatePatch(to: collection) var testCollection = initialCollection for operation in patch { testCollection.apply(operation) } XCTAssertEqual(collection, testCollection, "Operations: \(operations), Diff: \(diff), Patch: \(patch)") } }
mit
ginppian/fif2016
ACTabScrollView/ContentViewController.swift
1
3953
// // ContentViewController.swift // ACTabScrollView // // Created by Azure Chen on 5/19/16. // Copyright © 2016 AzureChen. All rights reserved. // import UIKit class ContentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var eventoFif = EventoFIF() var category: NewsCategory? { didSet { for news in MockData.newsArray { if (news.category == category) { newsArray.append(news) } } } } var newsArray: [News] = [] override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44 tableView.delegate = self tableView.dataSource = self } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let news = newsArray[(indexPath as NSIndexPath).row] // set the cell let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ContentTableViewCell // cell.thumbnailImageView.image = UIImage(named: "thumbnail-\(news.id)") // cell.thumbnailImageView.layer.cornerRadius = 4 // cell.titleLabel.text = news.title // cell.categoryLabel.text = String(describing: news.category) // cell.categoryView.layer.backgroundColor = UIColor.white.cgColor // cell.categoryView.layer.cornerRadius = 4 // cell.categoryView.layer.borderWidth = 1 // cell.categoryView.layer.borderColor = UIColor(red: 32.0 / 255, green: 188.0 / 255, blue: 239.0 / 255, alpha: 1.0).cgColor cell.labelHour.text = news.horaIni cell.labelEvento.text = news.evento cell.labelPonente.text = news.ponente cell.tag = news.id cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let new = newsArray[indexPath.row] self.eventoFif.id = new.id self.eventoFif.fecha = new.fecha self.eventoFif.horaIni = new.horaIni self.eventoFif.horaFin = new.horaFin self.eventoFif.sede = new.sede self.eventoFif.direccion = new.direccion self.eventoFif.evento = new.evento self.eventoFif.ponente = new.ponente self.eventoFif.pais = new.pais self.eventoFif.descripcion = new.descripcion performSegue(withIdentifier: "detailContentIdentifier", sender: self) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 3 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() // view.frame = CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: view.frame.height*2.0) view.backgroundColor = UIColor(red: 31.0 / 255, green: 180.0 / 255, blue: 228.0 / 255, alpha: 1.0) return view } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier) == "detailContentIdentifier" { let vc = segue.destination as! DetailContentViewController vc.eventoFif = self.eventoFif } } } class ContentTableViewCell: UITableViewCell { @IBOutlet weak var labelHour: UILabel! @IBOutlet weak var labelEvento: UILabel! @IBOutlet weak var labelPonente: UILabel! override func awakeFromNib() { self.selectionStyle = .none } }
mit
ibm-bluemix-mobile-services/bms-clientsdk-swift-security
Source/mca/api/identity/MCAUserIdentity.swift
1
1317
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ import Foundation import BMSCore /// This class represents the base user identity class, with default methods and keys #if swift (>=3.0) public class MCAUserIdentity : BaseUserIdentity{ public override init() { super.init() } public convenience init(map: [String:AnyObject]?) { self.init(map: map as [String:Any]?) } public override init(map: [String : Any]?) { super.init(map: map) } } #else public class MCAUserIdentity : BaseUserIdentity{ public override init() { super.init() } public override init(map: [String : AnyObject]?) { super.init(map: map) } } #endif
apache-2.0
agrippa1994/iOS-PLC
Pods/Charts/Charts/Classes/Renderers/ChartLegendRenderer.swift
5
14927
// // ChartLegendRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartLegendRenderer: ChartRendererBase { /// the legend object this renderer renders internal var _legend: ChartLegend! public init(viewPortHandler: ChartViewPortHandler, legend: ChartLegend?) { super.init(viewPortHandler: viewPortHandler) _legend = legend } /// Prepares the legend and calculates all needed forms, labels and colors. public func computeLegend(data: ChartData) { if (!_legend.isLegendCustom) { var labels = [String?]() var colors = [UIColor?]() // loop for building up the colors and labels used in the legend for (var i = 0, count = data.dataSetCount; i < count; i++) { let dataSet = data.getDataSetByIndex(i)! var clrs: [UIColor] = dataSet.colors let entryCount = dataSet.entryCount // if we have a barchart with stacked bars if (dataSet.isKindOfClass(BarChartDataSet) && (dataSet as! BarChartDataSet).isStacked) { let bds = dataSet as! BarChartDataSet var sLabels = bds.stackLabels for (var j = 0; j < clrs.count && j < bds.stackSize; j++) { labels.append(sLabels[j % sLabels.count]) colors.append(clrs[j]) } if (bds.label != nil) { // add the legend description label colors.append(nil) labels.append(bds.label) } } else if (dataSet.isKindOfClass(PieChartDataSet)) { var xVals = data.xVals let pds = dataSet as! PieChartDataSet for (var j = 0; j < clrs.count && j < entryCount && j < xVals.count; j++) { labels.append(xVals[j]) colors.append(clrs[j]) } if (pds.label != nil) { // add the legend description label colors.append(nil) labels.append(pds.label) } } else { // all others for (var j = 0; j < clrs.count && j < entryCount; j++) { // if multiple colors are set for a DataSet, group them if (j < clrs.count - 1 && j < entryCount - 1) { labels.append(nil) } else { // add label to the last entry labels.append(dataSet.label) } colors.append(clrs[j]) } } } _legend.colors = colors + _legend._extraColors _legend.labels = labels + _legend._extraLabels } // calculate all dimensions of the legend _legend.calculateDimensions(labelFont: _legend.font, viewPortHandler: viewPortHandler) } public func renderLegend(context context: CGContext?) { if (_legend === nil || !_legend.enabled) { return } let labelFont = _legend.font let labelTextColor = _legend.textColor let labelLineHeight = labelFont.lineHeight let formYOffset = labelLineHeight / 2.0 var labels = _legend.labels var colors = _legend.colors let formSize = _legend.formSize let formToTextSpace = _legend.formToTextSpace let xEntrySpace = _legend.xEntrySpace let direction = _legend.direction // space between the entries let stackSpace = _legend.stackSpace let yoffset = _legend.yOffset let xoffset = _legend.xOffset let legendPosition = _legend.position switch (legendPosition) { case .BelowChartLeft: fallthrough case .BelowChartRight: fallthrough case .BelowChartCenter: let contentWidth: CGFloat = viewPortHandler.contentWidth var originPosX: CGFloat if (legendPosition == .BelowChartLeft) { originPosX = viewPortHandler.contentLeft + xoffset if (direction == .RightToLeft) { originPosX += _legend.neededWidth } } else if (legendPosition == .BelowChartRight) { originPosX = viewPortHandler.contentRight - xoffset if (direction == .LeftToRight) { originPosX -= _legend.neededWidth } } else // if (legendPosition == .BelowChartCenter) { originPosX = viewPortHandler.contentLeft + contentWidth / 2.0 } var calculatedLineSizes = _legend.calculatedLineSizes var calculatedLabelSizes = _legend.calculatedLabelSizes var calculatedLabelBreakPoints = _legend.calculatedLabelBreakPoints var posX: CGFloat = originPosX var posY: CGFloat = viewPortHandler.chartHeight - yoffset - _legend.neededHeight var lineIndex: Int = 0 for (var i = 0, count = labels.count; i < count; i++) { if (calculatedLabelBreakPoints[i]) { posX = originPosX posY += labelLineHeight } if (posX == originPosX && legendPosition == .BelowChartCenter) { posX += (direction == .RightToLeft ? calculatedLineSizes[lineIndex].width : -calculatedLineSizes[lineIndex].width) / 2.0 lineIndex++ } let drawingForm = colors[i] != nil let isStacked = labels[i] == nil; // grouped forms have null labels if (drawingForm) { if (direction == .RightToLeft) { posX -= formSize } drawForm(context, x: posX, y: posY + formYOffset, colorIndex: i, legend: _legend) if (direction == .LeftToRight) { posX += formSize } } if (!isStacked) { if (drawingForm) { posX += direction == .RightToLeft ? -formToTextSpace : formToTextSpace } if (direction == .RightToLeft) { posX -= calculatedLabelSizes[i].width } drawLabel(context, x: posX, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) if (direction == .LeftToRight) { posX += calculatedLabelSizes[i].width } posX += direction == .RightToLeft ? -xEntrySpace : xEntrySpace } else { posX += direction == .RightToLeft ? -stackSpace : stackSpace } } break case .PiechartCenter: fallthrough case .RightOfChart: fallthrough case .RightOfChartCenter: fallthrough case .RightOfChartInside: fallthrough case .LeftOfChart: fallthrough case .LeftOfChartCenter: fallthrough case .LeftOfChartInside: // contains the stacked legend size in pixels var stack = CGFloat(0.0) var wasStacked = false var posX: CGFloat = 0.0, posY: CGFloat = 0.0 if (legendPosition == .PiechartCenter) { posX = viewPortHandler.chartWidth / 2.0 + (direction == .LeftToRight ? -_legend.textWidthMax / 2.0 : _legend.textWidthMax / 2.0) posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0 + _legend.yOffset } else { let isRightAligned = legendPosition == .RightOfChart || legendPosition == .RightOfChartCenter || legendPosition == .RightOfChartInside if (isRightAligned) { posX = viewPortHandler.chartWidth - xoffset if (direction == .LeftToRight) { posX -= _legend.textWidthMax } } else { posX = xoffset if (direction == .RightToLeft) { posX += _legend.textWidthMax } } if (legendPosition == .RightOfChart || legendPosition == .LeftOfChart) { posY = viewPortHandler.contentTop + yoffset } else if (legendPosition == .RightOfChartCenter || legendPosition == .LeftOfChartCenter) { posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0 } else /*if (legend.position == .RightOfChartInside || legend.position == .LeftOfChartInside)*/ { posY = viewPortHandler.contentTop + yoffset } } for (var i = 0; i < labels.count; i++) { let drawingForm = colors[i] != nil var x = posX if (drawingForm) { if (direction == .LeftToRight) { x += stack } else { x -= formSize - stack } drawForm(context, x: x, y: posY + formYOffset, colorIndex: i, legend: _legend) if (direction == .LeftToRight) { x += formSize } } if (labels[i] != nil) { if (drawingForm && !wasStacked) { x += direction == .LeftToRight ? formToTextSpace : -formToTextSpace } else if (wasStacked) { x = posX } if (direction == .RightToLeft) { x -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width } if (!wasStacked) { drawLabel(context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } else { posY += labelLineHeight drawLabel(context, x: x, y: posY, label: labels[i]!, font: labelFont, textColor: labelTextColor) } // make a step down posY += labelLineHeight stack = 0.0 } else { stack += formSize + stackSpace wasStacked = true } } break } } private var _formLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) /// Draws the Legend-form at the given position with the color at the given index. internal func drawForm(context: CGContext?, x: CGFloat, y: CGFloat, colorIndex: Int, legend: ChartLegend) { let formColor = legend.colors[colorIndex] if (formColor === nil || formColor == UIColor.clearColor()) { return } let formsize = legend.formSize CGContextSaveGState(context) switch (legend.form) { case .Circle: CGContextSetFillColorWithColor(context, formColor!.CGColor) CGContextFillEllipseInRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) break case .Square: CGContextSetFillColorWithColor(context, formColor!.CGColor) CGContextFillRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize)) break case .Line: CGContextSetLineWidth(context, legend.formLineWidth) CGContextSetStrokeColorWithColor(context, formColor!.CGColor) _formLineSegmentsBuffer[0].x = x _formLineSegmentsBuffer[0].y = y _formLineSegmentsBuffer[1].x = x + formsize _formLineSegmentsBuffer[1].y = y CGContextStrokeLineSegments(context, _formLineSegmentsBuffer, 2) break } CGContextRestoreGState(context) } /// Draws the provided label at the given position. internal func drawLabel(context: CGContext?, x: CGFloat, y: CGFloat, label: String, font: UIFont, textColor: UIColor) { ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .Left, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor]) } }
mit
bitjammer/swift
test/sil-func-extractor/load-serialized-sil.swift
1
1799
// RUN: %target-swift-frontend -primary-file %s -module-name Swift -g -sil-serialize-all -module-link-name swiftCore -O -parse-as-library -parse-stdlib -emit-module -emit-module-path - -o /dev/null | %target-sil-func-extractor -module-name="Swift" -func="_T0s1XV4testyyF" | %FileCheck %s // RUN: %target-swift-frontend -primary-file %s -module-name Swift -g -O -parse-as-library -parse-stdlib -emit-sib -o - | %target-sil-func-extractor -module-name="Swift" -func="_T0s1XV4testyyF" | %FileCheck %s -check-prefix=SIB-CHECK // CHECK: import Builtin // CHECK: import Swift // CHECK: func unknown() // CHECK: struct X { // CHECK-NEXT: func test() // CHECK-NEXT: init // CHECK-NEXT: } // CHECK: sil @unknown : $@convention(thin) () -> () // CHECK-LABEL: sil hidden [fragile] @_T0s1XV4testyyF : $@convention(method) (X) -> () // CHECK: bb0 // CHECK-NEXT: function_ref // CHECK-NEXT: function_ref @unknown : $@convention(thin) () -> () // CHECK-NEXT: apply // CHECK-NEXT: tuple // CHECK-NEXT: return // CHECK-NOT: sil {{.*}} @_T0s1XVABycfC : $@convention(thin) (@thin X.Type) -> X // SIB-CHECK: import Builtin // SIB-CHECK: import Swift // SIB-CHECK: func unknown() // SIB-CHECK: struct X { // SIB-CHECK-NEXT: func test() // SIB-CHECK-NEXT: init // SIB-CHECK-NEXT: } // SIB-CHECK: sil @unknown : $@convention(thin) () -> () // SIB-CHECK-LABEL: sil hidden @_T0s1XV4testyyF : $@convention(method) (X) -> () // SIB-CHECK: bb0 // SIB-CHECK-NEXT: function_ref // SIB-CHECK-NEXT: function_ref @unknown : $@convention(thin) () -> () // SIB-CHECK-NEXT: apply // SIB-CHECK-NEXT: tuple // SIB-CHECK-NEXT: return // SIB-CHECK-NOT: sil {{.*}} @_T0s1XVABycfC : $@convention(thin) (@thin X.Type) -> X @_silgen_name("unknown") public func unknown() -> () struct X { func test() { unknown() } }
apache-2.0
tiagomartinho/webhose-cocoa
webhose-cocoa/Pods/Quick/Sources/Quick/Example.swift
45
3588
import Foundation private var numberOfExamplesRun = 0 /** Examples, defined with the `it` function, use assertions to demonstrate how code should behave. These are like "tests" in XCTest. */ final public class Example: NSObject { /** A boolean indicating whether the example is a shared example; i.e.: whether it is an example defined with `itBehavesLike`. */ public var isSharedExample = false /** The site at which the example is defined. This must be set correctly in order for Xcode to highlight the correct line in red when reporting a failure. */ public var callsite: Callsite weak internal var group: ExampleGroup? private let internalDescription: String private let closure: () -> Void private let flags: FilterFlags internal init(description: String, callsite: Callsite, flags: FilterFlags, closure: @escaping () -> Void) { self.internalDescription = description self.closure = closure self.callsite = callsite self.flags = flags } public override var description: String { return internalDescription } /** The example name. A name is a concatenation of the name of the example group the example belongs to, followed by the description of the example itself. The example name is used to generate a test method selector to be displayed in Xcode's test navigator. */ public var name: String { guard let groupName = group?.name else { return description } return "\(groupName), \(description)" } /** Executes the example closure, as well as all before and after closures defined in the its surrounding example groups. */ public func run() { let world = World.sharedWorld if numberOfExamplesRun == 0 { world.suiteHooks.executeBefores() } let exampleMetadata = ExampleMetadata(example: self, exampleIndex: numberOfExamplesRun) world.currentExampleMetadata = exampleMetadata world.exampleHooks.executeBefores(exampleMetadata) group!.phase = .beforesExecuting for before in group!.befores { before(exampleMetadata) } group!.phase = .beforesFinished closure() group!.phase = .aftersExecuting for after in group!.afters { after(exampleMetadata) } group!.phase = .aftersFinished world.exampleHooks.executeAfters(exampleMetadata) numberOfExamplesRun += 1 if !world.isRunningAdditionalSuites && numberOfExamplesRun >= world.includedExampleCount { world.suiteHooks.executeAfters() } } /** Evaluates the filter flags set on this example and on the example groups this example belongs to. Flags set on the example are trumped by flags on the example group it belongs to. Flags on inner example groups are trumped by flags on outer example groups. */ internal var filterFlags: FilterFlags { var aggregateFlags = flags for (key, value) in group!.filterFlags { aggregateFlags[key] = value } return aggregateFlags } } extension Example { /** Returns a boolean indicating whether two Example objects are equal. If two examples are defined at the exact same callsite, they must be equal. */ @nonobjc public static func == (lhs: Example, rhs: Example) -> Bool { return lhs.callsite == rhs.callsite } }
mit
bitjammer/swift
test/SILGen/cf.swift
1
4984
// RUN: %target-swift-frontend -import-cf-types -sdk %S/Inputs %s -emit-silgen -o - | %FileCheck %s // REQUIRES: objc_interop import CoreCooling // CHECK: sil hidden @_T02cf8useEmAllySo16CCMagnetismModelCF : // CHECK: bb0([[ARG:%.*]] : $CCMagnetismModel): func useEmAll(_ model: CCMagnetismModel) { // CHECK: function_ref @CCPowerSupplyGetDefault : $@convention(c) () -> @autoreleased Optional<CCPowerSupply> let power = CCPowerSupplyGetDefault() // CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (Optional<CCPowerSupply>) -> Optional<Unmanaged<CCRefrigerator>> let unmanagedFridge = CCRefrigeratorCreate(power) // CHECK: function_ref @CCRefrigeratorSpawn : $@convention(c) (Optional<CCPowerSupply>) -> @owned Optional<CCRefrigerator> let managedFridge = CCRefrigeratorSpawn(power) // CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (Optional<CCRefrigerator>) -> () CCRefrigeratorOpen(managedFridge) // CHECK: function_ref @CCRefrigeratorCopy : $@convention(c) (Optional<CCRefrigerator>) -> @owned Optional<CCRefrigerator> let copy = CCRefrigeratorCopy(managedFridge) // CHECK: function_ref @CCRefrigeratorClone : $@convention(c) (Optional<CCRefrigerator>) -> @autoreleased Optional<CCRefrigerator> let clone = CCRefrigeratorClone(managedFridge) // CHECK: function_ref @CCRefrigeratorDestroy : $@convention(c) (@owned Optional<CCRefrigerator>) -> () CCRefrigeratorDestroy(clone) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.refrigerator!1.foreign : (CCMagnetismModel) -> () -> Unmanaged<CCRefrigerator>!, $@convention(objc_method) (CCMagnetismModel) -> Optional<Unmanaged<CCRefrigerator>> let f0 = model.refrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.getRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator> let f1 = model.getRefrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.takeRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @owned Optional<CCRefrigerator> let f2 = model.takeRefrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.borrowRefrigerator!1.foreign : (CCMagnetismModel) -> () -> CCRefrigerator!, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator> let f3 = model.borrowRefrigerator() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.setRefrigerator!1.foreign : (CCMagnetismModel) -> (CCRefrigerator!) -> (), $@convention(objc_method) (Optional<CCRefrigerator>, CCMagnetismModel) -> () model.setRefrigerator(copy) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $CCMagnetismModel, #CCMagnetismModel.giveRefrigerator!1.foreign : (CCMagnetismModel) -> (CCRefrigerator!) -> (), $@convention(objc_method) (@owned Optional<CCRefrigerator>, CCMagnetismModel) -> () model.giveRefrigerator(copy) // rdar://16846555 let prop: CCRefrigerator = model.fridgeProp } // Ensure that accessors are emitted for fields used as protocol witnesses. protocol Impedance { associatedtype Component var real: Component { get } var imag: Component { get } } extension CCImpedance: Impedance {} // CHECK-LABEL: sil hidden [transparent] [fragile] [thunk] @_T0SC11CCImpedanceV2cf9ImpedanceA2cDP4real9ComponentQzfgTW // CHECK-LABEL: sil shared [transparent] [fragile] @_T0SC11CCImpedanceV4realSdfg // CHECK-LABEL: sil hidden [transparent] [fragile] [thunk] @_T0SC11CCImpedanceV2cf9ImpedanceA2cDP4imag9ComponentQzfgTW // CHECK-LABEL: sil shared [transparent] [fragile] @_T0SC11CCImpedanceV4imagSdfg class MyMagnetism : CCMagnetismModel { // CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC15getRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func getRefrigerator() -> CCRefrigerator { return super.getRefrigerator() } // CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC16takeRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @owned CCRefrigerator override func takeRefrigerator() -> CCRefrigerator { return super.takeRefrigerator() } // CHECK-LABEL: sil hidden [thunk] @_T02cf11MyMagnetismC18borrowRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func borrowRefrigerator() -> CCRefrigerator { return super.borrowRefrigerator() } }
apache-2.0
whiteath/ReadFoundationSource
TestFoundation/TestObjCRuntime.swift
11
1739
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class SwiftClass { class InnerClass {} } struct SwfitStruct {} enum SwiftEnum {} class TestObjCRuntime: XCTestCase { static var allTests: [(String, (TestObjCRuntime) -> () throws -> Void)] { return [ ("testStringFromClass", testStringFromClass), ("testClassFromString", testClassFromString), ] } func testStringFromClass() { XCTAssertEqual(NSStringFromClass(NSObject.self), "NSObject") XCTAssertEqual(NSStringFromClass(SwiftClass.self), "TestFoundation.SwiftClass") #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) XCTAssertEqual(NSStringFromClass(XCTestCase.self), "XCTest.XCTestCase"); #else XCTAssertEqual(NSStringFromClass(XCTestCase.self), "SwiftXCTest.XCTestCase"); #endif } func testClassFromString() { XCTAssertNotNil(NSClassFromString("NSObject")) XCTAssertNotNil(NSClassFromString("TestFoundation.SwiftClass")) XCTAssertNil(NSClassFromString("TestFoundation.SwiftClass.InnerClass")) XCTAssertNil(NSClassFromString("SwiftClass")) XCTAssertNil(NSClassFromString("MadeUpClassName")) XCTAssertNil(NSClassFromString("SwiftStruct")); XCTAssertNil(NSClassFromString("SwiftEnum")); } }
apache-2.0
gregomni/swift
utils/parser-lib/profile-input.swift
9
108227
/* 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 Photos import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire import Account import MobileCoreServices import SDWebImage import SwiftyJSON import Telemetry import Sentry import Deferred private let KVOs: [KVOConstants] = [ .estimatedProgress, .loading, .canGoBack, .canGoForward, .URL, .title, ] private let ActionSheetTitleMaxLength = 120 private struct BrowserViewControllerUX { fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32 fileprivate static let BookmarkStarAnimationDuration: Double = 0.5 fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80 } class BrowserViewController: UIViewController { var homePanelController: (UIViewController & Themeable)? var libraryPanelController: HomePanelViewController? var webViewContainer: UIView! var urlBar: URLBarView! var clipboardBarDisplayHandler: ClipboardBarDisplayHandler? var readerModeBar: ReaderModeBarView? var readerModeCache: ReaderModeCache var statusBarOverlay: UIView! fileprivate(set) var toolbar: TabToolbar? var searchController: SearchViewController? var screenshotHelper: ScreenshotHelper! fileprivate var homePanelIsInline = false fileprivate var searchLoader: SearchLoader? let alertStackView = UIStackView() // All content that appears above the footer should be added to this view. (Find In Page/SnackBars) var findInPageBar: FindInPageBar? lazy var mailtoLinkHandler: MailtoLinkHandler = MailtoLinkHandler() lazy fileprivate var customSearchEngineButton: UIButton = { let searchButton = UIButton() searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: []) searchButton.addTarget(self, action: #selector(addCustomSearchEngineForFocusedElement), for: .touchUpInside) searchButton.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton" return searchButton }() fileprivate var customSearchBarButton: UIBarButtonItem? // popover rotation handling var displayedPopoverController: UIViewController? var updateDisplayedPopoverProperties: (() -> Void)? var openInHelper: OpenInHelper? // location label actions fileprivate var pasteGoAction: AccessibleAction! fileprivate var pasteAction: AccessibleAction! fileprivate var copyAddressAction: AccessibleAction! fileprivate weak var tabTrayController: TabTrayController? let profile: Profile let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them var header: UIView! var footer: UIView! fileprivate var topTouchArea: UIButton! let urlBarTopTabsContainer = UIView(frame: CGRect.zero) var topTabsVisible: Bool { return topTabsViewController != nil } // Backdrop used for displaying greyed background for private tabs var webViewContainerBackdrop: UIView! var scrollController = TabScrollingController() fileprivate var keyboardState: KeyboardState? var pendingToast: Toast? // A toast that might be waiting for BVC to appear before displaying var downloadToast: DownloadToast? // A toast that is showing the combined download progress // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: TabToolbarProtocol { return toolbar ?? urlBar } var topTabsViewController: TopTabsViewController? let topTabsContainer = UIView() // Keep track of allowed `URLRequest`s from `webView(_:decidePolicyFor:decisionHandler:)` so // that we can obtain the originating `URLRequest` when a `URLResponse` is received. This will // allow us to re-trigger the `URLRequest` if the user requests a file to be downloaded. var pendingRequests = [String: URLRequest]() // This is set when the user taps "Download Link" from the context menu. We then force a // download of the next request through the `WKNavigationDelegate` that matches this web view. weak var pendingDownloadWebView: WKWebView? let downloadQueue = DownloadQueue() init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager self.readerModeCache = DiskReaderModeCache.sharedInstance super.init(nibName: nil, bundle: nil) didInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) dismissVisibleMenus() coordinator.animate(alongsideTransition: { context in self.scrollController.updateMinimumZoom() self.topTabsViewController?.scrollToCurrentTab(false, centerCell: false) if let popover = self.displayedPopoverController { self.updateDisplayedPopoverProperties?() self.present(popover, animated: true, completion: nil) } }, completion: { _ in self.scrollController.setMinimumZoom() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } fileprivate func didInit() { screenshotHelper = ScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) downloadQueue.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(displayThemeChanged), name: .DisplayThemeChanged, object: nil) } override var preferredStatusBarStyle: UIStatusBarStyle { return ThemeManager.instance.statusBarStyle } @objc func displayThemeChanged(notification: Notification) { applyTheme() } func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular } func shouldShowTopTabsForTraitCollection(_ newTraitCollection: UITraitCollection) -> Bool { return newTraitCollection.verticalSizeClass == .regular && newTraitCollection.horizontalSizeClass == .regular } func toggleSnackBarVisibility(show: Bool) { if show { UIView.animate(withDuration: 0.1, animations: { self.alertStackView.isHidden = false }) } else { alertStackView.isHidden = true } } fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) { let showToolbar = shouldShowFooterForTraitCollection(newCollection) let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection) urlBar.topTabsIsShowing = showTopTabs urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.tabToolbarDelegate = nil toolbar = nil if showToolbar { toolbar = TabToolbar() footer.addSubview(toolbar!) toolbar?.tabToolbarDelegate = self toolbar?.applyUIMode(isPrivate: tabManager.selectedTab?.isPrivate ?? false) toolbar?.applyTheme() updateTabCountUsingTabManager(self.tabManager) } if showTopTabs { if topTabsViewController == nil { let topTabsViewController = TopTabsViewController(tabManager: tabManager) topTabsViewController.delegate = self addChildViewController(topTabsViewController) topTabsViewController.view.frame = topTabsContainer.frame topTabsContainer.addSubview(topTabsViewController.view) topTabsViewController.view.snp.makeConstraints { make in make.edges.equalTo(topTabsContainer) make.height.equalTo(TopTabsUX.TopTabsViewHeight) } self.topTabsViewController = topTabsViewController topTabsViewController.applyTheme() } topTabsContainer.snp.updateConstraints { make in make.height.equalTo(TopTabsUX.TopTabsViewHeight) } } else { topTabsContainer.snp.updateConstraints { make in make.height.equalTo(0) } topTabsViewController?.view.removeFromSuperview() topTabsViewController?.removeFromParentViewController() topTabsViewController = nil } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab, let webView = tab.webView { updateURLBarDisplayURL(tab) navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) navigationToolbar.updateReloadStatus(tab.loading) } } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) // During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to // set things up. Make sure to only update the toolbar state if the view is ready for it. if isViewLoaded { updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator) } displayedPopoverController?.dismiss(animated: true, completion: nil) coordinator.animate(alongsideTransition: { context in self.scrollController.showToolbars(animated: false) if self.isViewLoaded { self.statusBarOverlay.backgroundColor = self.shouldShowTopTabsForTraitCollection(self.traitCollection) ? UIColor.Photon.Grey80 : self.urlBar.backgroundColor self.setNeedsStatusBarAppearanceUpdate() } }, completion: nil) } func dismissVisibleMenus() { displayedPopoverController?.dismiss(animated: true) if let _ = self.presentedViewController as? PhotonActionSheet { self.presentedViewController?.dismiss(animated: true, completion: nil) } } @objc func appDidEnterBackgroundNotification() { displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } } @objc func tappedTopArea() { scrollController.showToolbars(animated: true) } @objc func appWillResignActiveNotification() { // Dismiss any popovers that might be visible displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } // If we are displying a private tab, hide any elements in the tab that we wouldn't want shown // when the app is in the home switcher guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else { return } webViewContainerBackdrop.alpha = 1 webViewContainer.alpha = 0 urlBar.locationContainer.alpha = 0 topTabsViewController?.switchForegroundStatus(isInForeground: false) presentedViewController?.popoverPresentationController?.containerView?.alpha = 0 presentedViewController?.view.alpha = 0 } @objc func appDidBecomeActiveNotification() { // Re-show any components that might have been hidden because they were being displayed // as part of a private mode tab UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { self.webViewContainer.alpha = 1 self.urlBar.locationContainer.alpha = 1 self.topTabsViewController?.switchForegroundStatus(isInForeground: true) self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1 self.presentedViewController?.view.alpha = 1 self.view.backgroundColor = UIColor.clear }, completion: { _ in self.webViewContainerBackdrop.alpha = 0 }) // Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background) scrollController.showToolbars(animated: false) } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActiveNotification), name: .UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActiveNotification), name: .UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackgroundNotification), name: .UIApplicationDidEnterBackground, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) webViewContainerBackdrop = UIView() webViewContainerBackdrop.backgroundColor = UIColor.Photon.Grey50 webViewContainerBackdrop.alpha = 0 view.addSubview(webViewContainerBackdrop) webViewContainer = UIView() view.addSubview(webViewContainer) // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() view.addSubview(statusBarOverlay) topTouchArea = UIButton() topTouchArea.isAccessibilityElement = false topTouchArea.addTarget(self, action: #selector(tappedTopArea), for: .touchUpInside) view.addSubview(topTouchArea) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.translatesAutoresizingMaskIntoConstraints = false urlBar.delegate = self urlBar.tabToolbarDelegate = self header = urlBarTopTabsContainer urlBarTopTabsContainer.addSubview(urlBar) urlBarTopTabsContainer.addSubview(topTabsContainer) view.addSubview(header) // UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC pasteGoAction = AccessibleAction(name: Strings.PasteAndGoTitle, handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { self.urlBar(self.urlBar, didSubmitText: pasteboardContents) return true } return false }) pasteAction = AccessibleAction(name: Strings.PasteTitle, handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { // Enter overlay mode and make the search controller appear. self.urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true) return true } return false }) copyAddressAction = AccessibleAction(name: Strings.CopyAddressTitle, handler: { () -> Bool in if let url = self.tabManager.selectedTab?.canonicalURL?.displayURL ?? self.urlBar.currentURL { UIPasteboard.general.url = url } return true }) view.addSubview(alertStackView) footer = UIView() view.addSubview(footer) alertStackView.axis = .vertical alertStackView.alignment = .center clipboardBarDisplayHandler = ClipboardBarDisplayHandler(prefs: profile.prefs, tabManager: tabManager) clipboardBarDisplayHandler?.delegate = self scrollController.urlBar = urlBar scrollController.readerModeBar = readerModeBar scrollController.header = header scrollController.footer = footer scrollController.snackBars = alertStackView self.updateToolbarStateForTraitCollection(self.traitCollection) setupConstraints() // Setup UIDropInteraction to handle dragging and dropping // links into the view from other apps. let dropInteraction = UIDropInteraction(delegate: self) view.addInteraction(dropInteraction) } fileprivate func setupConstraints() { topTabsContainer.snp.makeConstraints { make in make.leading.trailing.equalTo(self.header) make.top.equalTo(urlBarTopTabsContainer) } urlBar.snp.makeConstraints { make in make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer) make.height.equalTo(UIConstants.TopToolbarHeight) make.top.equalTo(topTabsContainer.snp.bottom) } header.snp.makeConstraints { make in scrollController.headerTopConstraint = make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint make.left.right.equalTo(self.view) } webViewContainerBackdrop.snp.makeConstraints { make in make.edges.equalTo(webViewContainer) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() statusBarOverlay.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(self.topLayoutGuide.length) } } override var canBecomeFirstResponder: Bool { return true } override func becomeFirstResponder() -> Bool { // Make the web view the first responder so that it can show the selection menu. return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false } func loadQueuedTabs(receivedURLs: [URL]? = nil) { // Chain off of a trivial deferred in order to run on the background queue. succeed().upon() { res in self.dequeueQueuedTabs(receivedURLs: receivedURLs ?? []) } } fileprivate func dequeueQueuedTabs(receivedURLs: [URL]) { assert(!Thread.current.isMainThread, "This must be called in the background.") self.profile.queue.getQueuedTabs() >>== { cursor in // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. if cursor.count > 0 { // Filter out any tabs received by a push notification to prevent dupes. let urls = cursor.compactMap { $0?.url.asURL }.filter { !receivedURLs.contains($0) } if !urls.isEmpty { DispatchQueue.main.async { self.tabManager.addTabsForURLs(urls, zombie: false) } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } // Then, open any received URLs from push notifications. if !receivedURLs.isEmpty { DispatchQueue.main.async { self.tabManager.addTabsForURLs(receivedURLs, zombie: false) if let lastURL = receivedURLs.last, let tab = self.tabManager.getTabForURL(lastURL) { self.tabManager.selectTab(tab) } } } } } // Because crashedLastLaunch is sticky, it does not get reset, we need to remember its // value so that we do not keep asking the user to restore their tabs. var displayedRestoreTabsAlert = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.current.userInterfaceIdiom == .phone { self.view.alpha = (profile.prefs.intForKey(PrefsKeys.IntroSeen) != nil) ? 1.0 : 0.0 } if !displayedRestoreTabsAlert && !cleanlyBackgrounded() && crashedLastLaunch() { displayedRestoreTabsAlert = true showRestoreTabsAlert() } else { tabManager.restoreTabs() } updateTabCountUsingTabManager(tabManager, animated: false) clipboardBarDisplayHandler?.checkIfShouldDisplayBar() } fileprivate func crashedLastLaunch() -> Bool { return Sentry.crashedLastLaunch } fileprivate func cleanlyBackgrounded() -> Bool { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return false } return appDelegate.applicationCleanlyBackgrounded } fileprivate func showRestoreTabsAlert() { guard tabManager.hasTabsToRestoreAtStartup() else { tabManager.selectTab(tabManager.addTab()) return } let alert = UIAlertController.restoreTabsAlert( okayCallback: { _ in self.tabManager.restoreTabs() }, noCallback: { _ in self.tabManager.selectTab(self.tabManager.addTab()) } ) self.present(alert, animated: true, completion: nil) } override func viewDidAppear(_ animated: Bool) { presentIntroViewController() screenshotHelper.viewIsVisible = true screenshotHelper.takePendingScreenshots(tabManager.tabs) super.viewDidAppear(animated) if shouldShowWhatsNewTab() { // Only display if the SUMO topic has been configured in the Info.plist (present and not empty) if let whatsNewTopic = AppInfo.whatsNewTopic, whatsNewTopic != "" { if let whatsNewURL = SupportUtils.URLForTopic(whatsNewTopic) { self.openURLInNewTab(whatsNewURL, isPrivileged: false) profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } } } if let toast = self.pendingToast { self.pendingToast = nil show(toast: toast, afterWaiting: ButtonToastUX.ToastDelay) } showQueuedAlertIfAvailable() } // THe logic for shouldShowWhatsNewTab is as follows: If we do not have the LatestAppVersionProfileKey in // the profile, that means that this is a fresh install and we do not show the What's New. If we do have // that value, we compare it to the major version of the running app. If it is different then this is an // upgrade, downgrades are not possible, so we can show the What's New page. fileprivate func shouldShowWhatsNewTab() -> Bool { guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else { return false // Clean install, never show What's New } return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity() } fileprivate func showQueuedAlertIfAvailable() { if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() { let alertController = queuedAlertInfo.alertController() alertController.delegate = self present(alertController, animated: true, completion: nil) } } override func viewWillDisappear(_ animated: Bool) { screenshotHelper.viewIsVisible = false super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } func resetBrowserChrome() { // animate and reset transform for tab chrome urlBar.updateAlphaForSubviews(1) footer.alpha = 1 [header, footer, readerModeBar].forEach { view in view?.transform = .identity } statusBarOverlay.isHidden = false } override func updateViewConstraints() { super.updateViewConstraints() topTouchArea.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } readerModeBar?.snp.remakeConstraints { make in make.top.equalTo(self.header.snp.bottom) make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } webViewContainer.snp.remakeConstraints { make in make.left.right.equalTo(self.view) if let readerModeBarBottom = readerModeBar?.snp.bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp.bottom) } let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight) } else { make.bottom.equalTo(self.view).offset(-findInPageHeight) } } // Setup the bottom toolbar toolbar?.snp.remakeConstraints { make in make.edges.equalTo(self.footer) make.height.equalTo(UIConstants.BottomToolbarHeight) } footer.snp.remakeConstraints { make in scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint make.leading.trailing.equalTo(self.view) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp.remakeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp.top ?? self.view.snp.bottom) } else { make.bottom.equalTo(self.view.snp.bottom) } } alertStackView.snp.remakeConstraints { make in make.centerX.equalTo(self.view) make.width.equalTo(self.view.safeArea.width) if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 { make.bottom.equalTo(self.view).offset(-keyboardHeight) } else if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top) make.bottom.lessThanOrEqualTo(self.view.safeArea.bottom) } else { make.bottom.equalTo(self.view) } } } fileprivate func showHomePanelController(inline: Bool) { homePanelIsInline = inline if homePanelController == nil { var homePanelVC: (UIViewController & HomePanel)? let currentChoice = NewTabAccessors.getNewTabPage(self.profile.prefs) switch currentChoice { case .topSites: homePanelVC = ActivityStreamPanel(profile: profile) case .bookmarks: homePanelVC = BookmarksPanel(profile: profile) case .history: homePanelVC = HistoryPanel(profile: profile) case .readingList: homePanelVC = ReadingListPanel(profile: profile) default: break } if let vc = homePanelVC { let navController = ThemedNavigationController(rootViewController: vc) navController.setNavigationBarHidden(true, animated: false) navController.interactivePopGestureRecognizer?.delegate = nil navController.view.alpha = 0 self.homePanelController = navController vc.homePanelDelegate = self addChildViewController(navController) view.addSubview(navController.view) vc.didMove(toParentViewController: self) } } guard let homePanelController = self.homePanelController else { return } homePanelController.applyTheme() // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animate(withDuration: 0.2, animations: { () -> Void in homePanelController.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) view.setNeedsUpdateConstraints() } fileprivate func hideHomePanelController() { if let controller = homePanelController { self.homePanelController = nil UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { _ in controller.willMove(toParentViewController: nil) controller.view.removeFromSuperview() controller.removeFromParentViewController() self.webViewContainer.accessibilityElementsHidden = false UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getContentScript(name: ReaderMode.name()) as? ReaderMode, readerMode.state == .active { self.showReaderModeBar(animated: false) } }) } } fileprivate func updateInContentHomePanel(_ url: URL?) { if !urlBar.inOverlayMode { guard let url = url else { hideHomePanelController() return } if url.isAboutHomeURL { showHomePanelController(inline: true) } else if url.isErrorPageURL || !url.isLocalUtility || url.isReaderModeURL { hideHomePanelController() } } else if url?.isAboutHomeURL ?? false { showHomePanelController(inline: false) } } fileprivate func showSearchController() { if searchController != nil { return } let isPrivate = tabManager.selectedTab?.isPrivate ?? false searchController = SearchViewController(profile: profile, isPrivate: isPrivate) searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchLoader = SearchLoader(profile: profile, urlBar: urlBar) searchLoader?.addListener(searchController!) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp.makeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.isHidden = true searchController!.didMove(toParentViewController: self) } fileprivate func hideSearchController() { if let searchController = searchController { searchController.willMove(toParentViewController: nil) searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.isHidden = false searchLoader = nil } } func finishEditingAndSubmit(_ url: URL, visitType: VisitType, forTab tab: Tab) { urlBar.currentURL = url urlBar.leaveOverlayMode() if let webView = tab.webView { resetSpoofedUserAgentIfRequired(webView, newURL: url) } if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(_ tabState: TabState) { guard let url = tabState.url else { return } let absoluteString = url.absoluteString let shareItem = ShareItem(url: absoluteString, title: tabState.title, favicon: tabState.favicon) _ = profile.bookmarks.shareItem(shareItem) var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark, withUserData: userData, toApplication: UIApplication.shared) } override func accessibilityPerformEscape() -> Bool { if urlBar.inOverlayMode { urlBar.didClickCancel() return true } else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack { selectedTab.goBack() return true } return false } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let webView = object as? WKWebView else { assert(false) return } guard let kp = keyPath, let path = KVOConstants(rawValue: kp) else { assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") return } switch path { case .estimatedProgress: guard webView == tabManager.selectedTab?.webView else { break } if !(webView.url?.isLocalUtility ?? false) { urlBar.updateProgressBar(Float(webView.estimatedProgress)) // Profiler.end triggers a screenshot, and a delay is needed here to capture the correct screen // (otherwise the screen prior to this step completing is captured). if webView.estimatedProgress > 0.9 { Profiler.shared?.end(bookend: .load_url, delay: 0.200) } } else { urlBar.hideProgressBar() } case .loading: guard let loading = change?[.newKey] as? Bool else { break } if webView == tabManager.selectedTab?.webView { navigationToolbar.updateReloadStatus(loading) } if !loading { runScriptsOnWebView(webView) } case .URL: guard let tab = tabManager[webView] else { break } // To prevent spoofing, only change the URL immediately if the new URL is on // the same origin as the current URL. Otherwise, do nothing and wait for // didCommitNavigation to confirm the page load. if tab.url?.origin == webView.url?.origin { tab.url = webView.url if tab === tabManager.selectedTab && !tab.restoring { updateUIForReaderHomeStateForTab(tab) } } case .title: guard let tab = tabManager[webView] else { break } // Ensure that the tab title *actually* changed to prevent repeated calls // to navigateInTab(tab:). guard let title = tab.title else { break } if !title.isEmpty && title != tab.lastTitle { navigateInTab(tab: tab) } case .canGoBack: guard webView == tabManager.selectedTab?.webView, let canGoBack = change?[.newKey] as? Bool else { break } navigationToolbar.updateBackStatus(canGoBack) case .canGoForward: guard webView == tabManager.selectedTab?.webView, let canGoForward = change?[.newKey] as? Bool else { break } navigationToolbar.updateForwardStatus(canGoForward) default: assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") } } fileprivate func runScriptsOnWebView(_ webView: WKWebView) { guard let url = webView.url, url.isWebPage(), !url.isLocal else { return } if NoImageModeHelper.isActivated(profile.prefs) { webView.evaluateJavaScript("__firefox__.NoImageMode.setEnabled(true)", completionHandler: nil) } } func updateUIForReaderHomeStateForTab(_ tab: Tab) { updateURLBarDisplayURL(tab) scrollController.showToolbars(animated: false) if let url = tab.url { if url.isReaderModeURL { showReaderModeBar(animated: false) NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil) } else { hideReaderModeBar(animated: false) NotificationCenter.default.removeObserver(self, name: .DynamicFontChanged, object: nil) } updateInContentHomePanel(url as URL) } } /// Updates the URL bar text and button states. /// Call this whenever the page URL changes. fileprivate func updateURLBarDisplayURL(_ tab: Tab) { urlBar.currentURL = tab.url?.displayURL let isPage = tab.url?.displayURL?.isWebPage() ?? false navigationToolbar.updatePageStatus(isPage) } // MARK: Opening New Tabs func switchToPrivacyMode(isPrivate: Bool) { if let tabTrayController = self.tabTrayController, tabTrayController.tabDisplayManager.isPrivate != isPrivate { tabTrayController.changePrivacyMode(isPrivate) } topTabsViewController?.applyUIMode(isPrivate: isPrivate) } func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false, isPrivileged: Bool) { popToBVC() if let tab = tabManager.getTabForURL(url) { tabManager.selectTab(tab) } else { openURLInNewTab(url, isPrivate: isPrivate, isPrivileged: isPrivileged) } } func openURLInNewTab(_ url: URL?, isPrivate: Bool = false, isPrivileged: Bool) { if let selectedTab = tabManager.selectedTab { screenshotHelper.takeScreenshot(selectedTab) } let request: URLRequest? if let url = url { request = isPrivileged ? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url) } else { request = nil } switchToPrivacyMode(isPrivate: isPrivate) tabManager.selectTab(tabManager.addTab(request, isPrivate: isPrivate)) } func focusLocationTextField(forTab tab: Tab?, setSearchText searchText: String? = nil) { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) { // Without a delay, the text field fails to become first responder // Check that the newly created tab is still selected. // This let's the user spam the Cmd+T button without lots of responder changes. guard tab == self.tabManager.selectedTab else { return } self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView) if let text = searchText { self.urlBar.setLocation(text, search: true) } } } func openBlankNewTab(focusLocationField: Bool, isPrivate: Bool = false, searchFor searchText: String? = nil) { popToBVC() openURLInNewTab(nil, isPrivate: isPrivate, isPrivileged: true) let freshTab = tabManager.selectedTab if focusLocationField { focusLocationTextField(forTab: freshTab, setSearchText: searchText) } } func openSearchNewTab(isPrivate: Bool = false, _ text: String) { popToBVC() let engine = profile.searchEngines.defaultEngine if let searchURL = engine.searchURLForQuery(text) { openURLInNewTab(searchURL, isPrivate: isPrivate, isPrivileged: true) } else { // We still don't have a valid URL, so something is broken. Give up. print("Error handling URL entry: \"\(text)\".") assertionFailure("Couldn't generate search URL: \(text)") } } fileprivate func popToBVC() { guard let currentViewController = navigationController?.topViewController else { return } currentViewController.dismiss(animated: true, completion: nil) if currentViewController != self { _ = self.navigationController?.popViewController(animated: true) } else if urlBar.inOverlayMode { urlBar.didClickCancel() } } // MARK: User Agent Spoofing func resetSpoofedUserAgentIfRequired(_ webView: WKWebView, newURL: URL) { // Reset the UA when a different domain is being loaded if webView.url?.host != newURL.host { webView.customUserAgent = nil } } func restoreSpoofedUserAgentIfRequired(_ webView: WKWebView, newRequest: URLRequest) { // Restore any non-default UA from the request's header let ua = newRequest.value(forHTTPHeaderField: "User-Agent") webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil } fileprivate func presentActivityViewController(_ url: URL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) { let helper = ShareExtensionHelper(url: url, tab: tab) let controller = helper.createActivityViewController({ [unowned self] completed, _ in // After dismissing, check to see if there were any prompts we queued up self.showQueuedAlertIfAvailable() // Usually the popover delegate would handle nil'ing out the references we have to it // on the BVC when displaying as a popover but the delegate method doesn't seem to be // invoked on iOS 10. See Bug 1297768 for additional details. self.displayedPopoverController = nil self.updateDisplayedPopoverProperties = nil }) if let popoverPresentationController = controller.popoverPresentationController { popoverPresentationController.sourceView = sourceView popoverPresentationController.sourceRect = sourceRect popoverPresentationController.permittedArrowDirections = arrowDirection popoverPresentationController.delegate = self } present(controller, animated: true, completion: nil) LeanPlumClient.shared.track(event: .userSharedWebpage) } @objc fileprivate func openSettings() { assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread") let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager settingsTableViewController.settingsDelegate = self let controller = ThemedNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self controller.modalPresentationStyle = .formSheet self.present(controller, animated: true, completion: nil) } fileprivate func postLocationChangeNotificationForTab(_ tab: Tab, navigation: WKNavigation?) { let notificationCenter = NotificationCenter.default var info = [AnyHashable: Any]() info["url"] = tab.url?.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } info["isPrivate"] = tab.isPrivate notificationCenter.post(name: .OnLocationChange, object: self, userInfo: info) } func navigateInTab(tab: Tab, to navigation: WKNavigation? = nil) { tabManager.expireSnackbars() guard let webView = tab.webView else { print("Cannot navigate in tab without a webView") return } if let url = webView.url { if !url.isErrorPageURL, !url.isAboutHomeURL, !url.isFileURL { postLocationChangeNotificationForTab(tab, navigation: navigation) // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("\(ReaderModeNamespace).checkReadability()", completionHandler: nil) // Re-run additional scripts in webView to extract updated favicons and metadata. runScriptsOnWebView(webView) } TabEvent.post(.didChangeURL(url), for: tab) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } else if let webView = tab.webView { // To Screenshot a tab that is hidden we must add the webView, // then wait enough time for the webview to render. view.insertSubview(webView, at: 0) // This is kind of a hacky fix for Bug 1476637 to prevent webpages from focusing the // touch-screen keyboard from the background even though they shouldn't be able to. webView.resignFirstResponder() DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { self.screenshotHelper.takeScreenshot(tab) if webView.superview == self.view { webView.removeFromSuperview() } } } // Remember whether or not a desktop site was requested tab.desktopSite = webView.customUserAgent?.isEmpty == false } } extension BrowserViewController: ClipboardBarDisplayHandlerDelegate { func shouldDisplay(clipboardBar bar: ButtonToast) { show(toast: bar, duration: ClipboardBarToastUX.ToastDelay) } } extension BrowserViewController: QRCodeViewControllerDelegate { func didScanQRCodeWithURL(_ url: URL) { guard let tab = tabManager.selectedTab else { return } openBlankNewTab(focusLocationField: false) finishEditingAndSubmit(url, visitType: VisitType.typed, forTab: tab) UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeURL) } func didScanQRCodeWithText(_ text: String) { guard let tab = tabManager.selectedTab else { return } openBlankNewTab(focusLocationField: false) submitSearchText(text, forTab: tab) UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeText) } } extension BrowserViewController: SettingsDelegate { func settingsOpenURLInNewTab(_ url: URL) { self.openURLInNewTab(url, isPrivileged: false) } } extension BrowserViewController: PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) { self.dismiss(animated: animated, completion: nil) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(_ tab: Tab, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(_ tab: Tab, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(_ tab: Tab, navigation: WKNavigation?) -> VisitType? { guard let navigation = navigation else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.link } if let _ = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValue(forKey: navigation) ?? VisitType.link } } extension BrowserViewController: URLBarDelegate { func showTabTray() { Sentry.shared.clearBreadcrumbs() updateFindInPageVisibility(visible: false) let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) if let tab = tabManager.selectedTab { screenshotHelper.takeScreenshot(tab) } navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController } func urlBarDidPressReload(_ urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressQRButton(_ urlBar: URLBarView) { let qrCodeViewController = QRCodeViewController() qrCodeViewController.qrCodeDelegate = self let controller = QRCodeNavigationController(rootViewController: qrCodeViewController) self.present(controller, animated: true, completion: nil) } func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab, let urlString = tab.url?.absoluteString, !urlBar.inOverlayMode else { return } let actionMenuPresenter: (URL, Tab, UIView, UIPopoverArrowDirection) -> Void = { (url, tab, view, _) in self.presentActivityViewController(url, tab: tab, sourceView: view, sourceRect: view.bounds, arrowDirection: .up) } let findInPageAction = { self.updateFindInPageVisibility(visible: true) } let successCallback: (String) -> Void = { (successMessage) in SimpleToast().showAlertWithText(successMessage, bottomContainer: self.webViewContainer) } let deferredBookmarkStatus: Deferred<Maybe<Bool>> = fetchBookmarkStatus(for: urlString) let deferredPinnedTopSiteStatus: Deferred<Maybe<Bool>> = fetchPinnedTopSiteStatus(for: urlString) // Wait for both the bookmark status and the pinned status deferredBookmarkStatus.both(deferredPinnedTopSiteStatus).uponQueue(.main) { let isBookmarked = $0.successValue ?? false let isPinned = $1.successValue ?? false let pageActions = self.getTabActions(tab: tab, buttonView: button, presentShareMenu: actionMenuPresenter, findInPage: findInPageAction, presentableVC: self, isBookmarked: isBookmarked, isPinned: isPinned, success: successCallback) self.presentSheetWith(title: Strings.PageActionMenuTitle, actions: pageActions, on: self, from: button) } } func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab else { return } guard let url = tab.canonicalURL?.displayURL, self.presentedViewController == nil else { return } let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() presentActivityViewController(url, tab: tab, sourceView: button, sourceRect: button.bounds, arrowDirection: .up) } func urlBarDidTapShield(_ urlBar: URLBarView, from button: UIButton) { if let tab = self.tabManager.selectedTab { let trackingProtectionMenu = self.getTrackingSubMenu(for: tab) guard !trackingProtectionMenu.isEmpty else { return } self.presentSheetWith(actions: trackingProtectionMenu, on: self, from: urlBar) } } func urlBarDidPressStop(_ urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(_ urlBar: URLBarView) { showTabTray() } func urlBarDidPressReaderMode(_ urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getContentScript(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .available: enableReaderMode() UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeOpenButton) LeanPlumClient.shared.track(event: .useReaderView) case .active: disableReaderMode() UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeCloseButton) case .unavailable: break } } } } func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool { guard let tab = tabManager.selectedTab, let url = tab.url?.displayURL else { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed.")) return false } let result = profile.readingList.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) switch result.value { case .success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action.")) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it’s already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures.")) print("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)") } return true } func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.general.string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool) { // use the initial value for the URL so we can do proper pattern matching with search URLs var searchURL = self.tabManager.selectedTab?.currentInitialURL if searchURL?.isErrorPageURL ?? true { searchURL = url } if let query = profile.searchEngines.queryForSearchURL(searchURL as URL?) { return (query, true) } else { return (url?.absoluteString, false) } } func urlBarDidLongPressLocation(_ urlBar: URLBarView) { let urlActions = self.getLongPressLocationBarActions(with: urlBar) let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() if let tab = self.tabManager.selectedTab { let trackingProtectionMenu = self.getTrackingMenu(for: tab, presentingOn: urlBar) self.presentSheetWith(actions: [urlActions, trackingProtectionMenu], on: self, from: urlBar) } else { self.presentSheetWith(actions: [urlActions], on: self, from: urlBar) } } func urlBarDidPressScrollToTop(_ urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab, homePanelController == nil { // Only scroll to top if we are not showing the home view controller selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true) } } func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(_ urlBar: URLBarView, didEnterText text: String) { if text.isEmpty { hideSearchController() } else { showSearchController() searchController?.searchQuery = text searchLoader?.query = text } } func urlBar(_ urlBar: URLBarView, didSubmitText text: String) { guard let currentTab = tabManager.selectedTab else { return } if let fixupURL = URIFixup.getURL(text) { // The user entered a URL, so use it. finishEditingAndSubmit(fixupURL, visitType: VisitType.typed, forTab: currentTab) return } // We couldn't build a URL, so check for a matching search keyword. let trimmedText = text.trimmingCharacters(in: .whitespaces) guard let possibleKeywordQuerySeparatorSpace = trimmedText.index(of: " ") else { submitSearchText(text, forTab: currentTab) return } let possibleKeyword = String(trimmedText[..<possibleKeywordQuerySeparatorSpace]) let possibleQuery = String(trimmedText[trimmedText.index(after: possibleKeywordQuerySeparatorSpace)...]) profile.bookmarks.getURLForKeywordSearch(possibleKeyword).uponQueue(.main) { result in if var urlString = result.successValue, let escapedQuery = possibleQuery.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed), let range = urlString.range(of: "%s") { urlString.replaceSubrange(range, with: escapedQuery) if let url = URL(string: urlString) { self.finishEditingAndSubmit(url, visitType: VisitType.typed, forTab: currentTab) return } } self.submitSearchText(text, forTab: currentTab) } } fileprivate func submitSearchText(_ text: String, forTab tab: Tab) { let engine = profile.searchEngines.defaultEngine if let searchURL = engine.searchURLForQuery(text) { // We couldn't find a matching search keyword, so do a search query. Telemetry.default.recordSearch(location: .actionBar, searchEngine: engine.engineID ?? "other") finishEditingAndSubmit(searchURL, visitType: VisitType.typed, forTab: tab) } else { // We still don't have a valid URL, so something is broken. Give up. print("Error handling URL entry: \"\(text)\".") assertionFailure("Couldn't generate search URL: \(text)") } } func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) { guard let profile = profile as? BrowserProfile else { return } if .blankPage == NewTabAccessors.getNewTabPage(profile.prefs) { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } else { if let toast = clipboardBarDisplayHandler?.clipboardToast { toast.removeFromSuperview() } showHomePanelController(inline: false) } LeanPlumClient.shared.track(event: .interactWithURLBar) } func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url as URL?) } func urlBarDidBeginDragInteraction(_ urlBar: URLBarView) { dismissVisibleMenus() } } extension BrowserViewController: TabToolbarDelegate, PhotonActionSheetProtocol { func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() showBackForwardList() } func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard let tab = tabManager.selectedTab else { return } let urlActions = self.getRefreshLongPressMenu(for: tab) guard !urlActions.isEmpty else { return } let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: [urlActions], on: self, from: button, suppressPopover: shouldSuppress) } func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() showBackForwardList() } func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) { // ensure that any keyboards or spinners are dismissed before presenting the menu UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) var actions: [[PhotonActionSheetItem]] = [] if let syncAction = syncMenuButton(showFxA: presentSignInViewController) { actions.append(syncAction) } actions.append(getLibraryActions(vcDelegate: self)) actions.append(getOtherPanelActions(vcDelegate: self)) // force a modal if the menu is being displayed in compact split screen let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: actions, on: self, from: button, suppressPopover: shouldSuppress) } func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showTabTray() } func getTabToolbarLongPressActionsForModeSwitching() -> [PhotonActionSheetItem] { guard let selectedTab = tabManager.selectedTab else { return [] } let count = selectedTab.isPrivate ? tabManager.normalTabs.count : tabManager.privateTabs.count let infinity = "\u{221E}" let tabCount = (count < 100) ? count.description : infinity func action() { let result = tabManager.switchPrivacyMode() if result == .createdNewTab, NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage { focusLocationTextField(forTab: tabManager.selectedTab) } } let privateBrowsingMode = PhotonActionSheetItem(title: Strings.privateBrowsingModeTitle, iconString: "nav-tabcounter", iconType: .TabsButton, tabCount: tabCount) { _ in action() } let normalBrowsingMode = PhotonActionSheetItem(title: Strings.normalBrowsingModeTitle, iconString: "nav-tabcounter", iconType: .TabsButton, tabCount: tabCount) { _ in action() } if let tab = self.tabManager.selectedTab { return tab.isPrivate ? [normalBrowsingMode] : [privateBrowsingMode] } return [privateBrowsingMode] } func getMoreTabToolbarLongPressActions() -> [PhotonActionSheetItem] { let newTab = PhotonActionSheetItem(title: Strings.NewTabTitle, iconString: "quick_action_new_tab", iconType: .Image) { action in let shouldFocusLocationField = NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage self.openBlankNewTab(focusLocationField: shouldFocusLocationField, isPrivate: false)} let newPrivateTab = PhotonActionSheetItem(title: Strings.NewPrivateTabTitle, iconString: "quick_action_new_tab", iconType: .Image) { action in let shouldFocusLocationField = NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage self.openBlankNewTab(focusLocationField: shouldFocusLocationField, isPrivate: true)} let closeTab = PhotonActionSheetItem(title: Strings.CloseTabTitle, iconString: "tab_close", iconType: .Image) { action in if let tab = self.tabManager.selectedTab { self.tabManager.removeTabAndUpdateSelectedIndex(tab) self.updateTabCountUsingTabManager(self.tabManager) }} if let tab = self.tabManager.selectedTab { return tab.isPrivate ? [newPrivateTab, closeTab] : [newTab, closeTab] } return [newTab, closeTab] } func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard self.presentedViewController == nil else { return } var actions: [[PhotonActionSheetItem]] = [] actions.append(getTabToolbarLongPressActionsForModeSwitching()) actions.append(getMoreTabToolbarLongPressActions()) // Force a modal if the menu is being displayed in compact split screen. let shouldSuppress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() presentSheetWith(actions: actions, on: self, from: button, suppressPopover: shouldSuppress) } func showBackForwardList() { if let backForwardList = tabManager.selectedTab?.webView?.backForwardList { let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList) backForwardViewController.tabManager = tabManager backForwardViewController.bvc = self backForwardViewController.modalPresentationStyle = .overCurrentContext backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator() self.present(backForwardViewController, animated: true, completion: nil) } } } extension BrowserViewController: TabDelegate { func tab(_ tab: Tab, didCreateWebView webView: WKWebView) { webView.frame = webViewContainer.frame // Observers that live as long as the tab. Make sure these are all cleared in willDeleteWebView below! KVOs.forEach { webView.addObserver(self, forKeyPath: $0.rawValue, options: .new, context: nil) } webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue, options: .new, context: nil) webView.uiDelegate = self let formPostHelper = FormPostHelper(tab: tab) tab.addContentScript(formPostHelper, name: FormPostHelper.name()) let readerMode = ReaderMode(tab: tab) readerMode.delegate = self tab.addContentScript(readerMode, name: ReaderMode.name()) // only add the logins helper if the tab is not a private browsing tab if !tab.isPrivate { let logins = LoginsHelper(tab: tab, profile: profile) tab.addContentScript(logins, name: LoginsHelper.name()) } let contextMenuHelper = ContextMenuHelper(tab: tab) contextMenuHelper.delegate = self tab.addContentScript(contextMenuHelper, name: ContextMenuHelper.name()) let errorHelper = ErrorPageHelper() tab.addContentScript(errorHelper, name: ErrorPageHelper.name()) let sessionRestoreHelper = SessionRestoreHelper(tab: tab) sessionRestoreHelper.delegate = self tab.addContentScript(sessionRestoreHelper, name: SessionRestoreHelper.name()) let findInPageHelper = FindInPageHelper(tab: tab) findInPageHelper.delegate = self tab.addContentScript(findInPageHelper, name: FindInPageHelper.name()) let noImageModeHelper = NoImageModeHelper(tab: tab) tab.addContentScript(noImageModeHelper, name: NoImageModeHelper.name()) let downloadContentScript = DownloadContentScript(tab: tab) tab.addContentScript(downloadContentScript, name: DownloadContentScript.name()) let printHelper = PrintHelper(tab: tab) tab.addContentScript(printHelper, name: PrintHelper.name()) let customSearchHelper = CustomSearchHelper(tab: tab) tab.addContentScript(customSearchHelper, name: CustomSearchHelper.name()) let nightModeHelper = NightModeHelper(tab: tab) tab.addContentScript(nightModeHelper, name: NightModeHelper.name()) // XXX: Bug 1390200 - Disable NSUserActivity/CoreSpotlight temporarily // let spotlightHelper = SpotlightHelper(tab: tab) // tab.addHelper(spotlightHelper, name: SpotlightHelper.name()) tab.addContentScript(LocalRequestHelper(), name: LocalRequestHelper.name()) let historyStateHelper = HistoryStateHelper(tab: tab) historyStateHelper.delegate = self tab.addContentScript(historyStateHelper, name: HistoryStateHelper.name()) let blocker = FirefoxTabContentBlocker(tab: tab, prefs: profile.prefs) tab.contentBlocker = blocker tab.addContentScript(blocker, name: FirefoxTabContentBlocker.name()) tab.addContentScript(FocusHelper(tab: tab), name: FocusHelper.name()) } func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) { tab.cancelQueuedAlerts() KVOs.forEach { webView.removeObserver(self, forKeyPath: $0.rawValue) } webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue) webView.uiDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } fileprivate func findSnackbar(_ barToFind: SnackBar) -> Int? { let bars = alertStackView.arrangedSubviews for (index, bar) in bars.enumerated() where bar === barToFind { return index } return nil } func showBar(_ bar: SnackBar, animated: Bool) { view.layoutIfNeeded() UIView.animate(withDuration: animated ? 0.25 : 0, animations: { self.alertStackView.insertArrangedSubview(bar, at: 0) self.view.layoutIfNeeded() }) } func removeBar(_ bar: SnackBar, animated: Bool) { UIView.animate(withDuration: animated ? 0.25 : 0, animations: { bar.removeFromSuperview() }) } func removeAllBars() { alertStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } } func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) { updateFindInPageVisibility(visible: true) findInPageBar?.text = selection } func tab(_ tab: Tab, didSelectSearchWithFirefoxForSelection selection: String) { openSearchNewTab(isPrivate: tab.isPrivate, selection) } } extension BrowserViewController: HomePanelDelegate { func homePanelDidRequestToSignIn() { let fxaParams = FxALaunchParams(query: ["entrypoint": "homepanel"]) presentSignInViewController(fxaParams) // TODO UX Right now the flow for sign in and create account is the same } func homePanelDidRequestToCreateAccount() { let fxaParams = FxALaunchParams(query: ["entrypoint": "homepanel"]) presentSignInViewController(fxaParams) // TODO UX Right now the flow for sign in and create account is the same } func homePanel(didSelectURL url: URL, visitType: VisitType) { guard let tab = tabManager.selectedTab else { return } finishEditingAndSubmit(url, visitType: visitType, forTab: tab) } func homePanel(didSelectURLString url: String, visitType: VisitType) { guard let url = URIFixup.getURL(url) ?? profile.searchEngines.defaultEngine.searchURLForQuery(url) else { Logger.browserLogger.warning("Invalid URL, and couldn't generate a search URL for it.") return } return self.homePanel(didSelectURL: url, visitType: visitType) } func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) { let tab = self.tabManager.addTab(PrivilegedRequest(url: url) as URLRequest, afterTab: self.tabManager.selectedTab, isPrivate: isPrivate) // If we are showing toptabs a user can just use the top tab bar // If in overlay mode switching doesnt correctly dismiss the homepanels guard !topTabsVisible, !self.urlBar.inOverlayMode else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(toast: toast) } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) { guard let tab = tabManager.selectedTab else { return } finishEditingAndSubmit(url, visitType: VisitType.typed, forTab: tab) } func searchViewController(_ searchViewController: SearchViewController, didLongPressSuggestion suggestion: String) { self.urlBar.setLocation(suggestion, search: true) } func presentSearchSettingsController() { let ThemedNavigationController = SearchSettingsTableViewController() ThemedNavigationController.model = self.profile.searchEngines ThemedNavigationController.profile = self.profile let navController = ModalSettingsNavigationController(rootViewController: ThemedNavigationController) self.present(navController, animated: true, completion: nil) } func searchViewController(_ searchViewController: SearchViewController, didHighlightText text: String, search: Bool) { self.urlBar.setLocation(text, search: search) } } extension BrowserViewController: TabManagerDelegate { func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?, isRestoring: Bool) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { wv.endEditing(true) wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil wv.removeFromSuperview() } if let tab = selected, let webView = tab.webView { updateURLBarDisplayURL(tab) if previous == nil || tab.isPrivate != previous?.isPrivate { applyTheme() let ui: [PrivateModeUI?] = [toolbar, topTabsViewController, urlBar] ui.forEach { $0?.applyUIMode(isPrivate: tab.isPrivate) } } readerModeCache = tab.isPrivate ? MemoryReaderModeCache.sharedInstance : DiskReaderModeCache.sharedInstance if let privateModeButton = topTabsViewController?.privateModeButton, previous != nil && previous?.isPrivate != tab.isPrivate { privateModeButton.setSelected(tab.isPrivate, animated: true) } ReaderModeHandlers.readerModeCache = readerModeCache scrollController.tab = selected webViewContainer.addSubview(webView) webView.snp.makeConstraints { make in make.left.right.top.bottom.equalTo(self.webViewContainer) } webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false if webView.url == nil { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. tab.reload() } } updateTabCountUsingTabManager(tabManager) removeAllBars() if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } updateFindInPageVisibility(visible: false, tab: previous) navigationToolbar.updateReloadStatus(selected?.loading ?? false) navigationToolbar.updateBackStatus(selected?.canGoBack ?? false) navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false) if !(selected?.webView?.url?.isLocalUtility ?? false) { self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) } if let readerMode = selected?.getContentScript(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.unavailable) } if topTabsVisible { topTabsDidChangeTab() } updateInContentHomePanel(selected?.url as URL?) if let tab = selected, tab.url == nil, !tab.restoring, NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage { self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView) } } func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) { } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab, isRestoring: Bool) { // If we are restoring tabs then we update the count once at the end if !isRestoring { updateTabCountUsingTabManager(tabManager) } tab.tabDelegate = self } func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) { if let url = tab.url, !url.isAboutURL && !tab.isPrivate { profile.recentlyClosedTabs.addTab(url as URL, title: tab.title, faviconURL: tab.displayFavicon?.url) } } func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab, isRestoring: Bool) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidAddTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func show(toast: Toast, afterWaiting delay: DispatchTimeInterval = SimpleToastUX.ToastDelayBefore, duration: DispatchTimeInterval? = SimpleToastUX.ToastDismissAfter) { if let downloadToast = toast as? DownloadToast { self.downloadToast = downloadToast } // If BVC isnt visible hold on to this toast until viewDidAppear if self.view.window == nil { self.pendingToast = toast return } toast.showToast(viewController: self, delay: delay, duration: duration, makeConstraints: { make in make.left.right.equalTo(self.view) make.bottom.equalTo(self.webViewContainer?.safeArea.bottom ?? 0) }) } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { guard let toast = toast, !(tabTrayController?.tabDisplayManager.isPrivate ?? false) else { return } show(toast: toast, afterWaiting: ButtonToastUX.ToastDelay) } fileprivate func updateTabCountUsingTabManager(_ tabManager: TabManager, animated: Bool = true) { if let selectedTab = tabManager.selectedTab { let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count toolbar?.updateTabCount(count, animated: animated) urlBar.updateTabCount(count, animated: !urlBar.inOverlayMode) topTabsViewController?.updateTabCount(count, animated: animated) } } } // MARK: - UIPopoverPresentationControllerDelegate extension BrowserViewController: UIPopoverPresentationControllerDelegate { func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { displayedPopoverController = nil updateDisplayedPopoverProperties = nil } } extension BrowserViewController: UIAdaptivePresentationControllerDelegate { // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } } extension BrowserViewController: IntroViewControllerDelegate { @discardableResult func presentIntroViewController(_ force: Bool = false, animated: Bool = true) -> Bool { if let deeplink = self.profile.prefs.stringForKey("AdjustDeeplinkKey"), let url = URL(string: deeplink) { self.launchFxAFromDeeplinkURL(url) return true } if force || profile.prefs.intForKey(PrefsKeys.IntroSeen) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if topTabsVisible { introViewController.preferredContentSize = CGSize(width: IntroUX.Width, height: IntroUX.Height) introViewController.modalPresentationStyle = .formSheet } present(introViewController, animated: animated) { // On first run (and forced) open up the homepage in the background. if let homePageURL = HomePageAccessors.getHomePage(self.profile.prefs), let tab = self.tabManager.selectedTab, DeviceInfo.hasConnectivity() { tab.loadRequest(URLRequest(url: homePageURL)) } } return true } return false } func launchFxAFromDeeplinkURL(_ url: URL) { self.profile.prefs.removeObjectForKey("AdjustDeeplinkKey") var query = url.getQuery() query["entrypoint"] = "adjust_deepklink_ios" let fxaParams: FxALaunchParams fxaParams = FxALaunchParams(query: query) self.presentSignInViewController(fxaParams) } func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool) { self.profile.prefs.setInt(1, forKey: PrefsKeys.IntroSeen) introViewController.dismiss(animated: true) { if self.navigationController?.viewControllers.count ?? 0 > 1 { _ = self.navigationController?.popToRootViewController(animated: true) } if requestToLogin { let fxaParams = FxALaunchParams(query: ["entrypoint": "firstrun"]) self.presentSignInViewController(fxaParams) } } } func presentSignInViewController(_ fxaOptions: FxALaunchParams? = nil) { // Show the settings page if we have already signed in. If we haven't then show the signin page let vcToPresent: UIViewController if profile.hasAccount(), let status = profile.getAccount()?.actionNeeded, status == .none { let settingsTableViewController = SyncContentSettingsViewController() settingsTableViewController.profile = profile vcToPresent = settingsTableViewController } else { let signInVC = FxAContentViewController(profile: profile, fxaOptions: fxaOptions) signInVC.delegate = self vcToPresent = signInVC } vcToPresent.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSignInViewController)) let themedNavigationController = ThemedNavigationController(rootViewController: vcToPresent) themedNavigationController.modalPresentationStyle = .formSheet themedNavigationController.navigationBar.isTranslucent = false self.present(themedNavigationController, animated: true, completion: nil) } @objc func dismissSignInViewController() { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: FxAContentViewControllerDelegate { func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) { if flags.verified { self.dismiss(animated: true, completion: nil) } } func contentViewControllerDidCancel(_ viewController: FxAContentViewController) { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer) { // locationInView can return (0, 0) when the long press is triggered in an invalid page // state (e.g., long pressing a link before the document changes, then releasing after a // different page loads). let touchPoint = gestureRecognizer.location(in: view) guard touchPoint != CGPoint.zero else { return } let touchSize = CGSize(width: 0, height: 16) let actionSheetController = AlertController(title: nil, message: nil, preferredStyle: .actionSheet) var dialogTitle: String? if let url = elements.link, let currentTab = tabManager.selectedTab { dialogTitle = url.absoluteString let isPrivate = currentTab.isPrivate let addTab = { (rURL: URL, isPrivate: Bool) in let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate) LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Long Press Context Menu"]) guard !self.topTabsVisible else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(toast: toast) } if !isPrivate { let newTabTitle = NSLocalizedString("Open in New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: .default) { _ in addTab(url, false) } actionSheetController.addAction(openNewTabAction, accessibilityIdentifier: "linkContextMenu.openInNewTab") } let openNewPrivateTabTitle = NSLocalizedString("Open in New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab") let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: .default) { _ in addTab(url, true) } actionSheetController.addAction(openNewPrivateTabAction, accessibilityIdentifier: "linkContextMenu.openInNewPrivateTab") let downloadTitle = NSLocalizedString("Download Link", comment: "Context menu item for downloading a link URL") let downloadAction = UIAlertAction(title: downloadTitle, style: .default) { _ in self.pendingDownloadWebView = currentTab.webView currentTab.webView?.evaluateJavaScript("window.__firefox__.download('\(url.absoluteString)', '\(UserScriptManager.securityToken)')") UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .downloadLinkButton) } actionSheetController.addAction(downloadAction, accessibilityIdentifier: "linkContextMenu.download") let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: .default) { _ in UIPasteboard.general.url = url as URL } actionSheetController.addAction(copyAction, accessibilityIdentifier: "linkContextMenu.copyLink") let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL") let shareAction = UIAlertAction(title: shareTitle, style: .default) { _ in self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .any) } actionSheetController.addAction(shareAction, accessibilityIdentifier: "linkContextMenu.share") } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: .default) { _ in if photoAuthorizeStatus == .authorized || photoAuthorizeStatus == .notDetermined { self.getImageData(url as URL) { data in PHPhotoLibrary.shared().performChanges({ PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: nil) }) } } else { let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: .alert) let dismissAction = UIAlertAction(title: Strings.CancelString, style: .default, handler: nil) accessDenied.addAction(dismissAction) let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: .default ) { _ in UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:]) } accessDenied.addAction(settingsAction) self.present(accessDenied, animated: true, completion: nil) } } actionSheetController.addAction(saveImageAction, accessibilityIdentifier: "linkContextMenu.saveImage") let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: .default) { _ in // put the actual image on the clipboard // do this asynchronously just in case we're in a low bandwidth situation let pasteboard = UIPasteboard.general pasteboard.url = url as URL let changeCount = pasteboard.changeCount let application = UIApplication.shared var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTask (expirationHandler: { application.endBackgroundTask(taskId) }) Alamofire.request(url).validate(statusCode: 200..<300).response { response in // Only set the image onto the pasteboard if the pasteboard hasn't changed since // fetching the image; otherwise, in low-bandwidth situations, // we might be overwriting something that the user has subsequently added. if changeCount == pasteboard.changeCount, let imageData = response.data, response.error == nil { pasteboard.addImageWithData(imageData, forURL: url) } application.endBackgroundTask(taskId) } } actionSheetController.addAction(copyAction, accessibilityIdentifier: "linkContextMenu.copyImage") } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize) popoverPresentationController.permittedArrowDirections = .any popoverPresentationController.delegate = self } if actionSheetController.popoverPresentationController != nil { displayedPopoverController = actionSheetController } actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength) let cancelAction = UIAlertAction(title: Strings.CancelString, style: UIAlertActionStyle.cancel, handler: nil) actionSheetController.addAction(cancelAction) self.present(actionSheetController, animated: true, completion: nil) } fileprivate func getImageData(_ url: URL, success: @escaping (Data) -> Void) { Alamofire.request(url).validate(statusCode: 200..<300).response { response in if let data = response.data { success(data) } } } func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer) { displayedPopoverController?.dismiss(animated: true) { self.displayedPopoverController = nil } } } extension BrowserViewController { @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) { if error == nil { LeanPlumClient.shared.track(event: .saveImage) } } } extension BrowserViewController: HistoryStateHelperDelegate { func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab) { navigateInTab(tab: tab) tabManager.storeChanges() } } /** A third party search engine Browser extension **/ extension BrowserViewController { func addCustomSearchButtonToWebView(_ webView: WKWebView) { //check if the search engine has already been added. let domain = webView.url?.domainURL.host let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain} if !matches.isEmpty { self.customSearchEngineButton.tintColor = UIColor.Photon.Grey50 self.customSearchEngineButton.isUserInteractionEnabled = false } else { self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor self.customSearchEngineButton.isUserInteractionEnabled = true } /* This is how we access hidden views in the WKContentView Using the public headers we can find the keyboard accessoryView which is not usually available. Specific values here are from the WKContentView headers. https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h */ guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else { /* In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder and a search button should not be added. */ return } guard let input = webContentView.perform(#selector(getter: UIResponder.inputAccessoryView)), let inputView = input.takeUnretainedValue() as? UIInputView, let nextButton = inputView.value(forKey: "_nextItem") as? UIBarButtonItem, let nextButtonView = nextButton.value(forKey: "view") as? UIView else { //failed to find the inputView instead lets use the inputAssistant addCustomSearchButtonToInputAssistant(webContentView) return } inputView.addSubview(self.customSearchEngineButton) self.customSearchEngineButton.snp.remakeConstraints { make in make.leading.equalTo(nextButtonView.snp.trailing).offset(20) make.width.equalTo(inputView.snp.height) make.top.equalTo(nextButtonView.snp.top) make.height.equalTo(inputView.snp.height) } } /** This adds the customSearchButton to the inputAssistant for cases where the inputAccessoryView could not be found for example on the iPad where it does not exist. However this only works on iOS9 **/ func addCustomSearchButtonToInputAssistant(_ webContentView: UIView) { guard customSearchBarButton == nil else { return //The searchButton is already on the keyboard } let inputAssistant = webContentView.inputAssistantItem let item = UIBarButtonItem(customView: customSearchEngineButton) customSearchBarButton = item _ = Try(withTry: { inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item) }) { (exception) in Sentry.shared.send(message: "Failed adding custom search button to input assistant", tag: .general, severity: .error, description: "\(exception ??? "nil")") } } @objc func addCustomSearchEngineForFocusedElement() { guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let searchQuery = result as? String, let favicon = self.tabManager.selectedTab!.displayFavicon else { //Javascript responded with an incorrectly formatted message. Show an error. let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.addSearchEngine(searchQuery, favicon: favicon) self.customSearchEngineButton.tintColor = UIColor.Photon.Grey50 self.customSearchEngineButton.isUserInteractionEnabled = false } } func addSearchEngine(_ searchQuery: String, favicon: Favicon) { guard searchQuery != "", let iconURL = URL(string: favicon.url), let url = URL(string: searchQuery.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!), let shortName = url.domainURL.host else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in self.customSearchEngineButton.tintColor = UIColor.Photon.Grey50 self.customSearchEngineButton.isUserInteractionEnabled = false SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in guard let image = image else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image, searchTemplate: searchQuery, suggestTemplate: nil, isCustomEngine: true)) let Toast = SimpleToast() Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded, bottomContainer: self.webViewContainer) } } self.present(alert, animated: true, completion: {}) } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state updateViewConstraints() UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.alertStackView.layoutIfNeeded() } guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let _ = result as? String else { return } self.addCustomSearchButtonToWebView(webView) } } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil updateViewConstraints() //If the searchEngineButton exists remove it form the keyboard if let buttonGroup = customSearchBarButton?.buttonGroup { buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton } customSearchBarButton = nil } if self.customSearchEngineButton.superview != nil { self.customSearchEngineButton.removeFromSuperview() } UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.alertStackView.layoutIfNeeded() } } } extension BrowserViewController: SessionRestoreHelperDelegate { func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) { tab.restoring = false if let tab = tabManager.selectedTab, tab.webView === tab.webView { updateUIForReaderHomeStateForTab(tab) } } } extension BrowserViewController: TabTrayDelegate { // This function animates and resets the tab chrome transforms when // the tab tray dismisses. func tabTrayDidDismiss(_ tabTray: TabTrayController) { resetBrowserChrome() } func tabTrayDidAddTab(_ tabTray: TabTrayController, tab: Tab) {} func tabTrayDidAddBookmark(_ tab: Tab) { guard let url = tab.url?.absoluteString, !url.isEmpty else { return } self.addBookmark(tab.tabState) } func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListItem? { guard let url = tab.url?.absoluteString, !url.isEmpty else { return nil } return profile.readingList.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.current.name).value.successValue } func tabTrayRequestsPresentationOf(_ viewController: UIViewController) { self.present(viewController, animated: false, completion: nil) } } // MARK: Browser Chrome Theming extension BrowserViewController: Themeable { func applyTheme() { let ui: [Themeable?] = [urlBar, toolbar, readerModeBar, topTabsViewController, homePanelController, searchController] ui.forEach { $0?.applyTheme() } statusBarOverlay.backgroundColor = shouldShowTopTabsForTraitCollection(traitCollection) ? UIColor.Photon.Grey80 : urlBar.backgroundColor setNeedsStatusBarAppearanceUpdate() (presentedViewController as? Themeable)?.applyTheme() } } extension BrowserViewController: JSPromptAlertControllerDelegate { func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) { showQueuedAlertIfAvailable() } } extension BrowserViewController: TopTabsDelegate { func topTabsDidPressTabs() { urlBar.leaveOverlayMode(didCancel: true) self.urlBarDidPressTabs(urlBar) } func topTabsDidPressNewTab(_ isPrivate: Bool) { openBlankNewTab(focusLocationField: false, isPrivate: isPrivate) } func topTabsDidTogglePrivateMode() { guard let _ = tabManager.selectedTab else { return } urlBar.leaveOverlayMode() } func topTabsDidChangeTab() { urlBar.leaveOverlayMode(didCancel: true) } } extension BrowserViewController: ClientPickerViewControllerDelegate, InstructionsViewControllerDelegate { func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) { self.popToBVC() } func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) { self.popToBVC() } func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) { guard let tab = tabManager.selectedTab, let url = tab.canonicalURL?.displayURL?.absoluteString else { return } let shareItem = ShareItem(url: url, title: tab.title, favicon: tab.displayFavicon) guard shareItem.isShareable else { let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.popToBVC()}) present(alert, animated: true, completion: nil) return } profile.sendItem(shareItem, toClients: clients).uponQueue(.main) { _ in self.popToBVC() } } }
apache-2.0
rastogigaurav/mTV
mTV/mTVTests/Repositories/MovieDetailsRepositoryTest.swift
1
1201
// // MovieDetailsRepositoryTest.swift // mTV // // Created by Gaurav Rastogi on 6/25/17. // Copyright © 2017 Gaurav Rastogi. All rights reserved. // import XCTest @testable import mTV class MovieDetailsRepositoryTest: XCTestCase { var repository:MovieDetailsRepository? override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. self.repository = MovieDetailsRepository() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testGetMovieDetails(){ let expectedResult:XCTestExpectation = expectation(description: "Expected to get the details of movie from TMDB") let movieId = 0 self.repository?.getDetails(forMovieWith: movieId, completionHandler: { (movie, error) in expectedResult.fulfill() }) self.waitForExpectations(timeout: 2.0) { (error) in if let _ = error{ XCTFail("Failed to fetch details from TMDB") } } } }
mit
ZackKingS/Tasks
task/Classes/Others/Lib/TakePhoto/PhotoPickerController.swift
2
2624
// // PhotoPickerController.swift // PhotoPicker // // Created by liangqi on 16/3/5. // Copyright © 2016年 dailyios. All rights reserved. // import UIKit import Photos enum PageType{ case List case RecentAlbum case AllAlbum } protocol PhotoPickerControllerDelegate: class{ func onImageSelectFinished(images: [PHAsset]) } class PhotoPickerController: UINavigationController { // the select image max number static var imageMaxSelectedNum = 4 // already select total static var alreadySelectedImageNum = 0 weak var imageSelectDelegate: PhotoPickerControllerDelegate? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } init(type:PageType){ let rootViewController = PhotoAlbumsTableViewController(style:.plain) // clear cache PhotoImage.instance.selectedImage.removeAll() super.init(rootViewController: rootViewController) if type == .RecentAlbum || type == .AllAlbum { let currentType = type == .RecentAlbum ? PHAssetCollectionSubtype.smartAlbumRecentlyAdded : PHAssetCollectionSubtype.smartAlbumUserLibrary let results = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype:currentType, options: nil) if results.count > 0 { if let model = self.getModel(collection: results[0]) { if model.count > 0 { let layout = PhotoCollectionViewController.configCustomCollectionLayout() let controller = PhotoCollectionViewController(collectionViewLayout: layout) controller.fetchResult = model as? PHFetchResult<PHObject>; self.pushViewController(controller, animated: false) } } } } } private func getModel(collection: PHAssetCollection) -> PHFetchResult<PHAsset>?{ let fetchResult = PHAsset.fetchAssets(in: collection, options: PhotoFetchOptions.shareInstance) if fetchResult.count > 0 { return fetchResult } return nil } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func imageSelectFinish(){ if self.imageSelectDelegate != nil { self.dismiss(animated: true, completion: nil) self.imageSelectDelegate?.onImageSelectFinished(images: PhotoImage.instance.selectedImage) } } }
apache-2.0
bizz84/ReviewTime
ReviewTime/Own/NHView.swift
3
689
// // NHView.swift // ReviewTime // // Created by Nathan Hegedus on 25/05/15. // Copyright (c) 2015 Nathan Hegedus. All rights reserved. // import UIKit class NHView: UIView { @IBInspectable var isCircle: Bool = false { didSet { if isCircle { self.layer.cornerRadius = self.frame.size.width/2 } } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { self.layer.borderWidth = borderWidth } } @IBInspectable var borderColorHexa: String = "" { didSet { self.layer.borderColor = UIColor(hexa: borderColorHexa, alpha: 1.0).CGColor } } }
mit
kickstarter/Kickstarter-Prelude
Prelude-UIKit/lenses/UITextInputTraitsLenses.swift
1
1846
import Prelude import UIKit public protocol UITextInputTraitsProtocol: NSObjectProtocol { var autocapitalizationType: UITextAutocapitalizationType { get set } var autocorrectionType: UITextAutocorrectionType { get set } var keyboardAppearance: UIKeyboardAppearance { get set } var keyboardType: UIKeyboardType { get set } var returnKeyType: UIReturnKeyType { get set } var isSecureTextEntry: Bool { get set } var spellCheckingType: UITextSpellCheckingType { get set } } public extension LensHolder where Object: UITextInputTraitsProtocol { public var autocapitalizationType: Lens<Object, UITextAutocapitalizationType> { return Lens( view: { $0.autocapitalizationType }, set: { $1.autocapitalizationType = $0; return $1 } ) } public var autocorrectionType: Lens<Object, UITextAutocorrectionType> { return Lens( view: { $0.autocorrectionType }, set: { $1.autocorrectionType = $0; return $1 } ) } public var keyboardAppearance: Lens<Object, UIKeyboardAppearance> { return Lens( view: { $0.keyboardAppearance }, set: { $1.keyboardAppearance = $0; return $1 } ) } public var keyboardType: Lens<Object, UIKeyboardType> { return Lens( view: { $0.keyboardType }, set: { $1.keyboardType = $0; return $1 } ) } public var returnKeyType: Lens<Object, UIReturnKeyType> { return Lens( view: { $0.returnKeyType }, set: { $1.returnKeyType = $0; return $1 } ) } public var secureTextEntry: Lens<Object, Bool> { return Lens( view: { $0.isSecureTextEntry }, set: { $1.isSecureTextEntry = $0; return $1 } ) } public var spellCheckingType: Lens<Object, UITextSpellCheckingType> { return Lens( view: { $0.spellCheckingType }, set: { $1.spellCheckingType = $0; return $1 } ) } }
apache-2.0
loudnate/LoopKit
LoopKit/Extensions/HKHealthStore.swift
2
442
// // HKHealthStore.swift // LoopKit // // Copyright © 2018 LoopKit Authors. All rights reserved. // import HealthKit protocol HKSampleQueryTestable { func executeSampleQuery( for type: HKSampleType, matching predicate: NSPredicate, limit: Int, sortDescriptors: [NSSortDescriptor]?, resultsHandler: @escaping (_ query: HKSampleQuery, _ results: [HKSample]?, _ error: Error?) -> Void ) }
mit
BeezleLabs/HackerTracker-iOS
hackertracker/HTSpeakerViewController.swift
1
6991
// // HTSpeakerViewController.swift // hackertracker // // Created by Seth Law on 8/6/18. // Copyright © 2018 Beezle Labs. All rights reserved. // import SafariServices import UIKit class HTSpeakerViewController: UIViewController, UIViewControllerTransitioningDelegate, UITableViewDataSource, UITableViewDelegate, EventCellDelegate { @IBOutlet private var twitterButton: UIButton! @IBOutlet private var talkButton: UIButton! @IBOutlet private var nameLabel: UILabel! @IBOutlet private var bioLabel: UILabel! @IBOutlet private var vertStackView: UIStackView! @IBOutlet private var eventTableView: UITableView! @IBOutlet private var eventTableHeightConstraint: NSLayoutConstraint! var eventTokens: [UpdateToken] = [] var events: [UserEventModel] = [] var speaker: HTSpeaker? override func viewDidLoad() { super.viewDidLoad() if let speaker = speaker { nameLabel.text = speaker.name bioLabel.text = speaker.description bioLabel.sizeToFit() eventTableView.register(UINib(nibName: "EventCell", bundle: nil), forCellReuseIdentifier: "EventCell") eventTableView.register(UINib(nibName: "UpdateCell", bundle: nil), forCellReuseIdentifier: "UpdateCell") eventTableView.delegate = self eventTableView.dataSource = self eventTableView.backgroundColor = UIColor.clear eventTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) addEventList() twitterButton.isHidden = true if !speaker.twitter.isEmpty { twitterButton.setTitle(speaker.twitter, for: .normal) twitterButton.isHidden = false } self.eventTableView.reloadData() self.vertStackView.layoutSubviews() } } func addEventList() { var idx = 0 for eventModel in speaker?.events ?? [] { if eventTokens.indices.contains(idx) { // NSLog("Already an eventtoken for event \(e.title)") } else { let eToken = FSConferenceDataController.shared.requestEvents(forConference: AnonymousSession.shared.currentConference, eventId: eventModel.id) { result in switch result { case .success(let event): if self.events.contains(event), let idx = self.events.firstIndex(of: event) { self.events.remove(at: idx) self.events.insert(event, at: idx) } else { self.events.append(event) } self.eventTableView.reloadData() self.vertStackView.layoutSubviews() case .failure: // TODO: Properly log failure break } } eventTokens.append(eToken) } idx += 1 } if let speaker = speaker { if !speaker.events.isEmpty { eventTableHeightConstraint.constant = CGFloat(speaker.events.count * 200) } else { eventTableHeightConstraint.constant = 100 } } } @IBAction private func twitterTapped(_ sender: Any) { if let twit = speaker?.twitter { if let url = URL(string: "https://mobile.twitter.com/\(twit.replacingOccurrences(of: "@", with: ""))") { let controller = SFSafariViewController(url: url) controller.preferredBarTintColor = .backgroundGray controller.preferredControlTintColor = .white present(controller, animated: true) } } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "eventSegue" { let destController: HTEventDetailViewController if let destinationNav = segue.destination as? UINavigationController, let controller = destinationNav.viewControllers.first as? HTEventDetailViewController { destController = controller } else { destController = segue.destination as! HTEventDetailViewController } if let speaker = speaker { let events = speaker.events if !events.isEmpty { destController.event = events[0] } } destController.transitioningDelegate = self } } // Table Functions func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if !events.isEmpty { return events.count } else { return 1 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if !events.isEmpty { let cell = tableView.dequeueReusableCell(withIdentifier: "EventCell", for: indexPath) as! EventCell let event = events[indexPath.row] cell.bind(userEvent: event) cell.eventCellDelegate = self return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "UpdateCell") as! UpdateCell cell.bind(title: "404 - Not Found", desc: "No events found for this speaker, check with the #hackertracker team") return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let speaker = speaker, !speaker.events.isEmpty { let event: UserEventModel = events[indexPath.row] if let storyboard = self.storyboard, let eventController = storyboard.instantiateViewController(withIdentifier: "HTEventDetailViewController") as? HTEventDetailViewController { eventController.event = event.event eventController.bookmark = event.bookmark self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) self.navigationController?.pushViewController(eventController, animated: true) } } } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func numberOfSections(in tableView: UITableView) -> Int { return 1 } // Event Cell Delegate func updatedEvents() { // self.addEventList() self.eventTableView.reloadData() } }
gpl-2.0
ixx1232/swift-Tour
swiftTour/swiftTourUITests/swiftTourUITests.swift
1
1249
// // swiftTourUITests.swift // swiftTourUITests // // Created by ixxcome on 3/2/17. // Copyright © 2017 www.ixxcome.com. All rights reserved. // import XCTest class swiftTourUITests: 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
lakesoft/LKUserDefaultOption
Pod/Classes/LKUserDefaultOptionSingleSelectionViewController.swift
1
1842
// // LKUserDefaultModelSelectionViewController.swift // VideoEver // // Created by Hiroshi Hashiguchi on 2015/07/19. // Copyright (c) 2015年 lakesoft. All rights reserved. // import UIKit public class LKUserDefaultOptionSingleSelectionViewController: UITableViewController { var model:LKUserDefaultOptionModel! var selection: LKUserDefaultOptionSingleSelection! public override func viewDidLoad() { super.viewDidLoad() title = model.titleLabel() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "LKUserDefaultModelSingleSelectionViewControllerCell") self.tableView.reloadData() } // MARK: - Table view data source public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return selection.numberOfRows(section) } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("LKUserDefaultModelSingleSelectionViewControllerCell", forIndexPath: indexPath) cell.textLabel!.text = selection.label(indexPath) cell.accessoryType = selection.isSelected(indexPath) ? .Checkmark : .None return cell } public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let indexPaths:[NSIndexPath] = [indexPath, selection.selectedIndexPath] selection.selectedIndexPath = indexPath model.save() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None) if selection.closeWhenSelected() { self.navigationController?.popViewControllerAnimated(true) } } }
mit
chicio/Exploring-SceneKit
ExploringSceneKit/Model/Scenes/Collada/ColladaScene.swift
1
2860
// // ColladaScene.swift // ExploringSceneKit // // Created by Fabrizio Duroni on 28.08.17. // import SceneKit class ColladaScene: SCNScene, Scene { var colladaFileContents: SCNScene! var camera: Camera! var home: SCNNode! var light: SCNNode! override init() { super.init() colladaFileContents = ColladaLoader.loadFromSCNAssetsAColladaFileWith(name: "house") createCamera() createLights() createObjects() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: Camera func createCamera() { camera = Camera(cameraNode: colladaFileContents.rootNode.childNode(withName: "Camera", recursively: true)!) rootNode.addChildNode(camera.node) } //MARK: Light func createLights() { colladaFileContents.rootNode.enumerateChildNodes { node, stop in if node.name?.contains("Light") == true { rootNode.addChildNode(node) } } } //MARK: Objects private func createObjects() { addHome() addFloor() addBackground() pointCameraToHome() } private func addHome() { home = colladaFileContents.rootNode.childNode(withName: "home", recursively: true)! rootNode.addChildNode(colladaFileContents.rootNode.childNode(withName: "home", recursively: true)!) } private func addFloor() { rootNode.addChildNode( OpaqueFloor( material: BlinnPhongMaterial( ambient: 0.0, diffuse: BlinnPhongDiffuseMaterialComponent( value: UIColor(red: 67.0/255.0, green: 100.0/255.0, blue: 31.0/255.0, alpha: 1.0) ), specular: 0.0 ), position: SCNVector3(0.0, 0.0, 0.0), rotation: SCNVector4(0.0, 0.0, 0.0, 0.0) ).node ) } private func addBackground() { background.contents = ["right.png", "left.png", "up.png", "down.png", "back.png", "front.png"] } private func pointCameraToHome() { camera.node.constraints = [SCNLookAtConstraint(target: home)] } //MARK: Gestures func actionForOnefingerGesture(withLocation location: CGPoint, andHitResult hitResult: [Any]!) { let moveInFrontAnimation = MoveAnimationFactory.makeMoveTo(position: SCNVector3(0.0, 0.5, 15.0), time: 5) let moveLeftAnimation = MoveAnimationFactory.makeMoveTo(position: SCNVector3(-6.0, 0.5, 15.0), time: 5) self.camera.node.addAnimation( AnimationGroupFactory.makeGroupWith(animations: [moveInFrontAnimation, moveLeftAnimation], time: 10.0), forKey: nil ) } }
mit
ashfurrow/pragma-2015-rx-workshop
Session 4/Entities Demo/Entities Demo/AppDelegate.swift
2
3330
// // AppDelegate.swift // Entities Demo // // Created by Ash Furrow on 2015-10-08. // Copyright © 2015 Artsy. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self 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:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
OscarSwanros/swift
test/SILGen/vtables.swift
2
3952
// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen %s | %FileCheck %s // Test for compilation order independence class C : B { // foo inherited from B override func bar() {} // bas inherited from A override func qux() {} // zim inherited from B override func zang() {} required init(int i: Int) { } func flopsy() {} func mopsy() {} } // CHECK: sil_vtable C { // CHECK: #A.foo!1: {{.*}} : _T07vtables1BC3foo{{[_0-9a-zA-Z]*}}F // CHECK: #A.bar!1: {{.*}} : _T07vtables1CC3bar{{[_0-9a-zA-Z]*}}F // CHECK: #A.bas!1: {{.*}} : _T07vtables1AC3bas{{[_0-9a-zA-Z]*}}F // CHECK: #A.qux!1: {{.*}} : _T07vtables1CC3qux{{[_0-9a-zA-Z]*}}F // CHECK: #B.init!allocator.1: {{.*}} : _T07vtables1CC{{[_0-9a-zA-Z]*}}fC // CHECK: #B.init!initializer.1: {{.*}} : _T07vtables1CC{{[_0-9a-zA-Z]*}}fc // CHECK: #B.zim!1: {{.*}} : _T07vtables1BC3zim{{[_0-9a-zA-Z]*}}F // CHECK: #B.zang!1: {{.*}} : _T07vtables1CC4zang{{[_0-9a-zA-Z]*}}F // CHECK: #C.flopsy!1: {{.*}} : _T07vtables1CC6flopsy{{[_0-9a-zA-Z]*}}F // CHECK: #C.mopsy!1: {{.*}} : _T07vtables1CC5mopsy{{[_0-9a-zA-Z]*}}F // CHECK: } class A { func foo() {} func bar() {} func bas() {} func qux() {} } // CHECK: sil_vtable A { // CHECK: #A.foo!1: {{.*}} : _T07vtables1AC3foo{{[_0-9a-zA-Z]*}}F // CHECK: #A.bar!1: {{.*}} : _T07vtables1AC3bar{{[_0-9a-zA-Z]*}}F // CHECK: #A.bas!1: {{.*}} : _T07vtables1AC3bas{{[_0-9a-zA-Z]*}}F // CHECK: #A.qux!1: {{.*}} : _T07vtables1AC3qux{{[_0-9a-zA-Z]*}}F // CHECK: #A.init!initializer.1: {{.*}} : _T07vtables1AC{{[_0-9a-zA-Z]*}}fc // CHECK: } class B : A { required init(int i: Int) { } override func foo() {} // bar inherited from A // bas inherited from A override func qux() {} func zim() {} func zang() {} } // CHECK: sil_vtable B { // CHECK: #A.foo!1: {{.*}} : _T07vtables1BC3foo{{[_0-9a-zA-Z]*}}F // CHECK: #A.bar!1: {{.*}} : _T07vtables1AC3bar{{[_0-9a-zA-Z]*}}F // CHECK: #A.bas!1: {{.*}} : _T07vtables1AC3bas{{[_0-9a-zA-Z]*}}F // CHECK: #A.qux!1: {{.*}} : _T07vtables1BC3qux{{[_0-9a-zA-Z]*}}F // CHECK: #B.init!allocator.1: {{.*}} : _T07vtables1BC{{[_0-9a-zA-Z]*}}fC // CHECK: #B.init!initializer.1: {{.*}} : _T07vtables1BC{{[_0-9a-zA-Z]*}}fc // CHECK: #B.zim!1: {{.*}} : _T07vtables1BC3zim{{[_0-9a-zA-Z]*}}F // CHECK: #B.zang!1: {{.*}} : _T07vtables1BC4zang{{[_0-9a-zA-Z]*}}F // CHECK: } // CHECK: sil_vtable RequiredInitDerived { // CHECK-NEXT: #SimpleInitBase.init!initializer.1: {{.*}} : _T07vtables19RequiredInitDerivedC{{[_0-9a-zA-Z]*}}fc // CHECK-NEXT: #RequiredInitDerived.init!allocator.1: {{.*}} : _T07vtables19RequiredInitDerivedC // CHECK-NEXT: #RequiredInitDerived.deinit!deallocator: _T07vtables19RequiredInitDerivedCfD // CHECK-NEXT: } class SimpleInitBase { } class RequiredInitDerived : SimpleInitBase { required override init() { } } class Observed { var x: Int = 0 { didSet { } willSet { } } } // rdar://problem/21298214 class BaseWithDefaults { func a(_ object: AnyObject? = nil) {} } class DerivedWithoutDefaults : BaseWithDefaults { override func a(_ object: AnyObject?) { super.a(object) } } // CHECK-LABEL: sil_vtable Observed { // CHECK-NOT: #Observed.x!didSet // CHECK-NOT: #Observed.x!willSet // CHECK: #Observed.x!getter // CHECK: #Observed.x!setter // CHECK-LABEL: sil_vtable DerivedWithoutDefaults { // CHECK: #BaseWithDefaults.a!1: {{.*}} : _T07vtables22DerivedWithoutDefaultsC1a{{[_0-9a-zA-Z]*}}F // Escape identifiers that represent special names class SubscriptAsFunction { func `subscript`() {} } // CHECK-LABEL: sil_vtable SubscriptAsFunction { // CHECK-NOT: #SubscriptAsFunction.subscript // CHECK: #SubscriptAsFunction.`subscript`!1 class DeinitAsFunction { func `deinit`() {} } // CHECK-LABEL: sil_vtable DeinitAsFunction { // CHECK: #DeinitAsFunction.`deinit`!1 // CHECK: #DeinitAsFunction.deinit!deallocator
apache-2.0
mlgoogle/wp
wp/General/Base/BaseTableViewController.swift
1
5426
// // BaseTableViewController.swift // viossvc // // Created by yaowang on 2016/10/27. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import Foundation import SVProgressHUD class BaseTableViewController: UITableViewController , TableViewHelperProtocol { var tableViewHelper:TableViewHelper = TableViewHelper(); override func viewDidLoad() { super.viewDidLoad(); if tableView.tableFooterView == nil { tableView.tableFooterView = UIView(frame:CGRect(x: 0,y: 0,width: 0,height: 0.5)); } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) AppDataHelper.instance().userCash() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) checkUpdateVC() SVProgressHUD.dismiss() } //MARK:TableViewHelperProtocol func isCacheCellHeight() -> Bool { return false; } func isCalculateCellHeight() ->Bool { return isCacheCellHeight(); } func isSections() ->Bool { return false; } func tableView(_ tableView:UITableView ,cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? { return tableViewHelper.tableView(tableView, cellIdentifierForRowAtIndexPath: indexPath, controller: self); } func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? { return nil; } //MARK: -UITableViewDelegate override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell:UITableViewCell? = super.tableView(tableView,cellForRowAt:indexPath); if cell == nil { cell = tableViewHelper.tableView(tableView, cellForRowAtIndexPath: indexPath, controller: self); } return cell!; } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { tableViewHelper.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath, controller: self); } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if( isCalculateCellHeight() ) { let cellHeight:CGFloat = tableViewHelper.tableView(tableView, heightForRowAtIndexPath: indexPath, controller: self); if( cellHeight != CGFloat.greatestFiniteMagnitude ) { return cellHeight; } } return super.tableView(tableView, heightForRowAt: indexPath); } } class BaseRefreshTableViewController :BaseTableViewController { override func viewDidLoad() { super.viewDidLoad(); self.setupRefreshControl(); } internal func completeBlockFunc()->CompleteBlock { return { [weak self] (obj) in self?.didRequestComplete(obj) } } internal func didRequestComplete(_ data:AnyObject?) { endRefreshing() self.tableView.reloadData() } override func didRequestError(_ error:NSError) { self.endRefreshing() super.didRequestError(error) } deinit { performSelectorRemoveRefreshControl(); } } class BaseListTableViewController :BaseRefreshTableViewController { internal var dataSource:Array<AnyObject>?; override func didRequestComplete(_ data: AnyObject?) { dataSource = data as? Array<AnyObject>; super.didRequestComplete(dataSource as AnyObject?); } //MARK: -UITableViewDelegate override func numberOfSections(in tableView: UITableView) -> Int { var count:Int = dataSource != nil ? 1 : 0; if isSections() && count != 0 { count = dataSource!.count; } return count; } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var datas:Array<AnyObject>? = dataSource; if dataSource != nil && isSections() { datas = dataSource![section] as? Array<AnyObject>; } return datas == nil ? 0 : datas!.count; } //MARK:TableViewHelperProtocol override func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? { var datas:Array<AnyObject>? = dataSource; if dataSource != nil && isSections() { datas = dataSource![indexPath.section] as? Array<AnyObject>; } return (datas != nil && datas!.count > indexPath.row ) ? datas![indexPath.row] : nil; } } class BasePageListTableViewController :BaseListTableViewController { override func viewDidLoad() { super.viewDidLoad(); setupLoadMore(); } override func didRequestComplete(_ data: AnyObject?) { tableViewHelper.didRequestComplete(&self.dataSource, pageDatas: data as? Array<AnyObject>, controller: self); super.didRequestComplete(self.dataSource as AnyObject?); } override func didRequestError(_ error:NSError) { if (!(self.pageIndex == 1) ) { self.errorLoadMore() } self.setIsLoadData(true) super.didRequestError(error) } deinit { removeLoadMore(); } }
apache-2.0
LoopKit/LoopKit
LoopKitUI/Extensions/UIImage.swift
1
404
// // UIImage.swift // LoopKitUI // // Created by Nathaniel Hamming on 2020-07-15. // Copyright © 2020 LoopKit Authors. All rights reserved. // import UIKit private class FrameworkBundle { static let main = Bundle(for: FrameworkBundle.self) } extension UIImage { convenience init?(frameworkImage name: String) { self.init(named: name, in: FrameworkBundle.main, with: nil) } }
mit
swojtyna/starsview
StarsView/StarsViewTests/ImageDataImporterTests.swift
1
2996
// // ImageDataImporterTests.swift // StarsView // // Created by Sebastian Wojtyna on 30/08/16. // Copyright © 2016 Sebastian Wojtyna. All rights reserved. // import XCTest @testable import StarsView class ImageDataImporterTests: XCTestCase, LoadableTestStringFile { override class func setUp() { super.setUp() LSNocilla.sharedInstance().start() } override class func tearDown() { super.tearDown() LSNocilla.sharedInstance().stop() } override func tearDown() { LSNocilla.sharedInstance().clearStubs() } func testImportImageDataSuccess() { let expectation = self.expectationWithDescription("Success import all image data") let fakeRequest = ImagesListRequest() let fakeRequestURL = fakeRequest.buildRequest()!.URL!.absoluteString let filenameJSON = "imageList_success.json" let contentJSON = stringContentOfFile(filenameJSON, bundle: NSBundle(forClass: self.dynamicType)) stubRequest(fakeRequest.method, fakeRequestURL).withHeaders(fakeRequest.headers).andReturn(200).withBody(contentJSON) ImagesDataImporter().importDataList( success: { result in XCTAssertNotNil(result) expectation.fulfill() }, failure: { error in XCTAssertNil(error) }) waitForExpectationsWithTimeout(0.1, handler: nil) } func testImportImageDataJSONParseFailure() { let expectation = self.expectationWithDescription("JSON parse error during import all image data") let fakeRequest = ImagesListRequest() let fakeRequestURL = fakeRequest.buildRequest()!.URL!.absoluteString let filenameJSON = "imageList_jsonparse_failure.json" let contentJSON = stringContentOfFile(filenameJSON, bundle: NSBundle(forClass: self.dynamicType)) stubRequest(fakeRequest.method, fakeRequestURL).withHeaders(fakeRequest.headers).andReturn(200).withBody(contentJSON) ImagesDataImporter().importDataList( success: { result in XCTAssertNil(result) }, failure: { error in XCTAssertNotNil(error) expectation.fulfill() }) waitForExpectationsWithTimeout(0.1, handler: nil) } func testImportImageDataNotFoundFailure() { let expectation = self.expectationWithDescription("Not found 404 code during import all image data") let fakeRequest = ImagesListRequest() let fakeRequestURL = fakeRequest.buildRequest()!.URL!.absoluteString stubRequest(fakeRequest.method, fakeRequestURL).withHeaders(fakeRequest.headers).andReturn(404) ImagesDataImporter().importDataList( success: { result in XCTAssertNil(result) }, failure: { error in XCTAssertNotNil(error) expectation.fulfill() }) waitForExpectationsWithTimeout(0.1, handler: nil) } }
agpl-3.0
garynewby/GameOfLife
GameOfLifeTests/GameOfLifeTests.swift
1
911
// // GameOfLifeTests.swift // GameOfLifeTests // // Created by Gary Newby on 5/2/19. // Copyright © 2019 Gary Newby. All rights reserved. // import XCTest @testable import GameOfLife class GameOfLifeTests: XCTestCase { override func 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. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } 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
fen-x/OMM
OMM/Core/UndefinedValueError.swift
1
551
// // UndefinedValueError.swift // OMM // // Created by Ivan Nikitin on 06/11/15. // Copyright © 2015 Ivan Nikitin. All rights reserved. // /// Represents absence of retriving value /// It means that raw object of node does not exist. public struct UndefinedValueError: Error { } /// `CustomDebugStringConvertible` conformance. extension UndefinedValueError: CustomDebugStringConvertible { /// A textual representation, suitable for debugging. public var debugDescription: String { return "Value is \"undefined\"" } }
mit
gmilos/swift
test/SILGen/accessibility_warnings.swift
2
6696
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s // This file tests that the AST produced after fixing accessibility warnings // is valid according to SILGen and the verifiers. public struct PublicStruct { // CHECK-DAG: sil{{( \[.+\])*}} @_TFV22accessibility_warnings12PublicStructg9publicVarSi public var publicVar = 0 // CHECK-DAG: sil hidden @_TFV22accessibility_warnings12PublicStructCfT_S0_ } internal struct InternalStruct { public var publicVar = 0 public private(set) var publicVarPrivateSet = 0 public public(set) var publicVarPublicSet = 0 // CHECK-DAG: sil hidden @_TFV22accessibility_warnings14InternalStructg16publicVarGetOnlySi public var publicVarGetOnly: Int { return 0 } // CHECK-DAG: sil hidden @_TFV22accessibility_warnings14InternalStructg15publicVarGetSetSi public var publicVarGetSet: Int { get { return 0 } set {} } // CHECK-DAG: sil hidden @_TFV22accessibility_warnings14InternalStructCfT_S0_ } private struct PrivateStruct { public var publicVar = 0 // CHECK-DAG: sil private @_TFV22accessibility_warningsP33_5D2F2E026754A901C0FF90C404896D0213PrivateStructCfT_S0_ } extension PublicStruct { // CHECK-DAG: sil @_TFV22accessibility_warnings12PublicStructCfT1xSi_S0_ public init(x: Int) { self.init() } // CHECK-DAG: sil @_TFV22accessibility_warnings12PublicStructg18publicVarExtensionSi public var publicVarExtension: Int { get { return 0 } set {} } } extension InternalStruct { // CHECK-DAG: sil hidden @_TFV22accessibility_warnings14InternalStructCfT1xSi_S0_ public init(x: Int) { self.init() } // CHECK-DAG: sil hidden @_TFV22accessibility_warnings14InternalStructg18publicVarExtensionSi public var publicVarExtension: Int { get { return 0 } set {} } } extension PrivateStruct { // CHECK-DAG: sil private @_TFV22accessibility_warningsP33_5D2F2E026754A901C0FF90C404896D0213PrivateStructCfT1xSi_S0_ public init(x: Int) { self.init() } // CHECK-DAG: sil private @_TFV22accessibility_warningsP33_5D2F2E026754A901C0FF90C404896D0213PrivateStructg18publicVarExtensionSi public var publicVarExtension: Int { get { return 0 } set {} } } public extension PublicStruct { // CHECK-DAG: sil @_TFV22accessibility_warnings12PublicStruct15extMemberPublicfT_T_ public func extMemberPublic() {} // CHECK-DAG: sil private @_TFV22accessibility_warnings12PublicStructP33_5D2F2E026754A901C0FF90C404896D0213extImplPublicfT_T_ private func extImplPublic() {} } internal extension PublicStruct { // CHECK-DAG: sil hidden @_TFV22accessibility_warnings12PublicStruct17extMemberInternalfT_T_ public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}} // CHECK-DAG: sil private @_TFV22accessibility_warnings12PublicStructP33_5D2F2E026754A901C0FF90C404896D0215extImplInternalfT_T_ private func extImplInternal() {} } private extension PublicStruct { // CHECK-DAG: sil private @_TFV22accessibility_warnings12PublicStructP33_5D2F2E026754A901C0FF90C404896D0216extMemberPrivatefT_T_ public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} // CHECK-DAG: sil private @_TFV22accessibility_warnings12PublicStructP33_5D2F2E026754A901C0FF90C404896D0214extImplPrivatefT_T_ private func extImplPrivate() {} } internal extension InternalStruct { // CHECK-DAG: sil hidden @_TFV22accessibility_warnings14InternalStruct17extMemberInternalfT_T_ public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}} // CHECK-DAG: sil private @_TFV22accessibility_warnings14InternalStructP33_5D2F2E026754A901C0FF90C404896D0215extImplInternalfT_T_ private func extImplInternal() {} } private extension InternalStruct { // CHECK-DAG: sil private @_TFV22accessibility_warnings14InternalStructP33_5D2F2E026754A901C0FF90C404896D0216extMemberPrivatefT_T_ public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} // CHECK-DAG: sil private @_TFV22accessibility_warnings14InternalStructP33_5D2F2E026754A901C0FF90C404896D0214extImplPrivatefT_T_ private func extImplPrivate() {} } private extension PrivateStruct { // CHECK-DAG: sil private @_TFV22accessibility_warningsP33_5D2F2E026754A901C0FF90C404896D0213PrivateStruct16extMemberPrivatefT_T_ public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} // CHECK-DAG: sil private @_TFV22accessibility_warningsP33_5D2F2E026754A901C0FF90C404896D0213PrivateStruct14extImplPrivatefT_T_ private func extImplPrivate() {} } public protocol PublicReadOnlyOperations { var size: Int { get } subscript (_: Int) -> Int { get } } internal struct PrivateSettersForReadOnlyInternal : PublicReadOnlyOperations { // CHECK-DAG: sil hidden{{( \[.+\])*}} @_TFV22accessibility_warnings33PrivateSettersForReadOnlyInternalg4sizeSi public private(set) var size = 0 // CHECK-DAG: sil hidden @_TFV22accessibility_warnings33PrivateSettersForReadOnlyInternalg9subscriptFSiSi // CHECK-DAG: sil private @_TFV22accessibility_warnings33PrivateSettersForReadOnlyInternals9subscriptFSiSi internal private(set) subscript (_: Int) -> Int { // no-warning get { return 42 } set {} } } public class PublicClass { // CHECK-DAG: sil{{( \[.+\])*}} @_TFC22accessibility_warnings11PublicClassg9publicVarSi public var publicVar = 0 // CHECK-DAG: sil hidden @_TFC22accessibility_warnings11PublicClasscfT_S0_ } internal class InternalClass { // CHECK-DAG: sil hidden{{( \[.+\])*}} @_TFC22accessibility_warnings13InternalClassg9publicVarSi public var publicVar = 0 // CHECK-DAG: sil hidden @_TFC22accessibility_warnings13InternalClassg19publicVarPrivateSetSi public private(set) var publicVarPrivateSet = 0 public public(set) var publicVarPublicSet = 0 // CHECK-DAG: sil hidden @_TFC22accessibility_warnings13InternalClassg16publicVarGetOnlySi public var publicVarGetOnly: Int { return 0 } // CHECK-DAG: sil hidden @_TFC22accessibility_warnings13InternalClassg15publicVarGetSetSi public var publicVarGetSet: Int { get { return 0 } set {} } // CHECK-DAG: sil hidden @_TFC22accessibility_warnings13InternalClasscfT_S0_ } private class PrivateClass { // CHECK-DAG: sil private{{( \[.+\])*}} @_TFC22accessibility_warningsP33_5D2F2E026754A901C0FF90C404896D0212PrivateClassg9publicVarSi public var publicVar = 0 // CHECK-DAG: sil private @_TFC22accessibility_warningsP33_5D2F2E026754A901C0FF90C404896D0212PrivateClasscfT_S0_ }
apache-2.0
igorcferreira/DumbLogger
Sample/DumbLoggerSample/DumbLoggerSample/AppDelegate.swift
1
2185
// // AppDelegate.swift // DumbLoggerSample // // Created by Igor Ferreira on 01/12/16. // Copyright © 2016 Igor Ferreira. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
KaushalElsewhere/AllHandsOn
ViewControllerTransition/ViewControllerTransition/AppDelegate.swift
1
2173
// // AppDelegate.swift // ViewControllerTransition // // Created by Kaushal Elsewhere on 2/09/2016. // Copyright © 2016 Kaushal Elsewhere. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
renzifeng/ZFZhiHuDaily
ZFZhiHuDaily/NewsDatail/Controller/ZFNewsDetailViewController.swift
1
15226
// // ZFNewsDetailViewController.swift // ZFZhiHuDaily // // Created by 任子丰 on 16/1/12. // Copyright © 2016年 任子丰. All rights reserved. // import UIKit import NVActivityIndicatorView import Kingfisher import SKPhotoBrowser class ZFNewsDetailViewController: ZFBaseViewController { /// 容器view @IBOutlet weak var containerView: UIView! @IBOutlet weak var webView: UIWebView! @IBOutlet weak var zanBtn: ZanButton! @IBOutlet weak var commentBtn: UIButton! @IBOutlet weak var commentNumLabel: UILabel! @IBOutlet weak var zanNumLabel: UILabel! @IBOutlet weak var nextNewsBtn: UIButton! @IBOutlet weak var bottomView: UIView! /// 存放内容id的数组 var newsIdArray : [String]! /// 新闻id var newsId : String! var viewModel = ZFNewsDetailViewModel() var backgroundImg : UIImageView! /// top图片上的title var titleLabel : UILabel! /// 新闻额外信息 var newsExtra : ZFNewsExtra! /// loading var activityIndicatorView : NVActivityIndicatorView! /// 判断是否有图 var hasPic : Bool = false /// 是否正在加载 var isLoading : Bool = false /// headerView var headerView : ZFHeaderView! /// footerView var footerView : ZFFooterView! /// 是否为夜间模式 var isNight : Bool = false var tapGesture : UITapGestureRecognizer! // MARK: - life sycle override func viewDidLoad() { super.viewDidLoad() let mode = NSUserDefaults.standardUserDefaults().objectForKey("NightOrLightMode") as! String if mode == "light"{ //白天模式 isNight = false }else if mode == "night" { //夜间模式 isNight = true } setupUI() //赞 setupZan() viewModel.newsIdArray = self.newsIdArray getNewsWithId(self.newsId) bottomView.dk_backgroundColorPicker = BG_COLOR webView.dk_backgroundColorPicker = BG_COLOR view.dk_backgroundColorPicker = BG_COLOR tapGesture = UITapGestureRecognizer() tapGesture.addTarget(self, action: #selector(ZFNewsDetailViewController.tapAction(_:))) webView.addGestureRecognizer(tapGesture) tapGesture.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBarHidden = true navView.hidden = true closeTheDrawerGesture() } // MARK: - SetupUI func setupUI() { statusView.backgroundColor = UIColor.clearColor() navView.hidden = true backgroundImg = UIImageView() backgroundImg.contentMode = .ScaleAspectFill backgroundImg.clipsToBounds = true backgroundImg.frame = CGRectMake(0, -60, ScreenWidth, CGFloat(265)) webView.scrollView.addSubview(backgroundImg) webView.scrollView.delegate = self titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.textColor = UIColor.whiteColor() titleLabel.font = UIFont.boldSystemFontOfSize(20.0) backgroundImg.addSubview(titleLabel) titleLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(10) make.right.equalTo(-10) make.bottom.equalTo(-10) } let x = view.center.x let y = view.center.y let width = CGFloat(50.0) let height = CGFloat(50.0) // loading activityIndicatorView = NVActivityIndicatorView(frame: CGRectMake(x, y, width, height), type: .BallClipRotatePulse , color: UIColor.lightGrayColor(), padding: 5) activityIndicatorView.center = self.view.center self.view.addSubview(activityIndicatorView) // 上一篇header headerView = ZFHeaderView(frame: CGRectMake(0, -60, ScreenWidth, 60)) //先隐藏,待web加载完毕后显示 headerView.hidden = true self.webView.scrollView.addSubview(headerView) // 下一篇footer footerView = ZFFooterView(frame: CGRectMake(0, 0, ScreenWidth, 60)) // 先隐藏,待web加载完毕后显示 footerView.hidden = true self.webView.scrollView.addSubview(footerView) } func setupZan() { zanBtn.zanImage = UIImage(named: "News_Navigation_Vote") zanBtn.zanedImage = UIImage(named: "News_Navigation_Voted") // 赞 zanBtn.zanAction = { [weak self](number) -> Void in guard let strongSelf = self else { return } strongSelf.zanNumLabel.text = "\(number)" strongSelf.zanNumLabel.textColor = ThemeColor strongSelf.zanNumLabel.text = "\(number)" } // 取消赞 zanBtn.unzanAction = { [weak self](number)->Void in guard let strongSelf = self else { return } strongSelf.zanNumLabel.text = "\(number)" strongSelf.zanNumLabel.textColor = UIColor.lightGrayColor() strongSelf.zanNumLabel.text = "\(number)" } zanBtn.dk_backgroundColorPicker = BG_COLOR } // MARK: - 配置header 和 footerview func configHederAndFooterView() { // 配置header headerView.configTintColor(hasPic) if viewModel.hasPrevious { headerView.hasHeaderData() }else { headerView.notiNoHeaderData() } if viewModel.hasNext { footerView.hasMoreData() nextNewsBtn.enabled = true }else { footerView.notiNoMoreData() nextNewsBtn.enabled = false } } // MARK: - Networking func getNewsWithId(newsId : String!) { activityIndicatorView.startAnimation() self.isLoading = true //获取新闻详情 viewModel.loadNewsDetail(newsId, complate: { [weak self](newsDetail) -> Void in guard let strongSelf = self else { return } if let img = newsDetail.image { strongSelf.hasPic = true strongSelf.backgroundImg.hidden = false strongSelf.titleLabel.text = newsDetail.title! LightStatusBar() strongSelf.backgroundImg.kf_setImageWithURL(NSURL(string: img)!, placeholderImage: UIImage(named: "avatar")) strongSelf.webView.scrollView.contentInset = UIEdgeInsetsMake(-30, 0, 0, 0) }else { strongSelf.hasPic = false strongSelf.backgroundImg.hidden = true BlackStatusBar() strongSelf.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) } //配置header和footer strongSelf.configHederAndFooterView() if var body = newsDetail.body { if let css = newsDetail.css { if !strongSelf.isNight { //白天模式 body = "<html><head><link rel='stylesheet' href='\(css[0])'></head><body>\(body)</body></html>" }else { //夜间模式 body = "<html><head><link rel='stylesheet' href='\(css[0])'></head><body><div class='night'>\(body)</div></body></html>" } } //print("\(body)") strongSelf.webView.loadHTMLString(body, baseURL: nil) } }) { (error) -> Void in } /// 获取新闻额外信息 viewModel.loadNewsExra(newsId, complate: { [weak self](newsExtra) -> Void in guard let strongSelf = self else { return } strongSelf.newsExtra = newsExtra strongSelf.commentNumLabel.text = "\(newsExtra.comments!)" strongSelf.zanBtn.initNumber = newsExtra.popularity! strongSelf.zanNumLabel.text = "\(newsExtra.popularity!)" }) { (error) -> Void in } } // MARK: - Action // 返回 @IBAction func didClickLeft(sender: UIButton) { navigationController?.popViewControllerAnimated(true) } // 下一条新闻 @IBAction func didClickNext() { getNextNews() } // 分享 @IBAction func didClickShare(sender: UIButton) { print("分享") } // webView tap事件 func tapAction(gesture : UITapGestureRecognizer) { let touchPoint = gesture.locationInView(self.webView) getImage(touchPoint) } // 获取webView图片 func getImage(point : CGPoint) { let js = String(format: "document.elementFromPoint(%f, %f).tagName", arguments: [point.x,point.y]) let tagName = webView.stringByEvaluatingJavaScriptFromString(js) if tagName == "IMG" { let imgURL = String(format: "document.elementFromPoint(%f, %f).src", arguments: [point.x,point.y]) let urlToShow = webView.stringByEvaluatingJavaScriptFromString(imgURL) if let url = urlToShow { var images = [SKPhoto]() let photo = SKPhoto.photoWithImageURL(url) photo.shouldCachePhotoURLImage = true images.append(photo) let browser = SKPhotoBrowser(photos: images) presentViewController(browser, animated: true, completion: {}) } } } // 下一条新闻 func getNextNews() { // 取消赞 zanBtn.isZan = true zanBtn.zanAnimationPlay() UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveLinear, animations: { () -> Void in self.containerView.frame = CGRectMake(0, -ScreenHeight, ScreenWidth, ScreenHeight); self.getNewsWithId(self.viewModel.nextId) }) { (finished) -> Void in if !self.hasPic { if self.isNight { LightStatusBar() }else { BlackStatusBar() } } let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))) dispatch_after(delay, dispatch_get_main_queue()) { self.containerView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight); } } } // 上一条新闻 func getPreviousNews() { // 取消赞 zanBtn.isZan = true zanBtn.zanAnimationPlay() UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveLinear, animations: { () -> Void in self.containerView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight); self.getNewsWithId(self.viewModel.previousId) }) { (finished) -> Void in } } // 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. let commentVC = segue.destinationViewController as! ZFNewsCommentViewController commentVC.commentNum = String(self.newsExtra.comments!) commentVC.newsId = self.newsId } } // MARK: - UIWebViewDelegate extension ZFNewsDetailViewController: UIWebViewDelegate { func webViewDidFinishLoad(webView: UIWebView) { //显示header和footer footerView.hidden = false headerView.hidden = false activityIndicatorView.stopAnimation() self.isLoading = false footerView.y = webView.scrollView.contentSize.height } } // MARK: - UIScrollViewDelegate extension ZFNewsDetailViewController: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { let offSetY = scrollView.contentOffset.y //有图模式 if hasPic { if (Float)(offSetY) >= 170 { if !isNight { //白天模式 BlackStatusBar() }else { //夜间模式 LightStatusBar() } statusView.dk_backgroundColorPicker = BG_COLOR }else { LightStatusBar() statusView.backgroundColor = UIColor.clearColor() } }else { //无图模式 statusView.dk_backgroundColorPicker = BG_COLOR if !isNight { //白天模式 BlackStatusBar() }else { //夜间模式 LightStatusBar() } } //到-80 让webview不再能被拉动 if (-offSetY > 60) { webView.scrollView.contentOffset = CGPointMake(0, -60); } //改变header下拉箭头的方向 if (-offSetY >= 40 ) { UIView.animateWithDuration(0.3, animations: { () -> Void in self.headerView.arrowImageView.transform = CGAffineTransformMakeRotation((CGFloat)(M_PI)) }) }else if -offSetY < 40 { UIView.animateWithDuration(0.3, animations: { () -> Void in self.headerView.arrowImageView.transform = CGAffineTransformIdentity }) } //改变footer下拉箭头的方向 if offSetY + ScreenHeight - 100 > scrollView.contentSize.height { UIView.animateWithDuration(0.3, animations: { () -> Void in self.footerView.arrowImageView.transform = CGAffineTransformMakeRotation((CGFloat)(M_PI)) }) }else { UIView.animateWithDuration(0.3, animations: { () -> Void in self.footerView.arrowImageView.transform = CGAffineTransformIdentity }) } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { let offSetY = scrollView.contentOffset.y if (-offSetY <= 60 && -offSetY >= 40 ) { if !viewModel.hasPrevious { return } if isLoading { return } isLoading = true //上一条新闻 getPreviousNews() }else if (-offSetY > 60) {//到-80 让webview不再能被拉动 self.webView.scrollView.contentOffset = CGPointMake(0, -60); } if (offSetY + ScreenHeight - 100 > scrollView.contentSize.height) { if !viewModel.hasNext { return } if isLoading { return } isLoading = true getNextNews() } } } // MARK: - UIGestureRecognizerDelegate extension ZFNewsDetailViewController: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == tapGesture { return true } return false } }
apache-2.0
withcopper/CopperKit
CopperKit/NSURL+Copper.swift
1
465
// // NSURL+Copper.swift // Copper // // Created by Doug Williams on 10/1/15. // Copyright © 2015 Copper Technologies, Inc. All rights reserved. // import Foundation extension NSURLComponents { public func getQueryStringParameter(name: String) -> String? { if let queryItems = queryItems as [NSURLQueryItem]? { return queryItems.filter({ (item) in item.name == name }).first?.value } return String?() } }
mit
ahoppen/swift
test/stdlib/NSDictionary.swift
41
739
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import StdlibUnittest import Foundation var tests = TestSuite("NSDictionary") tests.test("copy construction") { let expected = ["A":1, "B":2, "C":3, "D":4] let x = NSDictionary(dictionary: expected as NSDictionary) expectEqual(expected, x as! Dictionary) let y = NSMutableDictionary(dictionary: expected as NSDictionary) expectEqual(expected, y as NSDictionary as! Dictionary) } // rdar://problem/27875914 tests.test("subscript with Any") { let d = NSMutableDictionary() d["k"] = "@this is how the world ends" expectEqual((d["k"]! as AnyObject).character(at: 0), 0x40) d["k"] = nil expectTrue(d["k"] == nil) } runAllTests()
apache-2.0
formbound/Plume
Sources/Plume/Result/RowSequence.swift
1
1530
/// A RowSequence is a sequence of database rows over multiple results public class RowSequence<T: Sequence> : Sequence where T.Element : ResultProtocol { internal var resultSequence: T internal init(_ resultSequence: T) { self.resultSequence = resultSequence } /// Returns an iterator over the rows in this sequence. public func makeIterator() -> AnyIterator<T.Element.Element> { var resultIterator = resultSequence.makeIterator() var result = resultIterator.next() guard let firstResult = result else { return AnyIterator<T.Element.Element> { return nil } } var rowIndex: T.Element.Index = firstResult.startIndex return AnyIterator<T.Element.Element> { var nonNilResult: T.Iterator.Element if let existingResult = result { nonNilResult = existingResult } else { if let next = resultIterator.next() { rowIndex = next.startIndex result = next nonNilResult = next } else { return nil } } if rowIndex < nonNilResult.endIndex { let row = nonNilResult[rowIndex] rowIndex = nonNilResult.index(after: rowIndex) if rowIndex > nonNilResult.endIndex { result = nil } return row } return nil } } }
mit
HassanEskandari/HEDatePicker
HEDatePicker/Classes/HEDatePickerComponents.swift
1
381
// // HEDatePickerComponents.swift // HEDatePicker // // Created by Hassan on 8/11/17. // Copyright © 2017 hassaneskandari. All rights reserved. // enum HEDatePickerComponents : Character { case invalid = "!", year = "y", month = "M", day = "d", hour = "h", minute = "m", space = "W" }
mit
nsagora/validation-kit
Sources/Result/ValidationResult.swift
1
1319
import Foundation /** A value that represents a successfull or a failed evalutation. In case of failure, it contains a `ValidationResult.Summary` that summarises the reason behind it. */ public enum ValidationResult { /** Validation was succesfull. */ case success /** Validation failed. Contains `ValidationResult.Summary` that details the cause for failure. */ case failure(Summary) } public extension ValidationResult { internal init(summary: Summary) { if summary.errors.isEmpty { self = .success } else { self = .failure(summary) } } /** `true` if the validation result is valid, `false` otherwise. */ var isSuccessful: Bool { switch self { case .success: return true case .failure: return false } } /** `false` if the validation result is `.failure` or `.unevaluated`, `true` otherwise. */ var isFailed: Bool { return !isSuccessful } /** `Summary` of the validation result. */ var summary: Summary { switch self { case .failure(let summary): return summary case .success: return .successful } } } extension ValidationResult: Equatable {}
apache-2.0
AboutObjectsTraining/swift-comp-reston-2017-01
examples/Shopping/ShoppingTests/Cart.swift
2
1724
// // Copyright (C) 2016 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this example's licensing information. // import Foundation extension Double { var dollarAmount: String { return String(format: "$%.2f", self) } } class Cart: CustomStringConvertible { var items: [Item] = [] init() { } init(items: [Item]) { self.items = items } func add(item: Item) { items.append(item) } var description: String { return items.description } var amount: Double { var total = 0.0 for item in items { total += item.amount } return total } var discountAmount: Double { var total = 0.0 for item in items { total += item.discountAmount } return total } class Item: CustomStringConvertible { let name: String let price: Double var quantity: Int var onSale = false init(name: String, price: Double, quantity: Int, onSale: Bool = false) { self.name = name self.price = price self.quantity = quantity self.onSale = onSale } var amount: Double { return price * Double(quantity) } var discount: Double { return amount < 100 ? 5 : fmin(amount/20, 30) } var discountAmount: Double { return onSale ? amount * (discount/100) : 0 } var description: String { let discountedAmount = (amount - discountAmount).dollarAmount return "\(quantity) \(name) @ $\(price) = \(discountedAmount)" } } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/00968-swift-typebase-isexistentialtype.swift
1
517
// 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 typealias h>(i: end: Range<U) extension Array { func b: (Any, AnyObject) -> T> func call() { enum A : a { } } enum b =
apache-2.0
Tarovk/Mundus_Client
Pods/Aldo/Aldo/AldoEncoding.swift
2
1473
// // AldoEncoding.swift // Pods // // Created by Team Aldo on 11/01/2017. // // import Foundation import Alamofire /** Encoding the information that is passed in the body when a request is send to the server runinng the Aldo Framework. This struct is a fix for a problem that occurs when using the **JSONEncoding** struct of **Alamofire**. **The code in this struct is a combination of JSONEncoding.default and URLEncoding implemented by Alamofire.** For more information about these structs, see [Alamofire](https://github.com/Alamofire/Alamofire). */ public struct AldoEncoding: ParameterEncoding { public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() if urlRequest.httpMethod != HTTPMethod.get.rawValue { guard let parameters = parameters else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: parameters, options: []) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } } return urlRequest } }
mit
tannernelson/ActivityBar
Pod/Classes/ActivityBar.swift
2
6759
import UIKit public class ActivityBar: UIView { //MARK: Properties private var bar = UIView() private var barLeft: NSLayoutConstraint! private var barRight: NSLayoutConstraint! private var animationTimer: NSTimer? //MARK: Constants private let duration: NSTimeInterval = 1 private let waitTime: NSTimeInterval = 0.5 //MARK: Lifecycle private func initializeBar() { super.awakeFromNib() self.bar.backgroundColor = self.color self.bar.translatesAutoresizingMaskIntoConstraints = false self.addSubview(self.bar) //Left and right margins from bar to container self.barLeft = NSLayoutConstraint(item: self.bar, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0) self.addConstraint(self.barLeft) self.barRight = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: self.bar, attribute: .Right, multiplier: 1, constant: 1) self.addConstraint(self.barRight!) //Align top and bottom of bar to container self.addConstraint( NSLayoutConstraint(item: self.bar, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0) ) self.addConstraint( NSLayoutConstraint(item: self.bar, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0) ) } func animate() { let toZero: NSLayoutConstraint let toWidth: NSLayoutConstraint if self.barRight.constant == 0 { toZero = self.barLeft toWidth = self.barRight self.barRight.constant = 0 self.barLeft.constant = self.frame.size.width } else { toZero = self.barRight toWidth = self.barLeft self.barRight.constant = self.frame.size.width self.barLeft.constant = 0 } self.layoutIfNeeded() UIView.animateWithDuration(self.duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { toZero.constant = 0 self.layoutIfNeeded() }, completion: nil) UIView.animateWithDuration(self.duration * 0.7, delay: self.duration * 0.3, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { toWidth.constant = self.frame.size.width self.layoutIfNeeded() }, completion:nil) } //MARK: Public /** Set the ActivityBar to a fixed progress. Valid values are between 0.0 and 1.0. The progress will be `nil` if the bar is currently animating. */ public var progress: Float? { didSet { if self.progress != nil { self.stop() self.hidden = false } else { self.hidden = true } if self.progress > 1.0 { self.progress = 1.0 } else if self.progress < 0 { self.progress = 0 } if let progress = self.progress { UIView.animateWithDuration(self.duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { self.barLeft.constant = 0 self.barRight.constant = self.frame.size.width - (CGFloat(progress) * self.frame.size.width) self.layoutIfNeeded() }, completion: nil) } } } /** The tint color of the ActivityBar. Defaults to the parent UIView's tint color. */ public var color = UIColor.blackColor() { didSet { self.bar.backgroundColor = self.color } } /** Starts animating the ActivityBar. Call `.stop()` to stop. */ public func start() { self.stop() self.barRight.constant = self.frame.size.width - 1 self.layoutIfNeeded() self.hidden = false self.animationTimer = NSTimer.scheduledTimerWithTimeInterval(self.duration + self.waitTime, target: self, selector: "animate", userInfo: nil, repeats: true) self.animate() } /** Stops animating the ActivityBar. Call `.start()` to start. */ public func stop() { self.animationTimer?.invalidate() self.animationTimer = nil } //MARK: Class /** Adds an ActivityBar to the supplied view controller. The added ActivityBar is returned. */ public class func addTo(viewController: UIViewController) -> ActivityBar { let activityBar = ActivityBar() activityBar.alpha = 0.8 var topOffset: CGFloat = 20 let view: UIView let xLayout: NSLayoutConstraint if let navigationBar = viewController.navigationController?.navigationBar { topOffset += navigationBar.frame.size.height view = navigationBar xLayout = NSLayoutConstraint(item: activityBar, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -2) } else { view = viewController.view xLayout = NSLayoutConstraint(item: activityBar, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: topOffset) } activityBar.translatesAutoresizingMaskIntoConstraints = false activityBar.hidden = true view.addSubview(activityBar) //Height = 2 activityBar.addConstraint( NSLayoutConstraint(item: activityBar, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: 2) ) //Insert view at top with top offset view.addConstraint( xLayout ) //Left and right align view to superview view.addConstraint( NSLayoutConstraint(item: activityBar, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0) ) view.addConstraint( NSLayoutConstraint(item: activityBar, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0) ) activityBar.initializeBar() activityBar.color = viewController.view.tintColor return activityBar } }
mit
ben-ng/swift
stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift
1
3657
//===--- PthreadBarriers.swift --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) import Glibc #endif // // Implement pthread barriers. // // (OS X does not implement them.) // public struct _stdlib_pthread_barrierattr_t { public init() {} } public func _stdlib_pthread_barrierattr_init( _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t> ) -> CInt { return 0 } public func _stdlib_pthread_barrierattr_destroy( _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t> ) -> CInt { return 0 } public var _stdlib_PTHREAD_BARRIER_SERIAL_THREAD: CInt { return 1 } public struct _stdlib_pthread_barrier_t { var mutex: UnsafeMutablePointer<pthread_mutex_t>? var cond: UnsafeMutablePointer<pthread_cond_t>? /// The number of threads to synchronize. var count: CUnsignedInt = 0 /// The number of threads already waiting on the barrier. /// /// This shared variable is protected by `mutex`. var numThreadsWaiting: CUnsignedInt = 0 public init() {} } public func _stdlib_pthread_barrier_init( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t>, _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t>?, _ count: CUnsignedInt ) -> CInt { barrier.pointee = _stdlib_pthread_barrier_t() if count == 0 { errno = EINVAL return -1 } barrier.pointee.mutex = UnsafeMutablePointer.allocate(capacity: 1) if pthread_mutex_init(barrier.pointee.mutex!, nil) != 0 { // FIXME: leaking memory. return -1 } barrier.pointee.cond = UnsafeMutablePointer.allocate(capacity: 1) if pthread_cond_init(barrier.pointee.cond!, nil) != 0 { // FIXME: leaking memory, leaking a mutex. return -1 } barrier.pointee.count = count return 0 } public func _stdlib_pthread_barrier_destroy( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t> ) -> CInt { if pthread_cond_destroy(barrier.pointee.cond!) != 0 { // FIXME: leaking memory, leaking a mutex. return -1 } if pthread_mutex_destroy(barrier.pointee.mutex!) != 0 { // FIXME: leaking memory. return -1 } barrier.pointee.cond!.deinitialize() barrier.pointee.cond!.deallocate(capacity: 1) barrier.pointee.mutex!.deinitialize() barrier.pointee.mutex!.deallocate(capacity: 1) return 0 } public func _stdlib_pthread_barrier_wait( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t> ) -> CInt { if pthread_mutex_lock(barrier.pointee.mutex!) != 0 { return -1 } barrier.pointee.numThreadsWaiting += 1 if barrier.pointee.numThreadsWaiting < barrier.pointee.count { // Put the thread to sleep. if pthread_cond_wait(barrier.pointee.cond!, barrier.pointee.mutex!) != 0 { return -1 } if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 { return -1 } return 0 } else { // Reset thread count. barrier.pointee.numThreadsWaiting = 0 // Wake up all threads. if pthread_cond_broadcast(barrier.pointee.cond!) != 0 { return -1 } if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 { return -1 } return _stdlib_PTHREAD_BARRIER_SERIAL_THREAD } }
apache-2.0
typelift/Basis
Basis/Search.swift
2
1708
// // Search.swift // Basis // // Created by Robert Widmann on 9/7/14. // Copyright (c) 2014 TypeLift. All rights reserved. // Released under the MIT license. // /// Returns whether an element is a member of an array. public func elem<A : Equatable>(e : A) -> [A] -> Bool { return { l in any({ $0 == e })(l) } } /// Returns whether an element is not a member of an array. public func notElem<A : Equatable>(e : A) -> [A] -> Bool { return { l in all({ $0 != e })(l) } } /// Returns whether an element is a member of a list. public func elem<A : Equatable>(e : A) -> List<A> -> Bool { return { l in any({ $0 == e })(l) } } /// Returns whether an element is not a member of a list. public func notElem<A : Equatable>(e : A) -> List<A> -> Bool { return { l in all({ $0 != e })(l) } } /// Looks up a key in a dictionary. public func lookup<A : Equatable, B>(e : A) -> [A:B] -> Optional<B> { return { d in switch destructure(d) { case .Empty: return .None case .Destructure(let (x, y), let xys): if e == x { return .Some(y) } return lookup(e)(xys) } } } /// Looks up a key in an array of key-value pairs. public func lookup<A : Equatable, B>(e : A) -> [(A, B)] -> Optional<B> { return { d in switch match(d) { case .Nil: return .None case .Cons(let (x, y), let xys): if e == x { return .Some(y) } return lookup(e)(xys) } } } /// Looks up a key in a list of key-value pairs. public func lookup<A : Equatable, B>(e : A) -> List<(A, B)> -> Optional<B> { return { d in switch d.match() { case .Nil: return .None case .Cons(let (x, y), let xys): if e == x { return .Some(y) } return lookup(e)(xys) } } }
mit
OSzhou/MyTestDemo
PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-Net.git-3268755499654502659/Tests/LinuxMain.swift
1
102
import XCTest @testable import PerfectNetTests XCTMain([ testCase(PerfectNetTests.allTests), ])
apache-2.0
eselkin/DirectionFieldiOS
Pods/GRDB.swift/GRDB/Foundation/DatabaseDateComponents.swift
1
9629
import Foundation /// DatabaseDateComponents reads and stores NSDateComponents in the database. public struct DatabaseDateComponents : DatabaseValueConvertible { /// The available formats for reading and storing date components. public enum Format : String { /// The format "yyyy-MM-dd". case YMD = "yyyy-MM-dd" /// The format "yyyy-MM-dd HH:mm". /// /// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP. case YMD_HM = "yyyy-MM-dd HH:mm" /// The format "yyyy-MM-dd HH:mm:ss". /// /// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP. case YMD_HMS = "yyyy-MM-dd HH:mm:ss" /// The format "yyyy-MM-dd HH:mm:ss.SSS". /// /// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP. case YMD_HMSS = "yyyy-MM-dd HH:mm:ss.SSS" /// The format "HH:mm". case HM = "HH:mm" /// The format "HH:mm:ss". case HMS = "HH:mm:ss" /// The format "HH:mm:ss.SSS". case HMSS = "HH:mm:ss.SSS" } // MARK: - NSDateComponents conversion /// The date components public let dateComponents: NSDateComponents /// The database format public let format: Format /// Creates a DatabaseDateComponents from an NSDateComponents and a format. /// /// The result is nil if and only if *dateComponents* is nil. /// /// - parameter dateComponents: An optional NSDateComponents. /// - parameter format: The format used for storing the date components in /// the database. /// - returns: An optional DatabaseDateComponents. public init?(_ dateComponents: NSDateComponents?, format: Format) { guard let dateComponents = dateComponents else { return nil } self.format = format self.dateComponents = dateComponents } // MARK: - DatabaseValueConvertible adoption /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { let dateString: String? switch format { case .YMD_HM, .YMD_HMS, .YMD_HMSS, .YMD: let year = (dateComponents.year == NSDateComponentUndefined) ? 0 : dateComponents.year let month = (dateComponents.month == NSDateComponentUndefined) ? 1 : dateComponents.month let day = (dateComponents.day == NSDateComponentUndefined) ? 1 : dateComponents.day dateString = NSString(format: "%04d-%02d-%02d", year, month, day) as String default: dateString = nil } let timeString: String? switch format { case .YMD_HM, .HM: let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute timeString = NSString(format: "%02d:%02d", hour, minute) as String case .YMD_HMS, .HMS: let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second timeString = NSString(format: "%02d:%02d:%02d", hour, minute, second) as String case .YMD_HMSS, .HMSS: let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second let nanosecond = (dateComponents.nanosecond == NSDateComponentUndefined) ? 0 : dateComponents.nanosecond timeString = NSString(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) as String default: timeString = nil } return DatabaseValue([dateString, timeString].flatMap { $0 }.joinWithSeparator(" ")) } /// Returns a DatabaseDateComponents if *databaseValue* contains a /// valid date. /// /// - parameter databaseValue: A DatabaseValue. /// - returns: An optional DatabaseDateComponents. public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseDateComponents? { // https://www.sqlite.org/lang_datefunc.html // // Supported formats are: // // - YYYY-MM-DD // - YYYY-MM-DD HH:MM // - YYYY-MM-DD HH:MM:SS // - YYYY-MM-DD HH:MM:SS.SSS // - YYYY-MM-DDTHH:MM // - YYYY-MM-DDTHH:MM:SS // - YYYY-MM-DDTHH:MM:SS.SSS // - HH:MM // - HH:MM:SS // - HH:MM:SS.SSS // We need a String guard let string = String.fromDatabaseValue(databaseValue) else { return nil } let dateComponents = NSDateComponents() let scanner = NSScanner(string: string) scanner.charactersToBeSkipped = NSCharacterSet() let hasDate: Bool // YYYY or HH var initialNumber: Int = 0 if !scanner.scanInteger(&initialNumber) { return nil } switch scanner.scanLocation { case 2: // HH hasDate = false let hour = initialNumber if hour >= 0 && hour <= 23 { dateComponents.hour = hour } else { return nil } case 4: // YYYY hasDate = true let year = initialNumber if year >= 0 && year <= 9999 { dateComponents.year = year } else { return nil } // - if !scanner.scanString("-", intoString: nil) { return nil } // MM var month: Int = 0 if scanner.scanInteger(&month) && month >= 1 && month <= 12 { dateComponents.month = month } else { return nil } // - if !scanner.scanString("-", intoString: nil) { return nil } // DD var day: Int = 0 if scanner.scanInteger(&day) && day >= 1 && day <= 31 { dateComponents.day = day } else { return nil } // YYYY-MM-DD if scanner.atEnd { return DatabaseDateComponents(dateComponents, format: .YMD) } // T/space if !scanner.scanString("T", intoString: nil) && !scanner.scanString(" ", intoString: nil) { return nil } // HH var hour: Int = 0 if scanner.scanInteger(&hour) && hour >= 0 && hour <= 23 { dateComponents.hour = hour } else { return nil } default: return nil } // : if !scanner.scanString(":", intoString: nil) { return nil } // MM var minute: Int = 0 if scanner.scanInteger(&minute) && minute >= 0 && minute <= 59 { dateComponents.minute = minute } else { return nil } // [YYYY-MM-DD] HH:MM if scanner.atEnd { if hasDate { return DatabaseDateComponents(dateComponents, format: .YMD_HM) } else { return DatabaseDateComponents(dateComponents, format: .HM) } } // : if !scanner.scanString(":", intoString: nil) { return nil } // SS var second: Int = 0 if scanner.scanInteger(&second) && second >= 0 && second <= 59 { dateComponents.second = second } else { return nil } // [YYYY-MM-DD] HH:MM:SS if scanner.atEnd { if hasDate { return DatabaseDateComponents(dateComponents, format: .YMD_HMS) } else { return DatabaseDateComponents(dateComponents, format: .HMS) } } // . if !scanner.scanString(".", intoString: nil) { return nil } // SSS var millisecondDigits: NSString? = nil if scanner.scanCharactersFromSet(NSCharacterSet.decimalDigitCharacterSet(), intoString: &millisecondDigits), var millisecondDigits = millisecondDigits { if millisecondDigits.length > 3 { millisecondDigits = millisecondDigits.substringToIndex(3) } dateComponents.nanosecond = millisecondDigits.integerValue * 1_000_000 } else { return nil } // [YYYY-MM-DD] HH:MM:SS.SSS if scanner.atEnd { if hasDate { return DatabaseDateComponents(dateComponents, format: .YMD_HMSS) } else { return DatabaseDateComponents(dateComponents, format: .HMSS) } } // Unknown format return nil } }
gpl-3.0
Mobilette/AniMee
Pods/p2.OAuth2/Sources/Base/OAuth2CodeGrant.swift
2
4928
// // OAuth2CodeGrant.swift // OAuth2 // // Created by Pascal Pfiffner on 6/16/14. // Copyright 2014 Pascal Pfiffner // // 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 /** A class to handle authorization for confidential clients via the authorization code grant method. This auth flow is designed for clients that are capable of protecting their client secret but can be used from installed apps. During code exchange and token refresh flows, **if** the client has a secret, a "Basic key:secret" Authorization header will be used. If not the client key will be embedded into the request body. */ public class OAuth2CodeGrant: OAuth2 { public override class var grantType: String { return "authorization_code" } override public class var responseType: String? { return "code" } // MARK: - Token Request /** Generate the URL to be used for the token request from known instance variables and supplied parameters. This will set "grant_type" to "authorization_code", add the "code" provided and forward to `authorizeURLWithBase()` to fill the remaining parameters. The "client_id" is only added if there is no secret (public client) or if the request body is used for id and secret. - parameter code: The code you want to exchange for an access token - parameter params: Optional additional params to add as URL parameters - returns: The URL you can use to exchange the code for an access token */ func tokenURLWithCode(code: String, params: OAuth2StringDict? = nil) throws -> NSURL { guard let redirect = context.redirectURL else { throw OAuth2Error.NoRedirectURL } var urlParams = params ?? OAuth2StringDict() urlParams["code"] = code urlParams["grant_type"] = self.dynamicType.grantType urlParams["redirect_uri"] = redirect if let secret = clientConfig.clientSecret { if authConfig.secretInBody { urlParams["client_secret"] = secret urlParams["client_id"] = clientConfig.clientId } } else { urlParams["client_id"] = clientConfig.clientId } return try authorizeURLWithParams(urlParams, asTokenURL: true) } /** Create a request for token exchange. */ func tokenRequestWithCode(code: String) throws -> NSMutableURLRequest { let url = try tokenURLWithCode(code) return try tokenRequestWithURL(url) } /** Extracts the code from the redirect URL and exchanges it for a token. */ override public func handleRedirectURL(redirect: NSURL) { logIfVerbose("Handling redirect URL \(redirect.description)") do { let code = try validateRedirectURL(redirect) exchangeCodeForToken(code) } catch let error { didFail(error) } } /** Takes the received code and exchanges it for a token. */ public func exchangeCodeForToken(code: String) { do { guard !code.isEmpty else { throw OAuth2Error.PrerequisiteFailed("I don't have a code to exchange, let the user authorize first") } let post = try tokenRequestWithCode(code) logIfVerbose("Exchanging code \(code) for access token at \(post.URL!)") performRequest(post) { data, status, error in do { guard let data = data else { throw error ?? OAuth2Error.NoDataInResponse } let params = try self.parseAccessTokenResponse(data) if status < 400 { self.logIfVerbose("Did exchange code for access [\(nil != self.clientConfig.accessToken)] and refresh [\(nil != self.clientConfig.refreshToken)] tokens") self.didAuthorize(params) } else { throw OAuth2Error.Generic("\(status)") } } catch let error { self.didFail(error) } } } catch let error { didFail(error) } } // MARK: - Utilities /** Validates the redirect URI: returns a tuple with the code and nil on success, nil and an error on failure. */ func validateRedirectURL(redirect: NSURL) throws -> String { let comp = NSURLComponents(URL: redirect, resolvingAgainstBaseURL: true) if let compQuery = comp?.query where compQuery.characters.count > 0 { let query = OAuth2CodeGrant.paramsFromQuery(comp!.percentEncodedQuery!) if let cd = query["code"] { // we got a code, use it if state is correct (and reset state) try assureMatchesState(query) return cd } throw OAuth2Error.ResponseError("No “code” received") } throw OAuth2Error.PrerequisiteFailed("The redirect URL contains no query fragment") } }
mit
changjiashuai/AudioKit
Tests/Tests/AKMoogVCF.swift
14
1537
// // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 12/19/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: NSTimeInterval = 10.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let filename = "AKSoundFiles.bundle/Sounds/PianoBassDrumLoop.wav" let audio = AKFileInput(filename: filename) let mono = AKMix(monoAudioFromStereoInput: audio) auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:mono) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let cutoffFrequency = AKLine( firstPoint: 200.ak, secondPoint: 6000.ak, durationBetweenPoints: testDuration.ak ) let moogVCF = AKMoogVCF(input: audioSource) moogVCF.cutoffFrequency = cutoffFrequency setAudioOutput(moogVCF) enableParameterLog( "Cutoff Frequency = ", parameter: moogVCF.cutoffFrequency, timeInterval:0.1 ) resetParameter(audioSource) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) processor.play() instrument.play() NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
mit
hwsyy/ruby-china-ios
RubyChina/Controllers/TopicsController.swift
4
9575
// // NodesController.swift // RubyChina // // Created by Jianqiu Xiao on 5/22/15. // Copyright (c) 2015 Jianqiu Xiao. All rights reserved. // import AFNetworking import CCBottomRefreshControl import SwiftyJSON import TPKeyboardAvoiding import UINavigationBar_Addition import UIKit class TopicsController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UIToolbarDelegate { var emptyView = EmptyView() var failureView = FailureView() var loadingView = LoadingView() var parameters: JSON = [:] var refreshing = false var segmentedControl = UISegmentedControl(items: ["默认", "最新", "热门", "精华"]) var tableView = TPKeyboardAvoidingTableView() var toolbar = UIToolbar() var topRefreshControl = UIRefreshControl() var topics: JSON = [] override func viewDidLoad() { automaticallyAdjustsScrollViewInsets = false navigationItem.rightBarButtonItem = UIBarButtonItem(title: "账号", style: .Plain, target: self, action: Selector("user")) navigationItem.title = JSON(NSBundle.mainBundle().localizedInfoDictionary!)["CFBundleDisplayName"].string view.backgroundColor = Helper.backgroundColor tableView.allowsMultipleSelection = false tableView.autoresizingMask = .FlexibleWidth | .FlexibleHeight tableView.backgroundColor = .clearColor() tableView.dataSource = self tableView.delegate = self tableView.frame = view.bounds tableView.registerClass(TopicCell.self, forCellReuseIdentifier: "Cell") tableView.tableFooterView = UIView() view.addSubview(tableView) let searchBar = UISearchBar() searchBar.autocapitalizationType = .None searchBar.autocorrectionType = .No searchBar.delegate = self searchBar.placeholder = "搜索" searchBar.sizeToFit() tableView.tableHeaderView = searchBar topRefreshControl.addTarget(self, action: Selector("topRefresh"), forControlEvents: .ValueChanged) tableView.addSubview(topRefreshControl) let bottomRefreshControl = UIRefreshControl() bottomRefreshControl.addTarget(self, action: Selector("bottomRefresh"), forControlEvents: .ValueChanged) tableView.bottomRefreshControl = bottomRefreshControl toolbar.autoresizingMask = .FlexibleWidth toolbar.delegate = self toolbar.frame.size.width = view.bounds.width view.addSubview(toolbar) segmentedControl.addTarget(self, action: Selector("segmentedControlValueChanged:"), forControlEvents: .ValueChanged) segmentedControl.autoresizingMask = .FlexibleLeftMargin | .FlexibleRightMargin | .FlexibleTopMargin | .FlexibleBottomMargin segmentedControl.frame.size.height = 28 segmentedControl.selectedSegmentIndex = max(0, segmentedControl.selectedSegmentIndex) toolbar.addSubview(segmentedControl) failureView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("autoRefresh"))) view.addSubview(failureView) view.addSubview(loadingView) emptyView.text = "没有帖子" view.addSubview(emptyView) } override func viewWillAppear(animated: Bool) { navigationController?.navigationBar.hideBottomHairline() if tableView.indexPathForSelectedRow() != nil { tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow()!, animated: true) } traitCollectionDidChange(nil) if topics.count == 0 { autoRefresh() } Helper.trackView(self) } override func viewWillDisappear(animated: Bool) { navigationController?.navigationBar.showBottomHairline() } func autoRefresh() { if refreshing { return } loadingView.show() loadData() } func topRefresh() { if refreshing { topRefreshControl.endRefreshing(); return } topics = [] loadData() } func bottomRefresh() { if refreshing { tableView.bottomRefreshControl.endRefreshing(); tableView.bottomRefreshControl.hidden = true; return } loadData() } func stopRefresh() { refreshing = false loadingView.hide() topRefreshControl.endRefreshing() tableView.bottomRefreshControl.endRefreshing() tableView.bottomRefreshControl.hidden = true } func loadData() { if refreshing { return } refreshing = true failureView.hide() emptyView.hide() let selectedSegmentIndex = segmentedControl.selectedSegmentIndex parameters["limit"].object = 30 parameters["offset"].object = topics.count parameters["type"].object = ["last_actived", "recent", "popular", "excellent"][selectedSegmentIndex] AFHTTPRequestOperationManager(baseURL: Helper.baseURL).GET("/topics.json", parameters: parameters.object, success: { (operation, responseObject) in self.stopRefresh() if JSON(responseObject)["topics"].count == 0 { if self.topics.count == 0 { self.emptyView.show() } else { return } } if self.topics.count == 0 { self.tableView.scrollRectToVisible(CGRect(x: 0, y: self.tableView.tableHeaderView?.frame.height ?? 0, width: 1, height: 1), animated: false) } self.topics = JSON(self.topics.arrayValue + JSON(responseObject)["topics"].arrayValue) self.tableView.reloadData() self.segmentedControl.selectedSegmentIndex = selectedSegmentIndex }) { (operation, error) in self.stopRefresh() self.failureView.show() } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return topics.count } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 61 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let cell = TopicCell() cell.accessoryType = .DisclosureIndicator cell.detailTextLabel?.text = " " cell.frame.size.width = tableView.frame.width cell.textLabel?.text = topics[indexPath.row]["title"].string cell.topic = topics[indexPath.row] cell.layoutSubviews() let textLabelHeight = cell.textLabel!.textRectForBounds(cell.textLabel!.frame, limitedToNumberOfLines: cell.textLabel!.numberOfLines).height return 10 + textLabelHeight + 4 + cell.detailTextLabel!.frame.height + 10 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TopicCell cell.topic = topics[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let topicController = TopicController() topicController.topic = topics[indexPath.row] splitViewController?.showDetailViewController(UINavigationController(rootViewController: topicController), sender: self) } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if (indexPath.row + 1) % 30 == 0 && indexPath.row + 1 == topics.count { autoRefresh() } } func positionForBar(bar: UIBarPositioning) -> UIBarPosition { return .Top } override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) toolbar.frame.origin.y = min(UIApplication.sharedApplication().statusBarFrame.width, UIApplication.sharedApplication().statusBarFrame.height) + navigationController!.navigationBar.frame.height toolbar.frame.size.height = navigationController!.navigationBar.frame.height tableView.contentInset.top = toolbar.frame.origin.y + toolbar.frame.height tableView.scrollIndicatorInsets.top = toolbar.frame.origin.y + toolbar.frame.height segmentedControl.frame.size.width = min(320, view.bounds.width, view.bounds.height) - 16 segmentedControl.frame.origin.x = (view.bounds.width - segmentedControl.frame.width) / 2 } func segmentedControlValueChanged(segmentedControl: UISegmentedControl) { topics = [] autoRefresh() } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() parameters["query"].string = searchBar.text != "" ? searchBar.text : nil topics = [] tableView.reloadData() autoRefresh() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() searchBar.setShowsCancelButton(false, animated: true) searchBar.text = "" searchBarSearchButtonClicked(searchBar) } func user() { navigationController?.pushViewController(UserController(), animated: true) } func selectNode(node: JSON) { parameters["node_id"].object = node["id"].object title = node["name"].string topics = [] tableView.reloadData() navigationController?.popToViewController(self, animated: true) } }
mit
Enziferum/iosBoss
iosBoss/Extensions.swift
1
3366
// // Extensions.swift // IosHelper // // Created by AlexRaag on 30/08/2017. // Copyright © 2017 AlexRaag. All rights reserved. // import UIKit /**TODO Block extension UIImageView need struct for printing exception */ extension String:URLable{ public func asURL() throws -> URL { guard let url = URL(string:self) else { throw urlError.NoAsURL } return url } public func Decode(_ data:Data)->String{ return String(data: data, encoding: .utf8)! } //MARK:allows Cut substring from given String /** NOTE: from Swift 3 in String Must be Range<String.Index> - Parameter lowerChar: lower Bound - Parameter upChar: up Bound - Returns:String */ public func getSubStr(Str:String,lowerChar:Character,upChar:Character)->String { var symbolIndex:Int=0 var lower:String.Index? var up:String.Index? for symbol in Str.characters { if symbol == lowerChar { lower = Str.index(Str.startIndex, offsetBy: symbolIndex+1) } if symbol == upChar { up = Str.index(Str.startIndex, offsetBy: symbolIndex) } symbolIndex += 1 } return String(Str[lower!..<up!]) } //Subscript for Giving index// // public subscript } extension UIView{ /** Allow to use Custom Constraints - Parameter Arg: Constraint Value as String - Parameter Views: Try to set Constraints to all Views */ func AddConstraints(use Arg:String,forViews Views:UIView...){ var ViewDict = [String:UIView]() for (index,view) in Views.enumerated(){ let Key = "v\(Views[index])" ViewDict[Key] = view } addConstraints(NSLayoutConstraint.constraints(withVisualFormat: Arg, options: NSLayoutFormatOptions(), metrics: nil, views: ViewDict)) } } extension UIColor { //MARK:Color /** By default UIColor - return not standard rgba color In this way need make Retranslation -Return UIColor */ func Color(red:CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)->UIColor{ return UIColor(red: red/255, green:green/255, blue: blue/255, alpha: alpha) } //MARK: Color Randomize public func Randomize(red:Int?=255,green:Int?=255,blue:Int?=255)->UIColor{ let Red = Int(arc4random_uniform(UInt32(red!))) let Green = Int(arc4random_uniform(UInt32(green!))) let Blue = Int(arc4random_uniform(UInt32(blue!))) return UIColor().Color(red: CGFloat(Red), green: CGFloat(Green), blue:CGFloat(Blue), alpha: 1) } } extension UIImageView{ public enum ErrorLoad:Error{ case NoData //print("No Data was given for loading Image") } /** Allow to LoadAsync Image using URL */ open func LoadAsync(fromURl url:String)throws{ let request=Request() request.accompishData(withUrl: url, handler: { (data) in guard let data = data else { //throw ErrorLoad.NoData return } DispatchQueue.main.async { self.image=UIImage(data: data) } }) } }
mit
khizkhiz/swift
test/Interpreter/array_of_optional.swift
8
404
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // <rdar://problem/15609900> // CHECK: 10 // CHECK: none // CHECK: 20 // CHECK: none // CHECK: 30 // CHECK: hello world func main() { var arrOpt : [Int?] = [10,.none,20,.none,30] for item in arrOpt { switch item { case .none: print("none") case .some(var v): print(v) } } print("hello world") } main()
apache-2.0
khizkhiz/swift
validation-test/compiler_crashers_fixed/00030-string-as-extensibe-collection.script.swift
2
255
// RUN: %target-swift-frontend %s -emit-ir // Test case submitted to project by https://github.com/tmu (Teemu Kurppa) extension String : RangeReplaceableCollection {} func f<S : RangeReplaceableCollection>(seq: S) -> S { return S() + seq } f("a")
apache-2.0
tkremenek/swift
test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-struct-1argument-1distinct_use.swift
14
3030
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main9NamespaceV5ValueOySS_SiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main9NamespaceV5ValueOySS_SiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 513, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceV5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] struct Namespace<Arg> { enum Value<First> { case first(First) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}}, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceV5ValueOySS_SiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: } func doit() { consume( Namespace<String>.Value.first(13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceV5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, // CHECK-SAME: i8* [[ERASED_TYPE_1]], // CHECK-SAME: i8* [[ERASED_TYPE_2]], // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceV5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
MasterGerhard/ParkShark
ParkShark/AboutViewController.swift
1
631
// // AboutViewController.swift // ParkShark // // Created by Steven Gerhard on 11/19/14. // Copyright (c) 2014 ParkShark. All rights reserved. // import UIKit class AboutViewController: UIViewController, navMenuBarButtionItem { override func viewDidLoad() { super.viewDidLoad() var menuTitle : String? = "Menu" var menuButton = UIBarButtonItem(title: menuTitle, style: UIBarButtonItemStyle.Plain, target: self, action: "menuButtonPressed") navigationItem.leftBarButtonItem = menuButton } func menuButtonPressed() { toggleSideMenuView() } }
mit
FirebaseExtended/firestore-codelab-extended-swift
FriendlyEats/Common/RestaurantTableViewDataSource.swift
1
2262
// // Copyright (c) 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import FirebaseFirestore /// A class that populates a table view using RestaurantTableViewCell cells /// with restaurant data from a Firestore query. Consumers should update the /// table view with new data from Firestore in the updateHandler closure. @objc class RestaurantTableViewDataSource: NSObject, UITableViewDataSource { private var restaurants: [Restaurant] = [] public init(query: Query, updateHandler: @escaping ([DocumentChange]) -> ()) { fatalError("Unimplemented") } // Pull data from Firestore /// Starts listening to the Firestore query and invoking the updateHandler. public func startUpdates() { fatalError("Unimplemented") } /// Stops listening to the Firestore query. updateHandler will not be called unless startListening /// is called again. public func stopUpdates() { fatalError("Unimplemented") } /// Returns the restaurant at the given index. subscript(index: Int) -> Restaurant { return restaurants[index] } /// The number of items in the data source. public var count: Int { return restaurants.count } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantTableViewCell", for: indexPath) as! RestaurantTableViewCell let restaurant = restaurants[indexPath.row] cell.populate(restaurant: restaurant) return cell } }
apache-2.0
joerocca/GitHawk
Pods/Pageboy/Sources/Pageboy/Extensions/PageboyViewController+ScrollDetection.swift
1
15999
// // PageboyScrollDetection.swift // Pageboy // // Created by Merrick Sapsford on 13/02/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit // MARK: - UIPageViewControllerDelegate, UIScrollViewDelegate extension PageboyViewController: UIPageViewControllerDelegate, UIScrollViewDelegate { // MARK: UIPageViewControllerDelegate public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { guard pageViewControllerIsActual(pageViewController) else { return } self.pageViewController(pageViewController, willTransitionTo: pendingViewControllers, animated: false) } internal func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController], animated: Bool) { guard pageViewControllerIsActual(pageViewController) else { return } guard let viewController = pendingViewControllers.first, let index = viewControllerMap.index(forObjectAfter: { return $0.object === viewController }) else { return } self.expectedTransitionIndex = index let direction = NavigationDirection.forPage(index, previousPage: self.currentIndex ?? index) self.delegate?.pageboyViewController(self, willScrollToPageAt: index, direction: direction, animated: animated) } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { guard pageViewControllerIsActual(pageViewController) else { return } guard completed == true else { return } if let viewController = pageViewController.viewControllers?.first, let index = viewControllerMap.index(forObjectAfter: { return $0.object === viewController }) { guard index == self.expectedTransitionIndex else { return } self.updateCurrentPageIndexIfNeeded(index) } } public func presentationCount(for pageViewController: UIPageViewController) -> Int { guard showsPageControl else { return -1 } return pageCount ?? 0 } public func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard showsPageControl else { return -1 } return targetIndex ?? 0 } // MARK: UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } guard self.updateContentOffsetForBounceIfNeeded(scrollView: scrollView) == false else { return } guard let currentIndex = self.currentIndex else { return } let previousPagePosition = self.previousPagePosition ?? 0.0 // calculate offset / page size for relative orientation var pageSize: CGFloat! var contentOffset: CGFloat! switch navigationOrientation { case .horizontal: pageSize = scrollView.frame.size.width if scrollView.layoutIsRightToLeft { contentOffset = pageSize + (pageSize - scrollView.contentOffset.x) } else { contentOffset = scrollView.contentOffset.x } case .vertical: pageSize = scrollView.frame.size.height contentOffset = scrollView.contentOffset.y } guard let scrollIndexDiff = self.pageScrollIndexDiff(forCurrentIndex: currentIndex, expectedIndex: self.expectedTransitionIndex, currentContentOffset: contentOffset, pageSize: pageSize) else { return } guard var pagePosition = self.pagePosition(forContentOffset: contentOffset, pageSize: pageSize, indexDiff: scrollIndexDiff) else { return } // do not continue if a page change is detected guard !self.detectCurrentPageIndexIfNeeded(pagePosition: pagePosition, scrollView: scrollView) else { return } // do not continue if previous position equals current if previousPagePosition == pagePosition { return } // update relative page position for infinite overscroll if required self.detectInfiniteOverscrollIfNeeded(pagePosition: &pagePosition) // provide scroll updates var positionPoint: CGPoint! let direction = NavigationDirection.forPosition(pagePosition, previous: previousPagePosition) if self.navigationOrientation == .horizontal { positionPoint = CGPoint(x: pagePosition, y: scrollView.contentOffset.y) } else { positionPoint = CGPoint(x: scrollView.contentOffset.x, y: pagePosition) } // ignore duplicate updates guard self.currentPosition != positionPoint else { return } self.currentPosition = positionPoint self.delegate?.pageboyViewController(self, didScrollTo: positionPoint, direction: direction, animated: self.isScrollingAnimated) self.previousPagePosition = pagePosition } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } if self.autoScroller.cancelsOnScroll { self.autoScroller.cancel() } } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } self.scrollView(didEndScrolling: scrollView) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } self.scrollView(didEndScrolling: scrollView) } public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { guard scrollViewIsActual(scrollView) else { return } self.updateContentOffsetForBounceIfNeeded(scrollView: scrollView) } private func scrollView(didEndScrolling scrollView: UIScrollView) { guard scrollViewIsActual(scrollView) else { return } if self.autoScroller.restartsOnScrollEnd { self.autoScroller.restart() } } // MARK: Calculations /// Detect whether the scroll view is overscrolling while infinite scroll is enabled /// Adjusts pagePosition if required. /// /// - Parameter pagePosition: the relative page position. private func detectInfiniteOverscrollIfNeeded(pagePosition: inout CGFloat) { guard self.isInfinitelyScrolling(forPosition: pagePosition) else { return } let maxPagePosition = CGFloat((self.viewControllerCount ?? 1) - 1) var integral: Double = 0.0 var progress = CGFloat(modf(fabs(Double(pagePosition)), &integral)) var maxInfinitePosition: CGFloat! if pagePosition > 0.0 { progress = 1.0 - progress maxInfinitePosition = 0.0 } else { maxInfinitePosition = maxPagePosition } var infinitePagePosition = maxPagePosition * progress if fmod(progress, 1.0) == 0.0 { infinitePagePosition = maxInfinitePosition } pagePosition = infinitePagePosition } /// Whether a position is infinitely scrolling between end ranges /// /// - Parameter pagePosition: The position. /// - Returns: Whether the position is infinitely scrolling. private func isInfinitelyScrolling(forPosition pagePosition: CGFloat) -> Bool { let maxPagePosition = CGFloat((self.viewControllerCount ?? 1) - 1) let overscrolling = pagePosition < 0.0 || pagePosition > maxPagePosition guard self.isInfiniteScrollEnabled && overscrolling else { return false } return true } /// Detects whether a page boundary has been passed. /// As pageViewController:didFinishAnimating is not reliable. /// /// - Parameters: /// - pageOffset: The current page scroll offset /// - scrollView: The scroll view that is being scrolled. /// - Returns: Whether a page transition has been detected. private func detectCurrentPageIndexIfNeeded(pagePosition: CGFloat, scrollView: UIScrollView) -> Bool { guard let currentIndex = self.currentIndex else { return false } guard scrollView.isDecelerating == false else { return false } let isPagingForward = pagePosition > self.previousPagePosition ?? 0.0 if scrollView.isTracking { if isPagingForward && pagePosition >= CGFloat(currentIndex + 1) { self.updateCurrentPageIndexIfNeeded(currentIndex + 1) return true } else if !isPagingForward && pagePosition <= CGFloat(currentIndex - 1) { self.updateCurrentPageIndexIfNeeded(currentIndex - 1) return true } } let isOnPage = pagePosition.truncatingRemainder(dividingBy: 1) == 0 if isOnPage { guard currentIndex != self.currentIndex else { return false} self.currentIndex = currentIndex } return false } /// Safely update the current page index. /// /// - Parameter index: the proposed index. private func updateCurrentPageIndexIfNeeded(_ index: Int) { guard self.currentIndex != index, index >= 0 && index < self.viewControllerCount ?? 0 else { return } self.currentIndex = index } /// Calculate the expected index diff for a page scroll. /// /// - Parameters: /// - index: The current index. /// - expectedIndex: The target page index. /// - currentContentOffset: The current content offset. /// - pageSize: The size of each page. /// - Returns: The expected index diff. private func pageScrollIndexDiff(forCurrentIndex index: Int?, expectedIndex: Int?, currentContentOffset: CGFloat, pageSize: CGFloat) -> CGFloat? { guard let index = index else { return nil } let expectedIndex = expectedIndex ?? index let expectedDiff = CGFloat(max(1, abs(expectedIndex - index))) let expectedPosition = self.pagePosition(forContentOffset: currentContentOffset, pageSize: pageSize, indexDiff: expectedDiff) ?? CGFloat(index) guard self.isInfinitelyScrolling(forPosition: expectedPosition) == false else { return 1 } return expectedDiff } /// Calculate the relative page position. /// /// - Parameters: /// - contentOffset: The current contentOffset. /// - pageSize: The current page size. /// - indexDiff: The expected difference between current / target page indexes. /// - Returns: The relative page position. private func pagePosition(forContentOffset contentOffset: CGFloat, pageSize: CGFloat, indexDiff: CGFloat) -> CGFloat? { guard let currentIndex = self.currentIndex else { return nil } let scrollOffset = contentOffset - pageSize let pageOffset = (CGFloat(currentIndex) * pageSize) + (scrollOffset * indexDiff) let position = pageOffset / pageSize return position.isFinite ? position : 0 } /// Update the scroll view contentOffset for bouncing preference if required. /// /// - Parameter scrollView: The scroll view. /// - Returns: Whether the contentOffset was manipulated to achieve bouncing preference. @discardableResult private func updateContentOffsetForBounceIfNeeded(scrollView: UIScrollView) -> Bool { guard self.bounces == false else { return false } let previousContentOffset = scrollView.contentOffset if self.currentIndex == 0 && scrollView.contentOffset.x < scrollView.bounds.size.width { scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0.0) } if self.currentIndex == (self.viewControllerCount ?? 1) - 1 && scrollView.contentOffset.x > scrollView.bounds.size.width { scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0.0) } return previousContentOffset != scrollView.contentOffset } // MARK: Utilities /// Check that a scroll view is the actual page view controller managed instance. /// /// - Parameter scrollView: The scroll view to check. /// - Returns: Whether it is the actual managed instance. private func scrollViewIsActual(_ scrollView: UIScrollView) -> Bool { return scrollView === pageViewController?.scrollView } /// Check that a UIPageViewController is the actual managed instance. /// /// - Parameter pageViewController: The page view controller to check. /// - Returns: Whether it is the actual managed instance. private func pageViewControllerIsActual(_ pageViewController: UIPageViewController) -> Bool { return pageViewController === self.pageViewController } } // MARK: - NavigationDirection detection internal extension PageboyViewController.NavigationDirection { var pageViewControllerNavDirection: UIPageViewControllerNavigationDirection { get { switch self { case .reverse: return .reverse default: return .forward } } } static func forPage(_ page: Int, previousPage: Int) -> PageboyViewController.NavigationDirection { return self.forPosition(CGFloat(page), previous: CGFloat(previousPage)) } static func forPosition(_ position: CGFloat, previous previousPosition: CGFloat) -> PageboyViewController.NavigationDirection { if position == previousPosition { return .neutral } return position > previousPosition ? .forward : .reverse } } internal extension UIScrollView { /// Whether the scroll view can be assumed to be interactively scrolling var isProbablyActiveInScroll: Bool { return self.isTracking || self.isDragging || self.isDecelerating } }
mit
xwu/swift
test/ModuleInterface/result_builders.swift
7
2343
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -typecheck -module-name ResultBuilders -emit-module-interface-path %t/ResultBuilders.swiftinterface %s // RUN: %FileCheck %s < %t/ResultBuilders.swiftinterface // RUN: %target-swift-frontend -I %t -typecheck -verify %S/Inputs/result_builders_client.swift // RUN: %target-swift-frontend -compile-module-from-interface %t/ResultBuilders.swiftinterface -o %t/ResultBuilders.swiftmodule // RUN: %FileCheck %s < %t/ResultBuilders.swiftinterface // CHECK: @_functionBuilder public struct TupleBuilder @resultBuilder public struct TupleBuilder { public static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) { return (t1, t2) } public static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3) -> (T1, T2, T3) { return (t1, t2, t3) } public static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4) -> (T1, T2, T3, T4) { return (t1, t2, t3, t4) } public static func buildBlock<T1, T2, T3, T4, T5>( _ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5 ) -> (T1, T2, T3, T4, T5) { return (t1, t2, t3, t4, t5) } public static func buildDo<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) { return (t1, t2) } public static func buildDo<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3) -> (T1, T2, T3) { return (t1, t2, t3) } public static func buildIf<T>(_ value: T?) -> T? { return value } } // CHECK-LABEL: public func tuplify<T>(_ cond: Swift.Bool, @ResultBuilders.TupleBuilder body: (Swift.Bool) -> T) public func tuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) { print(body(cond)) } public struct UsesBuilderProperty { // CHECK: public var myVar: (Swift.String, Swift.String) { // CHECK-NEXT: get // CHECK-NEXT: } @TupleBuilder public var myVar: (String, String) { "hello" "goodbye" } // CHECK: public func myFunc(@ResultBuilders.TupleBuilder fn: () -> ()) public func myFunc(@TupleBuilder fn: () -> ()) {} } public protocol ProtocolWithBuilderProperty { associatedtype Assoc // CHECK: @ResultBuilders.TupleBuilder var myVar: Self.Assoc { get } @TupleBuilder var myVar: Assoc { get } // CHECK: @ResultBuilders.TupleBuilder func myFunc<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) @TupleBuilder func myFunc<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) }
apache-2.0
Sojjocola/EladeDroneControl
EladeDroneControl/ViewController.swift
1
533
// // ViewController.swift // EladeDroneControl // // Created by François Chevalier on 20/09/2015. // Copyright © 2015 François Chevalier. 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. } }
mit
xBrux/Pensieve
Source/Core/Value.swift
1
3525
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // /// - Warning: `Binding` is a protocol that SQLite.swift uses internally to /// directly map SQLite types to Swift types. /// /// Do not conform custom types to the Binding protocol. See the `Value` /// protocol, instead. /*public*/ protocol Binding {} /*public*/ protocol Number : Binding {} /*public*/ protocol Value : Expressible { // extensions cannot have inheritance clauses typealias ValueType = Self typealias Datatype : Binding static var declaredDatatype: String { get } static func fromDatatypeValue(datatypeValue: Datatype) -> ValueType var datatypeValue: Datatype { get } } extension Double : Number, Value { /*public*/ static let declaredDatatype = "REAL" /*public*/ static func fromDatatypeValue(datatypeValue: Double) -> Double { return datatypeValue } /*public*/ var datatypeValue: Double { return self } } extension Int64 : Number, Value { /*public*/ static let declaredDatatype = "INTEGER" /*public*/ static func fromDatatypeValue(datatypeValue: Int64) -> Int64 { return datatypeValue } /*public*/ var datatypeValue: Int64 { return self } } extension String : Binding, Value { /*public*/ static let declaredDatatype = "TEXT" /*public*/ static func fromDatatypeValue(datatypeValue: String) -> String { return datatypeValue } /*public*/ var datatypeValue: String { return self } } extension Blob : Binding, Value { /*public*/ static let declaredDatatype = "BLOB" /*public*/ static func fromDatatypeValue(datatypeValue: Blob) -> Blob { return datatypeValue } /*public*/ var datatypeValue: Blob { return self } } // MARK: - extension Bool : Binding, Value { /*public*/ static var declaredDatatype = Int64.declaredDatatype /*public*/ static func fromDatatypeValue(datatypeValue: Int64) -> Bool { return datatypeValue != 0 } /*public*/ var datatypeValue: Int64 { return self ? 1 : 0 } } extension Int : Number, Value { /*public*/ static var declaredDatatype = Int64.declaredDatatype /*public*/ static func fromDatatypeValue(datatypeValue: Int64) -> Int { return Int(datatypeValue) } /*public*/ var datatypeValue: Int64 { return Int64(self) } }
mit
radex/swift-compiler-crashes
crashes-duplicates/10238-swift-inflightdiagnostic-fixitreplacechars.swift
11
382
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol P { typealias e : e { } { { { } } } let t: e { } { { } } } { { } { { } } { } struct S { { { } } func g { { } if true { func g { if true { { } { var d = { var d { { } { -> { { } { } class d { protocol S d
mit
ProjectDent/ARKit-CoreLocation
Sources/ARKit-CoreLocation/Nodes/ScalingScheme.swift
1
3742
// // ScalingScheme.swift // ARCL // // Created by Eric Internicola on 5/17/19. // import Foundation /// A set of schemes that can be used to scale a LocationNode. /// /// Values: /// - normal: The default way of scaling, Hardcoded value out to 3000 meters, and then 0.75 that factor beyond 3000 m. /// - tiered (threshold, scale): Return 1.0 at distance up to `threshold` meters, or `scale` beyond. /// - doubleTiered (firstThreshold, firstCale, secondThreshold, secondScale): A way of scaling everything /// beyond 2 specific distances at two specific scales. /// - linear (threshold): linearly scales an object based on its distance. /// - linearBuffer (threshold, buffer): linearly scales an object based on its distance as long as it is /// further than the buffer distance, otherwise it just returns 100% scale. public enum ScalingScheme { case normal case tiered(threshold: Double, scale: Float) case doubleTiered(firstThreshold: Double, firstScale: Float, secondThreshold: Double, secondScale: Float) case linear(threshold: Double) case linearBuffer(threshold: Double, buffer: Double) /// Returns a closure to compute appropriate scale factor based on the current value of `self` (a `ScalingSchee`). /// The closure accepts two parameters and returns the scale factor to apply to an `AnnotationNode`. public func getScheme() -> ( (_ distance: Double, _ adjustedDistance: Double) -> Float) { switch self { case .tiered(let threshold, let scale): return { (distance, adjustedDistance) in if adjustedDistance > threshold { return scale } else { return 1.0 } } case .doubleTiered(let firstThreshold, let firstScale, let secondThreshold, let secondScale): return { (distance, adjustedDistance) in if adjustedDistance > secondThreshold { return secondScale } else if adjustedDistance > firstThreshold { return firstScale } else { return 1.0 } } case .linear(let threshold): return { (distance, adjustedDistance) in let maxSize = 1.0 let absThreshold = abs(threshold) let absAdjDist = abs(adjustedDistance) let scaleToReturn = Float( max(maxSize - (absAdjDist / absThreshold), 0.0)) // print("threshold: \(absThreshold) adjDist: \(absAdjDist) scaleToReturn: \(scaleToReturn)") return scaleToReturn } case .linearBuffer(let threshold, let buffer): return { (distance, adjustedDistance) in let maxSize = 1.0 let absThreshold = abs(threshold) let absAdjDist = abs(adjustedDistance) if absAdjDist < buffer { // print("threshold: \(absThreshold) adjDist: \(absAdjDist)") return Float(maxSize) } else { let scaleToReturn = Float( max( maxSize - (absAdjDist / absThreshold), 0.0 )) // print("threshold: \(absThreshold) adjDist: \(absAdjDist) scaleToReturn: \(scaleToReturn)") return scaleToReturn } } case .normal: return { (distance, adjustedDistance) in // Scale it to be an appropriate size so that it can be seen var scale = Float(adjustedDistance) * 0.181 if distance > 3000 { scale *= 0.75 } return scale } } } }
mit
VladimirMilichenko/CountAnimationLabelSwift
Examples/Pods/CountAnimationLabel/CountAnimationLabel/UILabel+CountAnimation.swift
2
5659
// // UILabel+CountAnimation.swift // // Created by Vladimir Milichenko on 12/2/15. // Copyright © 2016 Vladimir Milichenko. All rights reserved. //import UIKit private struct AssociatedKeys { static var isAnimated = "isAnimated" } public extension UILabel { var isAnimated : Bool { get { guard let number = objc_getAssociatedObject(self, &AssociatedKeys.isAnimated) as? NSNumber else { return false } return number.boolValue } set(value) { objc_setAssociatedObject(self, &AssociatedKeys.isAnimated, NSNumber(bool: value), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func countAnimationWithDuration(duration: NSTimeInterval, numberFormatter: NSNumberFormatter?) { if !self.isAnimated { self.isAnimated = true let lastNumberSymbol = self.text!.substringFromIndex(self.text!.endIndex.predecessor()) let textWidth = self.text!.sizeWithAttributes([NSFontAttributeName: self.font]).width let halfWidthsDiff = (self.frame.size.width - textWidth) / 2.0 let lastNumberSymbolWidth = lastNumberSymbol.sizeWithAttributes([NSFontAttributeName: self.font]).width let textStorage = NSTextStorage(attributedString: self.attributedText!) let layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) let textContainer = NSTextContainer(size: self.bounds.size) textContainer.lineFragmentPadding = 0 layoutManager.addTextContainer(textContainer) let lastCharacterRange = NSRange(location: self.text!.characters.count - 1, length: 1) layoutManager.characterRangeForGlyphRange(lastCharacterRange, actualGlyphRange: nil) let lastNumberViewFrame = layoutManager.boundingRectForGlyphRange(lastCharacterRange, inTextContainer: textContainer) let lastNumberView = UIView( frame:CGRect( x: lastNumberViewFrame.origin.x + self.frame.origin.x, y: self.frame.origin.y, width: lastNumberSymbolWidth + halfWidthsDiff, height: self.frame.size.height ) ) lastNumberView.backgroundColor = UIColor.clearColor() lastNumberView.clipsToBounds = true let lastNumberUpperLabel = UILabel( frame: CGRect( x: 0.0, y: 0.0, width: lastNumberView.frame.size.width, height: lastNumberView.frame.size.height ) ) lastNumberUpperLabel.textAlignment = .Left; lastNumberUpperLabel.font = self.font; lastNumberUpperLabel.textColor = self.textColor; lastNumberUpperLabel.text = lastNumberSymbol; lastNumberView.addSubview(lastNumberUpperLabel) var lastNumber = Int(lastNumberSymbol)! lastNumber = lastNumber == 9 ? 0 : lastNumber + 1 let lastNumberBottomLabel = UILabel( frame: CGRect( x: lastNumberUpperLabel.frame.origin.x, y: (lastNumberUpperLabel.frame.origin.y + lastNumberUpperLabel.frame.size.height) - (lastNumberUpperLabel.frame.size.height) / 4.0, width: lastNumberUpperLabel.frame.size.width, height: lastNumberUpperLabel.frame.size.height ) ) lastNumberBottomLabel.textAlignment = .Left; lastNumberBottomLabel.font = self.font; lastNumberBottomLabel.textColor = self.textColor; lastNumberBottomLabel.text = "\(lastNumber)" lastNumberView.addSubview(lastNumberBottomLabel) self.superview!.insertSubview(lastNumberView, belowSubview: self.superview!) let attributedText = NSMutableAttributedString(string: self.text!) attributedText.addAttribute( NSForegroundColorAttributeName, value: UIColor.clearColor(), range: lastCharacterRange ) self.attributedText! = attributedText UIView.animateWithDuration(duration, animations: { var lastNumberBottomLabelFrame = lastNumberBottomLabel.frame lastNumberBottomLabelFrame.origin.y = lastNumberUpperLabel.frame.origin.y lastNumberBottomLabel.frame = lastNumberBottomLabelFrame var lastNumberUpperLabelFrame = lastNumberUpperLabel.frame lastNumberUpperLabelFrame.origin.y = lastNumberUpperLabel.frame.origin.y - lastNumberUpperLabel.frame.size.height; lastNumberUpperLabel.frame = lastNumberUpperLabelFrame }, completion: { [unowned self] finished in var likesCount = numberFormatter != nil ? Int(numberFormatter!.numberFromString(self.text!)!) : Int(self.text!) likesCount!++ self.text = numberFormatter != nil ? numberFormatter!.stringFromNumber(likesCount!) : "\(likesCount!)" lastNumberView.removeFromSuperview() self.isAnimated = false } ) } } }
mit
naokits/my-programming-marathon
ParseLoginDemo/ParseLoginDemoUITests/ParseLoginDemoUITests.swift
1
1269
// // ParseLoginDemoUITests.swift // ParseLoginDemoUITests // // Created by Naoki Tsutsui on 1/15/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import XCTest class ParseLoginDemoUITests: 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
SeptAi/Cooperate
Cooperate/Cooperate/Class/View/Main/base/BaseViewController.swift
1
7019
// // BaseViewController.swift // Cooperation // // Created by J on 2016/12/26. // Copyright © 2016年 J. All rights reserved. // import UIKit /* frame:x,y当前控件相对父控件的位置 bounds:x,y内部子控件相对(自己的坐标系统)原点的位置 ,就是scrollView的contentOffset 修改bounds会影响 其子视图的位置,而自身位置不会移动 */ /// 1.NavigationController的设置。2.TableView的设置 class BaseViewController: UIViewController { // MARK: - 属性 // 属性不能定义到分类 // 登陆标示 let userLogin = true // 导航栏 - 自定义导航条 lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64)) // 导航项 lazy var nvItem = UINavigationItem() // 访客视图信息字典 var visitorInfoDictionary: [String: String]? // 表格视图:未登录时不创建 var tableview:UITableView? // 刷新控件 var refreshControl:JRefreshControl? var isPullup = false override var title: String?{ didSet{ nvItem.title = title } } // MARK: - 方法 // 加载数据 func loadData(){ // 如果子类不实现方法,默认关闭控件 refreshControl?.endRefreshing() } // MARK: - 方法 // MARK: - 系统 override func viewDidLoad() { super.viewDidLoad() // 背景颜色 - 白色 view.backgroundColor = UIColor.white setupUI() NetworkManager.sharedInstance.userLogon ? loadData() : () // 注册通知 NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess(n:)), name: NSNotification.Name(rawValue: NoticeName.UserLoginSuccessedNotification), object: nil) // Do any additional setup after loading the view. } } /* 1.属性不能定义到分类 2.分类不能重写父类本类的方法{父类方法和子类方法位置一致、}可能导致不执行 */ extension BaseViewController{ /// 设置界面 func setupUI() { view.backgroundColor = UIColor.lightGray // 取消自动缩进 - 如果隐藏导航栏会缩进20 automaticallyAdjustsScrollViewInsets = false setupNav() if userLogin{ setuptableview() }else{ setupVisitorView() } } /// 设置表格 func setuptableview() { // 1.添加表格视图 tableview = UITableView(frame: view.bounds, style: .plain) // 将tableView添加到nav下方。仅层次 view.insertSubview(tableview!, belowSubview: navigationBar) // 2.设置代理&数据源 tableview?.delegate = self tableview?.dataSource = self // 3.实现协议方法 // 4.1设置内容缩进 - 那么你的contentview就是从scrollview的*开始显示 tableview?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0) // 4.2设置指示器的缩进 tableview?.scrollIndicatorInsets = tableview!.contentInset // 5.刷新控件 refreshControl = JRefreshControl() tableview?.addSubview(refreshControl!) // 6.添加监听事件 refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged) } /// 设置访客视图 func setupVisitorView(){ let visitorView = VisitorView(frame: view.bounds) view.insertSubview(visitorView, belowSubview: navigationBar) // 1.设置访客信息 visitorView.visitorInfo = visitorInfoDictionary // 2. 添加访客视图按钮的监听方法 visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside) visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside) // 3. 设置导航条按钮 nvItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register)) nvItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login)) } /// 设置Nav字体样式 func setupNav() { view.addSubview(navigationBar) navigationBar.items = [nvItem] // navigationBar.barTintColor = UIColor.white // FIXME: - 系统设置透明度过高 // 设置navBar的字体颜色 navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray] // 设置按钮字体颜色 navigationBar.tintColor = UIColor.orange } } extension BaseViewController{ func loginSuccess(n:NSNotification){ print("登录成功 \(n)") // 登录前左边是注册,右边是登录 nvItem.leftBarButtonItem = nil nvItem.rightBarButtonItem = nil // 更新 UI => 将访客视图替换为表格视图 // 需要重新设置 view // 在访问 view 的 getter 时,如果 view == nil 会调用 loadView -> viewDidLoad view = nil // 注销通知 -> 重新执行 viewDidLoad 会再次注册!避免通知被重复注册 NotificationCenter.default.removeObserver(self) } func login() { NotificationCenter.default.post(name: NSNotification.Name(rawValue: NoticeName.UserShouldLoginNotification), object: nil) } func register(){ print("用户注册") } } extension BaseViewController:UITableViewDelegate,UITableViewDataSource{ // 基类准备方法,子类进行实现;子类不需要super func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() return cell } // 实现上拉刷新 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // 判断最后一行 let row = indexPath.row let section = ((tableview?.numberOfSections)! - 1) if row<0 || section<0{ return } let count = tableview?.numberOfRows(inSection: section) if (row == (count! - 1) && !isPullup) { isPullup = true // 开始刷新 // FIXME: - 上拉刷新判断 // loadData() } } // 为了子类能重写此方法,这样子类方法才能被调用 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 10 } }
mit
debugsquad/Hyperborea
Hyperborea/Model/Search/MSearchOrigins.swift
1
4805
import UIKit class MSearchOrigins { let attributedString:NSAttributedString private let kBreak:String = "\n" private let kKeyResults:String = "results" private let kKeyWord:String = "word" private let kKeyLexicalEntries:String = "lexicalEntries" private let kKeyEntries:String = "entries" private let kKeyEtymologies:String = "etymologies" private let kWordFontSize:CGFloat = 40 private let kFontSize:CGFloat = 18 private let kNotFoundFontSize:CGFloat = 18 init(json:Any) { let mutableString:NSMutableAttributedString = NSMutableAttributedString() guard let jsonMap:[String:Any] = json as? [String:Any], let jsonResults:[Any] = jsonMap[kKeyResults] as? [Any] else { attributedString = mutableString return } let attributes:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:kFontSize), NSForegroundColorAttributeName:UIColor.black] let stringBreak:NSAttributedString = NSAttributedString( string:kBreak, attributes:attributes) var wordString:NSAttributedString? for jsonResult:Any in jsonResults { guard let jsonResultMap:[String:Any] = jsonResult as? [String:Any], let jsonLexicalEntries:[Any] = jsonResultMap[kKeyLexicalEntries] as? [Any] else { continue } if wordString == nil { if let word:String = jsonResultMap[kKeyWord] as? String { let wordCapitalized:String = word.capitalizedFirstLetter() let attributesWord:[String:AnyObject] = [ NSFontAttributeName:UIFont.medium(size:kWordFontSize), NSForegroundColorAttributeName:UIColor.black] wordString = NSAttributedString( string:wordCapitalized, attributes:attributesWord) } } for jsonLexicalEntry:Any in jsonLexicalEntries { guard let jsonLexicalEntryMap:[String:Any] = jsonLexicalEntry as? [String:Any], let jsonEntries:[Any] = jsonLexicalEntryMap[kKeyEntries] as? [Any] else { continue } for jsonEntry:Any in jsonEntries { guard let jsonEntryMap:[String:Any] = jsonEntry as? [String:Any], let jsonEtymologies:[Any] = jsonEntryMap[kKeyEtymologies] as? [Any] else { continue } for jsonEtymology:Any in jsonEtymologies { guard let titleEtymology:String = jsonEtymology as? String else { continue } let stringEtymology:NSAttributedString = NSAttributedString( string:titleEtymology, attributes:attributes) if !mutableString.string.isEmpty { mutableString.append(stringBreak) } mutableString.append(stringEtymology) } } } } if let wordString:NSAttributedString = wordString { if !mutableString.string.isEmpty { mutableString.insert(stringBreak, at:0) mutableString.insert(stringBreak, at:0) } mutableString.insert(wordString, at:0) } attributedString = mutableString } init() { let string:String = NSLocalizedString("MSearchOrigins_notFound", comment:"") let attributes:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:kNotFoundFontSize), NSForegroundColorAttributeName:UIColor(white:0.4, alpha:1)] attributedString = NSAttributedString( string:string, attributes:attributes) } }
mit
teamheisenberg/GeoFire-Image-Demo
Photo Drop/ViewController.swift
1
7810
// // ViewController.swift // Photo Drop // // Created by Bob Warwick on 2015-05-05. // Copyright (c) 2015 Whole Punk Creators. All rights reserved. // import UIKit import CoreLocation import MapKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate { // MARK: - Setup let locationManager = CLLocationManager() let imagePicker = UIImagePickerController() var firebase: Firebase? var geofire: GeoFire? var regionQuery: GFRegionQuery? var foundQuery: GFCircleQuery? var annotations: Dictionary<String, Pin> = Dictionary(minimumCapacity: 8) var lastExchangeKeyFound: String? var lastExchangeLocationFound: CLLocation? var inExchange = false @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var foundImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() imagePicker.sourceType = .PhotoLibrary imagePicker.delegate = self firebase = Firebase(url: "https://vivid-fire-6294.firebaseio.com/") geofire = GeoFire(firebaseRef: firebase!.childByAppendingPath("geo")) let gestureRecongnizer = UITapGestureRecognizer(target: self, action: Selector("hideImageView:")) foundImage.addGestureRecognizer(gestureRecongnizer) } // MARK: - Map Tracking override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) locationManager.requestWhenInUseAuthorization() self.mapView.userLocation.addObserver(self, forKeyPath: "location", options: NSKeyValueObservingOptions(), context: nil) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if (self.mapView.showsUserLocation && self.mapView.userLocation.location != nil) { let span = MKCoordinateSpanMake(0.0125, 0.0125) let region = MKCoordinateRegion(center: self.mapView.userLocation.location!.coordinate, span: span) self.mapView.setRegion(region, animated: true) if regionQuery == nil { regionQuery = geofire?.queryWithRegion(region) regionQuery!.observeEventType(GFEventTypeKeyEntered, withBlock: { (key: String!, location: CLLocation!) in let annotation = Pin(key: key) annotation.coordinate = location.coordinate self.mapView.addAnnotation(annotation) self.annotations[key] = annotation }) regionQuery!.observeEventType(GFEventTypeKeyExited, withBlock: { (key: String!, location: CLLocation!) -> Void in self.mapView.removeAnnotation(self.annotations[key]!) self.annotations[key] = nil }) } // We also want a query with an extremely limited span. When a photo enters that region, we want to notify the user they can exchange. if foundQuery == nil { foundQuery = geofire?.queryAtLocation(self.mapView.userLocation.location, withRadius: 0.05) foundQuery!.observeEventType(GFEventTypeKeyEntered, withBlock: { (key: String!, location: CLLocation!) -> Void in self.lastExchangeKeyFound = key self.lastExchangeLocationFound = location let foundAPhoto = UIAlertView(title: "You Found a Drop!", message: "You can view the photo by tapping exchange and providing a new photo.", delegate: self, cancelButtonTitle: "Not Here", otherButtonTitles: "Exchange") foundAPhoto.show() }) } else { foundQuery?.center = self.mapView.userLocation.location } } } // MARK: - Drop a Photo @IBAction func dropPhoto(sender: AnyObject) { self.presentViewController(imagePicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { self.dismissViewControllerAnimated(true, completion: nil) // Save the photo to Firebase let thumbnail = image.resizedImageWithContentMode(UIViewContentMode.ScaleAspectFit, bounds: CGSizeMake(400, 400), interpolationQuality:CGInterpolationQuality.High) let imgData = UIImagePNGRepresentation(thumbnail) let base64EncodedImage = imgData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) if inExchange { // Download the existing photo and show it firebase?.childByAppendingPath(lastExchangeKeyFound).observeEventType(.Value, withBlock: { (snapshot) -> Void in self.firebase?.childByAppendingPath(self.lastExchangeKeyFound).removeAllObservers() let existingImageInBase64 = snapshot.value as! String let existingImageData = NSData(base64EncodedString: existingImageInBase64, options: NSDataBase64DecodingOptions()) let image = UIImage(data: existingImageData!) self.foundImage.image = image self.foundImage.hidden = false UIView.animateWithDuration(0.5, animations: { () -> Void in self.foundImage.alpha = 1.0 var layer = self.foundImage.layer layer.shadowColor = UIColor.blackColor().CGColor layer.shadowRadius = 10.0 layer.shadowOffset = CGSizeMake(10.0, 5.0) layer.shadowOpacity = 0.8 }) // Overwrite the existing photo let existingReference = self.firebase?.childByAppendingPath(self.lastExchangeKeyFound) existingReference?.setValue(base64EncodedImage) // Go back to the non-exchange flow self.inExchange = false }) } else { let uniqueReference = firebase?.childByAutoId() uniqueReference!.setValue(base64EncodedImage) let key = uniqueReference?.key let location = mapView.userLocation.location geofire!.setLocation(mapView.userLocation.location, forKey: key) } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) inExchange = false } func hideImageView(sender: AnyObject?) { UIView.animateWithDuration(0.5, animations: { () -> Void in self.foundImage.alpha = 0.0 let layer = self.foundImage.layer layer.shadowColor = UIColor.blackColor().CGColor layer.shadowRadius = 0.0 layer.shadowOffset = CGSizeMake(0.0, 0.0) layer.shadowOpacity = 0.0 }) { (bool) -> Void in self.foundImage.image = nil self.foundImage.hidden = true } } // MARK: - Exchange Dialog Delegate func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if buttonIndex == 1 { inExchange = true self.dropPhoto(self) } } }
mit
Pingco/Side-Menu.iOS
MenuExample/Misc/AppDelegate.swift
14
303
// // Copyright © 2014 Yalantis // Licensed under the MIT license: http://opensource.org/licenses/MIT // Latest version can be found at http://github.com/yalantis/Side-Menu.iOS // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
mit
abdullasulaiman/RaeesIOSProject
SwiftOpenCV/SwiftOCR.swift
1
5852
// // SwiftOCR.swift // SwiftOpenCV // // Created by Lee Whitney on 10/28/14. // Copyright (c) 2014 WhitneyLand. All rights reserved. // import Foundation import UIKit class SwiftOCR { var _image: UIImage var _tesseract: Tesseract var _characterBoxes : Array<CharBox> var _groupedImage : UIImage var _recognizedText: String //Get grouped image after executing recognize method var groupedImage : UIImage { get { return _groupedImage; } } //Get Recognized Text after executing recognize method var recognizedText: String { get { return _recognizedText; } } var characterBoxes :Array<CharBox> { get { return _characterBoxes; } } /*init(fromImagePath path:String) { _image = UIImage(contentsOfFile: path)! _tesseract = Tesseract(language: "eng") _tesseract.setVariableValue("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", forKey: "tessedit_char_whitelist") _tesseract.image = _image _characterBoxes = Array<CharBox>() _groupedImage = _image _recognizedText = "" }*/ init(fromImage image:UIImage) { _image = image; _tesseract = Tesseract(language: "eng") _tesseract.setVariableValue("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ()@+.-,!#$%&*?''", forKey: "tessedit_char_whitelist") println(image) _tesseract.image = image _characterBoxes = Array<CharBox>() _groupedImage = image _recognizedText = "" NSLog("%d",image.imageOrientation.rawValue); } //Recognize function func recognize() { _characterBoxes = Array<CharBox>() var uImage = CImage(image: _image); var channels = uImage.channels; let classifier1 = NSBundle.mainBundle().pathForResource("trained_classifierNM1", ofType: "xml") let classifier2 = NSBundle.mainBundle().pathForResource("trained_classifierNM2", ofType: "xml") var erFilter1 = ExtremeRegionFilter.createERFilterNM1(classifier1, c: 8, x: 0.00015, y: 0.13, f: 0.2, a: true, scale: 0.1); var erFilter2 = ExtremeRegionFilter.createERFilterNM2(classifier2, andX: 0.5); var regions = Array<ExtremeRegionStat>(); var index : Int; for index = 0; index < channels.count; index++ { var region = ExtremeRegionStat() region = erFilter1.run(channels[index] as UIImage); regions.append(region); } _groupedImage = ExtremeRegionStat.groupImage(uImage, withRegions: regions); _tesseract.recognize(); /* @property (nonatomic, readonly) NSArray *getConfidenceByWord; @property (nonatomic, readonly) NSArray *getConfidenceBySymbol; @property (nonatomic, readonly) NSArray *getConfidenceByTextline; @property (nonatomic, readonly) NSArray *getConfidenceByParagraph; @property (nonatomic, readonly) NSArray *getConfidenceByBlock; */ var words = _tesseract.getConfidenceByWord; var paragraphs = _tesseract.getConfidenceByTextline var texts = Array<String>(); var windex: Int /*for windex = 0; windex < words.count; windex++ { let dict = words[windex] as Dictionary<String, AnyObject> let text = dict["text"]! as String //println(text) let confidence = dict["confidence"]! as Float let box = dict["boundingbox"] as NSValue if((text.utf16Count < 2 || confidence < 51) || (text.utf16Count < 4 && confidence < 60)){ continue } let rect = box.CGRectValue() _characterBoxes.append(CharBox(text: text, rect: rect)) texts.append(text) }*/ windex = 0 texts = Array<String>(); for windex = 0; windex < paragraphs.count; windex++ { let dict = paragraphs[windex] as Dictionary<String, AnyObject> let text = dict["text"]! as String println("paragraphs of \(windex) is \(text)") liguistingTagger(text) let confidence = dict["confidence"]! as Float let box = dict["boundingbox"] as NSValue if((text.utf16Count < 2 || confidence < 51) || (text.utf16Count < 4 && confidence < 60)){ continue } let rect = box.CGRectValue() _characterBoxes.append(CharBox(text: text, rect: rect)) texts.append(text) } var str : String = "" for (idx, item) in enumerate(texts) { str += item if idx < texts.count-1 { str += " " } } _recognizedText = str } func liguistingTagger(input:String) -> Array<String> { let options: NSLinguisticTaggerOptions = .OmitWhitespace | .OmitPunctuation | .JoinNames let schemes = NSLinguisticTagger.availableTagSchemesForLanguage("en") let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue)) tagger.string = input var results = Array<String>(); tagger.enumerateTagsInRange(NSMakeRange(0, (input as NSString).length), scheme: NSLinguisticTagSchemeNameTypeOrLexicalClass, options: options) { (tag, tokenRange, sentenceRange, _) in let token = (input as NSString).substringWithRange(tokenRange) results.append(token) } println("liguistingTagger \(results)") return results; } }
mit
mparrish91/gifRecipes
framework/Network/Session+messages.swift
1
11069
// // Session+messages.swift // reddift // // Created by sonson on 2015/05/19. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation extension Session { // MARK: Update message status /** Mark messages as "unread" - parameter id: A comma-separated list of thing fullnames - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func markMessagesAsUnread(_ fullnames: [String], modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let commaSeparatedFullameString = fullnames.joined(separator: ",") let parameter = ["id": commaSeparatedFullameString] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/unread_message", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** Mark messages as "read" - parameter id: A comma-separated list of thing fullnames - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func markMessagesAsRead(_ fullnames: [String], modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let commaSeparatedFullameString = fullnames.joined(separator: ",") let parameter = ["id": commaSeparatedFullameString] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/read_message", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** Mark all messages as "read" Queue up marking all messages for a user as read. This may take some time, and returns 202 to acknowledge acceptance of the request. - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func markAllMessagesAsRead(_ modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/read_all_messages", parameter:nil, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** Collapse messages - parameter id: A comma-separated list of thing fullnames - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func collapseMessages(_ fullnames: [String], modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let commaSeparatedFullameString = fullnames.joined(separator: ",") let parameter = ["id": commaSeparatedFullameString] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/collapse_message", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** Uncollapse messages - parameter id: A comma-separated list of thing fullnames - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func uncollapseMessages(_ fullnames: [String], modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let commaSeparatedFullameString = fullnames.joined(separator: ",") let parameter = ["id": commaSeparatedFullameString] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/uncollapse_message", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** For blocking via inbox. - parameter id: fullname of a thing - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func blockViaInbox(_ fullname: String, modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let parameter = ["id": fullname] guard let request = URLRequest.requestForOAuth(with: Session.OAuthEndpointURL, path:"/api/block", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } /** For unblocking via inbox. - parameter id: fullname of a thing - parameter modhash: A modhash, default is blank string not nil. - returns: Data task which requests search to reddit.com. */ @discardableResult public func unblockViaInbox(_ fullname: String, modhash: String = "", completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let parameter = ["id": fullname] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/unblock_subreddit", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) } return executeTask(request, handleResponse: closure, completion: completion) } // MARK: Get messages /** Get the message from the specified box. - parameter messageWhere: The box from which you want to get your messages. - parameter limit: The maximum number of comments to return. Default is 100. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ @discardableResult public func getMessage(_ messageWhere: MessageWhere, limit: Int = 100, completion: @escaping (Result<Listing>) -> Void) throws -> URLSessionDataTask { guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/message" + messageWhere.path, method:"GET", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<Listing> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) .flatMap(json2RedditAny) .flatMap(redditAny2Object) } return executeTask(request, handleResponse: closure, completion: completion) } // MARK: Compose a message /** Compose new message to specified user. - parameter to: Account object of user to who you want to send a message. - parameter subject: A string no longer than 100 characters - parameter text: Raw markdown text - parameter fromSubreddit: Subreddit name? - parameter captcha: The user's response to the CAPTCHA challenge - parameter captchaIden: The identifier of the CAPTCHA challenge - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ @discardableResult public func composeMessage(_ to: Account, subject: String, text: String, fromSubreddit: Subreddit, captcha: String, captchaIden: String, completion: @escaping (Result<JSONAny>) -> Void) throws -> URLSessionDataTask { let parameter = [ "api_type": "json", "captcha": captcha, "iden": captchaIden, "from_sr": fromSubreddit.displayName, "text": text, "subject": subject, "to": to.id ] guard let request = URLRequest.requestForOAuth(with: baseURL, path:"/api/submit", parameter:parameter, method:"POST", token:token) else { throw ReddiftError.canNotCreateURLRequest as NSError } let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<JSONAny> in return Result(from: Response(data: data, urlResponse: response), optional:error) .flatMap(response2Data) .flatMap(data2Json) .flatMap(json2RedditAny) .flatMap(redditAny2Object) } return executeTask(request, handleResponse: closure, completion: completion) } }
mit
jhaigler94/cs4720-iOS
Pensieve/Pods/SwiftyDropbox/Source/FilesRoutes.swift
1
32905
/// Routes for the files namespace public class FilesRoutes { public let client : BabelClient init(client: BabelClient) { self.client = client } /** Returns the metadata for a file or folder. - parameter path: The path of a file or folder on Dropbox - parameter includeMediaInfo: If true, :field:'FileMetadata.media_info' is set for photo and video. - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a `Files.GetMetadataError` object on failure. */ public func getMetadata(path path: String, includeMediaInfo: Bool = false) -> BabelRpcRequest<Files.MetadataSerializer, Files.GetMetadataErrorSerializer> { let request = Files.GetMetadataArg(path: path, includeMediaInfo: includeMediaInfo) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/get_metadata", params: Files.GetMetadataArgSerializer().serialize(request), responseSerializer: Files.MetadataSerializer(), errorSerializer: Files.GetMetadataErrorSerializer()) } /** A longpoll endpoint to wait for changes on an account. In conjunction with listFolder, this call gives you a low-latency way to monitor an account for file changes. The connection will block until there are changes available or a timeout occurs. - parameter cursor: A cursor as returned by listFolder or listFolderContinue - parameter timeout: A timeout in seconds. The request will block for at most this length of time, plus up to 90 seconds of random jitter added to avoid the thundering herd problem. Care should be taken when using this parameter, as some network infrastructure does not support long timeouts. - returns: Through the response callback, the caller will receive a `Files.ListFolderLongpollResult` object on success or a `Files.ListFolderLongpollError` object on failure. */ public func listFolderLongpoll(cursor cursor: String, timeout: UInt64 = 30) -> BabelRpcRequest<Files.ListFolderLongpollResultSerializer, Files.ListFolderLongpollErrorSerializer> { let request = Files.ListFolderLongpollArg(cursor: cursor, timeout: timeout) return BabelRpcRequest(client: self.client, host: "notify", route: "/files/list_folder/longpoll", params: Files.ListFolderLongpollArgSerializer().serialize(request), responseSerializer: Files.ListFolderLongpollResultSerializer(), errorSerializer: Files.ListFolderLongpollErrorSerializer()) } /** Returns the contents of a folder. - parameter path: The path to the folder you want to see the contents of. - parameter recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. - parameter includeMediaInfo: If true, :field:'FileMetadata.media_info' is set for photo and video. - returns: Through the response callback, the caller will receive a `Files.ListFolderResult` object on success or a `Files.ListFolderError` object on failure. */ public func listFolder(path path: String, recursive: Bool = false, includeMediaInfo: Bool = false) -> BabelRpcRequest<Files.ListFolderResultSerializer, Files.ListFolderErrorSerializer> { let request = Files.ListFolderArg(path: path, recursive: recursive, includeMediaInfo: includeMediaInfo) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/list_folder", params: Files.ListFolderArgSerializer().serialize(request), responseSerializer: Files.ListFolderResultSerializer(), errorSerializer: Files.ListFolderErrorSerializer()) } /** Once a cursor has been retrieved from listFolder, use this to paginate through all files and retrieve updates to the folder. - parameter cursor: The cursor returned by your last call to listFolder or listFolderContinue. - returns: Through the response callback, the caller will receive a `Files.ListFolderResult` object on success or a `Files.ListFolderContinueError` object on failure. */ public func listFolderContinue(cursor cursor: String) -> BabelRpcRequest<Files.ListFolderResultSerializer, Files.ListFolderContinueErrorSerializer> { let request = Files.ListFolderContinueArg(cursor: cursor) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/list_folder/continue", params: Files.ListFolderContinueArgSerializer().serialize(request), responseSerializer: Files.ListFolderResultSerializer(), errorSerializer: Files.ListFolderContinueErrorSerializer()) } /** A way to quickly get a cursor for the folder's state. Unlike listFolder, listFolderGetLatestCursor doesn't return any entries. This endpoint is for app which only needs to know about new files and modifications and doesn't need to know about files that already exist in Dropbox. - parameter path: The path to the folder you want to see the contents of. - parameter recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. - parameter includeMediaInfo: If true, :field:'FileMetadata.media_info' is set for photo and video. - returns: Through the response callback, the caller will receive a `Files.ListFolderGetLatestCursorResult` object on success or a `Files.ListFolderError` object on failure. */ public func listFolderGetLatestCursor(path path: String, recursive: Bool = false, includeMediaInfo: Bool = false) -> BabelRpcRequest<Files.ListFolderGetLatestCursorResultSerializer, Files.ListFolderErrorSerializer> { let request = Files.ListFolderArg(path: path, recursive: recursive, includeMediaInfo: includeMediaInfo) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/list_folder/get_latest_cursor", params: Files.ListFolderArgSerializer().serialize(request), responseSerializer: Files.ListFolderGetLatestCursorResultSerializer(), errorSerializer: Files.ListFolderErrorSerializer()) } /** Download a file from a user's Dropbox. - parameter path: The path of the file to download. - parameter rev: Deprecated. Please specify revision in :field:'path' instead - parameter destination: A closure used to compute the destination, given the temporary file location and the response - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.DownloadError` object on failure. */ public func download(path path: String, rev: String? = nil, destination: (NSURL, NSHTTPURLResponse) -> NSURL) -> BabelDownloadRequest<Files.FileMetadataSerializer, Files.DownloadErrorSerializer> { let request = Files.DownloadArg(path: path, rev: rev) return BabelDownloadRequest(client: self.client, host: "content", route: "/files/download", params: Files.DownloadArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.DownloadErrorSerializer(), destination: destination) } /** Upload sessions allow you to upload a single file using multiple requests. This call starts a new upload session with the given data. You can then use uploadSessionAppend to add more data and uploadSessionFinish to save all the data to a file in Dropbox. - parameter body: The file to upload, as an NSData object - returns: Through the response callback, the caller will receive a `Files.UploadSessionStartResult` object on success or a `Void` object on failure. */ public func uploadSessionStart(body body: NSData) -> BabelUploadRequest<Files.UploadSessionStartResultSerializer, VoidSerializer> { return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/start", params: Serialization._VoidSerializer.serialize(), responseSerializer: Files.UploadSessionStartResultSerializer(), errorSerializer: Serialization._VoidSerializer, body: .Data(body)) } /** Upload sessions allow you to upload a single file using multiple requests. This call starts a new upload session with the given data. You can then use uploadSessionAppend to add more data and uploadSessionFinish to save all the data to a file in Dropbox. - parameter body: The file to upload, as an NSURL object - returns: Through the response callback, the caller will receive a `Files.UploadSessionStartResult` object on success or a `Void` object on failure. */ public func uploadSessionStart(body body: NSURL) -> BabelUploadRequest<Files.UploadSessionStartResultSerializer, VoidSerializer> { return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/start", params: Serialization._VoidSerializer.serialize(), responseSerializer: Files.UploadSessionStartResultSerializer(), errorSerializer: Serialization._VoidSerializer, body: .File(body)) } /** Upload sessions allow you to upload a single file using multiple requests. This call starts a new upload session with the given data. You can then use uploadSessionAppend to add more data and uploadSessionFinish to save all the data to a file in Dropbox. - parameter body: The file to upload, as an NSInputStream object - returns: Through the response callback, the caller will receive a `Files.UploadSessionStartResult` object on success or a `Void` object on failure. */ public func uploadSessionStart(body body: NSInputStream) -> BabelUploadRequest<Files.UploadSessionStartResultSerializer, VoidSerializer> { return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/start", params: Serialization._VoidSerializer.serialize(), responseSerializer: Files.UploadSessionStartResultSerializer(), errorSerializer: Serialization._VoidSerializer, body: .Stream(body)) } /** Append more data to an upload session. - parameter sessionId: The upload session ID (returned by uploadSessionStart). - parameter offset: The amount of data that has been uploaded so far. We use this to make sure upload data isn't lost or duplicated in the event of a network error. - parameter body: The file to upload, as an NSData object - returns: Through the response callback, the caller will receive a `Void` object on success or a `Files.UploadSessionLookupError` object on failure. */ public func uploadSessionAppend(sessionId sessionId: String, offset: UInt64, body: NSData) -> BabelUploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> { let request = Files.UploadSessionCursor(sessionId: sessionId, offset: offset) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/append", params: Files.UploadSessionCursorSerializer().serialize(request), responseSerializer: Serialization._VoidSerializer, errorSerializer: Files.UploadSessionLookupErrorSerializer(), body: .Data(body)) } /** Append more data to an upload session. - parameter sessionId: The upload session ID (returned by uploadSessionStart). - parameter offset: The amount of data that has been uploaded so far. We use this to make sure upload data isn't lost or duplicated in the event of a network error. - parameter body: The file to upload, as an NSURL object - returns: Through the response callback, the caller will receive a `Void` object on success or a `Files.UploadSessionLookupError` object on failure. */ public func uploadSessionAppend(sessionId sessionId: String, offset: UInt64, body: NSURL) -> BabelUploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> { let request = Files.UploadSessionCursor(sessionId: sessionId, offset: offset) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/append", params: Files.UploadSessionCursorSerializer().serialize(request), responseSerializer: Serialization._VoidSerializer, errorSerializer: Files.UploadSessionLookupErrorSerializer(), body: .File(body)) } /** Append more data to an upload session. - parameter sessionId: The upload session ID (returned by uploadSessionStart). - parameter offset: The amount of data that has been uploaded so far. We use this to make sure upload data isn't lost or duplicated in the event of a network error. - parameter body: The file to upload, as an NSInputStream object - returns: Through the response callback, the caller will receive a `Void` object on success or a `Files.UploadSessionLookupError` object on failure. */ public func uploadSessionAppend(sessionId sessionId: String, offset: UInt64, body: NSInputStream) -> BabelUploadRequest<VoidSerializer, Files.UploadSessionLookupErrorSerializer> { let request = Files.UploadSessionCursor(sessionId: sessionId, offset: offset) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/append", params: Files.UploadSessionCursorSerializer().serialize(request), responseSerializer: Serialization._VoidSerializer, errorSerializer: Files.UploadSessionLookupErrorSerializer(), body: .Stream(body)) } /** Finish an upload session and save the uploaded data to the given file path. - parameter cursor: Contains the upload session ID and the offset. - parameter commit: Contains the path and other optional modifiers for the commit. - parameter body: The file to upload, as an NSData object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadSessionFinishError` object on failure. */ public func uploadSessionFinish(cursor cursor: Files.UploadSessionCursor, commit: Files.CommitInfo, body: NSData) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadSessionFinishErrorSerializer> { let request = Files.UploadSessionFinishArg(cursor: cursor, commit: commit) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/finish", params: Files.UploadSessionFinishArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadSessionFinishErrorSerializer(), body: .Data(body)) } /** Finish an upload session and save the uploaded data to the given file path. - parameter cursor: Contains the upload session ID and the offset. - parameter commit: Contains the path and other optional modifiers for the commit. - parameter body: The file to upload, as an NSURL object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadSessionFinishError` object on failure. */ public func uploadSessionFinish(cursor cursor: Files.UploadSessionCursor, commit: Files.CommitInfo, body: NSURL) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadSessionFinishErrorSerializer> { let request = Files.UploadSessionFinishArg(cursor: cursor, commit: commit) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/finish", params: Files.UploadSessionFinishArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadSessionFinishErrorSerializer(), body: .File(body)) } /** Finish an upload session and save the uploaded data to the given file path. - parameter cursor: Contains the upload session ID and the offset. - parameter commit: Contains the path and other optional modifiers for the commit. - parameter body: The file to upload, as an NSInputStream object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadSessionFinishError` object on failure. */ public func uploadSessionFinish(cursor cursor: Files.UploadSessionCursor, commit: Files.CommitInfo, body: NSInputStream) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadSessionFinishErrorSerializer> { let request = Files.UploadSessionFinishArg(cursor: cursor, commit: commit) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload_session/finish", params: Files.UploadSessionFinishArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadSessionFinishErrorSerializer(), body: .Stream(body)) } /** Create a new file with the contents provided in the request. - parameter path: Path in the user's Dropbox to save the file. - parameter mode: Selects what to do if the file already exists. - parameter autorename: If there's a conflict, as determined by mode, have the Dropbox server try to autorename the file to avoid conflict. - parameter clientModified: The value to store as the clientModified timestamp. Dropbox automatically records the time at which the file was written to the Dropbox servers. It can also record an additional timestamp, provided by Dropbox desktop clients, mobile clients, and API apps of when the file was actually created or modified. - parameter mute: Normally, users are made aware of any file modifications in their Dropbox account via notifications in the client software. If true, this tells the clients that this modification shouldn't result in a user notification. - parameter body: The file to upload, as an NSData object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadError` object on failure. */ public func upload(path path: String, mode: Files.WriteMode = .Add, autorename: Bool = false, clientModified: NSDate? = nil, mute: Bool = false, body: NSData) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadErrorSerializer> { let request = Files.CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload", params: Files.CommitInfoSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadErrorSerializer(), body: .Data(body)) } /** Create a new file with the contents provided in the request. - parameter path: Path in the user's Dropbox to save the file. - parameter mode: Selects what to do if the file already exists. - parameter autorename: If there's a conflict, as determined by mode, have the Dropbox server try to autorename the file to avoid conflict. - parameter clientModified: The value to store as the clientModified timestamp. Dropbox automatically records the time at which the file was written to the Dropbox servers. It can also record an additional timestamp, provided by Dropbox desktop clients, mobile clients, and API apps of when the file was actually created or modified. - parameter mute: Normally, users are made aware of any file modifications in their Dropbox account via notifications in the client software. If true, this tells the clients that this modification shouldn't result in a user notification. - parameter body: The file to upload, as an NSURL object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadError` object on failure. */ public func upload(path path: String, mode: Files.WriteMode = .Add, autorename: Bool = false, clientModified: NSDate? = nil, mute: Bool = false, body: NSURL) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadErrorSerializer> { let request = Files.CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload", params: Files.CommitInfoSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadErrorSerializer(), body: .File(body)) } /** Create a new file with the contents provided in the request. - parameter path: Path in the user's Dropbox to save the file. - parameter mode: Selects what to do if the file already exists. - parameter autorename: If there's a conflict, as determined by mode, have the Dropbox server try to autorename the file to avoid conflict. - parameter clientModified: The value to store as the clientModified timestamp. Dropbox automatically records the time at which the file was written to the Dropbox servers. It can also record an additional timestamp, provided by Dropbox desktop clients, mobile clients, and API apps of when the file was actually created or modified. - parameter mute: Normally, users are made aware of any file modifications in their Dropbox account via notifications in the client software. If true, this tells the clients that this modification shouldn't result in a user notification. - parameter body: The file to upload, as an NSInputStream object - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.UploadError` object on failure. */ public func upload(path path: String, mode: Files.WriteMode = .Add, autorename: Bool = false, clientModified: NSDate? = nil, mute: Bool = false, body: NSInputStream) -> BabelUploadRequest<Files.FileMetadataSerializer, Files.UploadErrorSerializer> { let request = Files.CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute) return BabelUploadRequest(client: self.client, host: "content", route: "/files/upload", params: Files.CommitInfoSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.UploadErrorSerializer(), body: .Stream(body)) } /** Searches for files and folders. - parameter path: The path in the user's Dropbox to search. Should probably be a folder. - parameter query: The string to search for. The search string is split on spaces into multiple tokens. For file name searching, the last token is used for prefix matching (i.e. "bat c" matches "bat cave" but not "batman car"). - parameter start: The starting index within the search results (used for paging). - parameter maxResults: The maximum number of search results to return. - parameter mode: The search mode (filename, filename_and_content, or deleted_filename). - returns: Through the response callback, the caller will receive a `Files.SearchResult` object on success or a `Files.SearchError` object on failure. */ public func search(path path: String, query: String, start: UInt64 = 0, maxResults: UInt64 = 100, mode: Files.SearchMode = .Filename) -> BabelRpcRequest<Files.SearchResultSerializer, Files.SearchErrorSerializer> { let request = Files.SearchArg(path: path, query: query, start: start, maxResults: maxResults, mode: mode) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/search", params: Files.SearchArgSerializer().serialize(request), responseSerializer: Files.SearchResultSerializer(), errorSerializer: Files.SearchErrorSerializer()) } /** Create a folder at a given path. - parameter path: Path in the user's Dropbox to create. - returns: Through the response callback, the caller will receive a `Files.FolderMetadata` object on success or a `Files.CreateFolderError` object on failure. */ public func createFolder(path path: String) -> BabelRpcRequest<Files.FolderMetadataSerializer, Files.CreateFolderErrorSerializer> { let request = Files.CreateFolderArg(path: path) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/create_folder", params: Files.CreateFolderArgSerializer().serialize(request), responseSerializer: Files.FolderMetadataSerializer(), errorSerializer: Files.CreateFolderErrorSerializer()) } /** Delete the file or folder at a given path. If the path is a folder, all its contents will be deleted too. - parameter path: Path in the user's Dropbox to delete. - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a `Files.DeleteError` object on failure. */ public func delete(path path: String) -> BabelRpcRequest<Files.MetadataSerializer, Files.DeleteErrorSerializer> { let request = Files.DeleteArg(path: path) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/delete", params: Files.DeleteArgSerializer().serialize(request), responseSerializer: Files.MetadataSerializer(), errorSerializer: Files.DeleteErrorSerializer()) } /** Permanently delete the file or folder at a given path (see https://www.dropbox.com/en/help/40). - parameter path: Path in the user's Dropbox to delete. - returns: Through the response callback, the caller will receive a `Void` object on success or a `Files.DeleteError` object on failure. */ public func permanentlyDelete(path path: String) -> BabelRpcRequest<VoidSerializer, Files.DeleteErrorSerializer> { let request = Files.DeleteArg(path: path) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/permanently_delete", params: Files.DeleteArgSerializer().serialize(request), responseSerializer: Serialization._VoidSerializer, errorSerializer: Files.DeleteErrorSerializer()) } /** Copy a file or folder to a different location in the user's Dropbox. If the source path is a folder all its contents will be copied. - parameter fromPath: Path in the user's Dropbox to be copied or moved. - parameter toPath: Path in the user's Dropbox that is the destination. - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a `Files.RelocationError` object on failure. */ public func copy(fromPath fromPath: String, toPath: String) -> BabelRpcRequest<Files.MetadataSerializer, Files.RelocationErrorSerializer> { let request = Files.RelocationArg(fromPath: fromPath, toPath: toPath) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/copy", params: Files.RelocationArgSerializer().serialize(request), responseSerializer: Files.MetadataSerializer(), errorSerializer: Files.RelocationErrorSerializer()) } /** Move a file or folder to a different location in the user's Dropbox. If the source path is a folder all its contents will be moved. - parameter fromPath: Path in the user's Dropbox to be copied or moved. - parameter toPath: Path in the user's Dropbox that is the destination. - returns: Through the response callback, the caller will receive a `Files.Metadata` object on success or a `Files.RelocationError` object on failure. */ public func move(fromPath fromPath: String, toPath: String) -> BabelRpcRequest<Files.MetadataSerializer, Files.RelocationErrorSerializer> { let request = Files.RelocationArg(fromPath: fromPath, toPath: toPath) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/move", params: Files.RelocationArgSerializer().serialize(request), responseSerializer: Files.MetadataSerializer(), errorSerializer: Files.RelocationErrorSerializer()) } /** Get a thumbnail for an image. This method currently supports files with the following file extensions: jpg, jpeg, png, tiff, tif, gif and bmp. Photos that are larger than 20MB in size won't be converted to a thumbnail. - parameter path: The path to the image file you want to thumbnail. - parameter format: The format for the thumbnail image, jpeg (default) or png. For images that are photos, jpeg should be preferred, while png is better for screenshots and digital arts. - parameter size: The size for the thumbnail image. - parameter destination: A closure used to compute the destination, given the temporary file location and the response - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.ThumbnailError` object on failure. */ public func getThumbnail(path path: String, format: Files.ThumbnailFormat = .Jpeg, size: Files.ThumbnailSize = .W64h64, destination: (NSURL, NSHTTPURLResponse) -> NSURL) -> BabelDownloadRequest<Files.FileMetadataSerializer, Files.ThumbnailErrorSerializer> { let request = Files.ThumbnailArg(path: path, format: format, size: size) return BabelDownloadRequest(client: self.client, host: "content", route: "/files/get_thumbnail", params: Files.ThumbnailArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.ThumbnailErrorSerializer(), destination: destination) } /** Get a preview for a file. Currently previews are only generated for the files with the following extensions: .doc, .docx, .docm, .ppt, .pps, .ppsx, .ppsm, .pptx, .pptm, .xls, .xlsx, .xlsm, .rtf - parameter path: The path of the file to preview. - parameter rev: Deprecated. Please specify revision in :field:'path' instead - parameter destination: A closure used to compute the destination, given the temporary file location and the response - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.PreviewError` object on failure. */ public func getPreview(path path: String, rev: String? = nil, destination: (NSURL, NSHTTPURLResponse) -> NSURL) -> BabelDownloadRequest<Files.FileMetadataSerializer, Files.PreviewErrorSerializer> { let request = Files.PreviewArg(path: path, rev: rev) return BabelDownloadRequest(client: self.client, host: "content", route: "/files/get_preview", params: Files.PreviewArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.PreviewErrorSerializer(), destination: destination) } /** Return revisions of a file - parameter path: The path to the file you want to see the revisions of. - parameter limit: The maximum number of revision entries returned. - returns: Through the response callback, the caller will receive a `Files.ListRevisionsResult` object on success or a `Files.ListRevisionsError` object on failure. */ public func listRevisions(path path: String, limit: UInt64 = 10) -> BabelRpcRequest<Files.ListRevisionsResultSerializer, Files.ListRevisionsErrorSerializer> { let request = Files.ListRevisionsArg(path: path, limit: limit) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/list_revisions", params: Files.ListRevisionsArgSerializer().serialize(request), responseSerializer: Files.ListRevisionsResultSerializer(), errorSerializer: Files.ListRevisionsErrorSerializer()) } /** Restore a file to a specific revision - parameter path: The path to the file you want to restore. - parameter rev: The revision to restore for the file. - returns: Through the response callback, the caller will receive a `Files.FileMetadata` object on success or a `Files.RestoreError` object on failure. */ public func restore(path path: String, rev: String) -> BabelRpcRequest<Files.FileMetadataSerializer, Files.RestoreErrorSerializer> { let request = Files.RestoreArg(path: path, rev: rev) return BabelRpcRequest(client: self.client, host: "meta", route: "/files/restore", params: Files.RestoreArgSerializer().serialize(request), responseSerializer: Files.FileMetadataSerializer(), errorSerializer: Files.RestoreErrorSerializer()) } }
apache-2.0
otaran/FormatterKit
IntegrationTests/CocoaPods-watchOS/watchOS App Extension/InterfaceController.swift
1
728
// // InterfaceController.swift // watchOS App Extension // // Created by Oleksii Taran on 6/25/16. // Copyright © 2016 Open Source. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
mit
XCEssentials/ProjectGenerator
Sources/Manager.swift
1
934
// // Manager.swift // MKHProjGen // // Created by Maxim Khatskevich on 3/16/17. // Copyright © 2017 Maxim Khatskevich. All rights reserved. // public enum Manager { public static func prepareSpec( _ format: Spec.Format, for project: Project ) -> String { let rawSpec: RawSpec //=== switch format { case .v1_2_1: rawSpec = Spec_1_2_1.generate(for: project) case .v1_3_0: rawSpec = Spec_1_3_0.generate(for: project) case .v2_0_0: rawSpec = Spec_2_0_0.generate(for: project) case .v2_1_0: rawSpec = Spec_2_1_0.generate(for: project) } //=== return rawSpec .map { "\(Spec.ident($0))\($1)" } .joined(separator: "\n") } }
mit
timd/ProiOSTableCollectionViews
Ch09/InCellCV/InCellCV/ViewController.swift
1
3372
// // ViewController.swift // InCellCV // // Created by Tim on 07/11/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var collectionView: UICollectionView! var cvData = [Int]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setupData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController { func setupData() { for index in 0...100 { cvData.append(index) } } func addButtonToCell(cell: UICollectionViewCell) { guard cell.contentView.viewWithTag(1000) != nil else { return } let button = UIButton(type: UIButtonType.RoundedRect) button.tag = 1000 button.setTitle("Tap me!", forState: UIControlState.Normal) button.sizeToFit() button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: "didTapButtonInCell:", forControlEvents: UIControlEvents.TouchUpInside) let vConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0) let hConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -10) cell.contentView.addSubview(button) cell.contentView.addConstraints([vConstraint, hConstraint]) } func didTapButtonInCell(sender: UIButton) { let cell = sender.superview!.superview as! UICollectionViewCell let indexPathAtTap = collectionView.indexPathForCell(cell) let alert = UIAlertController(title: "Something happened!", message: "A button was tapped in item \(indexPathAtTap!.row)", preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } } extension ViewController: UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return cvData.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellIdentifier", forIndexPath: indexPath) if let label = cell.contentView.viewWithTag(1000) as? UILabel { label.text = "Item \(cvData[indexPath.row])" } addButtonToCell(cell) cell.layer.borderColor = UIColor.blackColor().CGColor cell.layer.borderWidth = 1.0 return cell } }
mit
omochi/numsw
Playgrounds/LineGraphRenderer.swift
1
2562
// // LineGraphRenderer.swift // sandbox // // Created by omochimetaru on 2017/03/04. // Copyright © 2017年 sonson. All rights reserved. // import UIKit import CoreGraphics public class LineGraphRenderer: Renderer { public init(viewport: CGRect, line: LineGraph) { self.viewport = viewport self.line = line } public let viewport: CGRect public let line: LineGraph public func render(context: CGContext, windowSize: CGSize) { viewportTransform = RendererUtil.computeViewportTransform(viewport: viewport, windowSize: windowSize) drawLine(context: context, points: line.points) } // public func drawPoints(context ctx: CGContext) { // ctx.setStrokeColor(UIColor.white.cgColor) // // if lines.count >= 1 { // drawLine(context: ctx, points: lines[0].points) // } // if lines.count >= 2 { // drawSanpuzu(context: ctx, line: lines[1]) // } // } public func drawSanpuzu(context ctx: CGContext, line: LineGraph) { ctx.setStrokeColor(UIColor.green.cgColor) let t = viewportTransform! for point in line.points { let p = point.applying(t) RendererUtil.drawLine(context: ctx, points: [ CGPoint(x: p.x - 10, y: p.y - 10), CGPoint(x: p.x + 10, y: p.y + 10) ]) RendererUtil.drawLine(context: ctx, points: [ CGPoint(x: p.x - 10, y: p.y + 10), CGPoint(x: p.x + 10, y: p.y - 10) ]) } } public func drawDebugX(context ctx: CGContext, point0: CGPoint, point1: CGPoint) { ctx.setStrokeColor(UIColor.red.cgColor) drawLine(context: ctx, points: [ CGPoint(x: point0.x, y: point0.y), CGPoint(x: point1.x, y: point1.y) ]) ctx.setStrokeColor(UIColor.green.cgColor) drawLine(context: ctx, points: [ CGPoint(x: point1.x, y: point0.y), CGPoint(x: point0.x, y: point1.y) ]) } public func drawLine(context: CGContext, points: [CGPoint]) { context.setStrokeColor(UIColor.white.cgColor) let t = viewportTransform! let points = points.map { $0.applying(t) } RendererUtil.drawLine(context: context, points: points) } private var viewportTransform: CGAffineTransform? }
mit
wireapp/wire-ios-data-model
Tests/Source/ManagedObjectContext/ManagedObjectContextChangeObserverTests.swift
1
3011
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // 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 Foundation class ManagedObjectContextChangeObserverTests: ZMBaseManagedObjectTest { func testThatItCallsTheCallbackWhenObjectsAreInserted() { // given let changeExpectation = expectation(description: "The callback should be called") let sut = ManagedObjectContextChangeObserver(context: uiMOC) { changeExpectation.fulfill() } // when uiMOC.perform { _ = ZMMessage(nonce: UUID(), managedObjectContext: self.uiMOC) } // then XCTAssert(waitForCustomExpectations(withTimeout: 0.1)) _ = sut } func testThatItCallsTheCallbackWhenObjectsAreDeleted() { // given let message = ZMMessage(nonce: UUID(), managedObjectContext: uiMOC) XCTAssert(uiMOC.saveOrRollback()) let changeExpectation = expectation(description: "The callback should be called") let sut = ManagedObjectContextChangeObserver(context: uiMOC) { changeExpectation.fulfill() } // when uiMOC.perform { self.uiMOC.delete(message) } // then XCTAssert(waitForCustomExpectations(withTimeout: 0.1)) _ = sut } func testThatItCallsTheCallbackWhenObjectsAreUpdated() { // given let message = ZMMessage(nonce: UUID(), managedObjectContext: uiMOC) XCTAssert(uiMOC.saveOrRollback()) let changeExpectation = expectation(description: "The callback should be called") let sut = ManagedObjectContextChangeObserver(context: uiMOC) { changeExpectation.fulfill() } // when uiMOC.perform { message.markAsSent() } // then XCTAssert(waitForCustomExpectations(withTimeout: 0.1)) _ = sut } func testThatItRemovesItselfAsObserverWhenReleased() { // given var called = false var sut: ManagedObjectContextChangeObserver? = ManagedObjectContextChangeObserver(context: uiMOC) { called = true } // when _ = sut sut = nil uiMOC.perform { _ = ZMMessage(nonce: UUID(), managedObjectContext: self.uiMOC) } // then spinMainQueue(withTimeout: 0.05) XCTAssertFalse(called) } }
gpl-3.0
SpencerCurtis/GYI
GYI/MenuPopoverViewController.swift
1
19754
// MenuPopoverViewController.swift // GYI // // Created by Spencer Curtis on 1/12/17. // Copyright © 2017 Spencer Curtis. All rights reserved. // import Cocoa class MenuPopoverViewController: NSViewController, NSPopoverDelegate, AccountCreationDelegate, AccountDeletionDelegate, ExecutableUpdateDelegate, VideoPasswordSubmissionDelegate { // MARK: - Properties @IBOutlet weak var inputTextField: NSTextField! @IBOutlet weak var outputPathControl: NSPathControl! @IBOutlet weak var accountSelectionPopUpButton: NSPopUpButtonCell! @IBOutlet weak var submitButton: NSButton! @IBOutlet weak var videoIsPasswordProtectedCheckboxButtton: NSButton! @IBOutlet weak var defaultOutputFolderCheckboxButton: NSButton! @IBOutlet weak var downloadProgressIndicator: NSProgressIndicator! @IBOutlet weak var playlistCountProgressIndicator: NSProgressIndicator! @IBOutlet weak var timeLeftLabel: NSTextField! @IBOutlet weak var videoCountLabel: NSTextField! @IBOutlet weak var downloadSpeedLabel: NSTextField! @IBOutlet weak var automaticallyUpdateYoutubeDLCheckboxButton: NSButton! let downloadController = DownloadController.shared var downloadProgressIndicatorIsAnimating = false var playlistCountProgressIndicatorIsAnimating = false var applicationIsDownloadingVideo = false var currentVideo = 1 var numberOfVideosInPlaylist = 1 var videoNeedsAudio = false private let defaultOutputFolderKey = "defaultOutputFolder" var executableUpdatingView: NSView! var userDidCancelDownload = false var appearance: String! // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.layer?.backgroundColor = CGColor.white NotificationCenter.default.addObserver(self, selector: #selector(processDidEnd), name: processDidEndNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(presentPasswordProtectedVideoAlert), name: downloadController.videoIsPasswordProtectedNotification, object: nil) downloadController.downloadDelegate = self downloadSpeedLabel.stringValue = "0KiB/s" videoCountLabel.stringValue = "No video downloading" timeLeftLabel.stringValue = "Add a video above" downloadProgressIndicator.doubleValue = 0.0 playlistCountProgressIndicator.doubleValue = 0.0 let userWantsAutoUpdate = UserDefaults.standard.bool(forKey: downloadController.autoUpdateYoutubeDLKey) automaticallyUpdateYoutubeDLCheckboxButton.state = userWantsAutoUpdate ? .on : .off outputPathControl.doubleAction = #selector(openOutputFolderPanel) if let defaultPath = UserDefaults.standard.url(forKey: defaultOutputFolderKey) { outputPathControl.url = defaultPath print(outputPathControl.url!) } else { outputPathControl.url = URL(string: "file:///Users/\(NSUserName)/Downloads") } defaultOutputFolderCheckboxButton.state = NSControl.StateValue(rawValue: 1) guard let popover = downloadController.popover else { return } popover.delegate = self } override func viewWillAppear() { setupAccountSelectionPopUpButton() } @objc func processDidEnd() { submitButton.title = "Submit" if !userDidCancelDownload { inputTextField.stringValue = "" } downloadProgressIndicatorIsAnimating = false guard timeLeftLabel.stringValue != "Video already downloaded" else { return } playlistCountProgressIndicator.doubleValue = 100.0 if downloadProgressIndicator.doubleValue == 100.0 { playlistCountProgressIndicator.doubleValue = 100.0 timeLeftLabel.stringValue = "Download Complete" } else if downloadController.userDidCancelDownload { timeLeftLabel.stringValue = "Download canceled" } else if downloadProgressIndicator.doubleValue != 100.0 { timeLeftLabel.stringValue = "Error downloading video" } downloadSpeedLabel.stringValue = "0KiB/s" downloadSpeedLabel.isHidden = true applicationIsDownloadingVideo = false downloadProgressIndicator.stopAnimation(self) playlistCountProgressIndicator.stopAnimation(self) } func presentVideoPasswordSubmissionSheet() { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) guard let accountModificationWC = (storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "VideoPasswordSubmissionWC")) as? NSWindowController), let window = accountModificationWC.window, let videoPasswordSubmissionVC = window.contentViewController as? VideoPasswordSubmissionViewController else { return } videoPasswordSubmissionVC.delegate = self self.view.window?.beginSheet(window, completionHandler: nil) } @IBAction func manageAccountsButtonClicked(_ sender: NSMenuItem) { manageAccountsSheet() } // MARK: - Account Creation/Deletion Delegates func newAccountWasCreated() { setupAccountSelectionPopUpButton() } func accountWasDeletedWith(title: String) { accountSelectionPopUpButton.removeItem(withTitle: title) } func manageAccountsSheet() { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) guard let accountModificationWC = (storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "AccountModificationWC")) as? NSWindowController), let window = accountModificationWC.window, let accountModificationVC = window.contentViewController as? AccountModificationViewController else { return } accountModificationVC.delegate = self self.view.window?.beginSheet(window, completionHandler: { (response) in self.setupAccountSelectionPopUpButton() }) } func setupAccountSelectionPopUpButton() { for account in AccountController.accounts.reversed() { guard let title = account.title else { return } accountSelectionPopUpButton.insertItem(withTitle: title, at: 0) } } // MARK: - Output folder selection @IBAction func chooseOutputFolderButtonTapped(_ sender: NSButton) { openOutputFolderPanel() } @IBAction func defaultOutputFolderButtonClicked(_ sender: NSButton) { if sender.state.rawValue == 1 { let path = outputPathControl.url UserDefaults.standard.set(path, forKey: defaultOutputFolderKey) } } @objc func openOutputFolderPanel() { let openPanel = NSOpenPanel() openPanel.allowsMultipleSelection = false openPanel.canChooseFiles = false openPanel.canChooseDirectories = true openPanel.begin { (result) in guard let path = openPanel.url, result.rawValue == NSFileHandlingPanelOKButton else { return } if self.outputPathControl.url != path { self.defaultOutputFolderCheckboxButton.state = NSControl.StateValue(rawValue: 0) } self.outputPathControl.url = path if self.appearance == "Dark" { self.outputPathControl.pathComponentCells().forEach({$0.textColor = NSColor.white}) } } } // MARK: - ExecutableUpdateDelegate func executableDidBeginUpdateWith(dataString: String) { self.view.addSubview(self.executableUpdatingView, positioned: .above, relativeTo: nil) } func executableDidFinishUpdatingWith(dataString: String) { } func setupExecutableUpdatingView() { let executableUpdatingView = NSView(frame: self.view.frame) executableUpdatingView.wantsLayer = true executableUpdatingView.layer?.backgroundColor = appearance == "Dark" ? .white : .black self.executableUpdatingView = executableUpdatingView // WARNING: - Remove this. This is only for testing. self.view.addSubview(self.executableUpdatingView, positioned: .above, relativeTo: nil) } // MARK: - Password Protected Videos @objc func presentPasswordProtectedVideoAlert() { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) guard let accountModificationWC = (storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "VideoPasswordSubmissionWC")) as? NSWindowController), let window = accountModificationWC.window, let videoPasswordSubmissionVC = window.contentViewController as? VideoPasswordSubmissionViewController else { return } videoPasswordSubmissionVC.delegate = self self.view.window?.beginSheet(window, completionHandler: { (response) in }) } // MARK: - Appearance func changeAppearanceForMenuStyle() { if appearance == "Dark" { outputPathControl.pathComponentCells().forEach({$0.textColor = NSColor.white}) inputTextField.focusRingType = .none } else { outputPathControl.pathComponentCells().forEach({$0.textColor = NSColor.black}) inputTextField.focusRingType = .default inputTextField.backgroundColor = .clear } } func popoverWillShow(_ notification: Notification) { appearance = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") ?? "Light" changeAppearanceForMenuStyle() guard let executableUpdatingView = executableUpdatingView else { return } executableUpdatingView.layer?.backgroundColor = appearance == "Dark" ? .white : .black } // MARK: - Other override func cancelOperation(_ sender: Any?) { NotificationCenter.default.post(name: closePopoverNotification, object: self) } @IBAction func quitButtonClicked(_ sender: Any) { if applicationIsDownloadingVideo { let alert: NSAlert = NSAlert() alert.messageText = "You are currently downloading a video." alert.informativeText = "Do you stil want to quit GYI?" alert.alertStyle = NSAlert.Style.informational alert.addButton(withTitle: "OK") alert.addButton(withTitle: "Cancel") guard let window = self.view.window else { return } alert.beginSheetModal(for: window, completionHandler: { (response) in if response == NSApplication.ModalResponse.alertFirstButtonReturn { NSApplication.shared.terminate(self) } }) } else { downloadController.popover?.performClose(nil) Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(terminateApp), userInfo: nil, repeats: false) } } } // MARK: - Download Delegate/ General Downloading extension MenuPopoverViewController: DownloadDelegate { @IBAction func submitButtonTapped(_ sender: NSButton) { guard inputTextField.stringValue != "" else { return } guard videoIsPasswordProtectedCheckboxButtton.state.rawValue == 0 else { presentVideoPasswordSubmissionSheet(); return } if downloadController.applicationIsDownloading { downloadController.terminateCurrentTask() submitButton.title = "Submit" downloadController.userDidCancelDownload = true } else { beginDownloadOfVideoWith(url: inputTextField.stringValue) } } func beginDownloadOfVideoWith(url: String) { submitButton.title = "Stop Download" downloadController.applicationIsDownloading = true self.processDidBegin() guard let outputFolder = outputPathControl.url?.absoluteString else { return } let outputWithoutPrefix = outputFolder.replacingOccurrences(of: "file://", with: "") let output = outputWithoutPrefix + "%(title)s.%(ext)s" guard let selectedAccountItem = accountSelectionPopUpButton.selectedItem else { return } let account = AccountController.accounts.filter({$0.title == selectedAccountItem.title}).first downloadController.downloadVideoAt(videoURL: url, outputFolder: output, account: account) } func beginDownloadOfVideoWith(additionalArguments: [String]) { let url = inputTextField.stringValue submitButton.title = "Stop Download" downloadController.applicationIsDownloading = true self.processDidBegin() guard let outputFolder = outputPathControl.url?.absoluteString else { return } let outputWithoutPrefix = outputFolder.replacingOccurrences(of: "file://", with: "") let output = outputWithoutPrefix + "%(title)s.%(ext)s" guard let selectedAccountItem = accountSelectionPopUpButton.selectedItem else { return } let account = AccountController.accounts.filter({$0.title == selectedAccountItem.title}).first downloadController.downloadVideoAt(videoURL: url, outputFolder: output, account: account, additionalArguments: additionalArguments) } func processDidBegin() { videoCountLabel.stringValue = "Video 1 of 1" timeLeftLabel.stringValue = "Getting video..." playlistCountProgressIndicator.doubleValue = 0.0 downloadProgressIndicator.doubleValue = 0.0 downloadProgressIndicator.isIndeterminate = true downloadProgressIndicator.startAnimation(self) downloadSpeedLabel.isHidden = false applicationIsDownloadingVideo = true } func updateProgressBarWith(percentString: String?) { let numbersOnly = percentString?.trimmingCharacters(in: NSCharacterSet.decimalDigits.inverted) guard let numbersOnlyUnwrapped = numbersOnly, let progressPercentage = Double(numbersOnlyUnwrapped) else { return } if downloadProgressIndicator.isIndeterminate { downloadProgressIndicator.isIndeterminate = false } if progressPercentage > downloadProgressIndicator.doubleValue { downloadProgressIndicator.doubleValue = progressPercentage } if progressPercentage == 100.0 && (currentVideo + 1) <= numberOfVideosInPlaylist { currentVideo += 1 videoCountLabel.stringValue = "Video \(currentVideo) of \(numberOfVideosInPlaylist)" playlistCountProgressIndicator.doubleValue = Double(currentVideo) / Double(numberOfVideosInPlaylist) } if currentVideo == 1 && numberOfVideosInPlaylist == 1 && progressPercentage == 100.0 { videoNeedsAudio = true if !downloadProgressIndicator.isIndeterminate { downloadProgressIndicator.isIndeterminate = true } } } func updatePlaylistProgressBarWith(downloadString: String) { if downloadString.contains("Downloading video") { let downloadStringWords = downloadString.components(separatedBy: " ") var secondNumber = 1.0 var secondNumberInt = 1 if let secondNum = downloadStringWords.last { var secondNumb = secondNum if secondNumb.contains("\n") { secondNumb.removeLast() guard let secondNum = Double(secondNumb), let secondNumInt = Int(secondNumb) else { return } secondNumber = secondNum secondNumberInt = secondNumInt } else { guard let secondNum = Double(secondNumb), let secondNumInt = Int(secondNumb) else { return } secondNumber = secondNum secondNumberInt = secondNumInt } } playlistCountProgressIndicator.minValue = 0.0 playlistCountProgressIndicator.maxValue = 1.0 playlistCountProgressIndicator.startAnimation(self) let percentage = Double(currentVideo) / secondNumber numberOfVideosInPlaylist = Int(secondNumber) videoCountLabel.stringValue = "Video \(currentVideo) of \(secondNumberInt)" playlistCountProgressIndicator.doubleValue = percentage } } func updateDownloadSpeedLabelWith(downloadString: String) { let downloadStringWords = downloadString.components(separatedBy: " ") guard let atStringIndex = downloadStringWords.index(of: "at") else { return } var speed = downloadStringWords[(atStringIndex + 1)] if speed == "" { speed = downloadStringWords[(atStringIndex + 2)] } downloadSpeedLabel.stringValue = speed } func parseResponseStringForETA(responseString: String) { let words = responseString.components(separatedBy: " ") guard let timeLeft = words.last else { return } var timeLeftString = timeLeft if (timeLeftString.contains("00:")) { timeLeftString.removeFirst() } if videoNeedsAudio { timeLeftLabel.stringValue = "Getting audio. Almost done." } else { timeLeftLabel.stringValue = "Getting video. Time remaining: \(timeLeft)" } // timeLeftLabel.stringValue = "Time remaining: \(timeLeft)" } func userHasAlreadyDownloadedVideo() { timeLeftLabel.stringValue = "Video already downloaded" let alert: NSAlert = NSAlert() alert.messageText = "You have already downloaded this video." alert.informativeText = "Please check your output directory." alert.alertStyle = NSAlert.Style.informational alert.addButton(withTitle: "OK") alert.addButton(withTitle: "Cancel") guard let window = self.view.window else { return } alert.beginSheetModal(for: window, completionHandler: nil) } @objc func terminateApp() { NSApplication.shared.terminate(_:self) } @IBAction func automaticallyUpdateYoutubeDLCheckboxButtonClicked(_ sender: NSButton) { switch sender.state { case .off: UserDefaults.standard.set(false, forKey: downloadController.autoUpdateYoutubeDLKey) case .on: UserDefaults.standard.set(true, forKey: downloadController.autoUpdateYoutubeDLKey) default: break } } } // MARK: - Resizing (may not be needed) extension NSWindow { func change(height: CGFloat) { var frame = self.frame frame.size.height += height frame.origin.y -= height self.setFrame(frame, display: true) } } var processDidBeginNotification = Notification.Name("processDidBegin") var processDidEndNotification = Notification.Name("processDidEnd")
mit
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Animation/ChartAnimationEasing.swift
7
13883
// // ChartAnimationUtils.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase @objc public enum ChartEasingOption: Int { case Linear case EaseInQuad case EaseOutQuad case EaseInOutQuad case EaseInCubic case EaseOutCubic case EaseInOutCubic case EaseInQuart case EaseOutQuart case EaseInOutQuart case EaseInQuint case EaseOutQuint case EaseInOutQuint case EaseInSine case EaseOutSine case EaseInOutSine case EaseInExpo case EaseOutExpo case EaseInOutExpo case EaseInCirc case EaseOutCirc case EaseInOutCirc case EaseInElastic case EaseOutElastic case EaseInOutElastic case EaseInBack case EaseOutBack case EaseInOutBack case EaseInBounce case EaseOutBounce case EaseInOutBounce } public typealias ChartEasingFunctionBlock = ((elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat); internal func easingFunctionFromOption(easing: ChartEasingOption) -> ChartEasingFunctionBlock { switch easing { case .Linear: return EasingFunctions.Linear; case .EaseInQuad: return EasingFunctions.EaseInQuad; case .EaseOutQuad: return EasingFunctions.EaseOutQuad; case .EaseInOutQuad: return EasingFunctions.EaseInOutQuad; case .EaseInCubic: return EasingFunctions.EaseInCubic; case .EaseOutCubic: return EasingFunctions.EaseOutCubic; case .EaseInOutCubic: return EasingFunctions.EaseInOutCubic; case .EaseInQuart: return EasingFunctions.EaseInQuart; case .EaseOutQuart: return EasingFunctions.EaseOutQuart; case .EaseInOutQuart: return EasingFunctions.EaseInOutQuart; case .EaseInQuint: return EasingFunctions.EaseInQuint; case .EaseOutQuint: return EasingFunctions.EaseOutQuint; case .EaseInOutQuint: return EasingFunctions.EaseInOutQuint; case .EaseInSine: return EasingFunctions.EaseInSine; case .EaseOutSine: return EasingFunctions.EaseOutSine; case .EaseInOutSine: return EasingFunctions.EaseInOutSine; case .EaseInExpo: return EasingFunctions.EaseInExpo; case .EaseOutExpo: return EasingFunctions.EaseOutExpo; case .EaseInOutExpo: return EasingFunctions.EaseInOutExpo; case .EaseInCirc: return EasingFunctions.EaseInCirc; case .EaseOutCirc: return EasingFunctions.EaseOutCirc; case .EaseInOutCirc: return EasingFunctions.EaseInOutCirc; case .EaseInElastic: return EasingFunctions.EaseInElastic; case .EaseOutElastic: return EasingFunctions.EaseOutElastic; case .EaseInOutElastic: return EasingFunctions.EaseInOutElastic; case .EaseInBack: return EasingFunctions.EaseInBack; case .EaseOutBack: return EasingFunctions.EaseOutBack; case .EaseInOutBack: return EasingFunctions.EaseInOutBack; case .EaseInBounce: return EasingFunctions.EaseInBounce; case .EaseOutBounce: return EasingFunctions.EaseOutBounce; case .EaseInOutBounce: return EasingFunctions.EaseInOutBounce; } } internal struct EasingFunctions { internal static let Linear = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return CGFloat(elapsed / duration); }; internal static let EaseInQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position; }; internal static let EaseOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return -position * (position - 2.0); }; internal static let EaseInOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position; } return -0.5 * ((--position) * (position - 2.0) - 1.0); }; internal static let EaseInCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position * position; }; internal static let EaseOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return (position * position * position + 1.0); }; internal static let EaseInOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position * position; } position -= 2.0; return 0.5 * (position * position * position + 2.0); }; internal static let EaseInQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position * position * position; }; internal static let EaseOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return -(position * position * position * position - 1.0); }; internal static let EaseInOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position * position * position; } position -= 2.0; return -0.5 * (position * position * position * position - 2.0); }; internal static let EaseInQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position * position * position * position; }; internal static let EaseOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return (position * position * position * position * position + 1.0); }; internal static let EaseInOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position * position * position * position; } else { position -= 2.0; return 0.5 * (position * position * position * position * position + 2.0); } }; internal static let EaseInSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; return CGFloat( -cos(position * M_PI_2) + 1.0 ); }; internal static let EaseOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; return CGFloat( sin(position * M_PI_2) ); }; internal static let EaseInOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; return CGFloat( -0.5 * (cos(M_PI * position) - 1.0) ); }; internal static let EaseInExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return (elapsed == 0) ? 0.0 : CGFloat(pow(2.0, 10.0 * (elapsed / duration - 1.0))); }; internal static let EaseOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return (elapsed == duration) ? 1.0 : (-CGFloat(pow(2.0, -10.0 * elapsed / duration)) + 1.0); }; internal static let EaseInOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0) { return 0.0; } if (elapsed == duration) { return 1.0; } var position: NSTimeInterval = elapsed / (duration / 2.0); if (position < 1.0) { return CGFloat( 0.5 * pow(2.0, 10.0 * (position - 1.0)) ); } return CGFloat( 0.5 * (-pow(2.0, -10.0 * --position) + 2.0) ); }; internal static let EaseInCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return -(CGFloat(sqrt(1.0 - position * position)) - 1.0); }; internal static let EaseOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return CGFloat( sqrt(1 - position * position) ); }; internal static let EaseInOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / (duration / 2.0); if (position < 1.0) { return CGFloat( -0.5 * (sqrt(1.0 - position * position) - 1.0) ); } position -= 2.0; return CGFloat( 0.5 * (sqrt(1.0 - position * position) + 1.0) ); }; internal static let EaseInElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0.0) { return 0.0; } var position: NSTimeInterval = elapsed / duration; if (position == 1.0) { return 1.0; } var p = duration * 0.3; var s = p / (2.0 * M_PI) * asin(1.0); position -= 1.0; return CGFloat( -(pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) ); }; internal static let EaseOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0.0) { return 0.0; } var position: NSTimeInterval = elapsed / duration; if (position == 1.0) { return 1.0; } var p = duration * 0.3; var s = p / (2.0 * M_PI) * asin(1.0); return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) + 1.0 ); }; internal static let EaseInOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0.0) { return 0.0; } var position: NSTimeInterval = elapsed / (duration / 2.0); if (position == 2.0) { return 1.0; } var p = duration * (0.3 * 1.5); var s = p / (2.0 * M_PI) * asin(1.0); if (position < 1.0) { position -= 1.0; return CGFloat( -0.5 * (pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) ); } position -= 1.0; return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) * 0.5 + 1.0 ); }; internal static let EaseInBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in let s: NSTimeInterval = 1.70158; var position: NSTimeInterval = elapsed / duration; return CGFloat( position * position * ((s + 1.0) * position - s) ); }; internal static let EaseOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in let s: NSTimeInterval = 1.70158; var position: NSTimeInterval = elapsed / duration; position--; return CGFloat( (position * position * ((s + 1.0) * position + s) + 1.0) ); }; internal static let EaseInOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var s: NSTimeInterval = 1.70158; var position: NSTimeInterval = elapsed / (duration / 2.0); if (position < 1.0) { s *= 1.525; return CGFloat( 0.5 * (position * position * ((s + 1.0) * position - s)) ); } s *= 1.525; position -= 2.0; return CGFloat( 0.5 * (position * position * ((s + 1.0) * position + s) + 2.0) ); }; internal static let EaseInBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return 1.0 - EaseOutBounce(duration - elapsed, duration); }; internal static let EaseOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; if (position < (1.0 / 2.75)) { return CGFloat( 7.5625 * position * position ); } else if (position < (2.0 / 2.75)) { position -= (1.5 / 2.75); return CGFloat( 7.5625 * position * position + 0.75 ); } else if (position < (2.5 / 2.75)) { position -= (2.25 / 2.75); return CGFloat( 7.5625 * position * position + 0.9375 ); } else { position -= (2.625 / 2.75); return CGFloat( 7.5625 * position * position + 0.984375 ); } }; internal static let EaseInOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed < (duration / 2.0)) { return EaseInBounce(elapsed * 2.0, duration) * 0.5; } return EaseOutBounce(elapsed * 2.0 - duration, duration) * 0.5 + 0.5; }; };
gpl-2.0
nickdex/cosmos
code/graph_algorithms/src/breadth_first_search/breadth_first_search.swift
17
496
func breadthFirstSearch(_ graph: Graph, source: Node) -> [String] { var queue = Queue<Node>() queue.enqueue(source) var nodesExplored = [source.label] source.visited = true while let current = queue.dequeue() { for edge in current.neighbors { let neighborNode = edge.neighbor if !neighborNode.visited { queue.enqueue(neighborNode) neighborNode.visited = true nodesExplored.append(neighborNode.label) } } } return nodesExplored }
gpl-3.0
milseman/swift
test/PCMacro/init.swift
21
1190
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift %S/Inputs/SilentPlaygroundsRuntime.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test // XFAIL: * // FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode // UNSUPPORTED: OS=linux-gnu class A { func access() -> Void { } } class B { var a : A = A() init() { a.access() } func mutateIvar() -> Void { a.access() } } var b = B() // CHECK: [25:1-25:12] pc before // this should be logging the init, this is tracked in the init.swift test. // Once fixed update this test to include it. // CHECK-NEXT: [17:3-17:9] pc before // CHECK-NEXT: [17:3-17:9] pc after // CHECK-NEXT: [18:5-18:15] pc before // CHECK-NEXT: [11:3-11:24] pc before // CHECK-NEXT: [11:3-11:24] pc after // CHECK-NEXT: [18:5-18:15] pc after // CHECK-NEXT: [25:1-25:12] pc after
apache-2.0
SettlePad/client-iOS
SettlePad/keychain.swift
1
1999
// // keychain.swift // SettlePad // // Created by Rob Everhardt on 06/01/15. // Copyright (c) 2015 SettlePad. All rights reserved. // import UIKit import Security class Keychain { class func save(key: String, data: NSData) -> Bool { let query = [ kSecClass as String : kSecClassGenericPassword as String, kSecAttrAccount as String : key, kSecValueData as String : data ] SecItemDelete(query as CFDictionaryRef) let status: OSStatus = SecItemAdd(query as CFDictionaryRef, nil) return status == noErr } class func load(key: String) -> NSData? { let query = [ kSecClass as String : kSecClassGenericPassword, kSecAttrAccount as String : key, kSecReturnData as String : kCFBooleanTrue, kSecMatchLimit as String : kSecMatchLimitOne ] var extractedData: AnyObject? let status = SecItemCopyMatching(query, &extractedData) if status == noErr { return extractedData as? NSData } else { return nil } } class func delete(key: String) -> Bool { let query = [ kSecClass as String : kSecClassGenericPassword, kSecAttrAccount as String : key ] let status: OSStatus = SecItemDelete(query as CFDictionaryRef) return status == noErr } class func clear() -> Bool { let query = [ kSecClass as String : kSecClassGenericPassword ] let status: OSStatus = SecItemDelete(query as CFDictionaryRef) return status == noErr } } extension String { public var dataValue: NSData { return dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } } extension NSData { public var stringValue: String { return NSString(data: self, encoding: NSUTF8StringEncoding)! as String } }
mit
pkc456/Roastbook
Roastbook/Roastbook/SecondViewController.swift
1
530
// // SecondViewController.swift // Roastbook // // Created by Pradeep Choudhary on 3/28/17. // Copyright © 2017 Pardeep chaudhary. All rights reserved. // import UIKit class SecondViewController: 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
iMetalk/TCZKit
TCZKitDemo/TCZKit/Views/Cells/标题 TCZTitleCell/TCZTitleCell.swift
1
891
// // TCZTitleCell.swift // Dormouse // // Created by tczy on 2017/8/14. // Copyright © 2017年 WangSuyan. All rights reserved. // import UIKit import Foundation class TCZTitleCell: TCZBaseTableCell { /// Title label lazy var titleLabel: UILabel = { let label = UILabel.tczLabel() return label }() override func tczCreateBaseCellUI() { accessoryType = .disclosureIndicator // Title label contentView.addSubview(self.titleLabel) titleLabel.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(kLeftEdge) make.right.equalToSuperview().offset(-kLeftEdge) make.centerY.equalToSuperview() } } override func tczConfigureData(aItem: TCZTableViewData) { titleLabel.text = aItem.title } }
mit
LibraryLoupe/PhotosPlus
PhotosPlus/Cameras/Pentax/PentaxK7.swift
3
513
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // import Foundation extension Cameras.Manufacturers.Pentax { //swiftlint:disable type_name public struct K7: CameraModel { public init() {} public let name = "Pentax K-7" public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Pentax.self } } public typealias PentaxK7 = Cameras.Manufacturers.Pentax.K7
mit
SusanDoggie/Doggie
Sources/DoggieGraphics/SVGContext/SVGEffect/SVGConvolveMatrixEffect.swift
1
4890
// // SVGConvolveMatrixEffect.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // public struct SVGConvolveMatrixEffect: SVGEffectElement { public var region: Rect = .null public var regionUnit: SVGEffect.RegionUnit = .objectBoundingBox public var source: SVGEffect.Source public var matrix: [Double] public var divisor: Double public var bias: Double public var orderX: Int public var orderY: Int public var targetX: Int public var targetY: Int public var edgeMode: EdgeMode public var preserveAlpha: Bool public var sources: [SVGEffect.Source] { return [source] } public init(source: SVGEffect.Source = .source, matrix: [Double], divisor: Double = 1, bias: Double = 0, orderX: Int, orderY: Int, edgeMode: EdgeMode = .duplicate, preserveAlpha: Bool = false) { precondition(orderX > 0, "nonpositive width is not allowed.") precondition(orderY > 0, "nonpositive height is not allowed.") precondition(orderX * orderY == matrix.count, "mismatch matrix count.") self.source = source self.matrix = matrix self.divisor = divisor self.bias = bias self.orderX = orderX self.orderY = orderY self.targetX = orderX / 2 self.targetY = orderY / 2 self.edgeMode = edgeMode self.preserveAlpha = preserveAlpha } public enum EdgeMode { case duplicate case wrap case none } public func visibleBound(_ sources: [SVGEffect.Source: Rect]) -> Rect? { guard let source = sources[source] else { return nil } guard !preserveAlpha else { return source } let minX = source.minX - Double(orderX - targetX - 1) let minY = source.minY - Double(orderY - targetY - 1) let width = source.width + Double(orderX - 1) let height = source.height + Double(orderY - 1) return Rect(x: minX, y: minY, width: width, height: height) } } extension SVGConvolveMatrixEffect { public init() { self.init(matrix: [0, 0, 0, 0, 0, 0, 0, 0, 0], orderX: 3, orderY: 3) } } extension SVGConvolveMatrixEffect { public var xml_element: SDXMLElement { let matrix = self.matrix.map { "\(Decimal($0).rounded(scale: 9))" } var filter = SDXMLElement(name: "feConvolveMatrix", attributes: ["kernelMatrix": matrix.joined(separator: " "), "order": orderX == orderY ? "\(orderX)" : "\(orderX) \(orderY)"]) let sum = self.matrix.reduce(0, +) if divisor != (sum == 0 ? 1 : sum) { filter.setAttribute(for: "divisor", value: "\(Decimal(divisor).rounded(scale: 9))") } if bias != 0 { filter.setAttribute(for: "bias", value: "\(Decimal(bias).rounded(scale: 9))") } if targetX != orderX / 2 { filter.setAttribute(for: "targetX", value: "\(targetX)") } if targetY != orderY / 2 { filter.setAttribute(for: "targetY", value: "\(targetY)") } filter.setAttribute(for: "preserveAlpha", value: "\(preserveAlpha)") switch edgeMode { case .duplicate: filter.setAttribute(for: "edgeMode", value: "duplicate") case .wrap: filter.setAttribute(for: "edgeMode", value: "wrap") case .none: filter.setAttribute(for: "edgeMode", value: "none") } switch self.source { case .source: filter.setAttribute(for: "in", value: "SourceGraphic") case .sourceAlpha: filter.setAttribute(for: "in", value: "SourceAlpha") case let .reference(uuid): filter.setAttribute(for: "in", value: uuid.uuidString) } return filter } }
mit
royratcliffe/ManagedObject
Sources/ObjectsDidChangeObserver.swift
1
5407
// ManagedObject ObjectsDidChangeObserver.swift // // Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom // // 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, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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 CoreData /// Observes managed-object changes, collates those changes and notifies change /// controllers; automatically instantiates such change controllers if required. /// /// Set up the observer by adding it to the notification centre. Then add change /// controllers, one for each entity that might change. The observer invokes the /// controllers when one or more objects of interest change: either inserted, /// updated or deleted. When inserting objects, a change controller receives a /// `insertedObjects(objects: [NSManagedObject])` method invocation where the /// argument is an array of managed objects for insertion. Similarly for updated /// and deleted. public class ObjectsDidChangeObserver: NSObject { /// True if you want the observer to use the Objective-C run-time to /// automatically instantiate change controllers based on entity name. Looks /// for entity name plus `ChangeController` as an Objective-C class name. This /// is not the default behaviour because change controllers will typically /// require additional set-up beyond just simple instantiation before they /// are ready to begin observing changes. public var automaticallyInstantiatesChangeControllers = false /// Handles a managed-object change notification. Instantiates change /// controllers automatically if the Objective-C run-time environment has a /// controller class matching the entity name plus `ChangeController`. @objc private func objectsDidChange(_ notification: Notification) { guard NSNotification.Name.NSManagedObjectContextObjectsDidChange == notification.name else { return } guard let objectsDidChange = ObjectsDidChange(notification: notification) else { return } // Iterate change keys and entity names. The change key becomes part of the // selector. The entity name becomes part of the controller class name. for (changeKey, objectsByEntityName) in objectsDidChange.managedObjectsByEntityNameByChangeKey { let selector = Selector("\(changeKey)Objects:") for (entityName, objects) in objectsByEntityName { var changeController = changeControllersByEntityName[entityName] if automaticallyInstantiatesChangeControllers && changeController == nil { let changeControllerClassName = "\(entityName)ChangeController" if let changeControllerClass = NSClassFromString(changeControllerClassName) as? NSObject.Type { changeController = changeControllerClass.init() changeControllersByEntityName[entityName] = changeController } } if let controller = changeController { if controller.responds(to: selector) { controller.perform(selector, with: objects) } } } } } //---------------------------------------------------------------------------- // MARK: - Change Controllers var changeControllersByEntityName = [String: NSObject]() /// Adds a change controller for the given entity name. There can be only one /// controller for each entity. If your application requires more than one /// controller, use more than one observer. public func add(changeController: NSObject, forEntityName entityName: String) { changeControllersByEntityName[entityName] = changeController } /// Removes a change controller. public func removeChangeController(forEntityName entityName: String) { changeControllersByEntityName.removeValue(forKey: entityName) } //---------------------------------------------------------------------------- // MARK: - Notification Centre /// Adds this observer to the given notification centre. public func add(to center: NotificationCenter, context: NSManagedObjectContext? = nil) { center.addObserver(self, selector: #selector(ObjectsDidChangeObserver.objectsDidChange(_:)), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: context) } /// Removes this observer from the given notification centre. public func remove(from center: NotificationCenter) { center.removeObserver(self) } }
mit
gregttn/GTToast
Pod/Classes/GTToastView.swift
1
7779
// // GTToastView.swift // Pods // // Created by Grzegorz Tatarzyn on 03/10/2015. // // open class GTToastView: UIView, GTAnimatable { fileprivate let animationOffset: CGFloat = 20 fileprivate let margin: CGFloat = 5 fileprivate let config: GTToastConfig fileprivate let image: UIImage? fileprivate let message: String fileprivate var messageLabel: UILabel! fileprivate var imageView: UIImageView! fileprivate lazy var contentSize: CGSize = { [unowned self] in return CGSize(width: self.frame.size.width - self.config.contentInsets.leftAndRight, height: self.frame.size.height - self.config.contentInsets.topAndBottom) }() fileprivate lazy var imageSize: CGSize = { [unowned self] in guard let image = self.image else { return CGSize.zero } return CGSize( width: min(image.size.width, self.config.maxImageSize.width), height: min(image.size.height, self.config.maxImageSize.height) ) }() override open var frame: CGRect { didSet { guard let _ = messageLabel else { return } messageLabel.frame = createLabelFrame() guard let _ = image else { return } imageView.frame = createImageViewFrame() } } open var displayed: Bool { return superview != nil } init() { fatalError("init() has not been implemented") } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public init(message: String, config: GTToastConfig, image: UIImage? = .none) { self.config = config self.message = message self.image = image super.init(frame: CGRect.zero) self.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin] self.backgroundColor = config.backgroundColor self.layer.cornerRadius = config.cornerRadius messageLabel = createLabel() addSubview(messageLabel) if let image = image { imageView = createImageView() imageView.image = image addSubview(imageView) } } // MARK: creating views fileprivate func createLabel() -> UILabel { let label = UILabel() label.backgroundColor = UIColor.clear label.textAlignment = config.textAlignment label.textColor = config.textColor label.font = config.font label.numberOfLines = 0 label.text = message label.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin] return label } fileprivate func createImageView() -> UIImageView { let imageView = UIImageView() imageView.contentMode = UIViewContentMode.scaleAspectFit return imageView } fileprivate func createLabelFrame() -> CGRect { var x: CGFloat = config.contentInsets.left var y: CGFloat = config.contentInsets.top var width: CGFloat = contentSize.width var height: CGFloat = contentSize.height switch config.imageAlignment { case .left: x += imageWithMarginsSize().width fallthrough case .right: width -= imageWithMarginsSize().width case .top: y += config.imageMargins.topAndBottom + imageSize.height fallthrough case .bottom: height = height - config.imageMargins.topAndBottom - imageSize.height } return CGRect(x: x, y: y, width: width, height: height) } fileprivate func createImageViewFrame() -> CGRect { let allInsets = config.contentInsets + config.imageMargins var x: CGFloat = allInsets.left var y: CGFloat = allInsets.top var width: CGFloat = imageSize.width var height: CGFloat = imageSize.height switch config.imageAlignment { case .right: x = frame.width - allInsets.right - imageSize.width fallthrough case .left: height = contentSize.height - config.imageMargins.topAndBottom case .bottom: y += calculateLabelSize().height fallthrough case .top: width = frame.size.width - allInsets.leftAndRight } return CGRect(x: x, y: y, width: width, height: height) } // MARK: size and frame calculation open override func sizeThatFits(_ size: CGSize) -> CGSize { let imageLocationAdjustment = imageLocationSizeAdjustment() let labelSize = calculateLabelSize() let height = labelSize.height + config.contentInsets.topAndBottom + imageLocationAdjustment.height let width = labelSize.width + config.contentInsets.leftAndRight + imageLocationAdjustment.width return CGSize(width: width, height: height) } fileprivate func calculateLabelSize() -> CGSize { let imageLocationAdjustment = imageLocationSizeAdjustment() let screenSize = UIScreen.main.bounds let maxLabelWidth = screenSize.width - 2 * margin - config.contentInsets.leftAndRight - imageLocationAdjustment.width let size = config.font.sizeFor(message, constrain: CGSize(width: maxLabelWidth, height: 0)) return CGSize(width: ceil(size.width), height: ceil(size.height)) } fileprivate func imageLocationSizeAdjustment() -> CGSize { switch config.imageAlignment { case .left, .right: return CGSize(width: imageWithMarginsSize().width, height: 0) case .top, .bottom: return CGSize(width: 0, height: imageWithMarginsSize().height) } } fileprivate func imageWithMarginsSize() -> CGSize { guard let _ = image else { return CGSize.zero } return CGSize( width: imageSize.width + config.imageMargins.leftAndRight, height: imageSize.height + config.imageMargins.topAndBottom ) } open func show() { guard let window = UIApplication.shared.windows.first else { return } if !displayed { window.addSubview(self) animateAll(self, interval: config.displayInterval, animations: config.animation) } } open func dismiss() { self.config.animation.show(self) layer.removeAllAnimations() animate(0, animations: { self.config.animation.hide(self) }) { _ in self.removeFromSuperview() } } } internal protocol GTAnimatable {} internal extension GTAnimatable { func animateAll(_ view: UIView, interval: TimeInterval, animations: GTAnimation) { animations.before(view) animate(0, animations: { animations.show(view) }, completion: { _ in self.animate(interval, animations: { animations.hide(view) }) { finished in if finished { view.removeFromSuperview() } } } ) } fileprivate func animate(_ interval: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) { UIView.animate(withDuration: 0.6, delay: interval, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .allowUserInteraction, animations: animations, completion: completion) } }
mit
mactive/rw-courses-note
advanced-swift-types-and-operations/AdvancePOP.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
1
575
import Foundation var str = "Hello, playground" protocol Distribution { func sample() -> Double func sample(count: Int) -> [Double] } extension Distribution { func sample(count: Int) -> [Double] { return (1...count).map { _ in sample() } } } struct UniformDistribution: Distribution { var range: ClosedRange<Int> init(range: ClosedRange<Int>) { self.range = range } func sample() -> Double { return Double(Int.random(in: range)) } } var d10 = UniformDistribution(range: 1...30) d10.sample(count: 10)
mit
zhaoxin151/SpeechTranslate
SpeechTranslate/Controller/SpeechController.swift
1
11294
// // SpeechController.swift // SpeechTranslate // // Created by NATON on 2017/6/1. // Copyright © 2017年 NATON. All rights reserved. // import UIKit import Speech import AVFoundation class SpeechController: UIViewController, SFSpeechRecognizerDelegate, AVSpeechSynthesizerDelegate{ @IBOutlet weak var microphoneButton: UIButton! @IBOutlet weak var speechButton: UIButton! @IBOutlet weak var translateButton: UIButton! @IBOutlet weak var speechLanguageTextView: UITextView! @IBOutlet weak var translateLanguageTextview: UITextView! //录音 private var speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "zh-cn"))! private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? private var recognitionTask: SFSpeechRecognitionTask? private let audioEngine = AVAudioEngine() private let av = AVSpeechSynthesizer() var language = Language() override func viewDidLoad() { super.viewDidLoad() microphoneButton.isEnabled = false speechRecognizer.delegate = self av.delegate = self // Do any additional setup after loading the view. SFSpeechRecognizer.requestAuthorization { (authStatus) in var isButtonEnabled = false switch authStatus { case .authorized: isButtonEnabled = true case .denied: isButtonEnabled = false print("User denied access to speech recognition") case .restricted: isButtonEnabled = false print("Speech recognition restricted on this device") case .notDetermined: isButtonEnabled = false print("Speech recognition not yet authorized") } OperationQueue.main.addOperation() { self.microphoneButton.isEnabled = isButtonEnabled } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ //说话语言被按下 @IBAction func speechLangugateClick(_ sender: UIButton) { self.speechLanguageTextView.text = "" let sb = UIStoryboard(name: "Main", bundle:nil) let vc = sb.instantiateViewController(withIdentifier: "LanguageListController") as! LanguageListController //VC为该界面storyboardID,Main.storyboard中选中该界面View,Identifier inspector中修改 vc.languageStr = sender.currentTitle! vc.selectBlock = {(titleStr) in sender.setTitle(titleStr, for: .normal) let codeStr = self.language.languageCodeByTitle(titleStr: titleStr) self.speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: codeStr))! self.speechRecognizer.delegate = self } self.present(vc, animated: true, completion: nil) } //翻译语言被按下 @IBAction func tranlatorLanguageClick(_ sender: UIButton) { let sb = UIStoryboard(name: "Main", bundle:nil) let vc = sb.instantiateViewController(withIdentifier: "LanguageListController") as! LanguageListController vc.languageStr = sender.currentTitle! //VC为该界面storyboardID,Main.storyboard中选中该界面View,Identifier inspector中修改 vc.selectBlock = {(titleStr) in sender.setTitle(titleStr, for: .normal) } self.present(vc, animated: true, completion: nil) } //翻译按钮被按下 @IBAction func translateButtonClick(_ sender: UIButton) { let transelateStr = speechLanguageTextView.text! let appid = "20170522000048682" let salt = "858585858" let sercet = "QFaDv625Kk7ocCnT8xlv" let baseUrl = "http://api.fanyi.baidu.com/api/trans/vip/translate" let sign = appid+transelateStr+salt+sercet let speechCode = language.baiduLanguageCodeByTitle(titleStr: speechButton.currentTitle!) let tranlateCode = language.baiduLanguageCodeByTitle(titleStr: translateButton.currentTitle!) let signMd5 = MD5(sign) let params = ["q":transelateStr, "from":speechCode, "to":tranlateCode, "appid":appid, "salt":salt, "sign":signMd5] HttpRequest.instanceRequst.request(method: .Get, usrString: baseUrl, params: params as AnyObject, resultBlock: { (responseObject, error) in if error != nil { print(error) return } guard (responseObject as [String : AnyObject]?) != nil else{ return } let re = responseObject?["trans_result"] as! Array<Dictionary<String,AnyObject>> let dst = re[0] self.translateLanguageTextview.text = dst["dst"] as! String }) } //播放按钮被按下 @IBAction func playButtonClick(_ sender: UIButton) { if(sender.isSelected == false) { if(av.isPaused) { //如果暂停则恢复,会从暂停的地方继续 av.continueSpeaking() sender.isSelected = !sender.isSelected; }else{ //AVSpeechUtterance*utterance = [[AVSpeechUtterance alloc]initWithString:"];//需要转换的文字 let str: String = self.translateLanguageTextview.text //let utterance = AVSpeechUtterance(string: str) let utterance = AVSpeechUtterance.init(string: "Hello") utterance.rate=0.4;// 设置语速,范围0-1,注意0最慢,1最快;AVSpeechUtteranceMinimumSpeechRate最慢,AVSpeechUtteranceMaximumSpeechRate最快 //AVSpeechSynthesisVoice*voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-us"];//设置发音,这是中文普通话 //let voice = AVSpeechSynthesisVoice(language: "en-us") let voice = AVSpeechSynthesisVoice(language: language.languageCodeByTitle(titleStr: translateButton.currentTitle!)) utterance.voice = voice //[_av speakUtteran ce:utterance];//开始 av.speak(utterance) sender.isSelected = !sender.isSelected } }else{ //[av stopSpeakingAtBoundary:AVSpeechBoundaryWord];//感觉效果一样,对应代理>>>取消 //[_av pauseSpeakingAtBoundary:AVSpeechBoundaryWord];//暂停 av.pauseSpeaking(at: .word) sender.isSelected = !sender.isSelected; } } //录音按钮被按下 @IBAction func recodeButtonClick(_ sender: UIButton) { if audioEngine.isRunning { audioEngine.stop() recognitionRequest?.endAudio() sender.isEnabled = false sender.setTitle("开始录音", for: .normal) } else { startRecording() sender.setTitle("结束录音", for: .normal) } } func startRecording() { if recognitionTask != nil { //1 recognitionTask?.cancel() recognitionTask = nil } let audioSession = AVAudioSession.sharedInstance() //2 do { try audioSession.setCategory(AVAudioSessionCategoryRecord) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) } catch { print("audioSession properties weren't set because of an error.") } recognitionRequest = SFSpeechAudioBufferRecognitionRequest() //3 guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") } //4 guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object") } //5 recognitionRequest.shouldReportPartialResults = true //6 recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in //7 var isFinal = false //8 if result != nil { self.speechLanguageTextView.text = result?.bestTranscription.formattedString //9 isFinal = (result?.isFinal)! } if error != nil || isFinal { //10 self.audioEngine.stop() inputNode.removeTap(onBus: 0) self.recognitionRequest = nil self.recognitionTask = nil self.microphoneButton.isEnabled = true } }) let recordingFormat = inputNode.outputFormat(forBus: 0) //11 inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in self.recognitionRequest?.append(buffer) } audioEngine.prepare() //12 do { try audioEngine.start() } catch { print("audioEngine couldn't start because of an error.") } speechLanguageTextView.text = "Say something, I'm listening!" } func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) { if available { microphoneButton.isEnabled = true } else { microphoneButton.isEnabled = false } } func MD5(_ string: String) -> String? { let length = Int(CC_MD5_DIGEST_LENGTH) var digest = [UInt8](repeating: 0, count: length) if let d = string.data(using: String.Encoding.utf8) { _ = d.withUnsafeBytes { (body: UnsafePointer<UInt8>) in CC_MD5(body, CC_LONG(d.count), &digest) } } return (0..<length).reduce("") { $0 + String(format: "%02x", digest[$1]) } } func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) { print("Speaker class started") } func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { print("Speaker class finished") } }
mit
reeseugolf/EffectsModalSegue
EffectsModalSegue/EffectsModalSegue.swift
2
4194
// // EffectsModalSegue.swift // EffectsModalSegue // // Created by UGolf_Reese on 15/7/17. // Copyright (c) 2015年 reese. All rights reserved. // import UIKit enum EffectsModalSegueType: Int { case Blur case Draken } enum EffectsModalSegueTransitionStyle: Int { case Fade = 0 case FromTop = 1 case FromBottom = 2 case FromLeft = 3 case FromRight = 4 } class EffectsModalSegue: UIStoryboardSegue { var type: EffectsModalSegueType = .Draken var transitionStyle: EffectsModalSegueTransitionStyle = .Fade var backgroundOpacity: CGFloat = 0.4 var backgroundBlurRadius: CGFloat = 8 var backgroundSaturationDeltaFactor: CGFloat = 1 var backgroundTintColor = UIColor.clearColor() private var backgroundImageView: UIImageView! private var maskView: UIView! private var backgroundView: UIView! private var contentView: UIView! override init!(identifier: String?, source: UIViewController, destination: UIViewController) { super.init(identifier: identifier, source: source, destination: destination) } override func perform() { let source = self.sourceViewController as! UIViewController let destination = self.destinationViewController as! UIViewController contentView = destination.view contentView.backgroundColor = UIColor.clearColor() contentView.autoresizingMask = .FlexibleHeight | .FlexibleWidth backgroundImageView = UIImageView(frame: destination.view.frame) backgroundImageView.autoresizingMask = .FlexibleHeight | .FlexibleWidth maskView = UIView(frame: destination.view.frame) maskView.autoresizingMask = .FlexibleHeight | .FlexibleWidth maskView.backgroundColor = UIColor.blackColor() maskView.alpha = 0.0 backgroundView = UIView(frame: destination.view.frame) destination.view = backgroundView destination.view.insertSubview(backgroundImageView, atIndex: 0) destination.view.insertSubview(maskView, atIndex: 1) destination.view.addSubview(contentView) var beginFrame = destination.view.frame switch self.transitionStyle { case .FromTop: beginFrame.origin.y = -1 * beginFrame.size.height case .FromBottom : beginFrame.origin.y = 1 * beginFrame.size.height case .FromLeft : beginFrame.origin.x = -1 * beginFrame.size.width case .FromRight : beginFrame.origin.x = 1 * beginFrame.size.width default: beginFrame = destination.view.frame } self.contentView.frame = beginFrame let windowBounds = source.view.window!.bounds UIGraphicsBeginImageContextWithOptions(windowBounds.size, true, 0.0) source.view.window!.drawViewHierarchyInRect(windowBounds, afterScreenUpdates: true) var snaphost = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if self.type == .Blur { snaphost = snaphost.applyBlurWithRadius(backgroundBlurRadius, tintColor: backgroundTintColor, saturationDeltaFactor: backgroundSaturationDeltaFactor, maskImage: nil) } backgroundImageView.image = snaphost destination.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve source.presentViewController(destination, animated: true, completion: nil) destination.transitionCoordinator()?.animateAlongsideTransition({ [weak self] (context) -> Void in if self!.type == .Draken { self!.maskView.alpha = self!.backgroundOpacity } self!.contentView.frame = self!.backgroundView.frame }, completion: nil) } }
mit
edwin123chen/NSData-GZIP
Sources/NSData+GZIP.swift
2
4432
// // NSData+GZIP.swift // // Version 1.1.0 /* The MIT License (MIT) © 2014-2015 1024jp <wolfrosch.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 private let CHUNK_SIZE : Int = 2 ^ 14 private let STREAM_SIZE : Int32 = Int32(sizeof(z_stream)) public extension NSData { /// Return gzip-compressed data object or nil. public func gzippedData() -> NSData? { if self.length == 0 { return NSData() } var stream = self.createZStream() var status : Int32 status = deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, STREAM_SIZE) if status != Z_OK { if let errorMessage = String.fromCString(stream.msg) { println(String(format: "Compression failed: %@", errorMessage)) } return nil } var data = NSMutableData(length: CHUNK_SIZE)! while stream.avail_out == 0 { if Int(stream.total_out) >= data.length { data.length += CHUNK_SIZE } stream.next_out = UnsafeMutablePointer<Bytef>(data.mutableBytes).advancedBy(Int(stream.total_out)) stream.avail_out = uInt(data.length) - uInt(stream.total_out) deflate(&stream, Z_FINISH) } deflateEnd(&stream) data.length = Int(stream.total_out) return data } /// Return gzip-decompressed data object or nil. public func gunzippedData() -> NSData? { if self.length == 0 { return NSData() } var stream = self.createZStream() var status : Int32 status = inflateInit2_(&stream, 47, ZLIB_VERSION, STREAM_SIZE) if status != Z_OK { if let errorMessage = String.fromCString(stream.msg) { println(String(format: "Decompression failed: %@", errorMessage)) } return nil } var data = NSMutableData(length: self.length * 2)! do { if Int(stream.total_out) >= data.length { data.length += self.length / 2; } stream.next_out = UnsafeMutablePointer<Bytef>(data.mutableBytes).advancedBy(Int(stream.total_out)) stream.avail_out = uInt(data.length) - uInt(stream.total_out) status = inflate(&stream, Z_SYNC_FLUSH) } while status == Z_OK if inflateEnd(&stream) != Z_OK || status != Z_STREAM_END { if let errorMessage = String.fromCString(stream.msg) { println(String(format: "Decompression failed: %@", errorMessage)) } return nil } data.length = Int(stream.total_out) return data } private func createZStream() -> z_stream { return z_stream( next_in: UnsafeMutablePointer<Bytef>(self.bytes), avail_in: uint(self.length), total_in: 0, next_out: nil, avail_out: 0, total_out: 0, msg: nil, state: nil, zalloc: nil, zfree: nil, opaque: nil, data_type: 0, adler: 0, reserved: 0 ) } }
mit