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
morganabel/cordova-plugin-audio-playlist
src/ios/JukeboxItem.swift
1
14669
// // JukeboxItem.swift // // Copyright (c) 2015 Teodor Patraş // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import AVFoundation import MediaPlayer protocol JukeboxItemDelegate : class { func jukeboxItemDidLoadPlayerItem(_ item: JukeboxItem) func jukeboxItemReadyToPlay(_ item: JukeboxItem) func jukeboxItemDidUpdate(_ item: JukeboxItem) func jukeboxItemDidFail(_ item: JukeboxItem) } open class JukeboxItem: NSObject { // MARK:- Properties - fileprivate var didLoad = false var delegate: JukeboxItemDelegate? open var identifier: String open var localId: String? open var localTitle: String? open let URL: Foundation.URL open let remoteUrl: Foundation.URL fileprivate(set) open var playerItem: AVPlayerItem? fileprivate (set) open var currentTime: Double? fileprivate(set) open lazy var meta = Meta() /// Builder to supply custom metadata for item. public var customMetaBuilder: MetaBuilder? { didSet { self.configureMetadata() } } fileprivate var timer: Timer? fileprivate let observedValue = "timedMetadata" // MARK:- Initializer - /** Create an instance with an URL and local title - parameter URL: local or remote URL of the audio file - parameter localTitle: an optional title for the file - returns: JukeboxItem instance */ public required init(URL : Foundation.URL, remoteUrl: Foundation.URL, localTitle : String? = nil, id: String? = nil) { self.URL = URL self.remoteUrl = remoteUrl self.identifier = UUID().uuidString self.localId = id self.localTitle = localTitle super.init() configureMetadata() } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if change?[NSKeyValueChangeKey(rawValue:"name")] is NSNull { delegate?.jukeboxItemDidFail(self) return } if keyPath == observedValue { if let item = playerItem , item === object as? AVPlayerItem { guard let metadata = item.timedMetadata else { return } for item in metadata { if self.customMetaBuilder?.hasMetaItem(item) != true { // custom meta takes precedence meta.process(metaItem: item) } } } scheduleNotification() } if keyPath == #keyPath(AVPlayerItem.status) { let status: AVPlayerItemStatus // Get the status change from the change dictionary if let statusNumber = change?[.newKey] as? NSNumber { status = AVPlayerItemStatus(rawValue: statusNumber.intValue)! } else { status = .unknown } // Switch over the status switch status { case .readyToPlay: // Player item is ready to play. self.delegate?.jukeboxItemReadyToPlay(self) break case .failed: break // Player item failed. See error. case .unknown: break // Player item is not yet ready. } } if keyPath == #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp) { // Preloaded enough that it should play smoothly. // If going to play at this point, check not curently .paused status } if keyPath == #keyPath(AVPlayerItem.isPlaybackBufferEmpty) { // Playback likely to stall or end. } } deinit { removeObservers() } // MARK: - Internal methods - func loadPlayerItem() { if let item = playerItem { refreshPlayerItem(withAsset: item.asset) delegate?.jukeboxItemDidLoadPlayerItem(self) return } else if didLoad { return } else { didLoad = true } loadAsync { (asset) -> () in if self.validateAsset(asset) { self.refreshPlayerItem(withAsset: asset) self.delegate?.jukeboxItemDidLoadPlayerItem(self) } else { self.didLoad = false } } } func refreshPlayerItem(withAsset asset: AVAsset) { // Removed any existing observers. removeObservers() // Create player item with asset. playerItem = AVPlayerItem(asset: asset) // Add observers for metadata and item status, respectively. playerItem?.addObserver(self, forKeyPath: observedValue, options: NSKeyValueObservingOptions.new, context: nil) playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: nil) playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp), options: NSKeyValueObservingOptions.new, context: nil) playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty), options: NSKeyValueObservingOptions.new, context: nil) NotificationCenter.default.addObserver(self, selector: #selector(playerItemFailedToPlay(_:)), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil) // Update metadata. update() } func update() { if let item = playerItem { meta.duration = item.asset.duration.seconds currentTime = item.currentTime().seconds } } open override var description: String { return "<JukeboxItem:\ntitle: \(meta.title)\nalbum: \(meta.album)\nartist:\(meta.artist)\nduration : \(meta.duration),\ncurrentTime : \(currentTime)\nURL: \(URL)>" } // MARK:- Private methods - fileprivate func validateAsset(_ asset : AVURLAsset) -> Bool { var e: NSError? asset.statusOfValue(forKey: "duration", error: &e) if let error = e { var message = "\n\n***** Jukebox fatal error*****\n\n" if error.code == -1022 { message += "It looks like you're using Xcode 7 and due to an App Transport Security issue (absence of SSL-based HTTP) the asset cannot be loaded from the specified URL: \"\(URL)\".\nTo fix this issue, append the following to your .plist file:\n\n<key>NSAppTransportSecurity</key>\n<dict>\n\t<key>NSAllowsArbitraryLoads</key>\n\t<true/>\n</dict>\n\n" fatalError(message) } if error.code == NSNotFound { message += "Item not found at the specified URL: \"\(URL)\"" fatalError(message) } if error.code == NSURLErrorResourceUnavailable { message += "Item not found at the specified URL: \"\(URL)\"" fatalError(message) } // Notify of failure. self.delegate?.jukeboxItemDidFail(self) return false } return true } @objc fileprivate func playerItemFailedToPlay(_ notification : Notification) { let error = notification.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error } fileprivate func scheduleNotification() { timer?.invalidate() timer = nil timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(JukeboxItem.notifyDelegate), userInfo: nil, repeats: false) } func notifyDelegate() { timer?.invalidate() timer = nil self.delegate?.jukeboxItemDidUpdate(self) } fileprivate func loadAsync(_ completion: @escaping (_ asset: AVURLAsset) -> ()) { DispatchQueue.global(qos: .background).async { let asset = AVURLAsset(url: self.URL, options: nil) asset.loadValuesAsynchronously(forKeys: ["duration"], completionHandler: { () -> Void in DispatchQueue.main.async { completion(asset) } }) } } fileprivate func configureMetadata() { // process custom metadata first if let customMetaBuilder = self.customMetaBuilder { self.meta.processBuilder(customMetaBuilder) } DispatchQueue.global(qos: .background).async { let metadataArray = AVPlayerItem(url: self.URL).asset.commonMetadata for item in metadataArray { item.loadValuesAsynchronously(forKeys: [AVMetadataKeySpaceCommon], completionHandler: { () -> Void in self.meta.process(metaItem: item) DispatchQueue.main.async { self.scheduleNotification() } }) } } } fileprivate func removeObservers() { playerItem?.removeObserver(self, forKeyPath: observedValue) playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status)) playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp)) playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty)) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) } /// Item Metadata public class Meta: Any { /// The duration of the item internal(set) public var duration: Double? /// The title of the item. internal(set) public var title: String? /// The album name of the item. internal(set) public var album: String? /// The artist name of the item. internal(set) public var artist: String? /// Album artwork for the item. internal(set) public var artwork: UIImage? } /// Builder for custom Metadata public class MetaBuilder: Meta { public typealias MetaBuilderClosure = (MetaBuilder) -> () // MARK: Properties private var _title: String? public override var title: String? { get { return _title } set (newTitle) { _title = newTitle } } private var _album: String? public override var album: String? { get { return _album } set (newAlbum) { _album = newAlbum } } private var _artist: String? public override var artist: String? { get { return _artist } set (newArtist) { _artist = newArtist } } private var _artwork: UIImage? public override var artwork: UIImage? { get { return _artwork } set (newArtwork) { _artwork = newArtwork } } // MARK: Init public init(_ build: MetaBuilderClosure) { super.init() build(self) } } } private extension JukeboxItem.Meta { func process(metaItem item: AVMetadataItem) { switch item.commonKey { case "title"? : title = item.value as? String case "albumName"? : album = item.value as? String case "artist"? : artist = item.value as? String case "artwork"? : processArtwork(fromMetadataItem : item) default : break } } func processBuilder(_ metaBuilder: JukeboxItem.MetaBuilder) { if let builderTitle = metaBuilder.title { title = builderTitle } if let builderAlbum = metaBuilder.album { album = builderAlbum } if let builderArtist = metaBuilder.artist { artist = builderArtist } if let builderArtwork = metaBuilder.artwork { artwork = builderArtwork } } func processArtwork(fromMetadataItem item: AVMetadataItem) { guard let value = item.value else { return } let copiedValue: AnyObject = value.copy(with: nil) as AnyObject if let dict = copiedValue as? [AnyHashable: Any] { //AVMetadataKeySpaceID3 if let imageData = dict["data"] as? Data { artwork = UIImage(data: imageData) } } else if let data = copiedValue as? Data{ //AVMetadataKeySpaceiTunes artwork = UIImage(data: data) } } } fileprivate extension JukeboxItem.MetaBuilder { /// Whether the metadata builder has a specific AVMetadataItem value /// /// - Parameter metadataItem: The item to check for. /// - Returns: Whether the metadata exists. fileprivate func hasMetaItem(_ metadataItem: AVMetadataItem) -> Bool { switch metadataItem.commonKey { case "title"? : return self.title != nil case "albumName"? : return self.album != nil case "artist"? : return self.artist != nil case "artwork"? : return self.artwork != nil default : return false } } } private extension CMTime { var seconds: Double? { let time = CMTimeGetSeconds(self) guard time.isNaN == false else { return nil } return time } }
mit
ingresse/ios-sdk
IngresseSDK/Helpers/DateHelper.swift
1
1881
// // DateHelper.swift // IngresseSDK // // Created by Rubens Gondek on 1/20/17. // Copyright © 2016 Gondek. All rights reserved. // import Foundation enum DateFormat: String { case timestamp = "yyyy-MM-dd'T'HH:mm:ssZ" case gmtTimestamp = "yyyy-MM-dd'T'HH:mm:ss'Z'" case dateHourSpace = "dd/MM/yyyy HH:mm" case dateHourAt = "dd/MM/yyyy 'às' HH:mm" } extension Date { /// Transform into string based on format /// /// - Parameter format: String format of desired output (default is "dd/MM/yyyy HH:mm") /// - Returns: Date converted to string func toString(format: DateFormat = .dateHourSpace) -> String { let formatter = DateFormatter() formatter.dateFormat = format.rawValue formatter.timeZone = TimeZone(abbreviation: "GMT") formatter.locale = Locale(identifier: "en_US_POSIX") return formatter.string(from: self) } /// Get week day string with 3 characters func weekDay() -> String { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let comp = (calendar as NSCalendar).components(.weekday, from: self) guard let day = comp.weekday, day > 0 && day <= 7 else { return "---" } return ["DOM", "SEG", "TER", "QUA", "QUI", "SEX", "SAB"][day-1] } } extension String { /// Convert string to Date /// /// - Parameter format: Current string format (default is "yyyy-MM-dd'T'HH:mm:ssZ") /// - Returns: Date converted from string (Current date returned in case of error) func toDate(format: DateFormat = .timestamp) -> Date { let formatter = DateFormatter() formatter.dateFormat = format.rawValue let posix = Locale(identifier: "en_US_POSIX") formatter.locale = posix return formatter.date(from: self) ?? Date() } }
mit
hejunbinlan/GRDB.swift
GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift
2
13973
import XCTest import GRDB // MinimalRowID is the most tiny class with a Single row primary key which // supports read and write operations of Record. class MinimalSingle: Record { var UUID: String! override class func databaseTableName() -> String? { return "minimalSingles" } override var storedDatabaseDictionary: [String: DatabaseValueConvertible?] { return ["UUID": UUID] } override func updateFromRow(row: Row) { if let dbv = row["UUID"] { UUID = dbv.value() } super.updateFromRow(row) // Subclasses are required to call super. } static func setupInDatabase(db: Database) throws { try db.execute( "CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)") } } class MinimalPrimaryKeySingleTests: GRDBTestCase { override func setUp() { super.setUp() var migrator = DatabaseMigrator() migrator.registerMigration("createMinimalSingle", MinimalSingle.setupInDatabase) assertNoError { try migrator.migrate(dbQueue) } } // MARK: - Insert func testInsertWithNilPrimaryKeyThrowsDatabaseError() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() XCTAssertTrue(record.UUID == nil) do { try record.insert(db) XCTFail("Expected DatabaseError") } catch is DatabaseError { // Expected DatabaseError } } } } func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! for (key, value) in record.storedDatabaseDictionary { if let dbv = row[key] { XCTAssertEqual(dbv, value?.databaseValue ?? .Null) } else { XCTFail("Missing column \(key) in fetched row") } } } } } func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) do { try record.insert(db) XCTFail("Expected DatabaseError") } catch is DatabaseError { // Expected DatabaseError } } } } func testInsertAfterDeleteInsertsARow() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) try record.delete(db) try record.insert(db) let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! for (key, value) in record.storedDatabaseDictionary { if let dbv = row[key] { XCTAssertEqual(dbv, value?.databaseValue ?? .Null) } else { XCTFail("Missing column \(key) in fetched row") } } } } } // MARK: - Update func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" do { try record.update(db) XCTFail("Expected RecordError.RecordNotFound") } catch RecordError.RecordNotFound { // Expected RecordError.RecordNotFound } } } } func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) try record.update(db) let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! for (key, value) in record.storedDatabaseDictionary { if let dbv = row[key] { XCTAssertEqual(dbv, value?.databaseValue ?? .Null) } else { XCTFail("Missing column \(key) in fetched row") } } } } } func testUpdateAfterDeleteThrowsRecordNotFound() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) try record.delete(db) do { try record.update(db) XCTFail("Expected RecordError.RecordNotFound") } catch RecordError.RecordNotFound { // Expected RecordError.RecordNotFound } } } } // MARK: - Save func testSaveWithNilPrimaryKeyThrowsDatabaseError() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() XCTAssertTrue(record.UUID == nil) do { try record.save(db) XCTFail("Expected DatabaseError") } catch is DatabaseError { // Expected DatabaseError } } } } func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.save(db) let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! for (key, value) in record.storedDatabaseDictionary { if let dbv = row[key] { XCTAssertEqual(dbv, value?.databaseValue ?? .Null) } else { XCTFail("Missing column \(key) in fetched row") } } } } } func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) try record.save(db) let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! for (key, value) in record.storedDatabaseDictionary { if let dbv = row[key] { XCTAssertEqual(dbv, value?.databaseValue ?? .Null) } else { XCTFail("Missing column \(key) in fetched row") } } } } } func testSaveAfterDeleteInsertsARow() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) try record.delete(db) try record.save(db) let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! for (key, value) in record.storedDatabaseDictionary { if let dbv = row[key] { XCTAssertEqual(dbv, value?.databaseValue ?? .Null) } else { XCTFail("Missing column \(key) in fetched row") } } } } } // MARK: - Delete func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" let deletionResult = try record.delete(db) XCTAssertEqual(deletionResult, Record.DeletionResult.NoRowDeleted) } } } func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) let deletionResult = try record.delete(db) XCTAssertEqual(deletionResult, Record.DeletionResult.RowDeleted) let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID]) XCTAssertTrue(row == nil) } } } func testDeleteAfterDeleteDoesNothing() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) var deletionResult = try record.delete(db) XCTAssertEqual(deletionResult, Record.DeletionResult.RowDeleted) deletionResult = try record.delete(db) XCTAssertEqual(deletionResult, Record.DeletionResult.NoRowDeleted) } } } // MARK: - Reload func testReloadWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" do { try record.reload(db) XCTFail("Expected RecordError.RecordNotFound") } catch RecordError.RecordNotFound { // Expected RecordError.RecordNotFound } } } } func testReloadWithNotNilPrimaryKeyThatMatchesARowFetchesThatRow() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) try record.reload(db) let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])! for (key, value) in record.storedDatabaseDictionary { if let dbv = row[key] { XCTAssertEqual(dbv, value?.databaseValue ?? .Null) } else { XCTFail("Missing column \(key) in fetched row") } } } } } func testReloadAfterDeleteThrowsRecordNotFound() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) try record.delete(db) do { try record.reload(db) XCTFail("Expected RecordError.RecordNotFound") } catch RecordError.RecordNotFound { // Expected RecordError.RecordNotFound } } } } // MARK: - Select func testSelectWithPrimaryKey() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) let fetchedRecord = MinimalSingle.fetchOne(db, primaryKey: record.UUID)! XCTAssertTrue(fetchedRecord.UUID == record.UUID) } } } func testSelectWithKey() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) let fetchedRecord = MinimalSingle.fetchOne(db, key: ["UUID": record.UUID])! XCTAssertTrue(fetchedRecord.UUID == record.UUID) } } } // MARK: - Exists func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() { dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" XCTAssertFalse(record.exists(db)) } } func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) XCTAssertTrue(record.exists(db)) } } } func testExistsAfterDeleteReturnsTrue() { assertNoError { try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) try record.delete(db) XCTAssertFalse(record.exists(db)) } } } }
mit
overtake/TelegramSwift
packages/TGUIKit/Sources/TokenizedView.swift
1
18328
// // TokenizedView.swift // TGUIKit // // Created by keepcoder on 07/08/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit public struct SearchToken : Equatable { public let name:String public let uniqueId:Int64 public init(name:String, uniqueId: Int64) { self.name = name self.uniqueId = uniqueId } } public func ==(lhs:SearchToken, rhs: SearchToken) -> Bool { return lhs.name == rhs.name && lhs.uniqueId == rhs.uniqueId } private class TokenView : Control { fileprivate let token:SearchToken private var isFailed: Bool = false private let dismiss: ImageButton = ImageButton() private let nameView: TextView = TextView() fileprivate var immediatlyPaste: Bool = true override var isSelected: Bool { didSet { updateLocalizationAndTheme(theme: presentation) } } private let customTheme: ()->TokenizedView.Theme init(_ token: SearchToken, maxSize: NSSize, onDismiss:@escaping()->Void, onSelect: @escaping()->Void, customTheme:@escaping()->TokenizedView.Theme) { self.token = token self.customTheme = customTheme super.init() self.layer?.cornerRadius = 6 let layout = TextViewLayout(.initialize(string: token.name, color: customTheme().underSelectColor, font: .normal(.title)), maximumNumberOfLines: 1) layout.measure(width: maxSize.width - 30) self.nameView.update(layout) nameView.userInteractionEnabled = false nameView.isSelectable = false setFrameSize(NSMakeSize(layout.layoutSize.width + 30, maxSize.height)) dismiss.autohighlight = false updateLocalizationAndTheme(theme: presentation) needsLayout = true addSubview(nameView) addSubview(dismiss) dismiss.set(handler: { _ in onDismiss() }, for: .Click) set(handler: { _ in onSelect() }, for: .Click) } fileprivate func setFailed(_ isFailed: Bool, animated: Bool) { self.isFailed = isFailed self.updateLocalizationAndTheme(theme: presentation) if isFailed { self.shake() } } fileprivate var isPerfectSized: Bool { return nameView.textLayout?.isPerfectSized ?? false } override func change(size: NSSize, animated: Bool = true, _ save: Bool = true, removeOnCompletion: Bool = false, duration: Double = 0.2, timingFunction: CAMediaTimingFunctionName = CAMediaTimingFunctionName.easeOut, completion: ((Bool) -> Void)? = nil) { nameView.textLayout?.measure(width: size.width - 30) let size = NSMakeSize(min(((nameView.textLayout?.layoutSize.width ?? 0) + 30), size.width), size.height) super.change(size: size, animated: animated, save, duration: duration, timingFunction: timingFunction) let point = focus(dismiss.frame.size) dismiss.change(pos: NSMakePoint(frame.width - 5 - dismiss.frame.width, point.minY), animated: animated) nameView.update(nameView.textLayout) } override func layout() { super.layout() nameView.centerY(x: 5) nameView.setFrameOrigin(5, nameView.frame.minY - 1) dismiss.centerY(x: frame.width - 5 - dismiss.frame.width) } var _backgroundColor: NSColor { var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0 var redSelected = customTheme().redColor redSelected.getRed(&r, green: &g, blue: &b, alpha: &a) redSelected = NSColor(red: min(r + 0.1, 1.0), green: min(g + 0.1, 1.0), blue: min(b + 0.1, 1.0), alpha: a) return isSelected ? (isFailed ? redSelected : customTheme().accentSelectColor) : (isFailed ? customTheme().redColor : customTheme().accentColor) } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) dismiss.set(image: #imageLiteral(resourceName: "Icon_SearchClear").precomposed(customTheme().underSelectColor.withAlphaComponent(0.7)), for: .Normal) dismiss.set(image: #imageLiteral(resourceName: "Icon_SearchClear").precomposed(customTheme().underSelectColor), for: .Highlight) _ = dismiss.sizeToFit() nameView.backgroundColor = .clear self.background = _backgroundColor } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required public init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } } public protocol TokenizedProtocol : class { func tokenizedViewDidChangedHeight(_ view: TokenizedView, height: CGFloat, animated: Bool) } public class TokenizedView: ScrollView, AppearanceViewProtocol, NSTextViewDelegate { public struct Theme { let background: NSColor let grayBackground: NSColor let textColor: NSColor let grayTextColor: NSColor let underSelectColor: NSColor let accentColor: NSColor let accentSelectColor: NSColor let redColor: NSColor public init(background: NSColor = presentation.colors.background, grayBackground: NSColor = presentation.colors.grayBackground, textColor: NSColor = presentation.colors.text, grayTextColor: NSColor = presentation.colors.grayText, underSelectColor: NSColor = presentation.colors.underSelectedColor, accentColor: NSColor = presentation.colors.accent, accentSelectColor: NSColor = presentation.colors.accentSelect, redColor: NSColor = presentation.colors.redUI) { self.background = background self.textColor = textColor self.grayBackground = grayBackground self.grayTextColor = grayTextColor self.underSelectColor = underSelectColor self.accentColor = accentColor self.accentSelectColor = accentSelectColor self.redColor = redColor } } private var tokens:[SearchToken] = [] private var failedTokens:[Int64] = [] private let container: View = View() private let input:SearchTextField = SearchTextField() private(set) public var state: SearchFieldState = .None { didSet { stateValue.set(state) } } public let stateValue: ValuePromise<SearchFieldState> = ValuePromise(.None, ignoreRepeated: true) private var selectedIndex: Int? = nil { didSet { for view in container.subviews { if let view = view as? TokenView { view.isSelected = selectedIndex != nil && view.token == tokens[selectedIndex!] } } } } private let _tokensUpdater:Promise<[SearchToken]> = Promise([]) public var tokensUpdater:Signal<[SearchToken], NoError> { return _tokensUpdater.get() } private let _textUpdater:ValuePromise<String> = ValuePromise("", ignoreRepeated: true) public var textUpdater:Signal<String, NoError> { return _textUpdater.get() } public weak var delegate: TokenizedProtocol? = nil private let placeholder: TextView = TextView() public func addTokens(tokens: [SearchToken], animated: Bool) -> Void { self.tokens.append(contentsOf: tokens) for token in tokens { let view = TokenView(token, maxSize: NSMakeSize(80, 22), onDismiss: { [weak self] in self?.removeTokens(uniqueIds: [token.uniqueId], animated: true) }, onSelect: { [weak self] in self?.selectedIndex = self?.tokens.firstIndex(of: token) }, customTheme: self.customTheme) container.addSubview(view) } _tokensUpdater.set(.single(self.tokens)) input.string = "" textDidChange(Notification(name: NSText.didChangeNotification)) (contentView as? TGClipView)?.scroll(to: NSMakePoint(0, max(0, container.frame.height - frame.height)), animated: animated) } public func removeTokens(uniqueIds: [Int64], animated: Bool) { for uniqueId in uniqueIds { var index:Int? = nil for i in 0 ..< tokens.count { if tokens[i].uniqueId == uniqueId { index = i break } } if let index = index { tokens.remove(at: index) for view in container.subviews { if let view = view as? TokenView { if view.token.uniqueId == uniqueId { view.change(opacity: 0, animated: animated, completion: { [weak view] completed in if completed { view?.removeFromSuperview() } }) } } } } } layoutContainer(animated: animated) _tokensUpdater.set(.single(tokens)) } private func layoutContainer(animated: Bool) { CATransaction.begin() let mainw = frame.width let between = NSMakePoint(5, 4) var point: NSPoint = between var extraLine: Bool = false let count = container.subviews.count for i in 0 ..< count { let subview = container.subviews[i] let next = container.subviews[min(i + 1, count - 1)] if let token = subview as? TokenView, token.layer?.opacity != 0 { token.change(pos: point, animated: token.immediatlyPaste ? false : animated) if animated, token.immediatlyPaste { token.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } //token.change(size: NSMakeSize(100, token.frame.height), animated: animated) token.immediatlyPaste = false point.x += subview.frame.width + between.x let dif = mainw - (point.x + (i == count - 1 ? mainw/3 : next.frame.width) + between.x) if dif < between.x { // if !token.isPerfectSized { // token.change(size: NSMakeSize(frame.width - startPointX - between.x, token.frame.height), animated: animated) // } point.x = between.x point.y += token.frame.height + between.y } } if subview == container.subviews.last { if mainw - point.x > mainw/3 { extraLine = true } } } input.frame = NSMakeRect(point.x, point.y + 3, mainw - point.x - between.x, 16) placeholder.change(pos: NSMakePoint(point.x + 6, point.y + 3), animated: animated) placeholder.change(opacity: tokens.isEmpty ? 1.0 : 0.0, animated: animated) let contentHeight = max(point.y + between.y + (extraLine ? 22 : 0), 30) container.change(size: NSMakeSize(container.frame.width, contentHeight), animated: animated) let height = min(contentHeight, 108) if height != frame.height { _change(size: NSMakeSize(mainw, height), animated: animated) delegate?.tokenizedViewDidChangedHeight(self, height: height, animated: animated) } CATransaction.commit() } public func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { let range = input.selectedRange() if commandSelector == #selector(insertNewline(_:)) { return true } if range.location == 0 { if commandSelector == #selector(moveLeft(_:)) { if let index = selectedIndex { selectedIndex = max(index - 1, 0) } else { selectedIndex = tokens.count - 1 } return true } else if commandSelector == #selector(moveRight(_:)) { if let index = selectedIndex { if index + 1 == tokens.count { selectedIndex = nil input.setSelectedRange(NSMakeRange(input.string.length, 0)) } else { selectedIndex = index + 1 } return true } } if commandSelector == #selector(deleteBackward(_:)) { if let selectedIndex = selectedIndex { removeTokens(uniqueIds: [tokens[selectedIndex].uniqueId], animated: true) if selectedIndex != tokens.count { self.selectedIndex = min(selectedIndex, tokens.count - 1) } else { self.selectedIndex = nil input.setSelectedRange(NSMakeRange(input.string.length, 0)) } return true } else { if !tokens.isEmpty { self.selectedIndex = tokens.count - 1 return true } } } } return false } open func textDidChange(_ notification: Notification) { let pHidden = !input.string.isEmpty if placeholder.isHidden != pHidden { placeholder.isHidden = pHidden } if self.window?.firstResponder == self.input { self.state = .Focus } _textUpdater.set(input.string) selectedIndex = nil } public func textDidEndEditing(_ notification: Notification) { self.didResignResponder() } public func textDidBeginEditing(_ notification: Notification) { //self.didBecomeResponder() } public override var needsLayout: Bool { set { super.needsLayout = false } get { return super.needsLayout } } public override func layout() { super.layout() //layoutContainer(animated: false) } private let localizationFunc: (String)->String private let placeholderKey: String private let customTheme: ()->TokenizedView.Theme required public init(frame frameRect: NSRect, localizationFunc: @escaping(String)->String, placeholderKey:String, customTheme: @escaping()->TokenizedView.Theme = { TokenizedView.Theme() }) { self.localizationFunc = localizationFunc self.placeholderKey = placeholderKey self.customTheme = customTheme super.init(frame: frameRect) hasVerticalScroller = true container.frame = bounds container.autoresizingMask = [.width] contentView.documentView = container input.focusRingType = .none input.backgroundColor = NSColor.clear input.delegate = self input.isRichText = false input.textContainer?.widthTracksTextView = true input.textContainer?.heightTracksTextView = false input.isHorizontallyResizable = false input.isVerticallyResizable = false placeholder.set(handler: { [weak self] _ in self?.window?.makeFirstResponder(self?.responder) }, for: .Click) input.font = .normal(.text) container.addSubview(input) container.addSubview(placeholder) container.layer?.cornerRadius = 10 wantsLayer = true self.layer?.cornerRadius = 10 self.layer?.backgroundColor = presentation.colors.grayBackground.cgColor updateLocalizationAndTheme(theme: presentation) } public func markAsFailed(_ ids:[Int64], animated: Bool) { self.failedTokens = ids self.updateFailed(animated) } public func addTooltip(for id: Int64, text: String) { for token in self.container.subviews { if let token = token as? TokenView, token.token.uniqueId == id { tooltip(for: token, text: text) break } } } public func removeAllFailed(animated: Bool) { self.failedTokens = [] self.updateFailed(animated) } private func updateFailed(_ animated: Bool) { for token in self.container.subviews { if let token = token as? TokenView { token.setFailed(failedTokens.contains(token.token.uniqueId), animated: animated) } } } open func didResignResponder() { state = .None } open func didBecomeResponder() { state = .Focus } public var query: String { return input.string } override public func becomeFirstResponder() -> Bool { window?.makeFirstResponder(input) return true } public var responder: NSResponder? { return input } public func updateLocalizationAndTheme(theme: PresentationTheme) { background = customTheme().background contentView.background = customTheme().background self.container.backgroundColor = customTheme().grayBackground input.textColor = customTheme().textColor input.insertionPointColor = customTheme().textColor let placeholderLayout = TextViewLayout(.initialize(string: localizedString(placeholderKey), color: customTheme().grayTextColor, font: .normal(.title)), maximumNumberOfLines: 1) placeholderLayout.measure(width: .greatestFiniteMagnitude) placeholder.update(placeholderLayout) placeholder.backgroundColor = customTheme().grayBackground placeholder.isSelectable = false layoutContainer(animated: false) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/What's New/Data store/AnnouncementsDataSource.swift
1
1770
protocol AnnouncementsDataSource: UITableViewDataSource { func registerCells(for tableView: UITableView) var dataDidChange: (() -> Void)? { get set } } class FeatureAnnouncementsDataSource: NSObject, AnnouncementsDataSource { private let store: AnnouncementsStore private let cellTypes: [String: UITableViewCell.Type] private var features: [WordPressKit.Feature] { store.announcements.reduce(into: [WordPressKit.Feature](), { $0.append(contentsOf: $1.features) }) } var dataDidChange: (() -> Void)? init(store: AnnouncementsStore, cellTypes: [String: UITableViewCell.Type]) { self.store = store self.cellTypes = cellTypes super.init() } func registerCells(for tableView: UITableView) { cellTypes.forEach { tableView.register($0.value, forCellReuseIdentifier: $0.key) } } func numberOfSections(in: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return features.count + 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard indexPath.row <= features.count - 1 else { let cell = tableView.dequeueReusableCell(withIdentifier: "findOutMoreCell", for: indexPath) as? FindOutMoreCell ?? FindOutMoreCell() cell.configure(with: URL(string: store.announcements.first?.detailsUrl ?? "")) return cell } let cell = tableView.dequeueReusableCell(withIdentifier: "announcementCell", for: indexPath) as? AnnouncementCell ?? AnnouncementCell() cell.configure(feature: features[indexPath.row]) return cell } }
gpl-2.0
mziyut/TodoApp
TodoAppTests/TodoAppTests.swift
1
898
// // TodoAppTests.swift // TodoAppTests // // Created by Yuta Mizui on 9/30/14. // Copyright (c) 2014 Yuta Mizui. All rights reserved. // import UIKit import XCTest class TodoAppTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
heyogrady/SpaceEvaders
SpaceEvaders/Scoreboard.swift
2
1736
import SpriteKit import GameKit class Scoreboard { var viewController: GameViewController? let scoreboard = SKLabelNode(text: "Score: 0") var score: Int = 0 var isHighScore = false init(x: CGFloat, y: CGFloat) { scoreboard.setScale(2.5) scoreboard.fontName = "timeburner" scoreboard.position = CGPoint(x: x, y: y) scoreboard.horizontalAlignmentMode = .Left scoreboard.zPosition = 10 } func highScore() { if score > NSUserDefaults.standardUserDefaults().integerForKey("highscore") { NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore") NSUserDefaults.standardUserDefaults().synchronize() isHighScore = true GCHelper.sharedInstance.reportLeaderboardIdentifier("leaderBoardID", score: score) } } func addTo(parentNode: GameScene) -> Scoreboard { parentNode.addChild(scoreboard) return self } func addScore(score: Int) { self.score += score scoreboard.text = "Score: \(self.score)" highScore() } func getScore() -> Int { return score } func isHighscore() -> Bool { return isHighScore } func getHighscoreLabel(size: CGSize) -> SKLabelNode { let highscore = SKLabelNode(text: "High Score!") highscore.position = CGPointMake(size.width / 2, size.height / 2 + 50) highscore.fontColor = UIColor.redColor() highscore.fontSize = 80 highscore.fontName = "timeburner" highscore.runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.fadeInWithDuration(0.3), SKAction.fadeOutWithDuration(0.3)]))) return highscore } }
mit
interstateone/Climate
Climate/View Controllers/DataViewController.swift
1
4875
// // ViewController.swift // Climate // // Created by Brandon Evans on 2014-07-18. // Copyright (c) 2014 Brandon Evans. All rights reserved. // import UIKit class DataViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var dataTableView: UITableView! @IBOutlet var lastUpdatedButton: UIButton! private var feed: Feed? private let feedFormatter = FeedFormatter() private let lastUpdatedFormatter = TTTTimeIntervalFormatter() private var updateLabelTimer: NSTimer? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let groupUserDefaults = NSUserDefaults(suiteName: "group.brandonevans.Climate") { if let feedID = groupUserDefaults.valueForKey(SettingsFeedIDKey) as? NSString { feed = Feed(feedID: feedID, handler: { [weak self] in if let viewController = self { viewController.updateUI() viewController.updateLastUpdatedLabel() viewController.updateStreams() } }) } } NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidBecomeActiveNotification, object: nil, queue: NSOperationQueue.currentQueue(), usingBlock: { [weak self] (notification) -> Void in self?.feed?.subscribe() return }) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) updateLabelTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateLastUpdatedLabel", userInfo: nil, repeats: true); updateLabelTimer!.tolerance = 0.5 if let feed = feed { feed.subscribe() feed.fetchIfNotSubscribed() } } override func viewDidDisappear(animated: Bool) { updateLabelTimer?.invalidate() updateLabelTimer = nil } // MARK: UITableViewDataSource func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("DataCell", forIndexPath: indexPath) as DataCell if let feed = feed { let stream = feed.streams[indexPath.row] as XivelyDatastreamModel cell.nameLabel.text = feedFormatter.humanizeStreamName(stream.info["id"] as NSString) let unit = stream.info["unit"] as NSDictionary let symbol = unit["symbol"] as NSString let valueString = (stream.info["current_value"] as NSString) ?? "0" let value = valueString.floatValue cell.valueLabel.attributedText = formatValueColorized(value, symbol: symbol) } return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let streamCount = feed?.streams.count ?? 0 return streamCount } // MARK: Actions @IBAction func fetchFeed(sender: AnyObject?) { feed?.subscribe() feed?.fetchIfNotSubscribed() } // MARK: Private private func updateUI() { dataTableView.reloadData() } internal func updateLastUpdatedLabel() { if feed?.isSubscribed ?? false { lastUpdatedButton.setTitle("Auto-updating", forState: .Normal) } else if let date = NSUserDefaults.standardUserDefaults().valueForKey(DataLastUpdatedKey) as? NSDate { lastUpdatedButton.setTitle("Last updated \(lastUpdatedFormatter.stringForTimeIntervalFromDate(NSDate(), toDate: date))", forState: .Normal) } } private func updateStreams() { if let feed = feed { let streamKeys = map(feed.streams, { (stream) -> String in let s = stream as XivelyDatastreamModel return s.info["id"] as String }) if let groupDefaults = NSUserDefaults(suiteName: "group.brandonevans.Climate") { groupDefaults.setObject(streamKeys, forKey: "AvailableStreamNames") } } } private func formatValueColorized(value: Float, symbol: String) -> NSAttributedString { let formattedString = feedFormatter.formatValue(value, symbol: symbol) let attributedString = NSMutableAttributedString(string: formattedString) attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: NSMakeRange(attributedString.length - countElements(symbol), countElements(symbol))) return attributedString } }
mit
irshad281/IAImagePicker
IAImagePickerExample/IAImagePickerViewController.swift
1
27198
// // IAImagePickerViewController.swift // IAImagePickerExample // // Created by preeti rani on 26/04/17. // Copyright © 2017 Innotical. All rights reserved. // import UIKit import Photos import AVFoundation let keyWindow = UIApplication.shared.keyWindow let screen_width = UIScreen.main.bounds.width let screen_height = UIScreen.main.bounds.height @objc protocol IAImagePickerDelegate1{ @objc optional func didFinishPickingMediaInfo(mediaInfo:[String:Any]? , pickedImage:UIImage?) @objc optional func didCancelIAPicker() } enum MediaType{ case camera case library } class PhotoCell: UICollectionViewCell { let photoImageView:UIImageView = { let imgView = UIImageView() imgView.contentMode = .scaleAspectFill imgView.clipsToBounds = true imgView.translatesAutoresizingMaskIntoConstraints = false imgView.isUserInteractionEnabled = true return imgView }() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(photoImageView) self.backgroundColor = .clear self.photoImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true self.photoImageView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true self.photoImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true self.photoImageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class IAImagePickerViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource , UIImagePickerControllerDelegate , UINavigationControllerDelegate{ let name = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String var captureSession: AVCaptureSession?; var previewLayer : AVCaptureVideoPreviewLayer?; var captureDevice : AVCaptureDevice? var stillImageOutput:AVCaptureStillImageOutput? var photosArray = [PhotoModel]() var orignalframe:CGRect? var delegate:IAImagePickerDelegate1? var capturedImageView:UIImageView? var restrictionView:UIView! var activity:UIActivityIndicatorView = UIActivityIndicatorView() lazy var cameraView:UIView = { let view = UIView.init(frame:CGRect.init(x: 0, y: 0, width: screen_width, height: screen_height)) view.backgroundColor = .white return view }() lazy var photoCollectionView:UICollectionView = { let flowLayout = UICollectionViewFlowLayout.init() flowLayout.minimumLineSpacing = 5 flowLayout.itemSize = CGSize(width: 100, height: 100) flowLayout.scrollDirection = .horizontal let frame = CGRect.init(x: 0, y: screen_height - 200, width: screen_width, height: 100) let photoCollectionView = UICollectionView.init(frame: frame, collectionViewLayout: flowLayout) photoCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) photoCollectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "cellId") photoCollectionView.backgroundColor = .clear photoCollectionView.delegate = self photoCollectionView.dataSource = self return photoCollectionView }() lazy var crossButton:UIButton = { let crossButton = UIButton.init(frame:CGRect.init(x: 20, y: 20, width: 30, height: 30)) crossButton.tintColor = .clear crossButton.addTarget(self, action: #selector(self.handleCancel(_:)), for: .touchUpInside) crossButton.setImage(#imageLiteral(resourceName: "multiply"), for: .normal) return crossButton }() lazy var flashButton:UIButton = { let flashButton = UIButton.init(frame:CGRect.init(x: screen_width - 50, y: 20, width: 30, height: 30)) flashButton.setImage(#imageLiteral(resourceName: "flashON"), for: .normal) flashButton.setImage(#imageLiteral(resourceName: "flashOFF"), for: .selected) flashButton.tintColor = .clear flashButton.addTarget(self, action: #selector(self.handleFlash(_:)), for: .touchUpInside) return flashButton }() lazy var captureButton:UIButton = { let button = UIButton.init(frame: CGRect.init(x: 2, y: 2, width: 46, height: 46)) button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = .white button.layer.cornerRadius = 23 button.clipsToBounds = true button.addTarget(self, action: #selector(self.handleCapture(_:)), for: .touchUpInside) return button }() lazy var useImageButton:UIButton = { let button = UIButton.init(frame: CGRect.init(x: screen_width - 120, y: screen_height - 50, width: 100, height: 30)) button.setTitleColor(.white, for: .normal) button.titleLabel?.font = UIFont.init(name: "Helvetica Neue", size: 15) button.setTitle("USE PHOTO", for: .normal) button.layer.cornerRadius = 3 button.layer.borderWidth = 1.0 button.backgroundColor = .black button.layer.borderColor = UIColor.white.cgColor button.clipsToBounds = true button.addTarget(self, action: #selector(self.handleUseImage(_:)), for: .touchUpInside) return button }() lazy var retakeButton:UIButton = { let button = UIButton.init(frame: CGRect.init(x: 20, y: screen_height - 50, width: 80, height: 30)) button.setTitleColor(.white, for: .normal) button.backgroundColor = .black button.titleLabel?.font = UIFont.init(name: "Helvetica Neue", size: 15) button.setTitle("RETAKE", for: .normal) button.layer.cornerRadius = 3 button.layer.borderWidth = 1.0 button.layer.borderColor = UIColor.white.cgColor button.clipsToBounds = true button.addTarget(self, action: #selector(self.handleRetakePhoto(_:)), for: .touchUpInside) return button }() lazy var captureView:UIView = { let captureView = UIView.init(frame: CGRect.init(x: screen_width/2 - 25, y: screen_height - 70, width: 60, height: 60)) captureView.backgroundColor = .black captureView.layer.cornerRadius = 30 captureView.clipsToBounds = true captureView.layer.borderWidth = 5 captureView.layer.borderColor = UIColor.white.cgColor let button = UIButton.init(frame: CGRect.init(x: 7.5, y: 7.5, width: 45, height: 45)) button.backgroundColor = .white button.layer.cornerRadius = 22.5 button.clipsToBounds = true button.addTarget(self, action: #selector(self.handleCapture(_:)), for: .touchUpInside) captureView.addSubview(button) return captureView }() lazy var albumButton:UIButton={ let albumButton = UIButton.init(frame:CGRect.init(x: 15, y: screen_height - 55, width: 45, height: 30)) albumButton.setImage(#imageLiteral(resourceName: "picture"), for: .normal) albumButton.addTarget(self, action: #selector(self.hanldleOpenAlbum(_:)), for: .touchUpInside) return albumButton }() func openSetting(_ sender:UIButton) { print("Open Setting...") let name = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String print(name) UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) } override func viewDidLoad() { super.viewDidLoad() self.flushSessionData() self.view.backgroundColor = #colorLiteral(red: 0.9803921569, green: 0.9803921569, blue: 0.9803921569, alpha: 1) self.captureSession = AVCaptureSession(); self.previewLayer = AVCaptureVideoPreviewLayer(); self.captureSession?.sessionPreset = AVCaptureSessionPresetHigh self.stillImageOutput = AVCaptureStillImageOutput() self.stillImageOutput?.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG] self.photoCollectionView.reloadData() _ = self.checkAutherizationStatusForCameraAndPhotoLibrary() } func addAfterPermission() { accessPhotosFromLibrary() let devices = AVCaptureDevice.devices() // Loop through all the capture devices on this phone for device in devices! { // Make sure this particular device supports video if ((device as AnyObject).hasMediaType(AVMediaTypeVideo)) { // Finally check the position and confirm we've got the back camera if((device as AnyObject).position == AVCaptureDevicePosition.back) { self.captureDevice = device as? AVCaptureDevice if self.captureDevice != nil { self.beginSession() } } } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func setUpViews(){ DispatchQueue.main.async { self.cameraView.addSubview(self.crossButton) self.cameraView.addSubview(self.flashButton) self.cameraView.addSubview(self.albumButton) self.cameraView.addSubview(self.captureView) self.cameraView.addSubview(self.photoCollectionView) } } func checkAutherizationStatusForCameraAndPhotoLibrary()->Bool{ var permissionStatus:Bool! = false let libraryPermission = PHPhotoLibrary.authorizationStatus() let cameraPermission = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if libraryPermission == .notDetermined || cameraPermission == .notDetermined{ PHPhotoLibrary.requestAuthorization({ (handlerStatus) in if handlerStatus == .authorized{ if cameraPermission == .notDetermined{ self.checkPermissionForCamera() } permissionStatus = true }else{ self.checkPermissionForCamera() permissionStatus = false } }) }else{ if libraryPermission == .authorized && cameraPermission == .authorized{ DispatchQueue.main.async { self.photoCollectionView.reloadData() self.view.addSubview(self.cameraView) self.addAfterPermission() } }else{ self.showRestrictionView(mediaType: .library) } } return permissionStatus } func showRestrictionView(mediaType:MediaType){ if restrictionView != nil{ restrictionView.removeFromSuperview() restrictionView = nil } DispatchQueue.main.async { self.restrictionView = UIView.init(frame: UIScreen.main.bounds) self.restrictionView.backgroundColor = .white let imageView = UIImageView.init(frame: CGRect(x: screen_width/2 - 75, y: screen_height/2 - 145, width: 150, height: 150)) if mediaType == .camera{ imageView.image = #imageLiteral(resourceName: "camera3") }else{ imageView.image = #imageLiteral(resourceName: "album") } self.restrictionView.addSubview(imageView) let permissionDescriptionLable = UILabel.init(frame: CGRect.init(x: 10, y: screen_height/2 + 25, width: screen_width - 20, height: 60)) permissionDescriptionLable.numberOfLines = 0 permissionDescriptionLable.textColor = #colorLiteral(red: 0.1019607843, green: 0.3098039216, blue: 0.5098039216, alpha: 1) permissionDescriptionLable.textAlignment = .center permissionDescriptionLable.font = UIFont.init(name: "Helvetica Neue", size: 13) permissionDescriptionLable.text = "Allow \(self.name) access to your camera to take photos within app.Go to Setting and turn on Photo and Camera" self.restrictionView.addSubview(permissionDescriptionLable) let openSettingButton = UIButton.init(frame: CGRect.init(x: screen_width/2 - 60, y: screen_height/2 + 105, width: 120, height: 30)) openSettingButton.setTitle("Open Setting", for: .normal) openSettingButton.setTitleColor(#colorLiteral(red: 0.1019607843, green: 0.3098039216, blue: 0.5098039216, alpha: 1), for: .normal) openSettingButton.addTarget(self, action: #selector(self.openSetting(_:)), for: .touchUpInside) self.restrictionView.addSubview(openSettingButton) self.view.addSubview(self.restrictionView) self.view.bringSubview(toFront: self.restrictionView) } } func checkPermissionForCamera(){ AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (success) in if success{ if let window = keyWindow{ DispatchQueue.main.async { self.photoCollectionView.reloadData() window.addSubview(self.cameraView) self.addAfterPermission() } } }else{ DispatchQueue.main.async { self.showRestrictionView(mediaType: .library) } } }) } func configureDevice(flashMode:AVCaptureFlashMode) { if let device = captureDevice { do { try device.lockForConfiguration() if device.isFocusPointOfInterestSupported{ device.focusMode = .continuousAutoFocus device.flashMode = flashMode } device.unlockForConfiguration() } catch { print(error.localizedDescription) } } } func beginSession() { if (captureSession?.canAddOutput(stillImageOutput))! { captureSession?.addOutput(stillImageOutput) } configureDevice(flashMode: .auto) do { captureSession?.startRunning() captureSession?.addInput(try AVCaptureDeviceInput(device: captureDevice)) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer?.frame = cameraView.layer.frame self.cameraView.layer.addSublayer(self.previewLayer!) self.setUpViews() } catch{ print(error.localizedDescription) } } func handleFlash(_ sender:UIButton){ if sender.isSelected{ self.configureDevice(flashMode: .auto) }else{ self.configureDevice(flashMode: .off) } sender.isSelected = !sender.isSelected } func handleCancel(_ sender:UIButton){ print("Handling dismiss.....") UIView.animate(withDuration: 0.5, animations: { self.cameraView.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height) self.dismiss(animated: true, completion: nil) }) { (completed) in self.cameraView.removeFromSuperview() } } func handleUseImage(_ sender:UIButton){ print("Handling UseImage.....") if let capturedImage = self.zoomedImageView{ UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { self.cameraView.removeFromSuperview() capturedImage.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height) self.delegate?.didFinishPickingMediaInfo!(mediaInfo: nil, pickedImage: self.zoomedImageView?.image) self.dismiss(animated: true, completion: nil) self.retakeButton.removeFromSuperview() self.useImageButton.removeFromSuperview() }, completion: { (completed) in self.zoomedImageView?.removeFromSuperview() self.zoomedImageView = nil }) } if let capturedPhoto = self.capturedImageView{ UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { self.cameraView.removeFromSuperview() capturedPhoto.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height) self.delegate?.didFinishPickingMediaInfo!(mediaInfo: nil, pickedImage: capturedPhoto.image) self.dismiss(animated: true, completion: nil) self.retakeButton.removeFromSuperview() self.useImageButton.removeFromSuperview() }, completion: { (completed) in self.zoomedImageView?.removeFromSuperview() self.zoomedImageView = nil }) } } func handleRetakePhoto(_ sender:UIButton){ print("Handling Retake.....") if let capturedImage = self.capturedImageView{ UIView.animate(withDuration: 0.33, animations: { capturedImage.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height) self.retakeButton.removeFromSuperview() self.useImageButton.removeFromSuperview() }, completion: { (completed) in self.capturedImageView?.removeFromSuperview() self.capturedImageView = nil }) } if let capturedPhoto = self.zoomedImageView{ UIView.animate(withDuration: 0.33, animations: { capturedPhoto.frame = self.orignalframe! self.retakeButton.removeFromSuperview() self.useImageButton.removeFromSuperview() }, completion: { (completed) in self.orignalImageView?.isHidden = false self.zoomedImageView?.removeFromSuperview() self.zoomedImageView = nil }) } } func flushSessionData(){ captureSession = nil captureDevice = nil previewLayer?.removeFromSuperlayer() previewLayer = nil stillImageOutput = nil } func handleCapture(_ sender:UIButton){ print("Handling capture.....") UIView.animate(withDuration: 0.33, animations: { self.captureView.transform = CGAffineTransform(scaleX: 1.25, y: 1.25) }) { (completed) in self.captureView.transform = .identity if let videoConnection = self.stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) { self.stillImageOutput?.captureStillImageAsynchronously(from: videoConnection) { (imageDataSampleBuffer, error) -> Void in if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer){ let image = UIImage.init(data: imageData) self.capturedImageView = UIImageView.init(frame: UIScreen.main.bounds) self.capturedImageView?.image = image keyWindow?.addSubview(self.capturedImageView!) keyWindow?.addSubview(self.useImageButton) keyWindow?.addSubview(self.retakeButton) UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData)!, nil, nil, nil) } } } } } func hanldleOpenAlbum(_ sender:UIButton){ print("Handling OpenAlbum.....") let imagePickerController = UIImagePickerController.init() imagePickerController.sourceType = .photoLibrary imagePickerController.allowsEditing = true imagePickerController.delegate = self UIView.animate(withDuration: 0.50, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.3, options: .curveEaseOut, animations: { self.cameraView.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height) self.present(imagePickerController, animated: false, completion: nil) }, completion: { (completed) in self.cameraView.removeFromSuperview() }) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { var image:UIImage? if info["UIImagePickerControllerEditedImage"] != nil{ image = info["UIImagePickerControllerEditedImage"] as? UIImage }else if info["UIImagePickerControllerOriginalImage"] != nil{ image = info["UIImagePickerControllerOriginalImage"] as? UIImage } self.delegate?.didFinishPickingMediaInfo!(mediaInfo: info, pickedImage: image) picker.dismiss(animated: false, completion: nil) self.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: false, completion: nil) self.dismiss(animated: true, completion: nil) } func accessPhotosFromLibrary(){ let fetchOption = PHFetchOptions.init() fetchOption.fetchLimit = 100 fetchOption.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: false)] let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOption) assets.enumerateObjects(options: .concurrent) { (assest, id, bool) in self.photosArray.append(PhotoModel.getAssestsModel(assest: assest)) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photosArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PhotoCell cell.photoImageView.image = self.photosArray[indexPath.item].photoImage cell.photoImageView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(handleTap(tap:)))) return cell } var orignalImageView:UIImageView? var selectedAssest:PhotoModel? var zoomedImageView:UIImageView? func handleTap(tap:UITapGestureRecognizer){ if let indexPath = getIndexFromCollectionViewCell(tap.view!, collView: photoCollectionView){ print(indexPath.item) selectedAssest = photosArray[indexPath.item] orignalImageView = tap.view as? UIImageView orignalImageView?.isHidden = true orignalframe = orignalImageView?.convert((orignalImageView?.frame)!, to: nil) if zoomedImageView != nil{ zoomedImageView?.removeFromSuperview() zoomedImageView = nil } zoomedImageView = UIImageView.init(frame: orignalframe!) zoomedImageView?.contentMode = .scaleAspectFill zoomedImageView?.clipsToBounds = true zoomedImageView?.isUserInteractionEnabled = true zoomedImageView?.addGestureRecognizer(UIPanGestureRecognizer.init(target: self, action: #selector(handlePan(pan:)))) zoomedImageView?.image = getAssetThumbnail(asset: (selectedAssest?.assest!)!, size: PHImageManagerMaximumSize) keyWindow?.addSubview(zoomedImageView!) UIView.animate(withDuration: 0.5, animations: { self.zoomedImageView?.frame = self.view.frame }, completion: { (completed) in keyWindow?.addSubview(self.useImageButton) keyWindow?.addSubview(self.retakeButton) }) } } func handlePan(pan:UIPanGestureRecognizer){ if pan.state == .began || pan.state == .changed { let translation = pan.translation(in: self.view) let piont = CGPoint(x: pan.view!.center.x + translation.x, y: pan.view!.center.y + translation.y) print("POINT",piont) pan.view!.center = piont pan.setTranslation(CGPoint.zero, in: self.view) self.retakeButton.alpha = 0 self.useImageButton.alpha = 0 }else if pan.state == .ended{ if let yPosition = pan.view?.center.y{ print("Y Position ",yPosition) let maxDownpoint = self.view.frame.height - self.view.frame.height/4 print("MAX DOWN POINT",maxDownpoint) if yPosition >= maxDownpoint{ dismissZoomedImageView() }else{ UIView.animate(withDuration: 0.33, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.3, options: .curveLinear, animations: { self.zoomedImageView?.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height) self.retakeButton.alpha = 1 self.useImageButton.alpha = 1 }, completion: { (success) in }) } } } } func dismissZoomedImageView(){ UIView.animate(withDuration: 0.33, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options: .curveLinear, animations: { self.zoomedImageView?.frame = self.orignalframe! self.useImageButton.removeFromSuperview() self.retakeButton.removeFromSuperview() }, completion: { (success) in self.zoomedImageView?.removeFromSuperview() self.zoomedImageView = nil self.orignalImageView?.isHidden = false self.useImageButton.alpha = 1 self.retakeButton.alpha = 1 }) } } func getAssetThumbnail(asset: PHAsset , size:CGSize) -> UIImage { let manager = PHImageManager.default() let option = PHImageRequestOptions() var thumbnail = UIImage() option.isSynchronous = true option.resizeMode = .exact option.deliveryMode = .fastFormat manager.requestImage(for: asset, targetSize: size, contentMode: .default, options: option, resultHandler: {(result, info)->Void in thumbnail = result! }) return thumbnail } func getIndexFromCollectionViewCell(_ cellItem: UIView, collView: UICollectionView) -> IndexPath? { let pointInTable: CGPoint = cellItem.convert(cellItem.bounds.origin, to: collView) if let cellIndexPath = collView.indexPathForItem(at: pointInTable){ return cellIndexPath } return nil } class PhotoModel: NSObject { var photoImage:UIImage? var assest:PHAsset? static func getAssestsModel(assest:PHAsset)->PhotoModel{ let photoModel = PhotoModel.init() photoModel.assest = assest photoModel.photoImage = getAssetThumbnail(asset: assest, size: CGSize(width: 250, height: 250)) return photoModel } }
mit
cburrows/swift-protobuf
Sources/SwiftProtobuf/source_context.pb.swift
1
4782
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: google/protobuf/source_context.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _3: SwiftProtobuf.ProtobufAPIVersion_3 {} typealias Version = _3 } /// `SourceContext` represents information about the source of a /// protobuf element, like the file in which it is defined. public struct Google_Protobuf_SourceContext { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// The path-qualified name of the .proto file that contained the associated /// protobuf element. For example: `"google/protobuf/source_context.proto"`. public var fileName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } #if swift(>=5.5) && canImport(_Concurrency) extension Google_Protobuf_SourceContext: @unchecked Sendable {} #endif // swift(>=5.5) && canImport(_Concurrency) // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "google.protobuf" extension Google_Protobuf_SourceContext: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".SourceContext" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "file_name"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.fileName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.fileName.isEmpty { try visitor.visitSingularStringField(value: self.fileName, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Google_Protobuf_SourceContext, rhs: Google_Protobuf_SourceContext) -> Bool { if lhs.fileName != rhs.fileName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
apache-2.0
yilu1021/Swift--Super-Cool-App
Super Cool/AppDelegate.swift
1
2133
// // AppDelegate.swift // Super Cool // // Created by Yi Lu on 4/23/16. // Copyright © 2016 Yi Lu. 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
ZamzamInc/XcodeUnitTesting-Swift
SampleUnitTestingXCTests/SampleUnitTestingXCTests.swift
1
980
// // SampleUnitTestingXCTests.swift // SampleUnitTestingXCTests // // Created by Basem Emara on 1/21/16. // Copyright © 2016 Zamzam. All rights reserved. // import XCTest class SampleUnitTestingXCTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // 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.measureBlock { // Put the code you want to measure the time of here. } } }
mit
bengottlieb/stack-watcher
StackWatcher/Controllers/Question Details/QuestionDetailsViewController.swift
1
2102
// // QuestionDetailsViewController.swift // StackWatcher // // Created by Ben Gottlieb on 6/4/14. // Copyright (c) 2014 Stand Alone, Inc. All rights reserved. // import UIKit class QuestionDetailsViewController: UIViewController { deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } init() { super.init(nibName: nil, bundle: nil) self.navigationItem.rightBarButtonItem = self.reloadButton NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectQuestion:", name: StackInterface.DefaultInterface.questionSelectedNotificationName, object: nil) // Custom initialization } convenience init(question: PostedQuestion) { self.init() self.loadQuestion(question) } func reload() { self.webView.reload() } override func viewDidLoad() { super.viewDidLoad() if let pending = self.question { self.loadQuestion(pending) } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func didSelectQuestion(note: NSNotification) { self.loadQuestion(note.object as PostedQuestion) } var question: PostedQuestion? func loadQuestion(question: PostedQuestion) { self.question = question var link = question.link var url = NSURL(string: link) var request = NSURLRequest(URL: url) self.title = question.title self.webView?.loadRequest(request) } /* // #pragma 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. } */ var reloadButton: UIBarButtonItem { return UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "reload") } @IBOutlet var webView : UIWebView }
mit
RaylnJiang/Swift_Learning_Project
Second Chapter-控制流/Second Chapter-控制流/For-In 循环.playground/Contents.swift
1
999
//: Playground - noun: a place where people can play import Cocoa /* For-In循环 */ /* ------------------------------------------------------------------- 可以使用for-in循环来遍历一个集合中的所有元素。 可以遍历一个字典,来访问它的键值对。 ------------------------------------------------------------------ */ for index in 1...5 { // index 代表着闭区间内每一项的值 print("\(index) times 5 is \(index * 5)") } let baseValue = 2 let maxPower = 10 var sumValue = 1 for _ in 1...maxPower { // 如果不需要知道闭区间的每一项的值,则可用 _ 代替 sumValue *= baseValue } print("sumValue is \(sumValue)") var namesArray = ["张三", "李四", "王五", "赵六"] for name in namesArray { print("Hello \(name)!") } var animalDict = ["Dog": 4, "Cat": 4, "Snake": 0, "monkey": 2] for (animalName, legCount) in animalDict { print("\(animalName) has \(legCount) legs") }
apache-2.0
abertelrud/swift-package-manager
Tests/BasicsTests/DictionaryTest.swift
2
1575
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2022 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 // //===----------------------------------------------------------------------===// @testable import Basics import TSCBasic import XCTest final class DictionaryTests: XCTestCase { func testThrowingUniqueKeysWithValues() throws { do { let keysWithValues = [("key1", "value1"), ("key2", "value2")] let dictionary = try Dictionary(throwingUniqueKeysWithValues: keysWithValues) XCTAssertEqual(dictionary["key1"], "value1") XCTAssertEqual(dictionary["key2"], "value2") } do { let keysWithValues = [("key1", "value"), ("key2", "value")] let dictionary = try Dictionary(throwingUniqueKeysWithValues: keysWithValues) XCTAssertEqual(dictionary["key1"], "value") XCTAssertEqual(dictionary["key2"], "value") } do { let keysWithValues = [("key", "value1"), ("key", "value2")] XCTAssertThrowsError(try Dictionary(throwingUniqueKeysWithValues: keysWithValues)) { error in XCTAssertEqual(error as? StringError, StringError("duplicate key found: 'key'")) } } } }
apache-2.0
abertelrud/swift-package-manager
Tests/PackageCollectionsTests/PackageCollectionsModelTests.swift
2
7354
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2020-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SPMTestSupport import TSCBasic import XCTest @testable import PackageCollections @testable import PackageModel final class PackageCollectionsModelTests: XCTestCase { func testLatestVersions() { let targets = [PackageCollectionsModel.Target(name: "Foo", moduleName: "Foo")] let products = [PackageCollectionsModel.Product(name: "Foo", type: .library(.automatic), targets: targets)] let toolsVersion = ToolsVersion(string: "5.2")! let manifests = [toolsVersion: PackageCollectionsModel.Package.Version.Manifest( toolsVersion: toolsVersion, packageName: "FooBar", targets: targets, products: products, minimumPlatformVersions: nil )] let versions: [PackageCollectionsModel.Package.Version] = [ .init(version: .init(stringLiteral: "1.2.0"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), .init(version: .init(stringLiteral: "2.0.1"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), .init(version: .init(stringLiteral: "2.1.0-beta.3"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), .init(version: .init(stringLiteral: "2.1.0"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), .init(version: .init(stringLiteral: "3.0.0-beta.1"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), ] XCTAssertEqual("2.1.0", versions.latestRelease?.version.description) XCTAssertEqual("3.0.0-beta.1", versions.latestPrerelease?.version.description) } func testNoLatestReleaseVersion() { let targets = [PackageCollectionsModel.Target(name: "Foo", moduleName: "Foo")] let products = [PackageCollectionsModel.Product(name: "Foo", type: .library(.automatic), targets: targets)] let toolsVersion = ToolsVersion(string: "5.2")! let manifests = [toolsVersion: PackageCollectionsModel.Package.Version.Manifest( toolsVersion: toolsVersion, packageName: "FooBar", targets: targets, products: products, minimumPlatformVersions: nil )] let versions: [PackageCollectionsModel.Package.Version] = [ .init(version: .init(stringLiteral: "2.1.0-beta.3"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), .init(version: .init(stringLiteral: "3.0.0-beta.1"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), ] XCTAssertNil(versions.latestRelease) XCTAssertEqual("3.0.0-beta.1", versions.latestPrerelease?.version.description) } func testNoLatestPrereleaseVersion() { let targets = [PackageCollectionsModel.Target(name: "Foo", moduleName: "Foo")] let products = [PackageCollectionsModel.Product(name: "Foo", type: .library(.automatic), targets: targets)] let toolsVersion = ToolsVersion(string: "5.2")! let manifests = [toolsVersion: PackageCollectionsModel.Package.Version.Manifest( toolsVersion: toolsVersion, packageName: "FooBar", targets: targets, products: products, minimumPlatformVersions: nil )] let versions: [PackageCollectionsModel.Package.Version] = [ .init(version: .init(stringLiteral: "1.2.0"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), .init(version: .init(stringLiteral: "2.0.1"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), .init(version: .init(stringLiteral: "2.1.0"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil), ] XCTAssertEqual("2.1.0", versions.latestRelease?.version.description) XCTAssertNil(versions.latestPrerelease) } func testSourceValidation() throws { let httpsSource = PackageCollectionsModel.CollectionSource(type: .json, url: URL(string: "https://feed.mock.io")!) XCTAssertNil(httpsSource.validate(fileSystem: localFileSystem), "not expecting errors") let httpsSource2 = PackageCollectionsModel.CollectionSource(type: .json, url: URL(string: "HTTPS://feed.mock.io")!) XCTAssertNil(httpsSource2.validate(fileSystem: localFileSystem), "not expecting errors") let httpsSource3 = PackageCollectionsModel.CollectionSource(type: .json, url: URL(string: "HttpS://feed.mock.io")!) XCTAssertNil(httpsSource3.validate(fileSystem: localFileSystem), "not expecting errors") let httpSource = PackageCollectionsModel.CollectionSource(type: .json, url: URL(string: "http://feed.mock.io")!) XCTAssertEqual(httpSource.validate(fileSystem: localFileSystem)?.count, 1, "expecting errors") let otherProtocolSource = PackageCollectionsModel.CollectionSource(type: .json, url: URL(string: "ftp://feed.mock.io")!) XCTAssertEqual(otherProtocolSource.validate(fileSystem: localFileSystem)?.count, 1, "expecting errors") let brokenUrlSource = PackageCollectionsModel.CollectionSource(type: .json, url: URL(string: "blah")!) XCTAssertEqual(brokenUrlSource.validate(fileSystem: localFileSystem)?.count, 1, "expecting errors") } func testSourceValidation_localFile() throws { try fixture(name: "Collections", createGitRepo: false) { fixturePath in // File must exist in local FS let path = fixturePath.appending(components: "JSON", "good.json") let source = PackageCollectionsModel.CollectionSource(type: .json, url: path.asURL) XCTAssertNil(source.validate(fileSystem: localFileSystem)) } } func testSourceValidation_localFileDoesNotExist() throws { let source = PackageCollectionsModel.CollectionSource(type: .json, url: URL(fileURLWithPath: "/foo/bar")) let messages = source.validate(fileSystem: localFileSystem)! XCTAssertEqual(1, messages.count) guard case .error = messages[0].level else { return XCTFail("Expected .error") } XCTAssertNotNil(messages[0].message.range(of: "either a non-local path or the file does not exist", options: .caseInsensitive)) } }
apache-2.0
rdignard08/RGLockbox
RGLockbox-Tests/RGLockboxSpec.swift
1
11948
/* Copyright (c) 02/21/2016, Ryan Dignard All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation import XCTest import RGLockboxIOS let kKey1 = "aKey1" let kKey2 = "aKey2" let testKeys = [ kKey1, kKey2 ] class RGLockboxSpec : XCTestCase { override class func initialize() { rg_SecItemCopyMatch = replacementItemCopy rg_SecItemAdd = replacementAddItem rg_SecItemDelete = replacementDeleteItem rg_set_logging_severity(.trace) } override func setUp() { RGLockbox.bundleIdentifier = Bundle(for: type(of: self)).infoDictionary![kCFBundleIdentifierKey as String] as! String? for key in testKeys { RGLockbox().setData(nil, forKey: key) } let manager = RGLockbox(withNamespace: nil, accessibility: kSecAttrAccessibleAlways) for key in manager.allItems() { manager.setData(nil, forKey: key) } RGLockbox.valueCache.removeAll() } override func tearDown() { for key in testKeys { RGLockbox().setData(nil, forKey: key) } let manager = RGLockbox(withNamespace: nil, accessibility: kSecAttrAccessibleAlways) for key in manager.allItems() { manager .setData(nil, forKey: key) } RGLockbox.valueCache.removeAll() } // MARK: - Reading / Writing / Deleting func testReadNotExist() { let data = RGLockbox().dataForKey(kKey1) XCTAssert(data == nil) } func testReadNotExistDouble() { RGLockbox().dataForKey(kKey1) let data = RGLockbox().dataForKey(kKey1) XCTAssert(data == nil) } func testReadExist() { RGLockbox().setData(Data(), forKey: kKey1) let data = RGLockbox().dataForKey(kKey1) XCTAssert(data == Data()) } func testReadExistDouble() { RGLockbox().setData(Data(), forKey: kKey1) RGLockbox().dataForKey(kKey1) let data = RGLockbox().dataForKey(kKey1) XCTAssert(data == Data()) } func testReadNotSeen() { let fullKey = RGMultiKey(withFirst: "\(RGLockbox().namespace!).\(kKey2)") let data = "abcd".data(using: String.Encoding.utf8) RGLockbox().setData(data, forKey: kKey2) RGLockbox.valueCache[fullKey] = nil let readData = RGLockbox().dataForKey(kKey2) XCTAssert(readData == data) } func testReadNoNameSpace() { let rawLockbox = RGLockbox(withNamespace: nil) let data = "abes".data(using: String.Encoding.utf8)! rawLockbox.setData(data, forKey: "com.restgoatee.rglockbox.foobar") let readData = rawLockbox.dataForKey("com.restgoatee.rglockbox.foobar") XCTAssert(readData == data) } // MARK: - Updating func testUpdateValue() { let fullKey = RGMultiKey(withFirst: "\(RGLockbox().namespace!).\(kKey1)") let firstData = "abew".data(using: String.Encoding.utf8)! let secondData = "qwew".data(using: String.Encoding.utf8)! RGLockbox().setData(firstData, forKey: kKey1) RGLockbox().setData(secondData, forKey: kKey1) RGLockbox.valueCache[fullKey] = nil let readData = RGLockbox().dataForKey(kKey1) XCTAssert(readData == secondData) } // MARK: - allItems func testAllItemsNamespaced() { RGLockbox().setData(Data(), forKey: kKey1) RGLockbox().setData(Data(), forKey: kKey2) var keys = [ kKey1, kKey2 ] let items = RGLockbox().allItems() for key in items { XCTAssert(keys.contains(key)) keys.remove(at: keys.index(of: key)!) } XCTAssert(keys.count == 0) } func testAllItemsNoNamespace() { let manager = RGLockbox(withNamespace: nil, accessibility: kSecAttrAccessibleAlways) manager.setData(Data(), forKey: "\(RGLockbox.bundleIdentifier!).\(kKey1)") manager.setData(Data(), forKey: "\(RGLockbox.bundleIdentifier!).\(kKey2)") let keys = [ "\(RGLockbox.bundleIdentifier!).\(kKey1)", "\(RGLockbox.bundleIdentifier!).\(kKey2)" ] let items = manager.allItems() for key in keys { XCTAssert(items.contains(key)) } XCTAssert(items.count >= keys.count) } func testAllItemsWithAccount() { let manager = RGLockbox(withNamespace: nil, accessibility: kSecAttrAccessibleAlways, accountName: "com.restgoatee.rglockbox") RGLockbox().setData(Data(), forKey: "abcd") manager.setData(Data(), forKey: "\(RGLockbox.bundleIdentifier!).\(kKey1)") manager.setData(Data(), forKey: "\(RGLockbox.bundleIdentifier!).\(kKey2)") var keys = [ "\(RGLockbox.bundleIdentifier!).\(kKey1)", "\(RGLockbox.bundleIdentifier!).\(kKey2)" ] let items = manager.allItems() for item in items { XCTAssert(keys.contains(item)) keys.remove(at: keys.index(of: item)!) } XCTAssert(keys.count == 0) } // MARK: - isSynchronized func testReadWriteIsSynchronized() { let manager = RGLockbox(accessibility: kSecAttrAccessibleAlways, accountName: "com.restgoatee.rglockbox", synchronized: true) manager.setData(Data(), forKey: kKey2) RGLockbox.keychainQueue.sync {} RGLockbox.valueCache.removeAll() let value = manager.dataForKey(kKey2) XCTAssert(value == Data()) } func testAllItemsSynchronized() { let manager = RGLockbox(accessibility: kSecAttrAccessibleAlways, accountName: "com.restgoatee.rglockbox", synchronized: true) RGLockbox().setData(Data(), forKey: "abcd") manager.setData("abew".data(using: String.Encoding.utf8), forKey: kKey1) RGLockbox.keychainQueue.sync {} RGLockbox.valueCache.removeAll() RGLockbox().setData(Data(), forKey: kKey2) let items = manager.allItems() XCTAssert(items.first == kKey1) XCTAssert(items.count == 1) } func testMakeItemSynchronized() { let nonSyncManager = RGLockbox() let syncManager = RGLockbox(accessibility: kSecAttrAccessibleAlways, synchronized: true) nonSyncManager.setData("abew".data(using: String.Encoding.utf8), forKey: kKey1) var value = nonSyncManager.dataForKey(kKey1) XCTAssert(value == "abew".data(using: String.Encoding.utf8)) RGLockbox.keychainQueue.sync {} RGLockbox.valueCache.removeAll() syncManager.setData("abcd".data(using: String.Encoding.utf8), forKey: kKey1) RGLockbox.keychainQueue.sync {} RGLockbox.valueCache.removeAll() value = syncManager.dataForKey(kKey1) XCTAssert(value == "abcd".data(using: String.Encoding.utf8)) RGLockbox.keychainQueue.sync {} RGLockbox.valueCache.removeAll() value = nonSyncManager.dataForKey(kKey1) XCTAssert(value == "abcd".data(using: String.Encoding.utf8)) } func testMakeItemNotSynchronized() { let nonSyncManager = RGLockbox() let syncManager = RGLockbox(accessibility: kSecAttrAccessibleAlways, synchronized: true) syncManager.setData("qwas".data(using: String.Encoding.utf8), forKey: kKey2) RGLockbox.keychainQueue.sync {} RGLockbox.valueCache.removeAll() var value = nonSyncManager.dataForKey(kKey2) XCTAssert(value == "qwas".data(using: String.Encoding.utf8)) RGLockbox.keychainQueue.sync {} RGLockbox.valueCache.removeAll() nonSyncManager.setData("abcd".data(using: String.Encoding.utf8), forKey: kKey2) RGLockbox.keychainQueue.sync {} RGLockbox.valueCache.removeAll() value = nonSyncManager.dataForKey(kKey2) XCTAssert(value == "abcd".data(using: String.Encoding.utf8)) RGLockbox.keychainQueue.sync {} RGLockbox.valueCache.removeAll() value = syncManager.dataForKey(kKey2) XCTAssert(value == "abcd".data(using: String.Encoding.utf8)) } func testFlushResignActive() { RGLockbox().setData("abcd".data(using: String.Encoding.utf8), forKey: kKey1) RGLockbox().setData("qweq".data(using: String.Encoding.utf8), forKey: kKey1) NotificationCenter.default.post(name: RGApplicationWillResignActive, object: nil) let service = "\(RGLockbox.bundleIdentifier!).\(kKey1)" let query:[NSString:AnyObject] = [ kSecClass : kSecClassGenericPassword, kSecMatchLimit : kSecMatchLimitOne, kSecReturnData : true as NSNumber, kSecAttrService : service as NSString ]; var data:CFTypeRef? = nil; XCTAssert(rg_SecItemCopyMatch(query as NSDictionary, &data) == 0); let bridgedData = data as? NSData XCTAssert(bridgedData == "qweq".data(using: String.Encoding.utf8) as NSData?); } func testFlushBackground() { RGLockbox().setData("abcd".data(using: String.Encoding.utf8), forKey: kKey1) RGLockbox().setData("qweq".data(using: String.Encoding.utf8), forKey: kKey1) NotificationCenter.default.post(name: RGApplicationWillBackground, object: nil) let service = "\(RGLockbox.bundleIdentifier!).\(kKey1)" let query:[NSString:AnyObject] = [ kSecClass : kSecClassGenericPassword, kSecMatchLimit : kSecMatchLimitOne, kSecReturnData : true as NSNumber, kSecAttrService : service as NSString ]; var data:CFTypeRef? = nil; XCTAssert(rg_SecItemCopyMatch(query as NSDictionary, &data) == 0); let bridgedData = data as? NSData XCTAssert(bridgedData == "qweq".data(using: String.Encoding.utf8) as NSData?); } func testFlushTerminate() { RGLockbox().setData("abcd".data(using: String.Encoding.utf8), forKey: kKey1) RGLockbox().setData("qweq".data(using: String.Encoding.utf8), forKey: kKey1) NotificationCenter.default.post(name: RGApplicationWillTerminate, object: nil) let service = "\(RGLockbox.bundleIdentifier!).\(kKey1)" let query:[NSString:AnyObject] = [ kSecClass : kSecClassGenericPassword, kSecMatchLimit : kSecMatchLimitOne, kSecReturnData : true as NSNumber, kSecAttrService : service as NSString ]; var data:CFTypeRef? = nil; XCTAssert(rg_SecItemCopyMatch(query as NSDictionary, &data) == 0); let bridgedData = data as? NSData XCTAssert(bridgedData == "qweq".data(using: String.Encoding.utf8) as NSData?); } }
bsd-2-clause
mackoj/GOTiPad
GOTIpad/GameLogic/Player.swift
1
806
// // Player.swift // GOTIpad // // Created by jeffreymacko on 29/12/2015. // Copyright © 2015 jeffreymacko. All rights reserved. // import Foundation struct Player { let name : String let house : HouseHold var ironThronePosition : UInt = 0 var valerianSwordPosition : UInt = 0 var kingsCourtPosition : UInt = 0 var starsLimit : UInt = 0 var victoryTrackPosition : UInt = 0 var supplyPosition : UInt = 0 var hasLost : Bool = false var powerTokens : [PowerToken] = [] var lands : [Land] = [] var hand : [HouseHoldMemberCard] = [] var discardPile : [HouseHoldMemberCard] = [] init(playerName: String, houseHoldType : HouseHoldType) { self.name = playerName self.house = HouseHold(houseHold: houseHoldType) } }
mit
cc001/learnSwiftBySmallProjects
01-StopWatch/StopWatchTests/StopWatchTests.swift
1
969
// // StopWatchTests.swift // StopWatchTests // // Created by 陈闯 on 2016/12/14. // Copyright © 2016年 CC. All rights reserved. // import XCTest @testable import StopWatch class StopWatchTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // 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
sztoth/PodcastChapters
PodcastChapters/Utilities/Extensions/NSCollectionViewItem+PCH.swift
1
499
// // NSTableView.swift // PodcastChapters // // Created by Szabolcs Toth on 2016. 02. 19.. // Copyright © 2016. Szabolcs Toth. All rights reserved. // import Cocoa protocol Reusable: class { static var reuseIdentifier: String { get } static var nib: NSNib? { get } } extension Reusable { static var reuseIdentifier: String { return String(describing: Self.self) } static var nib: NSNib? { return nil } } extension NSCollectionViewItem: Reusable {}
mit
movier/learn-ios
learn-ios/Playing Audio/PlayingAudioViewController.swift
1
1943
// // PlayingAudioViewController.swift // learn-ios // // Created by Oliver on 16/1/18. // Copyright © 2016年 movier. All rights reserved. // import UIKit import AVFoundation class PlayingAudioViewController: UIViewController { var player : AVAudioPlayer! = nil 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. } // http://www.raywenderlich.com/69369/audio-tutorial-ios-playing-audio-programatically-2014-edition @IBAction func playButtonTapped(sender: UIButton) { let path = NSBundle.mainBundle().pathForResource("1940_s_Slow_Dance_Sting", ofType:"mp3") let fileURL = NSURL(fileURLWithPath: path!) do { try player = AVAudioPlayer(contentsOfURL: fileURL) } catch { print("Something went wrong!") } player.prepareToPlay() player.play() } @IBAction func systemSoundServicesButtonTapped(sender: AnyObject) { var soundID: SystemSoundID = 0 if let pewPewPath = NSBundle.mainBundle().pathForResource("1940_s_Slow_Dance_Sting", ofType:"mp3") { let pewPewURL = NSURL.fileURLWithPath(pewPewPath) AudioServicesCreateSystemSoundID(pewPewURL, &soundID) AudioServicesPlaySystemSound(1001) } else { print("Could not find sound file") } } /* // 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
MillmanY/MMPlayerView
MMPlayerView/Classes/Swift/MMPlayerLayer.swift
1
25154
// // MMPlayerLayer.swift // Pods // // Created by Millman YANG on 2017/8/22. // // import UIKit import AVFoundation // MARK: - Enum define public extension MMPlayerLayer { enum SubtitleType { case srt(info: String) } enum CoverFitType { case fitToPlayerView case fitToVideoRect } } public class MMPlayerLayer: AVPlayerLayer { /** Subtitle Setting ``` subtitleSetting.defaultFont = UIFont.systemFont(ofSize: 17) subtitleSetting.defaultTextColor = .white subtitleSetting.defaultLabelEdge = (20,10,10) subtitleSetting.subtitleType = .srt(info: "XXX") ``` */ public private(set) lazy var subtitleSetting: MMSubtitleSetting = { return MMSubtitleSetting(delegate: self) }() /** Set progress type on player center ``` mmplayerLayer.progressType = .custom(view: UIView & MMProgressProtocol) ``` */ public var progressType: MMProgress.ProgressType = .default { didSet { indicator.set(progress: progressType) } } /** Set progress type on player center ``` // Cover view fit to videoRect mmplayerLayer.coverFitType = .fitToVideoRect // Cover view fit to playerLayer frame mmplayerLayer.coverFitType = .fitToPlayerView ``` */ public var coverFitType: MMPlayerLayer.CoverFitType = .fitToVideoRect { didSet { thumbImageView.contentMode = (coverFitType == .fitToVideoRect) ? .scaleAspectFit : .scaleAspectFill self.updateCoverConstraint() } } /** Set cover view auto hide after n interval ``` // Cover view auto hide with n interval mmplayerLayer.autoHideCoverType = .MMPlayerLayer.CoverAutoHideType.autoHide(after: 3.0) // Cover view auto hide disable mmplayerLayer.autoHideCoverType = .disable ``` */ public var autoHideCoverType = CoverAutoHideType.autoHide(after: 3.0) { didSet { switch autoHideCoverType { case .disable: NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(MMPlayerLayer.showCover(isShow:)), object: nil) case .autoHide(let after): self.perform(#selector(MMPlayerLayer.showCover(isShow:)), with: nil, afterDelay: after) } } } /** Set to show image before video ready ``` // Set thumbImageView mmplayerLayer.thumbImageView.image = 'Background Image' ``` */ public lazy var thumbImageView: UIImageView = { let t = UIImageView() t.clipsToBounds = true return t }() /** MMPlayerLayer will show in playView ``` // Set thumbImageView mmplayerLayer.playView = cell.imageView ``` */ public var playView: UIView? { set { if self.playView != newValue { self._playView = newValue } } get { return _playView } } /** Loop video when end ``` mmplayerLayer.repeatWhenEnd = true ``` */ public var repeatWhenEnd: Bool = false /** Current cover view on mmplayerLayer ``` mmplayerLayer.coverView ``` */ public private(set) var coverView: (UIView & MMPlayerCoverViewProtocol)? /** Auto play when video ready */ public var autoPlay = true /** Current player status ``` case ready case unknown case failed(err: String) case playing case pause case end ``` */ public var currentPlayStatus: PlayStatus = .unknown { didSet { if currentPlayStatus == oldValue { return } if let block = self.playStatusBlock { block(currentPlayStatus) } coverView?.currentPlayer(status: currentPlayStatus) switch self.currentPlayStatus { case .ready: self.thumbImageView.isHidden = false self.coverView?.isHidden = false if self.autoPlay { self.player?.play() } case .failed(err: _): self.thumbImageView.isHidden = false self.coverView?.isHidden = false self.startLoading(isStart: false) case .unknown: self.thumbImageView.isHidden = false self.coverView?.isHidden = true self.startLoading(isStart: false) default: self.thumbImageView.isHidden = true self.coverView?.isHidden = false break } } } /** Set AVPlayerItem cache in memory or not ``` case none case memory(count: Int) ``` */ public var cacheType: PlayerCacheType = .none /** Current play url */ public var playUrl: URL? { get { return (self.player?.currentItem?.asset as? AVURLAsset)?.url } } public weak var mmDelegate: MMPlayerLayerProtocol? /** If true, player will fullscreen when roatate to landscape ``` mmplayerLayer.fullScreenWhenLandscape = true ``` */ public var fullScreenWhenLandscape = true /** Player current orientation ``` mmplayerLayer.orientation = .protrait mmplayerLayer.orientation = .landscapeLeft mmplayerLayer.orientation = .landscapeRight ``` */ public private(set) var orientation: PlayerOrientation = .protrait { didSet { self.landscapeWindow.update() if orientation == oldValue { return } self.layerOrientationBlock?(orientation) } } public var isShrink: Bool { return shrinkControl.isShrink } // MARK: - Private Parameter lazy var subtitleView = MMSubtitleView() lazy var shrinkControl = { return MMPlayerShrinkControl(mmPlayerLayer: self) }() private lazy var bgView: UIView = { let v = UIView() v.translatesAutoresizingMaskIntoConstraints = false v.addSubview(self.thumbImageView) v.addSubview(self.indicator) // self.indicator // .mmLayout // .setCenterX(anchor: v.centerXAnchor, type: .equal(constant: 0)) // .setCentoMerY(anchor: v.centerYAnchor, type: .equal(constant: 0)) self.indicator.mmLayout.layoutFitSuper() self.thumbImageView.mmLayout.layoutFitSuper() v.frame = .zero v.backgroundColor = UIColor.clear return v }() private lazy var tapGesture: UITapGestureRecognizer = { let g = UITapGestureRecognizer(target: self, action: #selector(MMPlayerLayer.touchAction(gesture:))) return g }() public private(set) lazy var landscapeWindow: MMLandscapeWindow = { let window = MMLandscapeWindow(playerLayer: self) return window }() weak private var _playView: UIView? { willSet { bgView.removeFromSuperview() self.removeFromSuperlayer() _playView?.removeGestureRecognizer(tapGesture) } didSet { guard let new = _playView else { return } new.layer.insertSublayer(self, at: 0) new.addSubview(self.bgView) self.bgView.mmLayout.layoutFitSuper() new.layoutIfNeeded() self.updateCoverConstraint() new.isUserInteractionEnabled = true new.addGestureRecognizer(tapGesture) } } private var asset: AVURLAsset? private var isInitLayer = false private var isCoverShow = false private var timeObserver: Any? private var isBackgroundPause = false private var cahce = MMPlayerCache() private var playStatusBlock: ((_ status: PlayStatus) ->Void)? private var layerOrientationBlock: ((_ status: PlayerOrientation) ->Void)? private var indicator = MMProgress() // MARK: - Init public override init(layer: Any) { isInitLayer = true super.init(layer: layer) (layer as? MMPlayerLayer)?.isInitLayer = false } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init() { super.init() self.setup() } deinit { if !isInitLayer { self.removeAllObserver() } } } // MARK: - Public function extension MMPlayerLayer { public func shrinkView(onVC: UIViewController, isHiddenVC: Bool, maxWidth: CGFloat = 150.0, completedToView: (()->UIView?)?) { shrinkControl.shrinkView(onVC: onVC, isHiddenVC: isHiddenVC, maxWidth: maxWidth, completedToView: completedToView) } /** Set player current Orientation ``` mmplayerLayer.setOrientation(.protrait) ``` */ public func setOrientation(_ status: PlayerOrientation) { self.orientation = status } /** If cover enable show on video, else hidden */ public func setCoverView(enable: Bool) { self.coverView?.isHidden = !enable self.tapGesture.isEnabled = enable } public func delayHideCover() { self.showCover(isShow: true) switch self.autoHideCoverType { case .autoHide(let after): NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(MMPlayerLayer.showCover(isShow:)), object: nil) self.perform(#selector(MMPlayerLayer.showCover(isShow:)), with: nil, afterDelay: after) default: break } } /** Set player cover view ** Cover view need implement 'MMPlayerCoverViewProtocol' ** ``` mmplayerLayer.replace(cover: XXX) ``` */ public func replace(cover: UIView & MMPlayerCoverViewProtocol) { if let c = self.coverView ,c.isMember(of: cover.classForCoder) { c.alpha = 1.0 return } cover.backgroundColor = UIColor.clear cover.layoutIfNeeded() coverView?.removeFromSuperview() coverView?.removeObserver?() coverView = cover coverView?.playLayer = self bgView.insertSubview(cover, belowSubview: indicator) cover.addObserver?() self.updateCoverConstraint() if let m = self.player?.isMuted { cover.player?(isMuted: m) } cover.currentPlayer(status: self.currentPlayStatus) } /** Get player play status */ public func getStatusBlock(value: ((_ status: PlayStatus) -> Void)?) { self.playStatusBlock = value } /** Get player orientation status */ public func getOrientationChange(status: ((_ status: PlayerOrientation) ->Void)?) { self.layerOrientationBlock = status } public func set(asset: AVURLAsset?, lodDiskIfExist: Bool = true) { if asset?.url == self.asset?.url { return } if let will = asset , self.cahce.getItem(key: will.url) == nil, let real = MMPlayerDownloader.shared.localFileFrom(url: will.url), lodDiskIfExist { switch real.type { case .hls: var statle = false if let data = try? Data(contentsOf: real.localURL), let convert = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &statle) { self.asset = AVURLAsset(url: convert) } else { self.asset = asset } case .mp4: self.asset = AVURLAsset(url: real.localURL) } return } self.asset = asset } /** Set player playUrl */ public func set(url: URL?, lodDiskIfExist: Bool = true) { guard let u = url else { self.set(asset: nil, lodDiskIfExist: lodDiskIfExist) return } self.set(asset: AVURLAsset(url: u), lodDiskIfExist: lodDiskIfExist) } /** Stop player and clear url */ public func invalidate() { self.initStatus() self.asset = nil } /** Start player to play video */ public func resume() { switch self.currentPlayStatus { case .playing , .pause: if (self.player?.currentItem?.asset as? AVURLAsset)?.url == self.asset?.url { return } default: break } self.initStatus() guard let current = self.asset else { return } self.startLoading(isStart: true) if let cacheItem = self.cahce.getItem(key: current.url) , cacheItem.status == .readyToPlay { self.player?.replaceCurrentItem(with: cacheItem) } else { current.loadValuesAsynchronously(forKeys: assetKeysRequiredToPlay) { [weak self] in DispatchQueue.main.async { let keys = assetKeysRequiredToPlay if let a = self?.asset { for key in keys { var error: NSError? let _ = a.statusOfValue(forKey: key, error: &error) if let e = error { self?.currentPlayStatus = .failed(err: e.localizedDescription) return } } let item = MMPlayerItem(asset: a, delegate: self) switch self?.cacheType { case .some(.memory(let count)): self?.cahce.cacheCount = count self?.cahce.appendCache(key: current.url, item: item) default: self?.cahce.removeAll() } self?.player?.replaceCurrentItem(with: item) } } } } } @objc func touchAction(gesture: UITapGestureRecognizer) { switch self.currentPlayStatus { case .unknown: return default: break } if let p = self.playView { let point = gesture.location(in: p) if self.videoRect.isEmpty || self.videoRect.contains(point) { self.showCover(isShow: !self.isCoverShow) } mmDelegate?.touchInVideoRect(contain: self.videoRect.contains(point)) } } @objc public func showCover(isShow: Bool) { self.isCoverShow = isShow if isShow { switch self.autoHideCoverType { case .autoHide(let after): NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(MMPlayerLayer.showCover(isShow:)), object: nil) self.perform(#selector(MMPlayerLayer.showCover(isShow:)), with: nil, afterDelay: after) default: break } } if let cover = self.coverView , cover.responds(to: #selector(cover.coverView(isShow:))) { cover.coverView!(isShow: isShow) return } UIView.animate(withDuration: 0.2, animations: { [weak self] in self?.coverView?.alpha = (isShow) ? 1.0 : 0.0 }) } } // MARK: - Private function extension MMPlayerLayer { private func setup() { self.player = AVPlayer() self.backgroundColor = UIColor.black.cgColor self.progressType = .default self.addPlayerObserver() bgView.addSubview(subtitleView) subtitleView.mmLayout.layoutFitSuper() let edge = subtitleSetting.defaultLabelEdge self.subtitleSetting.defaultLabelEdge = edge NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { [weak self] (_) in guard let self = self, self.fullScreenWhenLandscape else {return} switch UIDevice.current.orientation { case .landscapeLeft: self.orientation = .landscapeLeft case .landscapeRight: self.orientation = .landscapeRight case .portrait: self.orientation = .protrait default: break } } } private func updateCoverConstraint() { let vRect = self.coverFitType == .fitToVideoRect ? videoRect : bgView.bounds if !vRect.isEmpty { self.coverView?.isHidden = (self.tapGesture.isEnabled) ? false : true self.coverView?.frame = vRect } if bgView.bounds == self.frame { return } self.frame = bgView.bounds } private func startLoading(isStart: Bool) { if isStart { self.indicator.start() } else { self.indicator.stop() } } } // MARK: - Observer extension MMPlayerLayer { private func addPlayerObserver() { NotificationCenter.default.removeObserver(self) if timeObserver == nil { timeObserver = self.player?.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 100), queue: DispatchQueue.main, using: { [weak self] (time) in if time.isIndefinite { return } if let sub = self?.subtitleSetting.subtitleObj { switch sub { case let srt as SubtitleConverter<SRT>: let sec = time.seconds srt.search(duration: sec, completed: { [weak self] (info) in guard let self = self else {return} self.subtitleView.update(infos: info, setting: self.subtitleSetting) }, queue: DispatchQueue.main) default: break } } if let cover = self?.coverView, cover.responds(to: #selector(cover.timerObserver(time:))) { cover.timerObserver!(time: time) } }) } NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil, using: { [weak self] (nitification) in switch self?.currentPlayStatus ?? .unknown { case .pause: self?.isBackgroundPause = true default: self?.isBackgroundPause = false } self?.player?.pause() }) NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil, using: { [weak self] (nitification) in if self?.isBackgroundPause == false { self?.player?.play() } self?.isBackgroundPause = false }) NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: nil, using: { [weak self] (_) in if self?.repeatWhenEnd == true { self?.player?.seek(to: CMTime.zero) self?.player?.play() } else if let s = self?.currentPlayStatus { switch s { case .playing, .pause: if let u = self?.asset?.url { self?.cahce.removeCache(key: u) } self?.currentPlayStatus = .end default: break } } }) self.addObserver(self, forKeyPath: "videoRect", options: [.new, .old], context: nil) bgView.addObserver(self, forKeyPath: "frame", options: [.new, .old], context: nil) bgView.addObserver(self, forKeyPath: "bounds", options: [.new, .old], context: nil) self.player?.addObserver(self, forKeyPath: "muted", options: [.new, .old], context: nil) self.player?.addObserver(self, forKeyPath: "rate", options: [.new, .old], context: nil) } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { switch keyPath { case "videoRect", "frame", "bounds": let new = change?[.newKey] as? CGRect ?? .zero let old = change?[.oldKey] as? CGRect ?? .zero if new != old { self.updateCoverConstraint() } case "muted": let new = change?[.newKey] as? Bool ?? false let old = change?[.oldKey] as? Bool ?? false if new != old { self.coverView?.player?(isMuted: new) } case "rate": let new = change?[.newKey] as? Float ?? 1.0 let status = self.currentPlayStatus switch status { case .playing, .pause, .ready: self.currentPlayStatus = (new == 0.0) ? .pause : .playing case .end: let total = self.player?.currentItem?.duration.seconds ?? 0.0 let current = self.player?.currentItem?.currentTime().seconds ?? 0.0 if current < total { self.currentPlayStatus = (new == 0.0) ? .pause : .playing } default: break } default: super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } private func removeAllObserver() { self.removeObserver(self, forKeyPath: "videoRect") bgView.removeObserver(self, forKeyPath: "frame") bgView.removeObserver(self, forKeyPath: "bounds") self.player?.removeObserver(self, forKeyPath: "muted") self.player?.removeObserver(self, forKeyPath: "rate") self.player?.replaceCurrentItem(with: nil) self.player?.pause() NotificationCenter.default.removeObserver(self) coverView?.removeObserver?() if let t = timeObserver { self.player?.removeTimeObserver(t) timeObserver = nil } } private func convertItemStatus() -> PlayStatus { return self.player?.currentItem?.convertStatus() ?? .unknown } private func initStatus() { self.currentPlayStatus = .unknown self.isBackgroundPause = false self.player?.replaceCurrentItem(with: nil) self.showCover(isShow: false) } } // MARK: - Download extension MMPlayerLayer { public func download(observer status: @escaping ((MMPlayerDownloader.DownloadStatus)->Void)) -> MMPlayerObservation? { guard let asset = self.asset else { status(.failed(err: "URL empty")) return nil } if asset.url.isFileURL { status(.failed(err: "Input fileURL are Invalid")) return nil } MMPlayerDownloader.shared.download(asset: asset) return self.observerDownload(status: status) } public func observerDownload(status: @escaping ((MMPlayerDownloader.DownloadStatus)->Void)) -> MMPlayerObservation? { guard let url = self.asset?.url else { status(.failed(err: "URL empty")) return nil } return MMPlayerDownloader.shared.observe(downloadURL: url, status: status) } } // MARK: - MMPlayerItem delegate extension MMPlayerLayer: MMPlayerItemProtocol { func status(change: AVPlayerItem.Status) { let s = self.convertItemStatus() switch s { case .failed(_) , .unknown: self.currentPlayStatus = s case .ready: switch self.currentPlayStatus { case .ready: if self.isBackgroundPause { return } self.currentPlayStatus = s case .failed(_) ,.unknown: self.currentPlayStatus = s default: break } default: break } } func isPlaybackKeepUp(isKeepUp: Bool) { if isKeepUp == true { self.startLoading(isStart: false) } } func isPlaybackEmpty(isEmpty: Bool) { if isEmpty { self.startLoading(isStart: true) } } } extension MMPlayerLayer: MMSubtitleSettingProtocol { public func setting(_ mmsubtitleSetting: MMSubtitleSetting, fontChange: UIFont) { } public func setting(_ mmsubtitleSetting: MMSubtitleSetting, textColorChange: UIColor) { } public func setting(_ mmsubtitleSetting: MMSubtitleSetting, labelEdgeChange: (bottom: CGFloat, left: CGFloat, right: CGFloat)) { } public func setting(_ mmsubtitleSetting: MMSubtitleSetting, typeChange: MMSubtitleSetting.SubtitleType?) { self.subtitleView.isHidden = typeChange == nil } }
mit
nathawes/swift
test/SourceKit/CodeComplete/complete_docbrief_1.swift
15
1885
protocol P { /// This is a doc comment of P.foo /// /// Do whatever. func foo() /// This is a doc comment of P.bar /// /// May have default information. func bar() } extension P { func bar() {} } struct S: P { func foo() {} } func test() { S(). } // All in main module. // RUN: %sourcekitd-test -req=complete -pos=22:7 %s -- %s -module-name DocBriefTest | %FileCheck %s -check-prefix=CHECK // CHECK: { // CHECK: key.results: [ // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.decl.function.method.instance, // CHECK-NEXT: key.name: "bar()", // CHECK-NEXT: key.sourcetext: "bar()", // CHECK-NEXT: key.description: "bar()", // CHECK-NEXT: key.typename: "Void", // CHECK-NEXT: key.doc.brief: "This is a doc comment of P.bar", // CHECK-NEXT: key.context: source.codecompletion.context.superclass, // CHECK-NEXT: key.typerelation: source.codecompletion.typerelation.unknown, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NEXT: key.associated_usrs: "s:12DocBriefTest1PPAAE3baryyF", // CHECK-NEXT: key.modulename: "DocBriefTest" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.decl.function.method.instance, // CHECK-NEXT: key.name: "foo()", // CHECK-NEXT: key.sourcetext: "foo()", // CHECK-NEXT: key.description: "foo()", // CHECK-NEXT: key.typename: "Void", // CHECK-NEXT: key.doc.brief: "This is a doc comment of P.foo", // CHECK-NEXT: key.context: source.codecompletion.context.thisclass, // CHECK-NEXT: key.typerelation: source.codecompletion.typerelation.unknown, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NEXT: key.associated_usrs: "s:12DocBriefTest1SV3fooyyF s:12DocBriefTest1PP3fooyyF", // CHECK-NEXT: key.modulename: "DocBriefTest" // CHECK-NEXT: }
apache-2.0
colemancda/SwiftSequence
SwiftSequenceTests/HopJumpTests.swift
1
1001
import XCTest @testable import SwiftSequence class HopJumpTests: XCTestCase { // MARK: Eager func testHop() { for randAr in (1..<10).map(Array<Int>.init) { let hop = Int.randLim(randAr.count - 1) + 1 let expectation = randAr .indices .filter { n in n % hop == 0 } .map { i in randAr[i] } let reality = AnySequence(randAr).hop(hop) let intReality = randAr.hop(hop) XCTAssertEqual(expectation)(reality) XCTAssertEqual(expectation)(intReality) } } // MARK: Lazy func testLazyHop() { for randAr in (1..<10).map(Array<Int>.init) { let hop = Int.randLim(randAr.count - 1) + 1 let expectation = randAr.hop(hop) let randReality = randAr.lazy.hop(hop) let reality = AnySequence(randAr).lazy.hop(hop) XCTAssertEqual(expectation)(reality) XCTAssertEqual(expectation)(randReality) } } }
mit
JeffJin/ios9_notification
twilio/Services/Models/ViewModel/SearchResultsViewModel.swift
2
732
// // SearchResultsViewModel.swift // ReactiveSwiftFlickrSearch // // Created by Colin Eberhardt on 15/07/2014. // Copyright (c) 2014 Colin Eberhardt. All rights reserved. // import Foundation // A ViewModel that exposes the results of a Flickr search @objc public class SearchResultsViewModel: NSObject { var searchResults: [SearchResultsItemViewModel] let title: String private let services: ViewModelServices init(services: ViewModelServices, searchResults: ScheduleSearchResults) { self.services = services self.title = searchResults.searchString self.searchResults = []//searchResults.appointments.map { SearchResultsItemViewModel(photo: $0, services: services ) } super.init() } }
apache-2.0
davieds/WWDC
WWDC/DataStore.swift
1
8451
// // DataStore.swift // WWDC // // Created by Guilherme Rambo on 18/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Foundation private let _internalServiceURL = "http://wwdc.guilhermerambo.me/index.json" private let _liveServiceURL = "http://wwdc.guilhermerambo.me/live.json" private let _liveNextServiceURL = "http://wwdc.guilhermerambo.me/next.json" private let _SharedStore = DataStore() private let _MemoryCacheSize = 500*1024*1024 private let _DiskCacheSize = 1024*1024*1024 class DataStore: NSObject { class var SharedStore: DataStore { return _SharedStore } private let sharedCache = NSURLCache(memoryCapacity: _MemoryCacheSize, diskCapacity: _DiskCacheSize, diskPath: nil) override init() { super.init() NSURLCache.setSharedURLCache(sharedCache) loadFavorites() } typealias fetchSessionsCompletionHandler = (Bool, [Session]) -> Void var appleSessionsURL: NSURL? = nil private var _cachedSessions: [Session]? = nil private(set) var cachedSessions: [Session]? { get { if _cachedSessions == nil { self.fetchSessions({ (_, sessions) -> Void in return sessions }) } return _cachedSessions } set { _cachedSessions = newValue } } let URLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let URLSession2 = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration()) func fetchSessions(completionHandler: fetchSessionsCompletionHandler) { if appleSessionsURL != nil { doFetchSessions(completionHandler) } else { let internalServiceURL = NSURL(string: _internalServiceURL) URLSession.dataTaskWithURL(internalServiceURL!, completionHandler: { [unowned self] data, response, error in if data == nil { completionHandler(false, []) return } let parsedJSON: JSON? = JSON(data: data!) if let json = parsedJSON, dictionary = json.dictionary { let appleURL = dictionary["url"]!.string! self.appleSessionsURL = NSURL(string: appleURL)! } else { completionHandler(false, []) return } self.doFetchSessions(completionHandler) }).resume() } } func fetchSessions(completionHandler: fetchSessionsCompletionHandler, disableCache: Bool) { if disableCache { if let url = appleSessionsURL { sranddev() appleSessionsURL = NSURL(string: "\(url.absoluteString)?\(rand())") } } fetchSessions(completionHandler) } func doFetchSessions(completionHandler: fetchSessionsCompletionHandler) { URLSession.dataTaskWithURL(appleSessionsURL!, completionHandler: { data, response, error in if data == nil { completionHandler(false, []) return } if let container = JSON(data: data!).dictionary { let jsonSessions = container["sessions"]!.array! var sessions: [Session] = [] for jsonSession:JSON in jsonSessions { var focuses:[String] = [] for focus:JSON in jsonSession["focus"].array! { focuses.append(focus.string!) } if jsonSession["title"].string != nil && jsonSession["id"].int != nil && jsonSession["year"].int != nil { let session = Session(date: jsonSession["date"].string, description: jsonSession["description"].string!, focus: focuses, id: jsonSession["id"].int!, slides: jsonSession["slides"].string, title: jsonSession["title"].string!, track: (jsonSession["track"].string != nil) ? jsonSession["track"].string! : "", url: (jsonSession["url"].string != nil) ? jsonSession["url"].string! : "", year: jsonSession["year"].int!, hd_url: jsonSession["download_hd"].string) sessions.append(session) } } sessions = sessions.sort { sessionA, sessionB in if(sessionA.year == sessionB.year) { return sessionA.id < sessionB.id } else { return sessionA.year > sessionB.year } } self.cachedSessions = sessions completionHandler(true, sessions) } else { completionHandler(false, []) } }).resume() } func downloadSessionSlides(session: Session, completionHandler: (Bool, NSData?) -> Void) { if session.slides == nil { completionHandler(false, nil) return } let task = URLSession.dataTaskWithURL(NSURL(string: session.slides!)!) { data, response, error in if data != nil { completionHandler(true, data) } else { completionHandler(false, nil) } } task.resume() } let defaults = NSUserDefaults.standardUserDefaults() func fetchSessionProgress(session: Session) -> Double { return defaults.doubleForKey(session.progressKey) } func putSessionProgress(session: Session, progress: Double) { defaults.setDouble(progress, forKey: session.progressKey) } func fetchSessionCurrentPosition(session: Session) -> Double { return defaults.doubleForKey(session.currentPositionKey) } func putSessionCurrentPosition(session: Session, position: Double) { defaults.setDouble(position, forKey: session.currentPositionKey) } private var favorites: [String] = [] private let favoritesKey = "Favorites" private func loadFavorites() { if let faves = defaults.arrayForKey(favoritesKey) as? [String] { favorites = faves } } private func storeFavorites() { defaults.setObject(favorites, forKey: favoritesKey) } func fetchSessionIsFavorite(session: Session) -> Bool { return favorites.contains(session.uniqueKey) } func putSessionIsFavorite(session: Session, favorite: Bool) { if favorite { favorites.append(session.uniqueKey) } else { favorites.remove(session.uniqueKey) } storeFavorites() } private var liveURL: NSURL { get { sranddev() // adds a random number as a parameter to completely prevent any caching return NSURL(string: "\(_liveServiceURL)?t=\(rand())&s=\(NSDate.timeIntervalSinceReferenceDate())")! } } private var liveNextURL: NSURL { get { sranddev() // adds a random number as a parameter to completely prevent any caching return NSURL(string: "\(_liveNextServiceURL)?t=\(rand())&s=\(NSDate.timeIntervalSinceReferenceDate())")! } } func checkForLiveEvent(completionHandler: (Bool, LiveEvent?) -> ()) { let task = URLSession2.dataTaskWithURL(liveURL) { data, response, error in if data == nil { completionHandler(false, nil) return } let jsonData = JSON(data: data!) let event = LiveEvent(jsonObject: jsonData) if event.isLiveRightNow { completionHandler(true, event) } else { completionHandler(false, nil) } } task.resume() } func fetchNextLiveEvent(completionHandler: (Bool, LiveEvent?) -> ()) { let task = URLSession2.dataTaskWithURL(liveNextURL) { data, response, error in if data == nil { completionHandler(false, nil) return } let jsonData = JSON(data: data!) let event = LiveEvent(jsonObject: jsonData) if event.title != "" { completionHandler(true, event) } else { completionHandler(false, nil) } } task.resume() } }
bsd-2-clause
QuaereVeritatem/TopHackIncStartup
TopHackIncStartUp/SettingsData.swift
1
388
// // SettingsData.swift // TopHackIncStartUp // // Created by Robert Martin on 10/4/16. // Copyright © 2016 Robert Martin. All rights reserved. // import Foundation class SettingsData { static let sharedInstance = SettingsData() var settingsChoices: [String] = ["Notification Manager", "About Me", "Help/FAQ's", "Report a Bug", "Privacy and Safety"] }
mit
IngmarStein/swift
stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift
3
3655
//===--- 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 http://swift.org/LICENSE.txt for license information // See http://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
brentsimmons/Frontier
BeforeTheRename/UserTalk/UserTalk/Node/CaseConditionNode.swift
1
1088
// // CaseConditionNode.swift // UserTalk // // Created by Brent Simmons on 5/7/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Foundation import FrontierData // case value // CaseNode // x // CaseConditionNode // thing() // BlockNode final class CaseConditionNode: CodeTreeNode { let operation = .caseItemOp let textPosition: TextPosition let conditionNode: CodeTreeNode let blockNode: BlockNode init(_ textPosition: TextPosition, _ conditionNode: CodeTreeNode, _ blockNode: BlockNode) { self.textPosition = textPosition self.conditionNode = conditionNode self.blockNode = blockNode } func evaluateCondition(_ stack: Stack) throws -> Value { do { var ignoredBreakOperation: CodeTreeOperation = .noOp return try condition.evaluate(stack, &breakOperation) } catch { throw error } } func evaluate(_ stack: Stack, _ breakOperation: inout CodeTreeOperation) throws -> Value { stack.push() defer { stack.pop() } do { try return blockNode.evaluate(stack, breakOperation) } catch { throw error } } }
gpl-2.0
motoom/ios-apps
Pour3/Pour/Sounds/SoundManager.swift
1
1625
import UIKit import AVFoundation class SoundManager { var playersInitialized = false var fillPlayer: AVAudioPlayer! // TODO: Map from soundname -> initialised AVAudioPlayer instances var pourPlayer: AVAudioPlayer! var drainPlayer: AVAudioPlayer! init() { // TODO: Initialize sounds in a loop. let fillUrl = Bundle.main.url(forResource: "Fillup.wav", withExtension: nil) do { try fillPlayer = AVAudioPlayer(contentsOf: fillUrl!) fillPlayer.prepareToPlay() } catch { print("Fillup.wav not playable") } // let pourUrl = Bundle.main.url(forResource: "Eau.wav", withExtension: nil) do { try pourPlayer = AVAudioPlayer(contentsOf: pourUrl!) pourPlayer.prepareToPlay() } catch { print("Eau.wav not playable") } // let drainUrl = Bundle.main.url(forResource: "Toilet.wav", withExtension: nil) do { try drainPlayer = AVAudioPlayer(contentsOf: drainUrl!) drainPlayer.prepareToPlay() } catch { print("Toilet.wav not playable") } } func sndFill() { fillPlayer.currentTime = 0 fillPlayer.play() } func sndPour() { pourPlayer.currentTime = 0 pourPlayer.play() } func sndDrain() { drainPlayer.currentTime = 0 drainPlayer.play() } func sndStop() { fillPlayer.stop() pourPlayer.stop() drainPlayer.stop() } }
mit
ranmocy/rCaltrain
ios/rCaltrain/Station.swift
1
1329
// // Station.swift // rCaltrain // // Created by Wanzhang Sheng on 10/25/14. // Copyright (c) 2014-2015 Ranmocy. All rights reserved. // import Foundation class Station { // Class variables/methods fileprivate struct StationStruct { static var names = NSMutableOrderedSet() static var idToStation = [Int: Station]() static var nameToStations = [String: [Station]]() } class func getNames() -> [String] { return (StationStruct.names.array as! [String]).sorted(by: <) } class func getStation(byId id: Int) -> Station? { return StationStruct.idToStation[id] } class func getStations(byName name: String) -> [Station]? { return StationStruct.nameToStations[name] } class func addStation(name: String, id: Int) { let station = Station(name: name, id: id) StationStruct.names.add(name) StationStruct.idToStation[id] = station if (StationStruct.nameToStations[name] != nil) { StationStruct.nameToStations[name]!.append(station) } else { StationStruct.nameToStations[name] = [station] } } // Instance variables/methods let name: String let id: Int fileprivate init(name: String, id: Int) { self.name = name self.id = id } }
mit
jjimeno/JJStaggeredGridCollectionView
Example/JJStaggeredGridCollectionView/AppDelegate.swift
1
2187
// // AppDelegate.swift // JJStaggeredGridCollectionView // // Created by jjimeno on 04/10/2017. // Copyright (c) 2017 jjimeno. 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 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
ehrenmurdick/timebox
TimeboxTests/TimeboxTests.swift
1
927
// // TimeboxTests.swift // TimeboxTests // // Created by Ehren Murdick on 4/11/16. // Copyright © 2016 Ehren Murdick. All rights reserved. // import XCTest @testable import Timebox class TimeboxTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testTimerCoding() { let timer = Timer(startTime: NSDate(), savedDuration: 100, name: "hoobajoob") let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(timer) let newTimer = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Timer XCTAssertEqual(timer.name, newTimer!.name) } }
mit
einsphy/test1
Swift字符串/Swift字符串UITests/Swift___UITests.swift
1
1247
// // Swift___UITests.swift // Swift字符串UITests // // Created by einsphy on 16/3/5. // Copyright © 2016年 einsphy. All rights reserved. // import XCTest class Swift___UITests: 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. } }
apache-2.0
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Menu View Controllers/MenuViewController/MenuView/MedalScene.swift
2
4392
// // MedalScene.swift // WikiRaces // // Created by Andrew Finke on 3/6/19. // Copyright © 2019 Andrew Finke. All rights reserved. // import SpriteKit final class MedalScene: SKScene { // MARK: Properties - private let goldNode: SKNode private let silverNode: SKNode private let bronzeNode: SKNode private let dnfNode: SKNode // MARK: - Initalization - override init(size: CGSize) { let physicsBody = SKPhysicsBody(circleOfRadius: 5) physicsBody.allowsRotation = true physicsBody.linearDamping = 1.75 physicsBody.angularDamping = 0.75 func texture(for text: String, width: CGFloat = 50) -> SKTexture { let size = CGSize(width: width, height: width) let emojiRect = CGRect(origin: .zero, size: size) let emojiRenderer = UIGraphicsImageRenderer(size: size) return SKTexture(image: emojiRenderer.image { context in UIColor.clear.setFill() context.fill(emojiRect) let text = text let attributes = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: width - 5) ] text.draw(in: emojiRect, withAttributes: attributes) }) } let goldNode = SKSpriteNode(texture: texture(for: "🥇")) goldNode.physicsBody = physicsBody self.goldNode = goldNode let silverNode = SKSpriteNode(texture: texture(for: "🥈")) silverNode.physicsBody = physicsBody self.silverNode = silverNode let bronzeNode = SKSpriteNode(texture: texture(for: "🥉")) bronzeNode.physicsBody = physicsBody self.bronzeNode = bronzeNode let dnfNode = SKSpriteNode(texture: texture(for: "❌", width: 20)) dnfNode.physicsBody = physicsBody self.dnfNode = dnfNode super.init(size: size) anchorPoint = CGPoint(x: 0, y: 0) backgroundColor = .clear physicsWorld.gravity = CGVector(dx: 0, dy: -7) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Update - override func update(_ currentTime: TimeInterval) { for node in children where node.position.y < -50 { node.removeFromParent() } DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.isPaused = self.children.isEmpty } } // MARK: - Other - func showMedals(gold: Int, silver: Int, bronze: Int, dnf: Int) { func createMedal(place: Int) { let node: SKNode if place == 1, let copy = goldNode.copy() as? SKNode { node = copy } else if place == 2, let copy = silverNode.copy() as? SKNode { node = copy } else if place == 3, let copy = bronzeNode.copy() as? SKNode { node = copy } else if place == 4, let copy = dnfNode.copy() as? SKNode { node = copy } else { return } let padding: CGFloat = 40 let maxX = size.width - padding node.position = CGPoint(x: CGFloat.random(in: padding..<maxX), y: size.height + 50) node.zRotation = CGFloat.random(in: (-CGFloat.pi / 4)..<(CGFloat.pi / 4)) addChild(node) var range: CGFloat = 0.5 let impulse = CGVector(dx: CGFloat.random(in: 0..<range) - range / 2, dy: CGFloat.random(in: 0..<range) - range / 2) node.physicsBody?.applyImpulse(impulse) range = 0.001 node.physicsBody?.applyTorque(CGFloat.random(in: 0..<range) - range / 2) } var places = [Int]() (0..<gold).forEach { _ in places.append(1) } (0..<silver).forEach {_ in places.append(2)} (0..<bronze).forEach { _ in places.append(3)} (0..<dnf).forEach { _ in places.append(4)} for (index, place) in places.shuffled().enumerated() { scene?.run(.sequence([ .wait(forDuration: Double(index) * 0.075), .run { createMedal(place: place) }])) } } }
mit
wdkk/CAIM
Metal/caimmetal04/CAIM/UIVIew+CAIM.swift
29
2140
// // UIView+CAIM.swift // CAIM Project // https://kengolab.net/CreApp/wiki/ // // Copyright (c) Watanabe-DENKI Inc. // https://wdkk.co.jp/ // // This software is released under the MIT License. // https://opensource.org/licenses/mit-license.php // import UIKit public extension UIView { var pixelX:CGFloat { get { return self.frame.origin.x * UIScreen.main.scale } set { self.frame.origin.x = newValue / UIScreen.main.scale } } var pixelY:CGFloat { get { return self.frame.origin.y * UIScreen.main.scale } set { self.frame.origin.y = newValue / UIScreen.main.scale } } var pixelWidth:CGFloat { get { return self.frame.size.width * UIScreen.main.scale } set { self.frame.size.width = newValue / UIScreen.main.scale } } var pixelHeight:CGFloat { get { return self.frame.size.height * UIScreen.main.scale } set { self.frame.size.height = newValue / UIScreen.main.scale } } var pixelFrame:CGRect { get { return CGRect(x: pixelX, y: pixelY, width: pixelWidth, height: pixelHeight) } set { self.frame = CGRect( x: newValue.origin.x / UIScreen.main.scale, y: newValue.origin.y / UIScreen.main.scale, width: newValue.size.width / UIScreen.main.scale, height: newValue.size.height / UIScreen.main.scale ) } } var pixelBounds:CGRect { get { return CGRect(x: bounds.origin.x * UIScreen.main.scale, y: bounds.origin.y * UIScreen.main.scale, width: bounds.size.width * UIScreen.main.scale, height: bounds.size.height * UIScreen.main.scale) } set { self.bounds = CGRect( x: newValue.origin.x / UIScreen.main.scale, y: newValue.origin.y / UIScreen.main.scale, width: newValue.size.width / UIScreen.main.scale, height: newValue.size.height / UIScreen.main.scale ) } } }
mit
acastano/swift-bootstrap
userinterfacekit/Sources/Classes/Views/Button/Button.swift
1
793
import UIKit open class Button: UIButton { open var initialHeight = CGFloat(0) @IBOutlet open weak var topConstraint: NSLayoutConstraint? @IBOutlet open weak var leftConstraint: NSLayoutConstraint? @IBOutlet open weak var widthConstraint: NSLayoutConstraint? @IBOutlet open weak var rightConstraint: NSLayoutConstraint? @IBOutlet open weak var heightConstraint: NSLayoutConstraint? @IBOutlet open weak var bottomConstraint: NSLayoutConstraint? @IBOutlet open weak var centerXConstraint: NSLayoutConstraint? @IBOutlet open weak var centerYConstraint: NSLayoutConstraint? open override func awakeFromNib() { super.awakeFromNib() initialHeight = heightConstraint?.constant ?? 0 } }
apache-2.0
OpenKitten/MongoKitten
Sources/MongoCore/MongoReplyDeserializer.swift
2
2352
import Foundation import BSON import NIO import Logging /// A type capable of deserializing messages from MongoDB public struct MongoServerReplyDeserializer { private var header: MongoMessageHeader? private var reply: MongoServerReply? let logger: Logger public mutating func takeReply() -> MongoServerReply? { if let reply = reply { self.reply = nil return reply } return nil } public init(logger: Logger) { self.logger = logger } /// Parses a buffer into a server reply /// /// Returns `.continue` if enough data was read for a single reply /// /// Sets `reply` to a the found ServerReply when done parsing it. /// It's replaced with a new reply the next successful iteration of the parser so needs to be extracted after each `parse` attempt /// /// Any remaining data left in the `buffer` needs to be left until the next interation, which NIO does by default public mutating func parse(from buffer: inout ByteBuffer) throws -> DecodingState { let header: MongoMessageHeader if let _header = self.header { header = _header } else { if buffer.readableBytes < MongoMessageHeader.byteSize { return .needMoreData } header = try buffer.assertReadMessageHeader() } guard header.messageLength - MongoMessageHeader.byteSize <= buffer.readableBytes else { self.header = header return .needMoreData } self.header = nil switch header.opCode { case .reply: // <= Wire Version 5 self.reply = try .reply(OpReply(reading: &buffer, header: header)) case .message: // >= Wire Version 6 self.reply = try .message(OpMessage(reading: &buffer, header: header)) default: logger.error("Mongo Protocol error: OpCode \(header.opCode) in reply is not supported") throw MongoProtocolParsingError(reason: .unsupportedOpCode) } self.header = nil return .continue } } fileprivate extension Optional { func assert() throws -> Wrapped { guard let `self` = self else { throw MongoOptionalUnwrapFailure() } return self } }
mit
pusher-community/pusher-websocket-swift
Sources/Models/Constants.swift
1
2178
import Foundation // swiftlint:disable nesting enum Constants { enum API { static let defaultHost = "ws.pusherapp.com" static let pusherDomain = "pusher.com" } enum ChannelTypes { static let presence = "presence" static let `private` = "private" static let privateEncrypted = "private-encrypted" } enum Events { enum Pusher { static let connectionEstablished = "pusher:connection_established" static let error = "pusher:error" static let subscribe = "pusher:subscribe" static let unsubscribe = "pusher:unsubscribe" static let subscriptionError = "pusher:subscription_error" static let subscriptionSucceeded = "pusher:subscription_succeeded" } enum PusherInternal { static let memberAdded = "pusher_internal:member_added" static let memberRemoved = "pusher_internal:member_removed" static let subscriptionSucceeded = "pusher_internal:subscription_succeeded" } } enum EventTypes { static let client = "client" static let pusher = "pusher" static let pusherInternal = "pusher_internal" } enum JSONKeys { static let activityTimeout = "activity_timeout" static let auth = "auth" static let channel = "channel" static let channelData = "channel_data" static let ciphertext = "ciphertext" static let code = "code" static let data = "data" static let event = "event" static let hash = "hash" static let message = "message" static let nonce = "nonce" static let presence = "presence" static let socketId = "socket_id" static let sharedSecret = "shared_secret" static let userId = "user_id" static let userInfo = "user_info" } }
mit
peihsendoyle/ZCPlayer
ZCPlayer/ZCPlayer/SecondViewController.swift
1
5326
// // SecondViewController.swift // ZCPlayer // // Created by Doyle Illusion on 7/8/17. // Copyright © 2017 Zyncas Technologies. All rights reserved. // import UIKit class SecondViewController: UIViewController { var isInTransition = false let urls = ["https://yosing.vn/master/files/records/records/record_record_59522512a7acd.mp4"] let image = UIImage.init(named: "cover.jpg") let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height), style: .plain) override func viewDidLoad() { super.viewDidLoad() self.tableView.backgroundColor = .white self.tableView.tableFooterView = UIView() self.tableView.separatorStyle = .none self.tableView.allowsSelection = false self.tableView.delegate = self self.tableView.dataSource = self self.tableView.register(VideoTableViewCell.self, forCellReuseIdentifier: "videoCell") self.view.addSubview(self.tableView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.isInTransition = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.isInTransition = false let cells = self.tableView.visibleCells for cell in cells { guard let videoCell = cell as? VideoTableViewCell else { continue } guard let indexPath = self.tableView.indexPath(for: videoCell) else { continue } if self.isFullyVisible(cell: videoCell, scrollView: self.tableView) { let url = self.urls[indexPath.row] if let controller = PlayerControllerManager.shared.dict[url] { controller.addPlayerViewToSuperview(view: videoCell.contentView) } } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.isInTransition = true let cells = self.tableView.visibleCells for cell in cells { guard let videoCell = cell as? VideoTableViewCell else { continue } guard let indexPath = self.tableView.indexPath(for: videoCell) else { continue } let url = self.urls[indexPath.row] if let controller = PlayerControllerManager.shared.dict[url] { controller.removePlayerViewFromSuperview() } } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.isInTransition = false } } extension SecondViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "videoCell", for: indexPath) as! VideoTableViewCell cell.coverImage = self.image let url = self.urls[indexPath.row] if let controller = PlayerControllerManager.shared.dict[url] { controller.addPlayerViewToSuperview(view: cell.contentView) } else { let controller = PlayerController.init(url: URL.init(string: url)!) controller.addPlayerViewToSuperview(view: cell.contentView) } return cell } func scrollViewDidScroll(_ scrollView: UIScrollView) { guard self.isInTransition == false else { return } let cells = self.tableView.visibleCells for cell in cells { guard let videoCell = cell as? VideoTableViewCell else { continue } guard let indexPath = self.tableView.indexPath(for: videoCell) else { continue } if self.isFullyVisible(cell: videoCell, scrollView: scrollView) { let url = self.urls[indexPath.row] if let controller = PlayerControllerManager.shared.dict[url] { controller.addPlayerViewToSuperview(view: cell.contentView) } } else { let url = self.urls[indexPath.row] if let controller = PlayerControllerManager.shared.dict[url] { controller.removePlayerViewFromSuperview() } } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } fileprivate func isFullyVisible(cell: VideoTableViewCell, scrollView: UIScrollView) -> Bool { let relativeToScrollViewRect = cell.convert(cell.bounds, to: scrollView) let visibleScrollViewRect = CGRect(x: CGFloat(scrollView.contentOffset.x), y: CGFloat(scrollView.contentOffset.y), width: CGFloat(scrollView.bounds.size.width), height: CGFloat(scrollView.bounds.size.height)) return visibleScrollViewRect.contains(CGPoint.init(x: relativeToScrollViewRect.midX, y: relativeToScrollViewRect.midY)) } } extension SecondViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200.0 } }
apache-2.0
exsortis/TenCenturiesKit
Sources/TenCenturiesKit/Models/Channel.swift
1
2476
// // Channel.swift // Yawp // // Created by Paul Schifferer on 21/5/17. // Copyright © 2017 Pilgrimage Software. All rights reserved. // import Foundation public struct Channel { public var id : Int public var guid : String public var createdAt : Date public var createdUnix : Int public var updatedAt : Date public var updatedUnix : Int public var type : ChannelType public var privacy : Privacy public var ownerId : Int? } public enum ChannelType : String { case global = "channel.global" } extension Channel : Serializable { public init?(from json : JSONDictionary) { guard let id = json["id"] as? Int, let guid = json["guid"] as? String, let c = json["created_at"] as? String, let createdAt = DateUtilities.isoFormatter.date(from: c), let createdUnix = json["created_unix"] as? Int, let u = json["updated_at"] as? String, let updatedAt = DateUtilities.isoFormatter.date(from: u), let updatedUnix = json["updated_unix"] as? Int, let t = json["type"] as? String, let type = ChannelType(rawValue: t), let p = json["privacy"] as? String, let privacy = Privacy(rawValue: p) else { return nil } self.id = id self.guid = guid self.createdAt = createdAt self.createdUnix = createdUnix self.updatedAt = updatedAt self.updatedUnix = updatedUnix self.type = type self.privacy = privacy self.ownerId = json["owner_id"] as? Int } public func toDictionary() -> JSONDictionary { var dict : JSONDictionary = [ "privacy": privacy.rawValue, "created_at": DateUtilities.isoFormatter.string(from: createdAt), "updated_unix": createdUnix, "updated_at": DateUtilities.isoFormatter.string(from: updatedAt), "created_unix": createdUnix, "guid": guid, "type": type.rawValue, "id": id, ] if let ownerId = ownerId { dict["owner_id"] = ownerId } return dict } } /* { "privacy": "visibility.public", "created_at": "2015-08-01T00:00:00Z", "updated_unix": 1438387200, "updated_at": "2015-08-01T00:00:00Z", "created_unix": 1438387200, "guid": "d9ba5a8d768d0dbd9fc9c3ea4c8e183b2aa7336c", "type": "channel.global", "id": 1, "owner_id": false } */
mit
ulrikdamm/Forbind
Forbind/Promise.swift
1
2177
// // Promise.swift // Forbind // // Created by Ulrik Damm on 06/06/15. // // import Foundation private enum PromiseState<T> { case noValue case value(T) } open class Promise<T> { public init(value : T? = nil) { value => setValue } public init(previousPromise : AnyObject) { self.previousPromise = previousPromise } fileprivate var _value : PromiseState<T> = .noValue var previousPromise : AnyObject? open func setValue(_ value : T) { _value = PromiseState.value(value) notifyListeners() } open var value : T? { get { switch _value { case .noValue: return nil case .value(let value): return value } } } fileprivate var listeners : [(T) -> Void] = [] open func getValue(_ callback : @escaping (T) -> Void) { getValueWeak { value in let _ = self callback(value) } } open func getValueWeak(_ callback : @escaping (T) -> Void) { if let value = value { callback(value) } else { listeners.append(callback) } } fileprivate func notifyListeners() { switch _value { case .noValue: break case .value(let value): for callback in listeners { callback(value) } } listeners = [] } } //public func ==<T : Equatable>(lhs : Promise<T>, rhs : Promise<T>) -> Promise<Bool> { // return (lhs ++ rhs) => { $0 == $1 } //} // //public func ==<T : Equatable>(lhs : Promise<T?>, rhs : Promise<T?>) -> Promise<Bool?> { // return (lhs ++ rhs) => { $0 == $1 } //} // //public func ==<T : Equatable>(lhs : Promise<Result<T>>, rhs : Promise<Result<T>>) -> Promise<Result<Bool>> { // return (lhs ++ rhs) => { $0 == $1 } //} extension Promise : CustomStringConvertible { public var description : String { if let value = value { return "Promise(\(value))" } else { return "Promise(\(T.self))" } } } //public func filterp<T>(_ source : [Promise<T>], includeElement : (T) -> Bool) -> Promise<[T]> { // return reducep(source, initial: []) { all, this in includeElement(this) ? all + [this] : all } //} // //public func reducep<T, U>(_ source : [Promise<T>], initial : U, combine : (U, T) -> U) -> Promise<U> { // return source.reduce(Promise(value: initial)) { $0 ++ $1 => combine } //}
mit
nodekit-io/nodekit-darwin
src/nodekit/NKElectro/NKEBrowser/platform-osx/NKEBrowserWindow_OSX.swift
1
11920
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright (c) 2013 GitHub, Inc. under MIT License * * 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. */ #if os(OSX) import Foundation import Cocoa extension NKE_BrowserWindow { internal func createWindow(options: Dictionary<String, AnyObject>) -> AnyObject { let isTaskBarPopup = (options[NKEBrowserOptions.kTaskBarPopup] as? Bool) ?? false ; let TaskBarIcon = (options[NKEBrowserOptions.kTaskBarIcon] as? String) ?? "" ; if !isTaskBarPopup { let width: CGFloat = CGFloat((options[NKEBrowserOptions.kWidth] as? Int) ?? NKEBrowserDefaults.kWidth) let height: CGFloat = CGFloat((options[NKEBrowserOptions.kHeight] as? Int) ?? NKEBrowserDefaults.kHeight) let title: String = (options[NKEBrowserOptions.kTitle] as? String) ?? NKEBrowserDefaults.kTitle let windowRect: NSRect = (NSScreen.mainScreen()!).frame let frameRect: NSRect = NSMakeRect( (NSWidth(windowRect) - width)/2, (NSHeight(windowRect) - height)/2, width, height) let window = NSWindow(contentRect: frameRect, styleMask: [NSTitledWindowMask , NSClosableWindowMask , NSResizableWindowMask], backing: NSBackingStoreType.Buffered, defer: false, screen: NSScreen.mainScreen()) objc_setAssociatedObject(self, unsafeAddressOf(NSWindow), window, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) window.title = title window.makeKeyAndOrderFront(nil) return window } else { let window = NSPopover() window.contentViewController = NSViewController() objc_setAssociatedObject(self, unsafeAddressOf(NSWindow), window, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) let nke_popover = NKE_Popover(Popover: window, imageName: TaskBarIcon) objc_setAssociatedObject(self, unsafeAddressOf(NKE_Popover), nke_popover, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return window } } } extension NKE_BrowserWindow: NKE_BrowserWindowProtocol { func destroy() -> Void { NotImplemented(); } func close() -> Void { guard let window = self._window as? NSWindow else {return;} window.close() self._window = nil NKE_BrowserWindow._windowArray[self._id] = nil _context = nil _webView = nil } func focus() -> Void { NotImplemented(); } func isFocused() -> Bool { NotImplemented(); return false; } func show() -> Void { NotImplemented(); } func showInactive() -> Void { NotImplemented(); } func hide() -> Void { NotImplemented(); } func isVisible() -> Bool { NotImplemented(); return true; } func maximize() -> Void { NotImplemented(); } func unmaximize() -> Void { NotImplemented(); } func isMaximized() -> Bool { NotImplemented(); return false; } func minimize() -> Void { NotImplemented(); } func isMinimized() -> Bool { NotImplemented(); return false; } func setFullScreen(flag: Bool) -> Void { NotImplemented(); } func isFullScreen() -> Bool { NotImplemented(); return false; } func setAspectRatio(aspectRatio: NSNumber, extraSize: [Int]) -> Void { NotImplemented(); } //OS X func setBounds(options: [NSObject : AnyObject]!) -> Void { NotImplemented(); } func getBounds() -> [NSObject : AnyObject]! { NotImplemented(); return [NSObject : AnyObject](); } func setSize(width: Int, height: Int) -> Void { NotImplemented(); } func getSize() -> [NSObject : AnyObject]! { NotImplemented(); return [NSObject : AnyObject](); } func setContentSize(width: Int, height: Int) -> Void { NotImplemented(); } func getContentSize() -> [Int] { NotImplemented(); return [Int](); } func setMinimumSize(width: Int, height: Int) -> Void { NotImplemented(); } func getMinimumSize() -> [Int] { NotImplemented(); return [Int](); } func setMaximumSize(width: Int, height: Int) -> Void { NotImplemented(); } func getMaximumSize() -> [Int] { NotImplemented(); return [Int](); } func setResizable(resizable: Bool) -> Void { NotImplemented(); } func isResizable() -> Bool { NotImplemented(); return false; } func setAlwaysOnTop(flag: Bool) -> Void { NotImplemented(); } func isAlwaysOnTop() -> Bool { NotImplemented(); return false; } func center() -> Void { NotImplemented(); } func setPosition(x: Int, y: Int) -> Void { NotImplemented(); } func getPosition() -> [Int] { NotImplemented(); return [Int]() } func setTitle(title: String) -> Void { NotImplemented(); } func getTitle() -> Void { NotImplemented(); } func flashFrame(flag: Bool) -> Void { NotImplemented(); } func setSkipTaskbar(skip: Bool) -> Void { NotImplemented(); } func setKiosk(flag: Bool) -> Void { NotImplemented(); } func isKiosk() -> Bool { NotImplemented(); return false; } // func hookWindowMessage(message: Int,callback: AnyObject) -> Void //WINDOWS // func isWindowMessageHooked(message: Int) -> Void //WINDOWS // func unhookWindowMessage(message: Int) -> Void //WINDOWS // func unhookAllWindowMessages() -> Void //WINDOWS func setRepresentedFilename(filename: String) -> Void { NotImplemented(); } //OS X func getRepresentedFilename() -> String { NotImplemented(); return "" } //OS X func setDocumentEdited(edited: Bool) -> Void { NotImplemented(); } //OS X func isDocumentEdited() -> Bool { NotImplemented(); return false; } //OS X func focusOnWebView() -> Void { NotImplemented(); } func blurWebView() -> Void { NotImplemented(); } func capturePage(rect: [NSObject : AnyObject]!, callback: AnyObject) -> Void { NotImplemented(); } func print(options: [NSObject : AnyObject]) -> Void { NotImplemented(); } func printToPDF(options: [NSObject : AnyObject], callback: AnyObject) -> Void { NotImplemented(); } func loadURL(url: String, options: [NSObject : AnyObject]) -> Void { NotImplemented(); } func reload() -> Void { NotImplemented(); } // func setMenu(menu) -> Void //LINUX WINDOWS func setProgressBar(progress: Double) -> Void { NotImplemented(); } // func setOverlayIcon(overlay, description) -> Void //WINDOWS 7+ // func setThumbarButtons(buttons) -> Void //WINDOWS 7+ func showDefinitionForSelection() -> Void { NotImplemented(); } //OS X func setAutoHideMenuBar(hide: Bool) -> Void { NotImplemented(); } func isMenuBarAutoHide() -> Bool { NotImplemented(); return false; } func setMenuBarVisibility(visible: Bool) -> Void { NotImplemented(); } func isMenuBarVisible() -> Bool { NotImplemented(); return false; } func setVisibleOnAllWorkspaces(visible: Bool) -> Void { NotImplemented(); } func isVisibleOnAllWorkspaces() -> Bool { NotImplemented(); return false; } func setIgnoreMouseEvents(ignore: Bool) -> Void { NotImplemented(); } //OS X private static func NotImplemented() -> Void { NSException(name: "NotImplemented", reason: "This function is not implemented", userInfo: nil).raise() } private func NotImplemented() -> Void { NSException(name: "NotImplemented", reason: "This function is not implemented", userInfo: nil).raise() } } class NKE_Popover : NSObject { let statusItem: NSStatusItem let popover: NSPopover var popoverMonitor: AnyObject? init( Popover: NSPopover, imageName: String) { popover = Popover statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSSquareStatusItemLength) super.init() setupStatusButton(imageName) } func setupStatusButton(imageName: String) { if let statusButton = statusItem.button { let mainBundle: NSBundle = NSBundle.mainBundle() guard let image: NSImage = mainBundle.imageForResource(imageName) else { return } statusButton.image = image statusButton.target = self statusButton.action = #selector(NKE_Popover.onPress(_:)) statusButton.sendActionOn(NSEventMask(rawValue: UInt64((NSEventMask.RightMouseDown).rawValue))) let dummyControl = DummyControl() dummyControl.frame = statusButton.bounds statusButton.addSubview(dummyControl) statusButton.superview!.subviews = [statusButton, dummyControl] dummyControl.action = #selector(NKE_Popover.onPress(_:)) dummyControl.target = self } } func quitApp(sender: AnyObject) { NSApplication.sharedApplication().terminate(self) } func onPress(sender: AnyObject) { let event:NSEvent! = NSApp.currentEvent! if (event.type == NSEventType.RightMouseDown) { let menu = NSMenu() let quitMenuItem = NSMenuItem(title:"Quit", action:#selector(NKE_Popover.quitApp(_:)), keyEquivalent:"") quitMenuItem.target = self menu.addItem(quitMenuItem) statusItem.popUpStatusItemMenu(menu) } else{ if popover.shown == false { openPopover() } else { closePopover() } } } func openPopover() { if let statusButton = statusItem.button { statusButton.highlight(true) popover.showRelativeToRect(NSZeroRect, ofView: statusButton, preferredEdge: NSRectEdge.MinY) popoverMonitor = NSEvent.addGlobalMonitorForEventsMatchingMask(.LeftMouseDown, handler: { (event: NSEvent) -> Void in self.closePopover() }) } } func closePopover() { popover.close() if let statusButton = statusItem.button { statusButton.highlight(false) } if let monitor : AnyObject = popoverMonitor { NSEvent.removeMonitor(monitor) popoverMonitor = nil } } } class DummyControl : NSControl { override func mouseDown(theEvent: NSEvent) { superview!.mouseDown(theEvent) sendAction(action, to: target) } } #endif
apache-2.0
clwm01/RTKitDemo
RCToolsDemo/RTRC.swift
2
742
// // RTRC.swift // RCToolsDemo // // Created by Rex Tsao on 5/18/16. // Copyright © 2016 rexcao. All rights reserved. // import Foundation class RTRC { private var stack: Dictionary<String, Int> init(key: String) { self.stack = [key: 0] } func add(key: String, count: Int) { } func increaseForKey(key: String) { var value = self.stack[key]! value += 1 self.stack[key] = value } func decreaseForKey(key: String) { var value = self.stack[key]! value -= 1 if value < 0 { value = 0 } self.stack[key] = value } func valueForKey(key: String) -> Int { return self.stack[key]! } }
mit
IdrissPiard/UnikornTube_Client
UnikornTube/UploadVideoVC.swift
1
5444
// // UploadVideoVC.swift // UnikornTube // // Created by Damien Serin on 03/06/2015. // Copyright (c) 2015 SimpleAndNew. All rights reserved. // import UIKit class UploadVideoVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var coverImage: UIImageView! var videoPickerController = UIImagePickerController() var coverPickerController = UIImagePickerController() var moviePath : String! var coverUrl : NSURL! 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. } @IBAction func uploadButtonTapped(sender: AnyObject) { videoUploadRequest() } @IBAction func selectVideoButtonTapped(sender: AnyObject) { videoPickerController.allowsEditing = false videoPickerController.delegate = self; videoPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary videoPickerController.mediaTypes = [kUTTypeMovie as NSString] self.presentViewController(videoPickerController, animated: true, completion: nil) } @IBAction func selectCoverButtonTapped(sender: AnyObject) { coverPickerController.allowsEditing = false coverPickerController.delegate = self; coverPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary coverPickerController.mediaTypes = [kUTTypeImage as NSString] self.presentViewController(coverPickerController, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { if picker == self.videoPickerController { var mediaType = info[UIImagePickerControllerMediaType] as! CFString! var compareResult = CFStringCompare(mediaType, kUTTypeMovie, CFStringCompareFlags.CompareCaseInsensitive) if(compareResult == CFComparisonResult.CompareEqualTo){ var videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL var moviePath = videoUrl.path if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath)){ //UISaveVideoAtPathToSavedPhotosAlbum(moviePath, nil, nil, nil) } self.moviePath = moviePath println(self.moviePath) } } if picker == self.coverPickerController { var coverUrl = info[UIImagePickerControllerReferenceURL] as! NSURL var image = info[UIImagePickerControllerOriginalImage] as! UIImage self.coverImage.image = image var coverPath = coverUrl.path self.coverUrl = coverUrl println(self.coverUrl) } self.dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func videoUploadRequest(){ //var json: JSON = ["meta_data": ["title":"titre", "idUser":"42", "description":"desc"]] let manager = AFHTTPRequestOperationManager() let url = "http://192.168.200.40:9000/upload" manager.requestSerializer = AFJSONRequestSerializer(writingOptions: nil) var videoURL = NSURL.fileURLWithPath(self.moviePath) var imageData = UIImageJPEGRepresentation(self.coverImage.image, CGFloat(1)) println(videoURL) var params = ["meta_data" : "{\"title\":\"titre\", \"idUser\":42, \"description\":\"ladesc\"}"] var json : String = "{ \"meta_data\" : [{\"title\":\"titre\", \"idUser\":42, \"description\":\"ladesc\"}]}" println(json) AFNetworkActivityLogger.sharedLogger().level = AFHTTPRequestLoggerLevel.AFLoggerLevelDebug manager.POST( url, parameters: params, constructingBodyWithBlock: { (data: AFMultipartFormData!) in var res = data.appendPartWithFileURL(videoURL, name: "video_data", error: nil) data.appendPartWithFileData(imageData, name: "cover_data", fileName: "cover.jpg", mimeType: "image/jpeg") println("was file added properly to the body? \(res)") }, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in println("Yes thies was a success") }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in println("We got an error here.. \(error)") println(operation.responseString) }) } /* // 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
CSullivan102/LearnApp
LearnKit/CreateTopic/CreateTopicModel.swift
1
1657
// // CreateTopicModel.swift // Learn // // Created by Christopher Sullivan on 9/23/15. // Copyright © 2015 Christopher Sullivan. All rights reserved. // import Foundation public struct CreateTopicModel { public init() {} private let maxEmojiTextLength = 1 private let emojiRanges = [ 0x0080...0x00FF, 0x2100...0x214F, 0x2190...0x21FF, 0x2300...0x23FF, 0x25A0...0x27BF, 0x2900...0x297F, 0x2B00...0x2BFF, 0x3001...0x303F, 0x3200...0x32FF, 0x1F000...0x1F02F, 0x1F110...0x1F251, 0x1F300...0x1F5FF, 0x1F600...0x1F64F, 0x1F680...0x1F6FF ] public func isValidTopicName(name: String, andIcon icon: String) -> Bool { return isValidTopicName(name) && isValidEmojiValue(icon) } public func canChangeTopicIconToString(string: String) -> Bool { return string.lengthWithEmoji() == 0 || isValidEmojiValue(string) } public func isValidTopicName(name: String) -> Bool { return name.lengthWithEmoji() > 0 } public func isValidEmojiValue(string: String) -> Bool { if string.lengthWithEmoji() == 0 || string.lengthWithEmoji() > maxEmojiTextLength { return false } if let scalarVal = string.unicodeScalars.first?.value { var found = false for range in emojiRanges { if range.contains(Int(scalarVal)) { found = true } } if !found { return false } } return true } }
mit
daltoniam/Starscream
examples/AutobahnTest/Autobahn/ViewController.swift
1
6021
// // ViewController.swift // Autobahn // // Created by Dalton Cherry on 7/24/15. // Copyright (c) 2015 vluxe. All rights reserved. // import UIKit import Starscream class ViewController: UIViewController { let host = "localhost:9001" var socketArray = [WebSocket]() var caseCount = 300 //starting cases override func viewDidLoad() { super.viewDidLoad() getCaseCount() //getTestInfo(1) //runTest(304) } func removeSocket(_ s: WebSocket?) { guard let s = s else {return} socketArray = socketArray.filter{$0 !== s} } func getCaseCount() { let req = URLRequest(url: URL(string: "ws://\(host)/getCaseCount")!) let s = WebSocket(request: req) socketArray.append(s) s.onEvent = { [weak self] event in switch event { case .text(let string): if let c = Int(string) { print("number of cases is: \(c)") self?.caseCount = c } case .disconnected(_, _): self?.runTest(1) self?.removeSocket(s) default: break } } s.connect() } func getTestInfo(_ caseNum: Int) { let s = createSocket("getCaseInfo",caseNum) socketArray.append(s) // s.onText = { (text: String) in // let data = text.dataUsingEncoding(NSUTF8StringEncoding) // do { // let resp: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!, // options: NSJSONReadingOptions()) // if let dict = resp as? Dictionary<String,String> { // let num = dict["id"] // let summary = dict["description"] // if let n = num, let sum = summary { // print("running case:\(caseNum) id:\(n) summary: \(sum)") // } // } // } catch { // print("error parsing the json") // } // } var once = false s.onEvent = { [weak self] event in switch event { case .disconnected(_, _), .error(_): if !once { once = true self?.runTest(caseNum) } self?.removeSocket(s) default: break } } s.connect() } func runTest(_ caseNum: Int) { let s = createSocket("runCase",caseNum) self.socketArray.append(s) var once = false s.onEvent = { [weak self, weak s] event in switch event { case .disconnected(_, _), .error(_): if !once { once = true print("case:\(caseNum) finished") //self?.verifyTest(caseNum) //disabled since it slows down the tests let nextCase = caseNum+1 if nextCase <= (self?.caseCount)! { self?.runTest(nextCase) //self?.getTestInfo(nextCase) //disabled since it slows down the tests } else { self?.finishReports() } self?.removeSocket(s) } self?.removeSocket(s) case .text(let string): s?.write(string: string) case .binary(let data): s?.write(data: data) // case .error(let error): // print("got an error: \(error)") default: break } } s.connect() } // func verifyTest(_ caseNum: Int) { // let s = createSocket("getCaseStatus",caseNum) // self.socketArray.append(s) // s.onText = { (text: String) in // let data = text.data(using: String.Encoding.utf8) // do { // let resp: Any? = try JSONSerialization.jsonObject(with: data!, // options: JSONSerialization.ReadingOptions()) // if let dict = resp as? Dictionary<String,String> { // if let status = dict["behavior"] { // if status == "OK" { // print("SUCCESS: \(caseNum)") // return // } // } // print("FAILURE: \(caseNum)") // } // } catch { // print("error parsing the json") // } // } // var once = false // s.onDisconnect = { [weak self, weak s] (error: Error?) in // if !once { // once = true // let nextCase = caseNum+1 // print("next test is: \(nextCase)") // if nextCase <= (self?.caseCount)! { // self?.getTestInfo(nextCase) // } else { // self?.finishReports() // } // } // self?.removeSocket(s) // } // s.connect() // } func finishReports() { let s = createSocket("updateReports",0) self.socketArray.append(s) s.onEvent = { [weak self, weak s] event in switch event { case .disconnected(_, _): print("finished all the tests!") self?.removeSocket(s) default: break } } s.connect() } func createSocket(_ cmd: String, _ caseNum: Int) -> WebSocket { let req = URLRequest(url: URL(string: "ws://\(host)\(buildPath(cmd,caseNum))")!) //return WebSocket(request: req, compressionHandler: WSCompression()) return WebSocket(request: req) } func buildPath(_ cmd: String, _ caseNum: Int) -> String { return "/\(cmd)?case=\(caseNum)&agent=Starscream" } }
apache-2.0
noremac/Logging
Logging/LogSync.swift
1
1554
/* The MIT License (MIT) Copyright (c) 2015 Cameron Pulsford Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public enum LogSync: CustomStringConvertible { case UnsafePrint case SyncPrint case AsyncPrint case Custom(logger: (statement: String) -> Void) public var description: String { switch self { case .UnsafePrint: return "Print" case .SyncPrint: return "SyncPrint" case .AsyncPrint: return "AsyncPrint" case .Custom: return "CustomSync" } } }
mit
kouky/MavlinkPrimaryFlightDisplay
Sources/iOS/BLE.swift
1
10813
/* Copyright (c) 2015 Fernando Reynoso Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import CoreBluetooth enum BLEBaudRate { case Bps9600 case Bps19200 case Bps38400 case Bps57600 case Bps115200 var data: NSData { switch self { case .Bps9600: return NSData(bytes: [0x00] as [UInt8],length: 1) case .Bps19200: return NSData(bytes: [0x01] as [UInt8],length: 1) case .Bps38400: return NSData(bytes: [0x02] as [UInt8],length: 1) case .Bps57600: return NSData(bytes: [0x03] as [UInt8],length: 1) case .Bps115200: return NSData(bytes: [0x04] as [UInt8],length: 1) } } } protocol BLEDelegate { func bleDidDiscoverPeripherals() func bleDidConnectToPeripheral() func bleDidDisconenctFromPeripheral() func bleDidDicoverCharacateristics() func bleDidReceiveData(data: NSData?) } class BLE: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate { let RBL_SERVICE_UUID = "713D0000-503E-4C75-BA94-3148F18D941E" let RBL_CHAR_TX_UUID = "713D0002-503E-4C75-BA94-3148F18D941E" let RBL_CHAR_RX_UUID = "713D0003-503E-4C75-BA94-3148F18D941E" let RBL_CHAR_BAUD_UUID = "713D0004-503E-4C75-BA94-3148F18D941E" var delegate: BLEDelegate? private var centralManager: CBCentralManager! private var activePeripheral: CBPeripheral? private var characteristics = [String : CBCharacteristic]() private var data: NSMutableData? private(set) var peripherals = [CBPeripheral]() private(set) var state = CBCentralManagerState.Unknown private var RSSICompletionHandler: ((NSNumber?, NSError?) -> ())? override init() { super.init() self.centralManager = CBCentralManager(delegate: self, queue: nil) self.data = NSMutableData() } @objc private func scanTimeout() { print("[DEBUG] Scanning stopped") self.centralManager.stopScan() } // MARK: Public methods func startScanning(timeout: Double) -> Bool { if self.centralManager.state != .PoweredOn { print("[ERROR] Couldn´t start scanning") return false } print("[DEBUG] Scanning started") // CBCentralManagerScanOptionAllowDuplicatesKey NSTimer.scheduledTimerWithTimeInterval(timeout, target: self, selector: #selector(BLE.scanTimeout), userInfo: nil, repeats: false) let services:[CBUUID] = [CBUUID(string: RBL_SERVICE_UUID)] self.centralManager.scanForPeripheralsWithServices(services, options: nil) return true } func connectToPeripheral(peripheral: CBPeripheral) -> Bool { if self.centralManager.state != .PoweredOn { print("[ERROR] Couldn´t connect to peripheral") return false } print("[DEBUG] Connecting to peripheral: \(peripheral.identifier.UUIDString)") self.centralManager.connectPeripheral(peripheral, options: [CBConnectPeripheralOptionNotifyOnDisconnectionKey : NSNumber(bool: true)]) return true } func disconnectFromPeripheral(peripheral: CBPeripheral) -> Bool { if self.centralManager.state != .PoweredOn { print("[ERROR] Couldn´t disconnect from peripheral") return false } self.centralManager.cancelPeripheralConnection(peripheral) return true } func disconnectActivePeripheral() { if let peripheral = activePeripheral { disconnectFromPeripheral(peripheral) } } func read() { guard let char = self.characteristics[RBL_CHAR_TX_UUID] else { return } self.activePeripheral?.readValueForCharacteristic(char) } func write(data data: NSData) { guard let char = self.characteristics[RBL_CHAR_RX_UUID] else { return } self.activePeripheral?.writeValue(data, forCharacteristic: char, type: .WithoutResponse) } func enableNotifications(enable: Bool) { guard let char = self.characteristics[RBL_CHAR_TX_UUID] else { return } self.activePeripheral?.setNotifyValue(enable, forCharacteristic: char) } func readRSSI(completion: (RSSI: NSNumber?, error: NSError?) -> ()) { self.RSSICompletionHandler = completion self.activePeripheral?.readRSSI() } func setBaudRate(baudRate: BLEBaudRate) { guard let characteristc = self.characteristics[RBL_CHAR_BAUD_UUID] else { print("[DEBUG] Cannot get BAUD characterictic") return } self.activePeripheral?.writeValue(baudRate.data, forCharacteristic: characteristc, type: .WithoutResponse) } // MARK: CBCentralManager delegate func centralManagerDidUpdateState(central: CBCentralManager) { switch central.state { case .Unknown: print("[DEBUG] Central manager state: Unknown") break case .Resetting: print("[DEBUG] Central manager state: Resseting") break case .Unsupported: print("[DEBUG] Central manager state: Unsopported") break case .Unauthorized: print("[DEBUG] Central manager state: Unauthorized") break case .PoweredOff: print("[DEBUG] Central manager state: Powered off") break case .PoweredOn: print("[DEBUG] Central manager state: Powered on") break } state = central.state } func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject],RSSI: NSNumber) { print("[DEBUG] Find peripheral: \(peripheral.identifier.UUIDString) RSSI: \(RSSI)") let index = peripherals.indexOf { $0.identifier.UUIDString == peripheral.identifier.UUIDString } if let index = index { peripherals[index] = peripheral } else { peripherals.append(peripheral) } delegate?.bleDidDiscoverPeripherals() } func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) { print("[ERROR] Could not connecto to peripheral \(peripheral.identifier.UUIDString) error: \(error!.description)") } func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { print("[DEBUG] Connected to peripheral \(peripheral.identifier.UUIDString)") self.activePeripheral = peripheral self.activePeripheral?.delegate = self self.activePeripheral?.discoverServices([CBUUID(string: RBL_SERVICE_UUID)]) self.delegate?.bleDidConnectToPeripheral() } func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) { var text = "[DEBUG] Disconnected from peripheral: \(peripheral.identifier.UUIDString)" if error != nil { text += ". Error: \(error!.description)" } print(text) self.activePeripheral?.delegate = nil self.activePeripheral = nil self.characteristics.removeAll(keepCapacity: false) self.delegate?.bleDidDisconenctFromPeripheral() } // MARK: CBPeripheral delegate func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) { if error != nil { print("[ERROR] Error discovering services. \(error!.description)") return } print("[DEBUG] Found services for peripheral: \(peripheral.identifier.UUIDString)") for service in peripheral.services! { let theCharacteristics = [CBUUID(string: RBL_CHAR_RX_UUID), CBUUID(string: RBL_CHAR_TX_UUID), CBUUID(string: RBL_CHAR_BAUD_UUID)] peripheral.discoverCharacteristics(theCharacteristics, forService: service) } } func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { if error != nil { print("[ERROR] Error discovering characteristics. \(error!.description)") return } print("[DEBUG] Found characteristics for peripheral: \(peripheral.identifier.UUIDString)") for characteristic in service.characteristics! { self.characteristics[characteristic.UUID.UUIDString] = characteristic } enableNotifications(true) delegate?.bleDidDicoverCharacateristics() } func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { if error != nil { print("[ERROR] Error updating value. \(error!.description)") return } if characteristic.UUID.UUIDString == RBL_CHAR_TX_UUID { self.delegate?.bleDidReceiveData(characteristic.value) } } func peripheral(peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: NSError?) { self.RSSICompletionHandler?(RSSI, error) self.RSSICompletionHandler = nil } }
mit
sarvex/SwiftRecepies
Maps/Customizing the View of the Map with a Camera/Customizing the View of the Map with a Camera/AppDelegate.swift
1
2924
// // AppDelegate.swift // Customizing the View of the Map with a Camera // // Created by Vandad Nahavandipoor on 7/8/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at vandad.np@gmail.com // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 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:. } }
isc
nguyenkhiem/Swift3Validation
SwiftValidator/Core/ValidationDelegate.swift
1
750
// // ValidationDelegate.swift // Validator // // Created by David Patterson on 1/2/16. // Copyright © 2016 jpotts18. All rights reserved. // import Foundation import UIKit /** Protocol for `ValidationDelegate` adherents, which comes with two required methods that are called depending on whether validation succeeded or failed. */ @objc public protocol ValidationDelegate { /** This method will be called on delegate object when validation is successful. - returns: No return value. */ func validationSuccessful() /** This method will be called on delegate object when validation fails. - returns: No return value. */ func validationFailed(_ errors: [UITextField:ValidationError]) }
mit
skylib/SnapPageableArray
SnapPageableArrayTests/InsertTests.swift
1
3523
import XCTest import SnapPageableArray class InsertTests: PageableArrayTests { func testInsertElementsWithSubscript() { let size = 10 let pageSize = 5 var array = createArrayWithSize(size, pageSize: pageSize) for i in 0..<size { let element = array[UInt(i)] XCTAssertNotNil(element) XCTAssertEqual(i, element!.data) } } func testAppendElementShouldIncreaseCount() { let size = 10 let pageSize = 5 var array = createArrayWithSize(size, pageSize: pageSize) array.appendElement(TestElement(id: 11, data: 11)) XCTAssertEqual(UInt(size + 1), array.count) } func testAppendElementShouldAppendElelemt() { let size = 10 let pageSize = 5 var array = createArrayWithSize(size, pageSize: pageSize) let data = 100 array.appendElement(TestElement(id: data, data: data)) let element = array[UInt(array.count - 1)] XCTAssertNotNil(element) XCTAssertEqual(data, element!.data) } func testTopUpShouldInsertNewElementsFirst() { let size = 10 let pageSize = 5 var array = createArrayWithSize(size, pageSize: pageSize) var newElements = [TestElement]() for i in size..<size * 2 { newElements.append(TestElement(id: i, data: i)) } array.topUpWithElements(newElements) for i in 0..<size { let element = array[UInt(i)] XCTAssertNotNil(element) XCTAssertEqual(i + size, element!.data) } } func testTopUpWithNoNewItemsShouldReturnNoNewItems() { let size = 10 let pageSize = 5 var array = PageableArray<TestElement>(capacity: UInt(size), pageSize: UInt(pageSize)) var elements = [TestElement]() for i in 0..<size { let element = TestElement(id: i, data: i) array[UInt(i)] = element elements.append(element) } let result = array.topUpWithElements(elements) XCTAssertEqual(result, UpdateResult.noNewItems) } func testTopUpWithSomeNewItemsShouldReturnSomeNewItems() { let size = 10 let pageSize = 5 var array = PageableArray<TestElement>(capacity: UInt(size), pageSize: UInt(pageSize)) var elements = [TestElement]() for i in 0..<size { var element = TestElement(id: i, data: i) array[UInt(i)] = element if i < size/2 { element = TestElement(id: i + 10, data: i + 10) } elements.append(element) } let result = array.topUpWithElements(elements) XCTAssertEqual(result, UpdateResult.someNewItems(newItems: size/2)) } func testTopUpWithAllNewItemsShouldReturnAllNewItems() { let size = 10 let pageSize = 5 var array = PageableArray<TestElement>(capacity: UInt(size), pageSize: UInt(pageSize)) var elements = [TestElement]() for i in 0..<size { var element = TestElement(id: i, data: i) array[UInt(i)] = element element = TestElement(id: i + 10, data: i + 10) elements.append(element) } let result = array.topUpWithElements(elements) XCTAssertEqual(result, UpdateResult.allNewItems) } }
bsd-3-clause
64characters/Telephone
Telephone/PresentationSoundIO.swift
1
2182
// // PresentationSoundIO.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone 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. // // Telephone 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. // import Domain import Foundation import UseCases final class PresentationSoundIO: NSObject { @objc let input: PresentationAudioDevice @objc let output: PresentationAudioDevice @objc let ringtoneOutput: PresentationAudioDevice @objc init(input: PresentationAudioDevice, output: PresentationAudioDevice, ringtoneOutput: PresentationAudioDevice) { self.input = input self.output = output self.ringtoneOutput = ringtoneOutput } } extension PresentationSoundIO { convenience init(soundIO: SystemDefaultingSoundIO, systemDefaultDeviceName name: String) { self.init( input: PresentationAudioDevice(item: soundIO.input, systemDefaultDeviceName: name), output: PresentationAudioDevice(item: soundIO.output, systemDefaultDeviceName: name), ringtoneOutput: PresentationAudioDevice(item: soundIO.ringtoneOutput, systemDefaultDeviceName: name) ) } } extension PresentationSoundIO { override func isEqual(_ object: Any?) -> Bool { guard let soundIO = object as? PresentationSoundIO else { return false } return isEqual(to: soundIO) } override var hash: Int { var hasher = Hasher() hasher.combine(input) hasher.combine(output) hasher.combine(ringtoneOutput) return hasher.finalize() } private func isEqual(to soundIO: PresentationSoundIO) -> Bool { return input == soundIO.input && output == soundIO.output && ringtoneOutput == soundIO.ringtoneOutput } }
gpl-3.0
C453/Force-Touch-Command-Center
Force Touch Command Center/AppDelegate.swift
1
2742
// // AppDelegate.swift // Force Touch Command Center // // Created by Case Wright on 9/24/15. // Copyright © 2015 C453. All rights reserved. // import Cocoa import MASShortcut @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let StatusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength) let settings = NSUserDefaults.standardUserDefaults() func applicationDidFinishLaunching(aNotification: NSNotification) { if settings.boolForKey("notFirstLaunch") == false { //First Launch settings.setBool(true, forKey: "notFirstLaunch") settings.setFloat(Options.lowerLimit, forKey: "lowerLimit") settings.setFloat(Options.upperLimit, forKey: "upperLimit") settings.setBool(Options.showLevel, forKey: "showLevel") settings.setBool(Options.showSlider, forKey: "showSlider") settings.setFloat(Float(Options.Shape.rawValue), forKey: "shapeType") settings.setInteger(Options.action.rawValue, forKey: "action") } Options.lowerLimit = settings.floatForKey("lowerLimit") Options.upperLimit = settings.floatForKey("upperLimit") Options.showLevel = settings.boolForKey("showLevel") Options.showSlider = settings.boolForKey("showSlider") Options.Shape = ShapeType(rawValue: CGFloat(settings.floatForKey("shapeType")))! Options.action = ActionType(rawValue: settings.integerForKey("action"))! StatusItem.button?.title = "Options" StatusItem.button?.image = NSImage(named: "statusIcon") Options.optionsWindowController = OptionsWindowController( windowNibName: "OptionsWindowController") Options.popupWindowController = PopupWindowController( windowNibName: "PopupWindowController") let menu = NSMenu() menu.addItem(NSMenuItem(title: "Options", action: Selector( "openOptions"), keyEquivalent: "")) menu.addItem(NSMenuItem(title: "Quit", action: Selector("terminate:"), keyEquivalent: "")) StatusItem.menu = menu Options.getVolumeDevice() MASShortcutBinder.sharedBinder().bindShortcutWithDefaultsKey("GlobalShortcut") { () -> Void in self.openPopup() self.centerCursor() } } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func openOptions() { Options.optionsWindowController?.showWindow(self) } func openPopup() { Options.popupWindowController?.showWindow(self) } func centerCursor() { CGDisplayMoveCursorToPoint(0, Options.center) } }
gpl-2.0
taqun/TodoEver
TodoEver/Classes/Config/TDEConfig-Default.swift
1
281
// // TDEConfig.swift // TodoEver // // Created by taqun on 2015/05/27. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit class TDEConfig: NSObject { static let ENSDK_CONSUMER_KEY = "" static let ENSDK_CONSUMER_SECRET = "" }
mit
iachievedit/swiftysockets
Source/IP.swift
1
2419
// IP.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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 Tide import Glibc public enum IPMode { case IPV4 case IPV6 case IPV4Prefered case IPV6Prefered } extension IPMode { var code: Int32 { switch self { case .IPV4: return 1 case .IPV6: return 2 case .IPV4Prefered: return 3 case .IPV6Prefered: return 4 } } } public struct IP { let address: ipaddr public init(port: Int, mode: IPMode = .IPV4) throws { self.address = iplocal(nil, Int32(port), mode.code) if errno != 0 { let description = IPError.lastSystemErrorDescription throw IPError(description: description) } } public init(networkInterface: String, port: Int, mode: IPMode = .IPV4) throws { self.address = iplocal(networkInterface, Int32(port), mode.code) if errno != 0 { let description = IPError.lastSystemErrorDescription throw IPError(description: description) } } public init(address: String, port: Int, mode: IPMode = .IPV4) throws { self.address = ipremote(address, Int32(port), mode.code) if errno != 0 { let description = IPError.lastSystemErrorDescription throw IPError(description: description) } } }
mit
benlangmuir/swift
validation-test/stdlib/Slice/Slice_Of_MinimalRangeReplaceableBidirectionalCollection_WithSuffix.swift
21
3200
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var SliceTests = TestSuite("Collection") let prefix: [Int] = [] let suffix: [Int] = [] func makeCollection(elements: [OpaqueValue<Int>]) -> Slice<MinimalRangeReplaceableBidirectionalCollection<OpaqueValue<Int>>> { var baseElements = prefix.map(OpaqueValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(OpaqueValue.init)) let base = MinimalRangeReplaceableBidirectionalCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: prefix.count) let endIndex = base.index( base.startIndex, offsetBy: prefix.count + elements.count) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfEquatable(elements: [MinimalEquatableValue]) -> Slice<MinimalRangeReplaceableBidirectionalCollection<MinimalEquatableValue>> { var baseElements = prefix.map(MinimalEquatableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init)) let base = MinimalRangeReplaceableBidirectionalCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: prefix.count) let endIndex = base.index( base.startIndex, offsetBy: prefix.count + elements.count) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfComparable(elements: [MinimalComparableValue]) -> Slice<MinimalRangeReplaceableBidirectionalCollection<MinimalComparableValue>> { var baseElements = prefix.map(MinimalComparableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init)) let base = MinimalRangeReplaceableBidirectionalCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: prefix.count) let endIndex = base.index( base.startIndex, offsetBy: prefix.count + elements.count) return Slice(base: base, bounds: startIndex..<endIndex) } var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap SliceTests.addRangeReplaceableBidirectionalSliceTests( "Slice_Of_MinimalRangeReplaceableBidirectionalCollection_WithSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 ) runAllTests()
apache-2.0
benlangmuir/swift
test/Profiler/coverage_force_emission.swift
4
1587
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sil -module-name coverage_force_emission %s | %FileCheck %s -check-prefix=COVERAGE // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -emit-sil -module-name coverage_force_emission %s | %FileCheck %s -check-prefix=PGO // RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-ir %s final class VarInit { // COVERAGE: sil_coverage_map {{.*}} "$s23coverage_force_emission7VarInitC04lazydE033_7D375D72BA8B0C53C9AD7E4DBC7FF493LLSSvgSSyXEfU_" // PGO-LABEL: coverage_force_emission.VarInit.(lazyVarInit in _7D375D72BA8B0C53C9AD7E4DBC7FF493).getter : Swift.String // PGO: increment_profiler_counter private lazy var lazyVarInit: String = { return "Hello" }() // CHECK: sil_coverage_map {{.*}} "$s23coverage_force_emission7VarInitC05basicdE033_7D375D72BA8B0C53C9AD7E4DBC7FF493LLSSvpfiSSyXEfU_" // PGO-LABEL: closure #1 () -> Swift.String in variable initialization expression of coverage_force_emission.VarInit.(basicVarInit in _7D375D72BA8B0C53C9AD7E4DBC7FF493) : Swift.String // PGO: increment_profiler_counter private var basicVarInit: String = { return "Hello" }() // CHECK: sil_coverage_map {{.*}} "$s23coverage_force_emission7VarInitC06simpleD033_7D375D72BA8B0C53C9AD7E4DBC7FF493LLSSvg" // PGO-LABEL: coverage_force_emission.VarInit.(simpleVar in _7D375D72BA8B0C53C9AD7E4DBC7FF493).getter : Swift.String // PGO: increment_profiler_counter private var simpleVar: String { return "Hello" } }
apache-2.0
mozilla-mobile/firefox-ios
Extensions/ShareTo/ShareTheme.swift
2
1546
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit private enum ColorScheme { case dark case light } public struct ModernColor { var darkColor: UIColor var lightColor: UIColor public init(dark: UIColor, light: UIColor) { self.darkColor = dark self.lightColor = light } public var color: UIColor { return UIColor { (traitCollection: UITraitCollection) -> UIColor in if traitCollection.userInterfaceStyle == .dark { return self.color(for: .dark) } else { return self.color(for: .light) } } } private func color(for scheme: ColorScheme) -> UIColor { return scheme == .dark ? darkColor : lightColor } } struct ShareTheme { static let defaultBackground = ModernColor(dark: UIColor.Photon.Grey80, light: .white) static let doneLabelBackground = ModernColor(dark: UIColor.Photon.Blue40, light: UIColor.Photon.Blue40) static let separator = ModernColor(dark: UIColor.Photon.Grey10, light: UIColor.Photon.Grey30) static let actionRowTextAndIcon = ModernColor(dark: .white, light: UIColor.Photon.Grey80) static let textColor = ModernColor(dark: UIColor.Photon.LightGrey05, light: UIColor.Photon.DarkGrey90) static let iconColor = ModernColor(dark: UIColor.Photon.LightGrey05, light: UIColor.Photon.DarkGrey90) }
mpl-2.0
LinkRober/RBRefresh
custom/RBBallScaleHeader.swift
1
2452
// // RBBallScaleHeader.swift // RBRefresh // // Created by 夏敏 on 08/02/2017. // Copyright © 2017 夏敏. All rights reserved. // import UIKit class RBBallScaleHeader: UIView ,RBPullDownToRefreshViewDelegate{ override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(red: CGFloat(237 / 255.0), green: CGFloat(85 / 255.0), blue: CGFloat(101 / 255.0), alpha: 1) let layer = CAShapeLayer() let path = UIBezierPath() path.addArc(withCenter: CGPoint.init(x: 15, y: 15), radius: 15, startAngle: 0, endAngle: 2*CGFloat(M_PI), clockwise: false) layer.path = path.cgPath layer.fillColor = UIColor.white.cgColor layer.frame = CGRect.init(x: (frame.size.width - 30)/2, y: (frame.size.height - 30)/2, width: 30, height: 30) let animtaion = getAnimation() layer.add(animtaion, forKey: "animation") self.layer.addSublayer(layer) } func getAnimation() -> CAAnimationGroup { let duration:CFTimeInterval = 1 //scale let scaleAnimation = CABasicAnimation.init(keyPath: "transform.scale") scaleAnimation.fromValue = 0 scaleAnimation.toValue = 1 scaleAnimation.duration = duration //opacity let opacityAnimation = CABasicAnimation.init(keyPath: "opacity") opacityAnimation.fromValue = 1 opacityAnimation.toValue = 0 opacityAnimation.duration = duration //group let animationGroup = CAAnimationGroup() animationGroup.animations = [scaleAnimation,opacityAnimation] animationGroup.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut) animationGroup.duration = duration animationGroup.repeatCount = HUGE animationGroup.isRemovedOnCompletion = false return animationGroup } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func pullDownToRefreshAnimationDidEnd(_ view: RBHeader) { } func pullDownToRefreshAnimationDidStart(_ view: RBHeader) { } func pullDownToRefresh(_ view: RBHeader, progressDidChange progress: CGFloat) { } func pullDownToRefresh(_ view: RBHeader, stateDidChange state: RBPullDownToRefreshViewState) { } }
mit
cafielo/iOS_BigNerdRanch_5th
Chap6_WorldTrotter_bronze_silver_gold/WorldTrotter/WebViewController.swift
1
422
// // WebViewController.swift // WorldTrotter // // Created by Joonwon Lee on 7/23/16. // Copyright © 2016 Joonwon Lee. All rights reserved. // import UIKit class WebViewController: UIViewController { @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() webView.loadRequest(NSURLRequest(URL: NSURL(string: "https://www.bignerdranch.com")!)) } }
mit
wireapp/wire-ios
Templates/Viper/Module.xctemplate/___FILEBASENAME___Module.Router.swift
1
1186
// // Wire // Copyright (C) 2021 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 import UIKit extension ___VARIABLE_productName:identifier___Module { final class Router: RouterInterface { // MARK: - Properties weak var view: View! } } // MARK: - Perform action extension ___VARIABLE_productName:identifier___Module.Router: ___VARIABLE_productName:identifier___RouterPresenterInterface { func performAction(_ action: ___VARIABLE_productName:identifier___Module.Action) { switch action { } } }
gpl-3.0
jpavley/Emoji-Tac-Toe2
SimpleSynonymmer.swift
1
590
// // SimpleSynonymer.swift // Emoji Spy // // Created by John Pavley on 1/14/18. // Copyright © 2018 Epic Loot. All rights reserved. // import Foundation class SimpleSynonymmer: SimpleSubstituter { init(synonymMap: [String: String]) { super.init(substituteMap: synonymMap) } override init?(sourceFileName: String = "EmojiSynonyms") { super.init(sourceFileName: sourceFileName) //print(super.substituteMap) } func getSynonyms(for term: String) -> [String]? { return super.getSubstitutes(for: term) } }
mit
Noobish1/KeyedAPIParameters
KeyedAPIParameters/Protocols/ParamJSONKey.swift
1
250
import Foundation public protocol ParamJSONKey: RawRepresentable, Hashable, CaseIterable { var stringValue: String { get } } extension ParamJSONKey where RawValue == String { public var stringValue: String { return rawValue } }
mit
Monnoroch/Cuckoo
Generator/Dependencies/FileKit/Sources/ArrayFile.swift
1
1350
// // ArrayFile.swift // FileKit // // The MIT License (MIT) // // Copyright (c) 2015-2016 Nikolai Vazquez // // 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 /// A representation of a filesystem array file. /// /// The data type is NSArray. public typealias ArrayFile = File<NSArray>
mit
zullevig/ZAStyles
ZAStylesDemoTests/ZAStylesDemoTests.swift
1
1002
// // ZAStylesDemoTests.swift // ZAStylesDemoTests // // Created by Zachary Ullevig on 11/5/15. // Copyright © 2015 Zachary Ullevig. All rights reserved. // import XCTest @testable import ZAStylesDemo class ZAStylesDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // 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.measureBlock { // Put the code you want to measure the time of here. } } }
mit
petersthuang/FantasticView
FantasticView/AppDelegate.swift
1
2188
// // AppDelegate.swift // FantasticView // // Created by Peter_st Huang_黃士丁 on 5/11/17. // Copyright © 2017 TutorMing. 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:. } }
mit
shrtlist/MCSessionP2P
MCSessionP2P/AppDelegate.swift
1
976
/* * Copyright 2020 shrtlist@gmail.com * * 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 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } }
apache-2.0
DaveChambers/SuperCrack
SuperCrack!/ShowOnlyTicksButton.swift
1
621
// // ShowOnlyTicksButton.swift // Pegs in the Head // // Created by Dave Chambers on 27/07/2017. // Copyright © 2017 Dave Chambers. All rights reserved. // import UIKit class ShowOnlyTicksButton: UIButton { private var showingOnlyTicks: Bool func isShowingOnlyTicks() -> Bool { return showingOnlyTicks } func setShowingOnlyTicks(showingOnly: Bool) { showingOnlyTicks = showingOnly } required init() { self.showingOnlyTicks = false super.init(frame: .zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01944-swift-type-print.swift
1
264
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import Foundation struct A } extension NSSet { { { { } } { } } enum A { } enum a<T class A : a
mit
youknowone/Say
macOS/ViewController.swift
1
5842
// // ViewController.swift // Say // // Created by Jeong YunWon on 2015. 4. 10.. // Copyright (c) 2015년 youknowone.org. All rights reserved. // import Cocoa // import SayKit /// Main window of the application class MainWindow: NSWindow { @IBOutlet var speechToolbarItem: NSToolbarItem! = nil @IBOutlet var pauseToolbarItem: NSToolbarItem! = nil @IBOutlet var exportToolbarItem: NSToolbarItem! = nil @IBOutlet var openToolbarItem: NSToolbarItem! = nil @IBOutlet var stopToolbarItem: NSToolbarItem! = nil override func awakeFromNib() { /** Load data from cache in NSUserDefaults or from URL. * * Load data from cache in NSUserDefaults. If cache data doesn't exist * in NSUserDefaults with given tag, download data from URL and save * it to the given tag before loading. */ func syncronizedData(_ tag: String, URL: Foundation.URL) -> Data? { let standardUserDefaults = UserDefaults.standard guard let iconData = standardUserDefaults.object(forKey: tag) as? Data else { if let downloadedData = try? Data(contentsOf: URL) { standardUserDefaults.set(downloadedData, forKey: tag) standardUserDefaults.synchronize() return downloadedData } else { //print("Icon is not loadable!") return nil } } return iconData } super.awakeFromNib() if let imageData = syncronizedData("icon_speech", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/1/10/Exquisite-microphone.png")!) { self.speechToolbarItem.image = NSImage(data: imageData) } if let imageData = syncronizedData("icon_pause", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/5/57/Pause_icon_status.png")!) { self.pauseToolbarItem.image = NSImage(data: imageData) } if let imageData = syncronizedData("icon_export", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Gnome-generic-empty.svg/500px-Gnome-generic-empty.svg.png?uselang=ko")!) { self.exportToolbarItem.image = NSImage(data: imageData) } if let imageData = syncronizedData("icon_open", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Inkscape_icons_document_import.svg/500px-Inkscape_icons_document_import.svg.png?uselang=ko")!) { self.openToolbarItem.image = NSImage(data: imageData) } if let imageData = syncronizedData("icon_stop_", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/b/bf/Stop_icon_status.png")!) { self.stopToolbarItem.image = NSImage(data: imageData) } } } /// The controller for main view in main window class ViewController: NSViewController { /// Text view to speech @IBOutlet var textView: NSTextView! = nil /// Combo box for voices. Default is decided by system locale @IBOutlet var voiceComboBox: NSComboBox! = nil /// Save panel for "Export" menu @IBOutlet var URLField: NSTextField! = nil; let voiceSavePanel = NSSavePanel() /// Open panel for "Open" menu let textOpenPanel = NSOpenPanel() var api: SayAPI! = SayAPI(text: " ", voice: nil) var pause: Bool = false @available(OSX 10.10, *) override func viewDidLoad() { super.viewDidLoad() assert(self.textView != nil) assert(self.voiceComboBox != nil) self.voiceSavePanel.allowedFileTypes = ["aiff"] // default output format is aiff. See `man say` self.voiceComboBox.addItems(withObjectValues: VoiceAPI.voices.map({ "\($0.name)(\($0.locale)): \($0.comment)"; })) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } var textForSpeech: String { var selectedText = self.textView.string let selectedRange = self.textView.selectedRange() if selectedRange.length > 0 { selectedText = (selectedText as NSString).substring(with: selectedRange) } return selectedText } var selectedVoice: VoiceAPI? { get { let index = self.voiceComboBox.indexOfSelectedItem guard index >= 0 && index != NSNotFound else { return nil } return VoiceAPI.voices[index - 1] } } @IBAction func say(_ sender: NSToolbarItem) { guard api.isplaying() else { return } if self.pause { self.pause = false api.continueSpeaking() } else { api = SayAPI(text: self.textForSpeech, voice: self.selectedVoice) api.play(false) } } @IBAction func pause(_ sender: NSControl) { self.pause = true api.pause() } @IBAction func stop(_ sender: NSControl) { self.pause = false api.stop() } @IBAction func saveDocumentAs(_ sender: NSControl) { self.voiceSavePanel.runModal() guard let fileURL = self.voiceSavePanel.url else { return } let say = SayAPI(text: self.textForSpeech, voice: self.selectedVoice) say.writeToURL(fileURL, atomically: true) } @IBAction func openTextFile(_ sender: NSControl) { self.textOpenPanel.runModal() guard let textURL = self.textOpenPanel.url else { // No given URL return } guard let text = try? String(contentsOf: textURL, encoding: .utf8) else { // No utf-8 data in the URL return } self.textView.string = text } }
gpl-3.0
DaveChambers/SuperCrack
SuperCrack!/SettingsViewController.swift
1
963
// // SettingsViewController.swift // Pegs in the Head // // Created by Dave Chambers on 04/07/2017. // Copyright © 2017 Dave Chambers. All rights reserved. // import UIKit import Foundation class SettingsViewController: UIViewController { var game: GameModel! var settings: Settings! var dimensions: GameDimensions! var setView: SettingsView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.title = "Settings" let pegboardVC = tabBarController?.viewControllers?[0] as! PegboardViewController setView = SettingsView(frame: self.view.frame, game: game, dimensions: pegboardVC.dimensions) self.view.addSubview(setView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var prefersStatusBarHidden: Bool { return true } }
mit
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Event Detail/Presenter Tests/WhenBindingEventSummary_EventDetailPresenterShould.swift
1
2358
@testable import Eurofurence import EurofurenceModel import EurofurenceModelTestDoubles import XCTest class WhenBindingEventSummary_EventDetailPresenterShould: XCTestCase { var context: EventDetailPresenterTestBuilder.Context! var summary: EventSummaryViewModel! var index: Int! var viewModel: StubEventSummaryViewModel! var boundComponent: Any? override func setUp() { super.setUp() let event = FakeEvent.random summary = .random index = .random viewModel = StubEventSummaryViewModel(summary: summary, at: index) let interactor = FakeEventDetailInteractor(viewModel: viewModel, for: event) context = EventDetailPresenterTestBuilder().with(interactor).build(for: event) context.simulateSceneDidLoad() boundComponent = context.scene.bindComponent(at: IndexPath(item: index, section: 0)) } func testTellTheSceneToBindTheExpectedNumberOfComponents() { XCTAssertEqual(viewModel.numberOfComponents, context.scene.numberOfBoundsComponents) } func testApplyTheTitleOntoTheScene() { XCTAssertEqual(summary.title, context.scene.stubbedEventSummaryComponent.capturedTitle) } func testApplyTheSubtitleOntoTheScene() { XCTAssertEqual(summary.subtitle, context.scene.stubbedEventSummaryComponent.capturedSubtitle) } func testApplyTheAbstractOntoTheScene() { XCTAssertEqual(summary.abstract, context.scene.stubbedEventSummaryComponent.capturedAbstract) } func testApplyTheEventStartTimeOntoTheScene() { XCTAssertEqual(summary.eventStartEndTime, context.scene.stubbedEventSummaryComponent.capturedEventStartTime) } func testApplyTheEventLocationOntoTheScene() { XCTAssertEqual(summary.location, context.scene.stubbedEventSummaryComponent.capturedEventLocation) } func testApplyTheTrackNameOntoTheScene() { XCTAssertEqual(summary.trackName, context.scene.stubbedEventSummaryComponent.capturedTrackName) } func testApplyTheEventHostsOntoTheScene() { XCTAssertEqual(summary.eventHosts, context.scene.stubbedEventSummaryComponent.capturedEventHosts) } func testReturnTheBoundEventSummaryComponent() { XCTAssertTrue((boundComponent as? CapturingEventSummaryComponent) === context.scene.stubbedEventSummaryComponent) } }
mit
takamashiro/XDYZB
XDYZB/XDYZB/Classes/LiveMySelf/LiveMySelfViewController.swift
1
8198
// // LiveMySelfViewController.swift // XLiveDemo // // Created by takamashiro on 2016/11/11. // Copyright © 2016年 com.takamashiro. All rights reserved. // import UIKit import LFLiveKit class LiveMySelfViewController: UIViewController { //MARK: - Getters and Setters //  默认分辨率368 * 640 音频:44.1 iphone6以上48 双声道 方向竖屏 var session: LFLiveSession = { let audioConfiguration = LFLiveAudioConfiguration.defaultConfiguration(for: LFLiveAudioQuality.high) let videoConfiguration = LFLiveVideoConfiguration.defaultConfiguration(for: LFLiveVideoQuality.low3) let session = LFLiveSession(audioConfiguration: audioConfiguration, videoConfiguration: videoConfiguration) return session! }() // 视图 var containerView: UIView = { let containerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) containerView.backgroundColor = UIColor.clear containerView.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleHeight] return containerView }() // 状态Label var stateLabel: UILabel = { let stateLabel = UILabel(frame: CGRect(x: 20, y: 20, width: 80, height: 40)) stateLabel.text = "未连接" stateLabel.textColor = UIColor.white stateLabel.font = UIFont.systemFont(ofSize: 14) return stateLabel }() // 关闭按钮 var closeButton: UIButton = { let closeButton = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 10 - 44, y: 20, width: 44, height: 44)) closeButton.setImage(UIImage(named: "close_preview"), for: UIControlState()) return closeButton }() // 摄像头 var cameraButton: UIButton = { let cameraButton = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 54 * 2, y: 20, width: 44, height: 44)) cameraButton.setImage(UIImage(named: "camra_preview"), for: UIControlState()) return cameraButton }() // 摄像头 var beautyButton: UIButton = { let beautyButton = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 54 * 3, y: 20, width: 44, height: 44)) beautyButton.setImage(UIImage(named: "camra_beauty"), for: UIControlState.selected) beautyButton.setImage(UIImage(named: "camra_beauty_close"), for: UIControlState()) return beautyButton }() // 开始直播按钮 var startLiveButton: UIButton = { let startLiveButton = UIButton(frame: CGRect(x: 30, y: UIScreen.main.bounds.height - 60, width: UIScreen.main.bounds.width - 10 - 44, height: 44)) startLiveButton.layer.cornerRadius = 22 startLiveButton.setTitleColor(UIColor.black, for:UIControlState()) startLiveButton.setTitle("开始直播", for: UIControlState()) startLiveButton.titleLabel!.font = UIFont.systemFont(ofSize: 14) startLiveButton.backgroundColor = UIColor(colorLiteralRed: 50, green: 32, blue: 245, alpha: 1) return startLiveButton }() override func viewDidLoad() { super.viewDidLoad() session.delegate = self session.preView = self.view self.requestAccessForVideo() self.requestAccessForAudio() self.view.backgroundColor = UIColor.clear self.view.addSubview(containerView) containerView.addSubview(stateLabel) containerView.addSubview(closeButton) containerView.addSubview(beautyButton) containerView.addSubview(cameraButton) containerView.addSubview(startLiveButton) cameraButton.addTarget(self, action: #selector(didTappedCameraButton(_:)), for:.touchUpInside) beautyButton.addTarget(self, action: #selector(didTappedBeautyButton(_:)), for: .touchUpInside) startLiveButton.addTarget(self, action: #selector(didTappedStartLiveButton(_:)), for: .touchUpInside) closeButton.addTarget(self, action: #selector(didTappedCloseButton(_:)), for: .touchUpInside) } deinit { print(#function) } //MARK: - Events // 开始直播 func didTappedStartLiveButton(_ button: UIButton) -> Void { startLiveButton.isSelected = !startLiveButton.isSelected; if (startLiveButton.isSelected) { startLiveButton.setTitle("结束直播", for: UIControlState()) let stream = LFLiveStreamInfo() stream.url = "rtmp://172.20.10.2:1935/rtmplive/room" session.startLive(stream) } else { startLiveButton.setTitle("开始直播", for: UIControlState()) session.stopLive() } } // 美颜 func didTappedBeautyButton(_ button: UIButton) -> Void { session.beautyFace = !session.beautyFace; beautyButton.isSelected = !session.beautyFace } // 摄像头 func didTappedCameraButton(_ button: UIButton) -> Void { let devicePositon = session.captureDevicePosition; session.captureDevicePosition = (devicePositon == AVCaptureDevicePosition.back) ? AVCaptureDevicePosition.front : AVCaptureDevicePosition.back; } // 关闭 func didTappedCloseButton(_ button: UIButton) -> Void { dismiss(animated: true, completion: nil) } } extension LiveMySelfViewController { //MARK: AccessAuth func requestAccessForVideo() -> Void { let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo); switch status { // 许可对话没有出现,发起授权许可 case AVAuthorizationStatus.notDetermined: AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted) in if(granted){ DispatchQueue.main.async { self.session.running = true } } }) break; // 已经开启授权,可继续 case AVAuthorizationStatus.authorized: session.running = true; break; // 用户明确地拒绝授权,或者相机设备无法访问 case AVAuthorizationStatus.denied: break case AVAuthorizationStatus.restricted:break; } } func requestAccessForAudio() -> Void { let status = AVCaptureDevice.authorizationStatus(forMediaType:AVMediaTypeAudio) switch status { // 许可对话没有出现,发起授权许可 case AVAuthorizationStatus.notDetermined: AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeAudio, completionHandler: { (granted) in }) break; // 已经开启授权,可继续 case AVAuthorizationStatus.authorized: break; // 用户明确地拒绝授权,或者相机设备无法访问 case AVAuthorizationStatus.denied: break case AVAuthorizationStatus.restricted:break; } } } //相机,麦克风授权 extension LiveMySelfViewController : LFLiveSessionDelegate { /** live status changed will callback */ func liveSession(_ session: LFLiveSession?, liveStateDidChange state: LFLiveState) { print("liveStateDidChange: \(state.rawValue)") switch state { case LFLiveState.ready: stateLabel.text = "未连接" break; case LFLiveState.pending: stateLabel.text = "连接中" break; case LFLiveState.start: stateLabel.text = "已连接" break; case LFLiveState.error: stateLabel.text = "连接错误" break; case LFLiveState.stop: stateLabel.text = "未连接" break; } } /** live debug info callback */ func liveSession(_ session: LFLiveSession?, debugInfo: LFLiveDebug?) { print("debugInfo: \(debugInfo?.currentBandwidth)") } /** callback socket errorcode */ func liveSession(_ session: LFLiveSession?, errorCode: LFLiveSocketErrorCode) { print("errorCode: \(errorCode.rawValue)") } }
mit
mohssenfathi/MTLImage
MTLImage/Sources/Filters/DepthToGrayscale.swift
1
1525
// // DepthToGrayscale.swift // Pods // // Created by Mohssen Fathi on 6/8/17. // struct DepthToGrayscaleUniforms: Uniforms { var offset: Float = 0.5 var range: Float = 0.5 } public class DepthToGrayscale: Filter { var uniforms = DepthToGrayscaleUniforms() @objc public var offset: Float = 0.5 { didSet { // clamp(&offset, low: 0, high: 1) needsUpdate = true } } @objc public var range: Float = 0.5 { didSet { // clamp(&range, low: 0, high: 1) needsUpdate = true } } public init() { super.init(functionName: "depthToGrayscale") title = "Depth To Grayscale" properties = [ Property(key: "offset", title: "Offset"), Property(key: "range", title: "Range") ] } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func update() { if self.input == nil { return } uniforms.offset = offset uniforms.range = range updateUniforms(uniforms: uniforms) } override func configureCommandEncoder(_ commandEncoder: MTLComputeCommandEncoder) { super.configureCommandEncoder(commandEncoder) if let context = (source as? Camera)?.depthContext { if context.minDepth < offset { offset = context.minDepth } if context.maxDepth < range { range = context.maxDepth } } } }
mit
invalidstream/cocoaconfappextensionsclass
CocoaConf App Extensions Class/CocoaConfExtensions_04_PhotoEditing_End/CocoaConf Photo Editing/PhotoEditingViewController.swift
1
3150
// // PhotoEditingViewController.swift // CocoaConf Photo Editing // // Created by Chris Adamson on 3/25/15. // Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved. // import UIKit import Photos import PhotosUI class PhotoEditingViewController: UIViewController, PHContentEditingController { var pixellateFilter: CIFilter! var input: PHContentEditingInput? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // CREATE CIFILTER // TODO: WRITE IN CLASS } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // APPLY FILTER // TODO: WRITE IN CLASS // MARK: - PHContentEditingController func canHandleAdjustmentData(adjustmentData: PHAdjustmentData?) -> Bool { // Inspect the adjustmentData to determine whether your extension can work with past edits. // (Typically, you use its formatIdentifier and formatVersion properties to do this.) return false } func startContentEditingWithInput(contentEditingInput: PHContentEditingInput?, placeholderImage: UIImage) { // Present content for editing, and keep the contentEditingInput for use when closing the edit session. // If you returned YES from canHandleAdjustmentData:, contentEditingInput has the original image and adjustment data. // If you returned NO, the contentEditingInput has past edits "baked in". input = contentEditingInput // UPDATE UI // TODO: WRITE IN CLASS } func finishContentEditingWithCompletionHandler(completionHandler: ((PHContentEditingOutput!) -> Void)!) { // Update UI to reflect that editing has finished and output is being rendered. // Render and provide output on a background queue. dispatch_async(dispatch_get_global_queue(CLong(DISPATCH_QUEUE_PRIORITY_DEFAULT), 0)) { // Create editing output from the editing input. let output = PHContentEditingOutput(contentEditingInput: self.input!) // Provide new adjustments and render output to given location. // output.adjustmentData = <#new adjustment data#> // let renderedJPEGData = <#output JPEG#> // renderedJPEGData.writeToURL(output.renderedContentURL, atomically: true) // TODO: WRITE IN CLASS // Call completion handler to commit edit to Photos. completionHandler?(output) // Clean up temporary files, etc. } } var shouldShowCancelConfirmation: Bool { // Determines whether a confirmation to discard changes should be shown to the user on cancel. // (Typically, this should be "true" if there are any unsaved changes.) return false } func cancelContentEditing() { // Clean up temporary files, etc. // May be called after finishContentEditingWithCompletionHandler: while you prepare output. } }
cc0-1.0
SwiftKit/Torch
Generator/Tests/SourceFiles/Expected/MultipleData.swift
1
1813
// MARK: - Torch entity extensions generated from file: ../../Tests/SourceFiles/MultipleData.swift import Torch import CoreData internal extension Data { internal static var torch_name: String { return "UserProject_Data" } internal static let id = Torch.Property<Data, Int?>(name: "id") internal init(fromManagedObject object: Torch.NSManagedObjectWrapper) throws { id = object.getValue(Data.id) } internal mutating func torch_updateManagedObject(object: Torch.NSManagedObjectWrapper) throws { object.setValue(id, for: Data.id) } internal static func torch_describeEntity(to registry: Torch.EntityRegistry) { registry.description(of: Data.self) } internal static func torch_describeProperties(to registry: Torch.PropertyRegistry) { registry.description(of: Data.id) } } internal extension Data2 { internal static var torch_name: String { return "UserProject_Data2" } internal static let id = Torch.Property<Data2, Int?>(name: "id") internal init(fromManagedObject object: Torch.NSManagedObjectWrapper) throws { id = object.getValue(Data2.id) } internal mutating func torch_updateManagedObject(object: Torch.NSManagedObjectWrapper) throws { object.setValue(id, for: Data2.id) } internal static func torch_describeEntity(to registry: Torch.EntityRegistry) { registry.description(of: Data2.self) } internal static func torch_describeProperties(to registry: Torch.PropertyRegistry) { registry.description(of: Data2.id) } } internal struct UserProjectEntityBundle: Torch.TorchEntityBundle { internal let entityTypes: [Torch.TorchEntity.Type] = [ Data.self, Data2.self, ] internal init() { } }
mit
ekranac/FoodPin
FoodPin/ReviewViewController.swift
1
2028
// // ReviewViewController.swift // FoodPin // // Created by Ziga Besal on 09/01/2017. // Copyright © 2017 Ziga Besal. All rights reserved. // import UIKit class ReviewViewController: UIViewController { @IBOutlet var backgroundImageView: UIImageView! @IBOutlet var containerView: UIView! @IBOutlet var containerImage: UIImageView! @IBOutlet var btnClose: UIButton! var restaurant: RestaurantMO! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. containerImage.image = UIImage(data: restaurant.image as! Data) let blurEffect = UIBlurEffect(style: .dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds backgroundImageView.addSubview(blurEffectView) let scaleTransform = CGAffineTransform.init(scaleX: 0, y: 0) let translateTransform = CGAffineTransform.init(translationX: 0, y: -1000) let combineTransform = scaleTransform.concatenating(translateTransform) containerView.transform = combineTransform btnClose.transform = CGAffineTransform.init(translationX: 1000, y: 0) } override func viewDidAppear(_ animated: Bool) { UIView.animate(withDuration: 0.7, animations: { self.containerView.transform = CGAffineTransform.identity self.btnClose.transform = CGAffineTransform.identity }) } 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. } */ }
gpl-3.0
sbcmadn1/swift
swiftweibo05/GZWeibo05/Class/Module/Compose/Controller/CZComposeViewController.swift
2
16221
// // CZComposeViewController.swift // GZWeibo05 // // Created by zhangping on 15/11/3. // Copyright © 2015年 zhangping. All rights reserved. // import UIKit import SVProgressHUD class CZComposeViewController: UIViewController { // MARK: - 属性 /// toolBar底部约束 private var toolBarBottomCon: NSLayoutConstraint? /// 照片选择器控制器view的底部约束 private var photoSelectorViewBottomCon: NSLayoutConstraint? /// 微博内容的最大长度 private let statusMaxLength = 20 override func viewDidLoad() { super.viewDidLoad() // 需要设置背景颜色,不然弹出时动画有问题 view.backgroundColor = UIColor.whiteColor() prepareUI() // 添加键盘frame改变的通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } /* notification:NSConcreteNotification 0x7f8fea5a4e20 {name = UIKeyboardDidChangeFrameNotification; userInfo = { UIKeyboardAnimationCurveUserInfoKey = 7; UIKeyboardAnimationDurationUserInfoKey = "0.25"; // 动画时间 UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}"; UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}"; UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}"; UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}"; UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}"; // 键盘最终的位置 UIKeyboardIsLocalUserInfoKey = 1; }} */ /// 键盘frame改变 func willChangeFrame(notification: NSNotification) { // print("notification:\(notification)") // 获取键盘最终位置 let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue // 动画时间 let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval toolBarBottomCon?.constant = -(UIScreen.height() - endFrame.origin.y) UIView.animateWithDuration(duration) { () -> Void in // 不能直接更新toolBar的约束 // self.toolBar.layoutIfNeeded() self.view.layoutIfNeeded() } } // MARK: - 准备UI private func prepareUI() { // 添加子控件 view.addSubview(textView) view.addSubview(photoSelectorVC.view) view.addSubview(toolBar) view.addSubview(lengthTipLabel) setupNavigationBar() setupTextView() preparePhotoSelectorView() setupToolBar() prepareLengthTipLabel() } // override func viewWillAppear(animated: Bool) { // super.viewWillAppear(animated) // // // 弹出键盘 // textView.becomeFirstResponder() // } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 10)) // view.backgroundColor = UIColor.redColor() // textView.inputView = view // 自定义键盘其实就是给 textView.inputView 赋值 // 如果照片选择器的view没有显示就弹出键盘 if photoSelectorViewBottomCon?.constant != 0 { textView.becomeFirstResponder() } } /// 设置导航栏 private func setupNavigationBar() { // 设置按钮, 左边 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close") // 右边 navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus") navigationItem.rightBarButtonItem?.enabled = false setupTitleView() } /// 设置toolBar private func setupToolBar() { // 添加约束 let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width(), height: 44)) // 获取底部约束 toolBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom) // 创建toolBar item var items = [UIBarButtonItem]() // 每个item对应的图片名称 let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"], ["imageName": "compose_trendbutton_background", "action": "trend"], ["imageName": "compose_mentionbutton_background", "action": "mention"], ["imageName": "compose_emoticonbutton_background", "action": "emoticon"], ["imageName": "compose_addbutton_background", "action": "add"]] var index = 0 // 遍历 itemSettings 获取图片名称,创建items for dict in itemSettings { // 获取图片的名称 let imageName = dict["imageName"]! // 获取图片对应点点击方法名称 let action = dict["action"]! let item = UIBarButtonItem(imageName: imageName) // 获取item里面的按钮 let button = item.customView as! UIButton button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside) items.append(item) // 添加弹簧 items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)) index++ } // 移除最后一个弹簧 items.removeLast() toolBar.items = items } /// 设置导航栏标题 private func setupTitleView() { let prefix = "发微博" // 获取用户的名称 if let name = CZUserAccount.loadAccount()?.name { // 有用户名 let titleName = prefix + "\n" + name // 创建可变的属性文本 let attrString = NSMutableAttributedString(string: titleName) // 创建label let label = UILabel() // 设置属性文本 label.numberOfLines = 0 label.textAlignment = NSTextAlignment.Center label.font = UIFont.systemFontOfSize(14) // 获取NSRange let nameRange = (titleName as NSString).rangeOfString(name) // 设置属性文本的属性 attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: nameRange) attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange) // 顺序不要搞错 label.attributedText = attrString label.sizeToFit() navigationItem.titleView = label } else { // 没有用户名 navigationItem.title = prefix } } /// 设置textView private func setupTextView() { /* 前提: 1.scrollView所在的控制器属于某个导航控制器 2.scrollView控制器的view或者控制器的view的第一个子view */ // scrollView会自动设置Insets, 比如scrollView所在的控制器属于某个导航控制器contentInset.top = 64 // automaticallyAdjustsScrollViewInsets = true // 添加约束 // 相对控制器的view的内部左上角 textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil) // 相对toolBar顶部右上角 textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil) } /// 准备 显示微博剩余长度 label func prepareLengthTipLabel() { // 添加约束 lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8)) } /// 准备 照片选择器 func preparePhotoSelectorView() { // 照片选择器控制器的view let photoSelectorView = photoSelectorVC.view photoSelectorView.translatesAutoresizingMaskIntoConstraints = false let views = ["psv": photoSelectorView] // 添加约束 // 水平 view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) // 高度 view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0)) // 底部重合,偏移photoSelectorView的高度 photoSelectorViewBottomCon = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.frame.height * 0.6) view.addConstraint(photoSelectorViewBottomCon!) } // MARK: - 按钮点击事件 func picture() { print("图片") // 让照片选择器的view移动上来 photoSelectorViewBottomCon?.constant = 0 // 退下键盘 textView.resignFirstResponder() UIView.animateWithDuration(0.25) { () -> Void in self.view.layoutIfNeeded() } } func trend() { print("#") } func mention() { print("@") } /* 1.textView.inputView == nil 弹出的是系统的键盘 2.正在显示的时候设置 textView.inputView 不会立马起效果 3.在弹出来之前判断使用什么键盘 */ /// 切换表情键盘 func emoticon() { print("切换前表情键盘:\(textView.inputView)") // 先让键盘退回去 textView.resignFirstResponder() // 延时0.25 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in // 如果inputView == nil 使用的是系统的键盘,切换到自定的键盘 // 如果inputView != nil 使用的是自定义键盘,切换到系统的键盘 self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil // 弹出键盘 self.textView.becomeFirstResponder() print("切换后表情键盘:\(self.textView.inputView)") } } func add() { print("加号") } /// toolBar item点击事件 // func itemClick(button: UIButton) { // print(button.tag) // switch button.tag { // case 0: // print("图片") // case 1: // print("#") // case 2: // print("@") // case 3: // print("表情") // case 4: // print("加号") // default: // print("没有这个按钮") // } // } /// 关闭控制器 @objc private func close() { // 关闭键盘 textView.resignFirstResponder() // 关闭sv提示 SVProgressHUD.dismiss() dismissViewControllerAnimated(true, completion: nil) } /// 发微博 func sendStatus() { // 获取textView的文本内容发送给服务器 let text = textView.emoticonText() // 判断微博内容的长度 < 0 不发送 let statusLength = text.characters.count if statusMaxLength - statusLength < 0 { // 微博内容超出,提示用户 SVProgressHUD.showErrorWithStatus("微博长度超出", maskType: SVProgressHUDMaskType.Black) return } // 获取图片选择器中的图片 let image = photoSelectorVC.photos.first // 显示正在发送 SVProgressHUD.showWithStatus("正在发布微博...", maskType: SVProgressHUDMaskType.Black) // 发送微博 CZNetworkTools.sharedInstance.sendStatus(image, status: text) { (result, error) -> () in if error != nil { print("error:\(error)") SVProgressHUD.showErrorWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black) return } // 发送成功, 直接关闭界面 self.close() } } // MARK: - 懒加载 /// toolBar private lazy var toolBar: UIToolbar = { let toolBar = UIToolbar() toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1) return toolBar }() /* iOS中可以让用户输入的控件: 1.UITextField: 1.只能显示一行 2.可以有占位符 3.不能滚动 2.UITextView: 1.可以显示多行 2.没有占位符 3.继承UIScrollView,可以滚动 */ /// textView private lazy var textView: CZPlaceholderTextView = { let textView = CZPlaceholderTextView() // 当textView被拖动的时候就会将键盘退回,textView能拖动 textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag textView.font = UIFont.systemFontOfSize(18) textView.backgroundColor = UIColor.brownColor() textView.textColor = UIColor.blackColor() textView.bounces = true textView.alwaysBounceVertical = true // 设置占位文本 textView.placeholder = "分享新鲜事..." // 设置顶部的偏移 // textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0) // 设置控制器作为textView的代理来监听textView文本的改变 textView.delegate = self return textView }() /// 表情键盘控制器 private lazy var emoticonVC: CZEmoticonViewController = { let controller = CZEmoticonViewController() // 设置textView controller.textView = self.textView return controller }() /// 显示微博剩余长度 private lazy var lengthTipLabel: UILabel = { let label = UILabel(fonsize: 12, textColor: UIColor.lightGrayColor()) // 设置默认的长度 label.text = String(self.statusMaxLength) return label }() /// 照片选择器的控制器 private lazy var photoSelectorVC: CZPhotoSelectorViewController = { let controller = CZPhotoSelectorViewController() // 让照片选择控制器被被人管理 self.addChildViewController(controller) return controller }() } extension CZComposeViewController: UITextViewDelegate { /// textView文本改变的时候调用 func textViewDidChange(textView: UITextView) { // 当textView 有文本的时候,发送按钮可用, // 当textView 没有文本的时候,发送按钮不可用 navigationItem.rightBarButtonItem?.enabled = textView.hasText() // 计算剩余微博的长度 let statusLength = textView.emoticonText().characters.count // 剩余长度 let length = statusMaxLength - statusLength lengthTipLabel.text = String(length) // 判断 length 大于等于0显示灰色, 小于0显示红色 lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor() } }
mit
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/Foundation/NSNotificationCenter+Rx.swift
32
1072
// // NSNotificationCenter+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 5/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif extension Reactive where Base: NotificationCenter { /** Transforms notifications posted to notification center to observable sequence of notifications. - parameter name: Optional name used to filter notifications. - parameter object: Optional object used to filter notifications. - returns: Observable sequence of posted notifications. */ public func notification(_ name: Notification.Name?, object: AnyObject? = nil) -> Observable<Notification> { return Observable.create { [weak object] observer in let nsObserver = self.base.addObserver(forName: name, object: object, queue: nil) { notification in observer.on(.next(notification)) } return Disposables.create { self.base.removeObserver(nsObserver) } } } }
apache-2.0
viczy/SwiftForward
SwiftForward/SFArrayDataSource.swift
1
1364
// // SFArrayDataSource.swift // SwiftForward // // Created by Vic Zhou on 3/18/15. // Copyright (c) 2015 everycode. All rights reserved. // import UIKit typealias CellConfigureBlock = (UITableViewCell, AnyObject) -> Void class SFArrayDataSource: NSObject, UITableViewDataSource { //MARK:Property var items:NSArray? var cellIdentifier:String? var configureCellBlock:CellConfigureBlock? override init() { super.init() } //MARK:Init convenience init(items anItems:NSArray?, cellIdentifier aCellidentifier:String?, configureCellBlock aConfigureCellBlock:CellConfigureBlock?) { self.init(); self.items = anItems self.cellIdentifier = aCellidentifier self.configureCellBlock = aConfigureCellBlock } //MARK:UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier!, forIndexPath: indexPath) as? UITableViewCell if let myItems = items { var item:AnyObject = myItems[indexPath.row] configureCellBlock!(cell!, item) } return cell! } }
apache-2.0
KeithPiTsui/Pavers
Pavers/Sources/CryptoSwift/SecureBytes.swift
2
2362
// // SecureBytes.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // #if os(Linux) || os(Android) || os(FreeBSD) import Glibc #else import Darwin #endif typealias Key = SecureBytes /// Keeps bytes in memory. Because this is class, bytes are not copied /// and memory area is locked as long as referenced, then unlocked on deinit final class SecureBytes { fileprivate let bytes: Array<UInt8> let count: Int init(bytes: Array<UInt8>) { self.bytes = bytes count = bytes.count self.bytes.withUnsafeBufferPointer { (pointer) -> Void in mlock(pointer.baseAddress, pointer.count) } } deinit { self.bytes.withUnsafeBufferPointer { (pointer) -> Void in munlock(pointer.baseAddress, pointer.count) } } } extension SecureBytes: Collection { typealias Index = Int var endIndex: Int { return bytes.endIndex } var startIndex: Int { return bytes.startIndex } subscript(position: Index) -> UInt8 { return bytes[position] } subscript(bounds: Range<Index>) -> ArraySlice<UInt8> { return bytes[bounds] } func formIndex(after i: inout Int) { bytes.formIndex(after: &i) } func index(after i: Int) -> Int { return bytes.index(after: i) } } extension SecureBytes: ExpressibleByArrayLiteral { public convenience init(arrayLiteral elements: UInt8...) { self.init(bytes: elements) } }
mit
guidouil/TouchBarBar
TouchBarBar/AppDelegate.swift
1
496
// // AppDelegate.swift // TouchBarBar // // Created by Guidouil on 10/29/16. // Copyright © 2016 Guidouil. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
mit
eoger/firefox-ios
Shared/AsyncReducer.swift
3
4364
/* 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 Foundation import Deferred public let DefaultDispatchQueue = DispatchQueue.global(qos: DispatchQoS.default.qosClass) public func asyncReducer<T, U>(_ initialValue: T, combine: @escaping (T, U) -> Deferred<Maybe<T>>) -> AsyncReducer<T, U> { return AsyncReducer(initialValue: initialValue, combine: combine) } /** * A appendable, async `reduce`. * * The reducer starts empty. New items need to be `append`ed. * * The constructor takes an `initialValue`, a `dispatch_queue_t`, and a `combine` function. * * The reduced value can be accessed via the `reducer.terminal` `Deferred<Maybe<T>>`, which is * run once all items have been combined. * * The terminal will never be filled if no items have been appended. * * Once the terminal has been filled, no more items can be appended, and `append` methods will error. */ open class AsyncReducer<T, U> { // T is the accumulator. U is the input value. The returned T is the new accumulated value. public typealias Combine = (T, U) -> Deferred<Maybe<T>> fileprivate let lock = NSRecursiveLock() private let dispatchQueue: DispatchQueue private let combine: Combine private let initialValueDeferred: Deferred<Maybe<T>> open let terminal: Deferred<Maybe<T>> = Deferred() private var queuedItems: [U] = [] private var isStarted: Bool = false /** * Has this task queue finished? * Once the task queue has finished, it cannot have more tasks appended. */ open var isFilled: Bool { lock.lock() defer { lock.unlock() } return terminal.isFilled } public convenience init(initialValue: T, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) { self.init(initialValue: deferMaybe(initialValue), queue: queue, combine: combine) } public init(initialValue: Deferred<Maybe<T>>, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) { self.dispatchQueue = queue self.combine = combine self.initialValueDeferred = initialValue } // This is always protected by a lock, so we don't need to // take another one. fileprivate func ensureStarted() { if self.isStarted { return } func queueNext(_ deferredValue: Deferred<Maybe<T>>) { deferredValue.uponQueue(dispatchQueue, block: continueMaybe) } func nextItem() -> U? { // Because popFirst is only available on array slices. // removeFirst is fine for range-replaceable collections. return queuedItems.isEmpty ? nil : queuedItems.removeFirst() } func continueMaybe(_ res: Maybe<T>) { lock.lock() defer { lock.unlock() } if res.isFailure { self.queuedItems.removeAll() self.terminal.fill(Maybe(failure: res.failureValue!)) return } let accumulator = res.successValue! guard let item = nextItem() else { self.terminal.fill(Maybe(success: accumulator)) return } let combineItem = deferDispatchAsync(dispatchQueue) { return self.combine(accumulator, item) } queueNext(combineItem) } queueNext(self.initialValueDeferred) self.isStarted = true } /** * Append one or more tasks onto the end of the queue. * * @throws AlreadyFilled if the queue has finished already. */ open func append(_ items: U...) throws -> Deferred<Maybe<T>> { return try append(items) } /** * Append a list of tasks onto the end of the queue. * * @throws AlreadyFilled if the queue has already finished. */ open func append(_ items: [U]) throws -> Deferred<Maybe<T>> { lock.lock() defer { lock.unlock() } if terminal.isFilled { throw ReducerError.alreadyFilled } queuedItems.append(contentsOf: items) ensureStarted() return terminal } } enum ReducerError: Error { case alreadyFilled }
mpl-2.0
SAP/IssieBoard
ConfigurableKeyboard/KeyboardViewController.swift
1
17771
import UIKit import AudioToolbox class KeyboardViewController: UIInputViewController { let backspaceDelay: NSTimeInterval = 0.5 let backspaceRepeat: NSTimeInterval = 0.07 var keyboard: Keyboard! var forwardingView: ForwardingView! var layout: KeyboardLayout? var heightConstraint: NSLayoutConstraint? var settingsView: ExtraView? var currentMode: Int { didSet { if oldValue != currentMode { setMode(currentMode) } } } var backspaceActive: Bool { get { return (backspaceDelayTimer != nil) || (backspaceRepeatTimer != nil) } } var backspaceDelayTimer: NSTimer? var backspaceRepeatTimer: NSTimer? enum AutoPeriodState { case NoSpace case FirstSpace } var autoPeriodState: AutoPeriodState = .NoSpace var lastCharCountInBeforeContext: Int = 0 var keyboardHeight: CGFloat { get { if let constraint = self.heightConstraint { return constraint.constant } else { return 0 } } set { self.setHeight(newValue) } } convenience init() { self.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.keyboard = standardKeyboard() self.currentMode = 0 super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.forwardingView = ForwardingView(frame: CGRectZero) self.view.addSubview(self.forwardingView) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("defaultsChanged:"), name: NSUserDefaultsDidChangeNotification, object: nil) } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } deinit { backspaceDelayTimer?.invalidate() backspaceRepeatTimer?.invalidate() NSNotificationCenter.defaultCenter().removeObserver(self) } func defaultsChanged(notification: NSNotification) { var defaults = notification.object as! NSUserDefaults defaults.synchronize() defaults = NSUserDefaults.standardUserDefaults() var i : Int = defaults.integerForKey("defaultBackgroundColor") defaults.synchronize() } var kludge: UIView? func setupKludge() { if self.kludge == nil { let kludge = UIView() self.view.addSubview(kludge) kludge.translatesAutoresizingMaskIntoConstraints = false kludge.hidden = true let a = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) let b = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) let c = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) let d = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) self.view.addConstraints([a, b, c, d]) self.kludge = kludge } } var constraintsAdded: Bool = false func setupLayout() { if !constraintsAdded { self.layout = self.dynamicType.layoutClass.init(model: self.keyboard, superview: self.forwardingView, layoutConstants: self.dynamicType.layoutConstants, globalColors: self.dynamicType.globalColors) self.layout?.initialize() self.setMode(0) self.setupKludge() self.addInputTraitsObservers() self.constraintsAdded = true } } var lastLayoutBounds: CGRect? override func viewDidLayoutSubviews() { if view.bounds == CGRectZero { return } self.setupLayout() let orientationSavvyBounds = CGRectMake(0, 0, self.view.bounds.width, self.heightForOrientation(self.interfaceOrientation, withTopBanner: false)) if (lastLayoutBounds != nil && lastLayoutBounds == orientationSavvyBounds) { } else { self.forwardingView.frame = orientationSavvyBounds self.layout?.layoutKeys(self.currentMode) self.lastLayoutBounds = orientationSavvyBounds self.setupKeys() } let newOrigin = CGPointMake(0, self.view.bounds.height - self.forwardingView.bounds.height) self.forwardingView.frame.origin = newOrigin } override func loadView() { super.loadView() } override func viewWillAppear(animated: Bool) { self.keyboardHeight = self.heightForOrientation(self.interfaceOrientation, withTopBanner: true) } override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { self.forwardingView.resetTrackedViews() if let keyPool = self.layout?.keyPool { for view in keyPool { view.shouldRasterize = true } } self.keyboardHeight = self.heightForOrientation(toInterfaceOrientation, withTopBanner: true) } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { if let keyPool = self.layout?.keyPool { for view in keyPool { view.shouldRasterize = false } } } func heightForOrientation(orientation: UIInterfaceOrientation, withTopBanner: Bool) -> CGFloat { let isPad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad let actualScreenWidth = (UIScreen.mainScreen().nativeBounds.size.width / UIScreen.mainScreen().nativeScale) let canonicalPortraitHeight = (isPad ? CGFloat(264) : CGFloat(orientation.isPortrait && actualScreenWidth >= 400 ? 226 : 216)) let canonicalLandscapeHeight = (isPad ? CGFloat(352) : CGFloat(162)) return CGFloat(orientation.isPortrait ? canonicalPortraitHeight : canonicalLandscapeHeight ) } func setupKeys() { if self.layout == nil { return } for page in keyboard.pages { for rowKeys in page.rows { for key in rowKeys { if let keyView = self.layout?.viewForKey(key) { keyView.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) switch key.type { case Key.KeyType.KeyboardChange: keyView.addTarget(self, action: "advanceTapped:", forControlEvents: .TouchUpInside) case Key.KeyType.Backspace: let cancelEvents: UIControlEvents = [UIControlEvents.TouchUpInside, UIControlEvents.TouchUpInside, UIControlEvents.TouchDragExit, UIControlEvents.TouchUpOutside, UIControlEvents.TouchCancel, UIControlEvents.TouchDragOutside] keyView.addTarget(self, action: "backspaceDown:", forControlEvents: .TouchDown) keyView.addTarget(self, action: "backspaceUp:", forControlEvents: cancelEvents) case Key.KeyType.ModeChange: keyView.addTarget(self, action: Selector("modeChangeTapped:"), forControlEvents: .TouchDown) case Key.KeyType.DismissKeyboard : keyView.addTarget(self, action: Selector("dismissKeyboardTapped:"), forControlEvents: .TouchDown) default: break } if key.isCharacter && key.type != Key.KeyType.HiddenKey { if UIDevice.currentDevice().userInterfaceIdiom != UIUserInterfaceIdiom.Pad { keyView.addTarget(self, action: Selector("showPopup:"), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter]) keyView.addTarget(keyView, action: Selector("hidePopup"), forControlEvents: [.TouchDragExit, .TouchCancel]) keyView.addTarget(self, action: Selector("hidePopupDelay:"), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside]) } } if key.type == Key.KeyType.Undo { keyView.addTarget(self, action: "undoTapped:", forControlEvents: .TouchUpInside) } if key.hasOutput && key.type != Key.KeyType.HiddenKey { keyView.addTarget(self, action: "keyPressedHelper:", forControlEvents: .TouchUpInside) } if key.type != Key.KeyType.ModeChange { keyView.addTarget(self, action: Selector("highlightKey:"), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter]) keyView.addTarget(self, action: Selector("unHighlightKey:"), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside, .TouchDragExit, .TouchCancel]) } if key.type != Key.KeyType.HiddenKey { keyView.addTarget(self, action: Selector("playKeySound"), forControlEvents: .TouchDown) } } } } } } ///////////////// // POPUP DELAY // ///////////////// var keyWithDelayedPopup: KeyboardKey? var popupDelayTimer: NSTimer? func showPopup(sender: KeyboardKey) { if sender == self.keyWithDelayedPopup { self.popupDelayTimer?.invalidate() } sender.showPopup() } func hidePopupDelay(sender: KeyboardKey) { self.popupDelayTimer?.invalidate() if sender != self.keyWithDelayedPopup { self.keyWithDelayedPopup?.hidePopup() self.keyWithDelayedPopup = sender } if sender.popup != nil { self.popupDelayTimer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("hidePopupCallback"), userInfo: nil, repeats: false) } } func hidePopupCallback() { self.keyWithDelayedPopup?.hidePopup() self.keyWithDelayedPopup = nil self.popupDelayTimer = nil } ///////////////////// // POPUP DELAY END // ///////////////////// override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated } override func textDidChange(textInput: UITextInput?) { self.contextChanged() } override func textWillChange(textInput: UITextInput?) { self.contextChanged() } func contextChanged() { self.autoPeriodState = .NoSpace } func setHeight(height: CGFloat) { self.heightConstraint?.constant = height } func updateAppearances(appearanceIsDark: Bool) { self.layout?.updateKeyAppearance() self.settingsView?.darkMode = appearanceIsDark } func highlightKey(sender: KeyboardKey) { sender.highlighted = true } func unHighlightKey(sender: KeyboardKey) { sender.highlighted = false } func keyPressedHelper(sender: KeyboardKey) { if let model = self.layout?.keyForView(sender) { self.keyPressed(model) if model.type == Key.KeyType.Return { self.currentMode = 0 } var lastCharCountInBeforeContext: Int = 0 var readyForDoubleSpacePeriod: Bool = true self.handleAutoPeriod(model) } } func handleAutoPeriod(key: Key) { if self.autoPeriodState == .FirstSpace { if key.type != Key.KeyType.Space { self.autoPeriodState = .NoSpace return } let charactersAreInCorrectState = { () -> Bool in let previousContext = (self.textDocumentProxy as? UITextDocumentProxy)?.documentContextBeforeInput if previousContext == nil || (previousContext!).characters.count < 3 { return false } var index = previousContext!.endIndex index = index.predecessor() if previousContext![index] != " " { return false } index = index.predecessor() if previousContext![index] != " " { return false } index = index.predecessor() let char = previousContext![index] if self.characterIsWhitespace(char) || self.characterIsPunctuation(char) || char == "," { return false } return true }() if charactersAreInCorrectState { (self.textDocumentProxy as? UITextDocumentProxy)?.deleteBackward() (self.textDocumentProxy as? UITextDocumentProxy)?.deleteBackward() (self.textDocumentProxy as? UITextDocumentProxy)?.insertText(".") (self.textDocumentProxy as? UITextDocumentProxy)?.insertText(" ") } self.autoPeriodState = .NoSpace } else { if key.type == Key.KeyType.Space { self.autoPeriodState = .FirstSpace } } } func cancelBackspaceTimers() { self.backspaceDelayTimer?.invalidate() self.backspaceRepeatTimer?.invalidate() self.backspaceDelayTimer = nil self.backspaceRepeatTimer = nil } func backspaceDown(sender: KeyboardKey) { self.cancelBackspaceTimers() if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { textDocumentProxy.deleteBackward() } self.backspaceDelayTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceDelay - backspaceRepeat, target: self, selector: Selector("backspaceDelayCallback"), userInfo: nil, repeats: false) } func backspaceUp(sender: KeyboardKey) { self.cancelBackspaceTimers() } func backspaceDelayCallback() { self.backspaceDelayTimer = nil self.backspaceRepeatTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceRepeat, target: self, selector: Selector("backspaceRepeatCallback"), userInfo: nil, repeats: true) } func backspaceRepeatCallback() { self.playKeySound() if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { textDocumentProxy.deleteBackward() } } func dismissKeyboardTapped (sender : KeyboardKey) { self.dismissKeyboard() } func undoTapped (sender : KeyboardKey) { } func modeChangeTapped(sender: KeyboardKey) { if let toMode = self.layout?.viewToModel[sender]?.toMode { self.currentMode = toMode } } func setMode(mode: Int) { self.forwardingView.resetTrackedViews() self.layout?.layoutKeys(mode) self.setupKeys() } func advanceTapped(sender: KeyboardKey) { self.forwardingView.resetTrackedViews() self.advanceToNextInputMode() } func characterIsPunctuation(character: Character) -> Bool { return (character == ".") || (character == "!") || (character == "?") } func characterIsNewline(character: Character) -> Bool { return (character == "\n") || (character == "\r") } func characterIsWhitespace(character: Character) -> Bool { return (character == " ") || (character == "\n") || (character == "\r") || (character == "\t") } func stringIsWhitespace(string: String?) -> Bool { if string != nil { for char in (string!).characters { if !characterIsWhitespace(char) { return false } } } return true } func playKeySound() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { AudioServicesPlaySystemSound(1104) }) } ////////////////////////////////////// // MOST COMMONLY EXTENDABLE METHODS // ////////////////////////////////////// class var layoutClass: KeyboardLayout.Type { get { return KeyboardLayout.self }} class var layoutConstants: LayoutConstants.Type { get { return LayoutConstants.self }} class var globalColors: GlobalColors.Type { get { return GlobalColors.self }} func keyPressed(key: Key) { if let proxy = (self.textDocumentProxy as? UIKeyInput) { proxy.insertText(key.getKeyOutput()) } } }
apache-2.0
haskellswift/swift-package-manager
Sources/PackageGraph/RepositoryPackageContainerProvider.swift
1
5642
/* This source file is part of the Swift.org open source project Copyright 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 Swift project authors */ import Basic import PackageLoading import SourceControl import Utility import struct PackageDescription.Version /// Adaptor for exposing repositories as PackageContainerProvider instances. /// /// This is the root class for bridging the manifest & SCM systems into the /// interfaces used by the `DependencyResolver` algorithm. public class RepositoryPackageContainerProvider: PackageContainerProvider { public typealias Container = RepositoryPackageContainer let repositoryManager: RepositoryManager let manifestLoader: ManifestLoaderProtocol /// Create a repository-based package provider. /// /// - Parameters: /// - repositoryManager: The repository manager responsible for providing repositories. /// - manifestLoader: The manifest loader instance. public init(repositoryManager: RepositoryManager, manifestLoader: ManifestLoaderProtocol) { self.repositoryManager = repositoryManager self.manifestLoader = manifestLoader } public func getContainer(for identifier: RepositorySpecifier) throws -> Container { // Resolve the container using the repository manager. // // FIXME: We need to move this to an async interface, or document the interface as thread safe. let handle = repositoryManager.lookup(repository: identifier) // Wait for the repository to be fetched. let wasAvailableCondition = Condition() var wasAvailableOpt: Bool? = nil handle.addObserver { handle in wasAvailableCondition.whileLocked{ wasAvailableOpt = handle.isAvailable wasAvailableCondition.signal() } } while wasAvailableCondition.whileLocked({ wasAvailableOpt == nil}) { wasAvailableCondition.wait() } let wasAvailable = wasAvailableOpt! if !wasAvailable { throw RepositoryPackageResolutionError.unavailableRepository } // Open the repository. // // FIXME: Do we care about holding this open for the lifetime of the container. let repository = try handle.open() // Create the container wrapper. return RepositoryPackageContainer(identifier: identifier, repository: repository, manifestLoader: manifestLoader) } } enum RepositoryPackageResolutionError: Swift.Error { /// A requested repository could not be cloned. case unavailableRepository } /// Abstract repository identifier. extension RepositorySpecifier: PackageContainerIdentifier {} public typealias RepositoryPackageConstraint = PackageContainerConstraint<RepositorySpecifier> /// Adaptor to expose an individual repository as a package container. public class RepositoryPackageContainer: PackageContainer, CustomStringConvertible { public typealias Identifier = RepositorySpecifier /// The identifier of the repository. public let identifier: RepositorySpecifier /// The available version list (in order). public let versions: [Version] /// The opened repository. let repository: Repository /// The manifest loader. let manifestLoader: ManifestLoaderProtocol /// The versions in the repository and their corresponding tags. let knownVersions: [Version: String] /// The cached dependency information. private var dependenciesCache: [Version: [RepositoryPackageConstraint]] = [:] private var dependenciesCacheLock = Lock() init(identifier: RepositorySpecifier, repository: Repository, manifestLoader: ManifestLoaderProtocol) { self.identifier = identifier self.repository = repository self.manifestLoader = manifestLoader // Compute the map of known versions and sorted version set. // // FIXME: Move this utility to a more stable location. self.knownVersions = Git.convertTagsToVersionMap(repository.tags) self.versions = [Version](knownVersions.keys).sorted() } public var description: String { return "RepositoryPackageContainer(\(identifier.url.debugDescription))" } public func getTag(for version: Version) -> String? { return knownVersions[version] } public func getRevision(for tag: String) throws -> Revision { return try repository.resolveRevision(tag: tag) } public func getDependencies(at version: Version) throws -> [RepositoryPackageConstraint] { // FIXME: Get a caching helper for this. return try dependenciesCacheLock.withLock{ if let result = dependenciesCache[version] { return result } // FIXME: We should have a persistent cache for these. let tag = knownVersions[version]! let revision = try repository.resolveRevision(tag: tag) let fs = try repository.openFileView(revision: revision) let manifest = try manifestLoader.load(packagePath: AbsolutePath.root, baseURL: identifier.url, version: version, fileSystem: fs) let result = manifest.package.dependencies.map{ RepositoryPackageConstraint(container: RepositorySpecifier(url: $0.url), versionRequirement: .range($0.versionRange)) } dependenciesCache[version] = result return result } } }
apache-2.0
mlilback/rc2SwiftClient
ClientCore/editing/DocumentManager.swift
1
11269
// // DocumentManager.swift // // Copyright ©2017 Mark Lilback. This file is licensed under the ISC license. // import Foundation import Rc2Common import ReactiveSwift import Networking import SwiftyUserDefaults import MJLLogger import iosMath public extension Notification.Name { /// sent before the currentDocument will be saved. object will be the EditorContext/DocummentManager static let willSaveDocument = Notification.Name(rawValue: "DocumentWillSaveNotification") } /// Manages open documents and the current document. Provides common properties to editor components via the EditorContext protocol. public class DocumentManager: EditorContext { let minTimeBetweenAutoSaves: TimeInterval = 2 // MARK: properties public let id = UUID() // when changed, should use .updateProgress() while loading file contents // use the double property paradigm to prevent any edits from publc property private let _currentDocument = MutableProperty<EditorDocument?>(nil) public let currentDocument: Property<EditorDocument?> public let editorFont: MutableProperty<PlatformFont> public var errorHandler: Rc2ErrorHandler { return self } private var openDocuments: [Int: EditorDocument] = [:] public var notificationCenter: NotificationCenter public var workspaceNotificationCenter: NotificationCenter public let lifetime: Lifetime var defaults: UserDefaults private var lastParsed: TimeInterval = 0 private var equationLabel: MTMathUILabel? /// object that actually saves the file to disk, has a workspace reference let fileSaver: FileSaver let fileCache: FileCache let loading = Atomic<Bool>(false) let saving = Atomic<Bool>(false) public var busy: Bool { return loading.value || saving.value } // MARK: methods /// Creates a new DocumentManager. Should only be a need for one. /// - Parameter fileSaver: The object that will do the actually saving of contents to disk /// - Parameter fileCache: Used to load files /// - Parameter lifetime: A lifetime to use when binding to a property via ReactiveSwift /// - Parameter notificationCenter: The notification center to use. Defaults to NotificationCenter.default /// - Parameter wspaceCenter: The notification to use for NSWorkspace notifications. Defaults to NSWorkspace.shared.notificationCenter /// - Parameter defaults: The UserDefaults to use. Defualts to NSNotifcationCenter.default public init(fileSaver: FileSaver, fileCache: FileCache, lifetime: Lifetime, notificationCenter: NotificationCenter = .default, wspaceCenter: NotificationCenter = NSWorkspace.shared.notificationCenter, defaults: UserDefaults = .standard) { currentDocument = Property<EditorDocument?>(_currentDocument) self.fileSaver = fileSaver self.fileCache = fileCache self.lifetime = lifetime self.notificationCenter = notificationCenter self.workspaceNotificationCenter = wspaceCenter self.defaults = defaults let defaultSize = CGFloat(defaults[.defaultFontSize]) // font defaults to user-fixed pitch font var initialFont = PlatformFont.userFixedPitchFont(ofSize: defaultSize)! // try loading a saved font, or if there isn't one, Menlo if let fontDesc = defaults[.editorFont], let font = PlatformFont(descriptor: fontDesc, size: fontDesc.pointSize) { initialFont = font } else if let menlo = PlatformFont(name: "Menlo-Regular", size: defaultSize) { initialFont = menlo } editorFont = MutableProperty<PlatformFont>(initialFont) fileSaver.workspace.fileChangeSignal.observe(on: UIScheduler()).observeValues { [weak self] changes in self?.process(changes: changes) } } func process(changes: [AppWorkspace.FileChange]) { guard !busy else { Log.info("skipping filechange message", .app); return } // only care about change if it is our current document guard let document = currentDocument.value, let change = changes.first(where: { $0.file.fileId == document.file.fileId }) else { return } if change.type == .modify { guard document.file.fileId == change.file.fileId else { return } document.fileUpdated() switchTo(document: document) } else if change.type == .remove { //document being editied was removed switchTo(document: nil) } } /// returns a SP that will save the current document and then load the document for file public func load(file: AppFile?) -> SignalProducer<String?, Rc2Error> { if loading.value { Log.warn("load called while already loading", .app) } // get a producer to save the old document let saveProducer: SignalProducer<(), Rc2Error> if let curDoc = currentDocument.value { saveProducer = save(document: curDoc) } else { // make a producer that does nothing saveProducer = SignalProducer<(), Rc2Error>(value: ()) } // if file is nil, nil out current document (saving current first) guard let theFile = file else { return saveProducer .on(starting: { self.loading.value = true }) .map { _ in () } .flatMap(.concat, nilOutCurrentDocument) .on(terminated: { self.loading.value = false }) } // save current document, get the document to load, and load it return saveProducer .map { _ in theFile } .flatMap(.concat, getDocumentFor) .flatMap(.concat, load) .on(starting: { self.loading.value = true }, completed: { self.loading.value = false }) } /// discards all changes to the current document public func revertCurrentDocument() { guard let doc = currentDocument.value else { return } // clear autosave document if exists let tmpUrl = autosaveUrl(document: doc) if tmpUrl.fileExists() { try? fileCache.fileManager.removeItem(at: tmpUrl) } switchTo(document: doc) } /// saves to server, fileCache, and memory cache public func save(document: EditorDocument, isAutoSave: Bool = false) -> SignalProducer<(), Rc2Error> { if isAutoSave { return autosave(document: document) } notificationCenter.post(name: .willSaveDocument, object: self) guard document.isDirty else { return SignalProducer<(), Rc2Error>(value: ()) } guard let contents = document.currentContents else { return SignalProducer<(), Rc2Error>(error: Rc2Error(type: .invalidArgument)) } return self.fileSaver.save(file: document.file, contents: contents) .on(starting: { self.saving.value = true }) .map { _ in (document.file, contents) } .flatMap(.concat, fileCache.save) .on(completed: { document.contentsSaved() }, terminated: { self.saving.value = false }) } /// Generates an image to use for the passed in latex, size based on the editor font's size /// /// - Parameter latex: The latex to use as an inline equation /// - Returns: an image of the latex as an inline equation public func inlineImageFor(latex: String) -> PlatformImage? { if nil == equationLabel { equationLabel = MTMathUILabel(frame: CGRect(x: 0, y: 0, width: 1000, height: 20)) // default max size for equation image equationLabel?.labelMode = .text } equationLabel?.fontSize = editorFont.value.pointSize equationLabel?.latex = latex equationLabel?.layout() guard let dlist = equationLabel?.displayList else { print("error with list no list") return nil } let size = equationLabel!.intrinsicContentSize #if os(macOS) let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0)! let nscontext = NSGraphicsContext(bitmapImageRep: rep)! NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = nscontext dlist.draw(nscontext.cgContext) NSGraphicsContext.restoreGraphicsState() let image = NSImage(size: size) image.addRepresentation(rep) return image #else #error("inlineImageFor not implemented for non-macOS platforms") #endif } // MARK: - private methods /// actually autosaves a file private func autosave(document: EditorDocument) -> SignalProducer<(), Rc2Error> { guard defaults[.autosaveEnabled] else { Log.info("skipping autosave", .app) return SignalProducer<(), Rc2Error>(value: ()) } Log.info("autosaving \(document.file.name)", .core) let tmpUrl = autosaveUrl(document: document) return SignalProducer<(), Rc2Error> { [weak self] observer, _ in var err: Rc2Error? defer { if let err = err { observer.send(error: err) } else { observer.send(value: ()) observer.sendCompleted() } } guard let me = self else { return } me.notificationCenter.post(name: .willSaveDocument, object: self) if let content = document.savedContents { do { try Data(content.utf8).write(to: tmpUrl) document.file.writeXAttributes(tmpUrl) Log.info("autosaved \(tmpUrl.lastPathComponent)", .core) } catch { err = Rc2Error(type: .file, nested: error, explanation: "failed to autosave \(tmpUrl.lastPathComponent)") } } } } private func autosaveUrl(document: EditorDocument) -> URL { return fileCache.fileCacheUrl.appendingPathComponent("~\(document.file.fileId).\(document.file.fileType.fileExtension)") } private func nilOutCurrentDocument() -> SignalProducer<String?, Rc2Error> { return SignalProducer<String?, Rc2Error>(value: nil) .on(started: { self.switchTo(document: nil) }) } // the only function that should change _currentDocument private func switchTo(document: EditorDocument?) { _currentDocument.value = document } // returns SP to return the specified document, creating and inserting into openDocuments if necessary private func getDocumentFor(file: AppFile) -> SignalProducer<EditorDocument, Rc2Error> { let doc = openDocuments[file.fileId] ?? EditorDocument(file: file) openDocuments[file.fileId] = doc guard doc.isLoaded else { return fileCache.contents(of: file) .map { String(data: $0, encoding: .utf8)! } .on(value: { doc.contentsLoaded(contents: $0) }) .map { _ in doc } } return SignalProducer<EditorDocument, Rc2Error>(value: doc) } private func load(document: EditorDocument) -> SignalProducer<String?, Rc2Error> { precondition(openDocuments[document.file.fileId] == document) if loading.value || document.isLoaded { switchTo(document: document) return SignalProducer<String?, Rc2Error>(value: document.currentContents) } // see if there is autosave data to use let tmpUrl = autosaveUrl(document: document) if tmpUrl.fileExists(), document.file.versionXAttributesMatch(url: tmpUrl), let contents = try? String(contentsOf: tmpUrl, encoding: .utf8) { Log.info("using contents from autosave file (\(document.file.fileId))", .core) return SignalProducer<String?, Rc2Error>(value: contents) } // read cache if fileCache.isFileCached(document.file) { return fileCache.contents(of: document.file) .on(value: { _ in self.switchTo(document: document) }) .map( { String(data: $0, encoding: .utf8) }) } // load from network return fileCache.validUrl(for: document.file) .map({ _ in return document.file }) .flatMap(.concat, fileCache.contents) .on(value: { _ in self.switchTo(document: document) }) .map( { String(data: $0, encoding: .utf8) }) } } extension DocumentManager: Rc2ErrorHandler { public func handle(error: Rc2Error) { } }
isc
emilstahl/swift
validation-test/compiler_crashers_fixed/1255-getselftypeforcontainer.swift
12
2030
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import Foundation class m<j>: NSObject { var h: j g -> k = l $n } b f: _ = j() { } } func k<g { enum k { func l var _ = l c j) func c<k>() -> (k, > k) -> k { d h d.f 1, k(j, i))) class k { typealias h = h protocol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { } } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } class l { func f((k, l() -> f } class d } class i: d, g { l func d() -> f { m "" } } } func m<j n j: g, j: d let l = h l() f protocol l : f { func f protocol g import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g struct c<d : SequenceType> { var b: [c<d>] { return [] } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() func f<T : BooleanType>(b: T) { } f(true as BooleanType) func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type func e() { d.e() } } b protocol c : b { func b otocol A { E == F>(f: B<T>) } struct } } struct l<e : SequenceType> { l g: e } func h<e>() -> [l<e>] { f [] } func i(e: g) -> <j>(() -> j) -> k func b(c) -> <d>(() -> d) { } func k<q>() -> [n<q>] { r [] } func k(l: Int = 0) { } n n = k n() func n<q { l n { func o o _ = o } } func ^(k: m, q) -> q { r !(k) } protocol k { j q j o = q j f = q } class l<r : n, l : n p r.q == l> : k { } class l<r, l> { } protocol n { j q } protocol k : k { } class k<f : l, q : l p f.q == q> { } protocol l { j q j o } struct n<r : l> struct c<d: SequenceType, b where Optional<b> == d.Generator.Element> } class p { u _ = q() { } } u l = r u s: k -> k = { n $h: m.j) { } } o l() { ({}) } struct m<t> { let p: [(t, () -> ())] = [] } protocol p : p { } protocol m { o u() -> String } class j { o m() -> String { n "" } } class h
apache-2.0
magi82/MGRelativeKit
Sources/RelativeLayout+center.swift
1
2044
// The MIT License (MIT) // // Copyright (c) 2017 ByungKook Hwang (https://magi82.github.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit extension RelativeLayout { public func centerHorizontalSuper() -> Self { guard let myView = self.myView, let superView = myView.superview else { return self } myView.frame.origin.x = (superView.frame.size.width - myView.frame.size.width) * 0.5 return self } public func centerVerticalSuper() -> Self { guard let myView = self.myView, let superView = myView.superview else { return self } myView.frame.origin.y = (superView.frame.size.height - myView.frame.size.height) * 0.5 return self } public func centerInSuper() -> Self { guard let myView = self.myView, let superView = myView.superview else { return self } myView.frame.origin.x = (superView.frame.size.width - myView.frame.size.width) * 0.5 myView.frame.origin.y = (superView.frame.size.height - myView.frame.size.height) * 0.5 return self } }
mit
justinplatz/SwiftExample
SwiftExample/AppDelegate.swift
1
30444
// // AppDelegate.swift // SwiftExample // // Created by Justin Platz on 7/10/15. // Copyright (c) 2015 ioJP. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, PNObjectEventListener { //MARK: Properties var window: UIWindow? var client: PubNub? var channel1: NSString? var channel2: NSString? var channelGroup1: NSString? var subKey: NSString? var pubKey: NSString? var authKey: NSString? var timer: NSTimer? var myConfig: PNConfiguration? //MARK: Configuration // func updateClientConfiguration(Void){} // func printClientConfiguration(Void){} func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //MARK: Pam Use Case Config //Settings Config for PAM Example //Uncomment this setion line for a PAM use-case example //http://www.pubnub.com/console/?channel=good&origin=d.pubnub.com&sub=pam&pub=pam&cipher=&ssl=false&secret=pam&auth=myAuthKey // self.channel1 = "good" // self.channel2 = "bad" // self.pubKey = "pam" // self.subKey = "pam" // self.authKey = "foo" //MARK: Settings Config for Non-PAM Use Case Config self.channel1 = "bot" self.channel2 = "myCh" self.channelGroup1 = "myChannelGroup" self.pubKey = "demo-36" self.subKey = "demo-36" self.authKey = "myAuthKey" tireKicker() return true } func pubNubInit(){ PNLog.enabled(true) PNLog.setMaximumLogFileSize(10) PNLog.setMaximumNumberOfLogFiles(10) //Initialize PubNub client myConfig = PNConfiguration(publishKey: pubKey! as String, subscribeKey: subKey! as String) // # as String ^^? updateClientConfiguration() printClientConfiguration() //Bind config self.client = PubNub.clientWithConfiguration(myConfig) // Bind didReceiveMessage, didReceiveStatus, and didReceivePresenceEvent 'listeners' to this delegate // just be sure the target has implemented the PNObjectEventListener extension self.client?.addListener(self) pubNubSetState() } func tireKicker(){ self.pubNubInit() //MARK: - Time self.pubNubTime() //MARK: - Publish self.pubNubPublish() //MARK: - History self.pubNubHistory() //MARK: - Channel Groups Subscribe / Unsubscribe self.pubNubSubscribeToChannelGroup() self.pubNubUnsubFromChannelGroups() //MARK: - Channel Subscribe / Unsubscribe self.pubNubSubscribeToChannels() self.pubNubUnsubscribeFromChannels() //MARK: - Presence Subscribe / Unsubscribe self.pubNubSubscribeToPresence() self.pubNubUnsubFromPresence() //MARK: - Here Nows self.pubNubHereNowForChannel() self.pubNubGlobalHereNow() self.pubNubHereNowForChannelGroups() self.pubNubWhereNow() //MARK: - CG Admin self.pubNubCGAdd() self.pubNubChannelsForGroup() self.pubNubCGRemoveAllChannels() self.pubNubCGRemoveSomeChannels() //MARK: - State Admin self.pubNubSetState() self.pubNubGetState() //MARK: - 3rd Party Push Notifications Admin self.pubNubAddPushNotifications() self.pubNubRemovePushNotification() self.pubNubRemoveAllPushNotifications() self.pubNubGetAllPushNotifications() //MARK: - Public Encryption/Decryption Methods self.pubNubAESDecrypt() self.pubNubAESEncrypt() //MARK: - Message Size Check Methods self.pubNubSizeOfMessage() } func pubNubSizeOfMessage(){ self.client?.sizeOfMessage("Connected! I'm here!", toChannel: channel1, withCompletion: { (size) -> Void in println("^^^^ Message size: \(size)") }) } func pubNubAESDecrypt(){ /* [PNAES decrypt:<#(NSString *)object#> withKey:<#(NSString *)key#>]; [PNAES decrypt:<#(NSString *)object#> withKey:<#(NSString *)key#> andError:<#(NSError *__autoreleasing *)error#>]; */ } func pubNubAESEncrypt(){ /* [PNAES encrypt:<#(NSData *)data#> withKey:<#(NSString *)key#>]; [PNAES encrypt:<#(NSData *)data#> withKey:<#(NSString *)key#> andError:<#(NSError *__autoreleasing *)error#>]; */ } func pubNubAddPushNotifications(){ /* self.client.addPushNotificationsOnChannels(<#(NSArray *)channels#> withDevicePushToken:<#(NSData *)pushToken#> andCompletion:<#(PNPushNotificationsStateModificationCompletionBlock)block#>) */ } func pubNubRemovePushNotification(){ /* self.client.removePushNotificationsFromChannels(<#(NSArray *)channels#> withDevicePushToken:<#(NSData *)pushToken#> andCompletion:<#(PNPushNotificationsStateModificationCompletionBlock)block#>) */ } func pubNubRemoveAllPushNotifications(){ /* self.client.removeAllPushNotificationsFromDeviceWithPushToken(<#(NSData *)pushToken#> andCompletion:<#(PNPushNotificationsStateModificationCompletionBlock)block#>) */ } func pubNubGetAllPushNotifications(){ /* self.client.pushNotificationEnabledChannelsForDeviceWithPushToken(<#(NSData *)pushToken#> andCompletion:<#(PNPushNotificationsStateAuditCompletionBlock)block#>) */ //^# does nothing? } func pubNubSetState(){ weak var weakSelf = self self.client?.setState(["foo":"bar"] , forUUID: myConfig?.uuid, onChannel: channel1, withCompletion: { (status) -> Void in var strongSelf = weakSelf handleStatus(strongSelf.status) }) //^# random string stuff not done right } func pubNubGetState(){ self.client?.stateForUUID(myConfig?.uuid, onChannel: channel1, withCompletion: { (result, status) -> Void in if(status){ handleStatus(status) } else if(result){ println("^^^^ Loaded state \(result.data.state) for channel \(channel1)") } }) } func pubNubUnsubFromChannelGroups(){ self.client?.unsubscribeFromChannelGroups(["myChannelGroup"], withPresence: false) } func pubNubSubscribeToPresence(){ self.client?.subscribeToPresenceChannels(channel1) } func pubNubUnsubFromPresence(){ self.client?.unsubscribeFromPresenceChannels(channel1) } func pubNubSubscribeToChannels(){ self.client?.subscribeToChannels(channel1, withPresence: true, clientState:(channel1:(["foo":"bar"])!)) //^ # not done right /* [self.client subscribeToChannels:<#(NSArray *)channels#> withPresence:<#(BOOL)shouldObservePresence#>]; [self.client isSubscribedOn:<#(NSString *)name#>] */ } func pubNubUnsubscribeFromChannels(){ self.client?.unsubscribeFromChannels(channelGroup1, withPresence: true) } func pubNubSubscribeToChannelGroup(){ self.client?.subscribeToChannelGroups(channelGroup1, withPresence: false) /* [self.client subscribeToChannelGroups:@[_channelGroup1] withPresence:YES clientState:@{@"foo":@"bar"}]; */ } func pubNubWhereNow(){ self.client?.whereNowUUID("123456", withCompletion: { (result, status) -> Void in if((status) != nil){ self.handleStatus(status) } else if((result) != nil){ println("^^^^ Loaded whereNow data: \(result.data.channels)") } }) } func pubNubCGRemoveSomeChannels(){ self.client?.removeChannels(channel2, fromGroup: channelGroup1, withCompletion: { (status) -> Void in if(!status.error){ println("^^^^CG Remove some channgels request succeeded at time token ") } else{ println("^^^^CG Remove some channels request did not succeed. All Subscribe operations will autoretry when possible") handleStatus(status) } }) } func pubNubCGRemoveAllChannels(){ self.client?.removeChannelsFromGroup(channelGroup1, withCompletion: { (status) -> Void in if(!status.error){ println("^^^^ CG Remove All Channels request succeeded") } else{ println("^^^^ CG Remove All Channels did not succeed. All Subscribe operations will autorety when possible.") handleStatus(status) } }) } func pubNubCGAdd(){ weak var weakSelf = self self.client?.addChannels([channel1,channel2], toGroup: channelGroup1, withCompletion: { (status) -> Void in var strongSelf = weakSelf if(status.error == nil){ println("^^^^ CGAdd Request Succeeded") } else{ println("^^^^ CGAdd Subscribe requet did not succeed. All Subscribe operations will autorety when possible") handleStatus(strongSelf.status) //^# strong self } }) } func pubNubChannelsForGroup(){ self.client?.channelsForGroup(channelGroup1, withCompletion: { (result, status) -> Void in if (status) { handleStatus(status) } else if (result) { println("^^^^ Loaded all channels \(result.data.channels) for group \(channelGroup1)"); } //^# channelgroup1 }) } func pubNubHereNowForChannel(){ self.client?.hereNowForChannel(channel1, withCompletion: { (result, status) -> Void in if (status) { handleStatus(status) } else if (result) { println("^^^^ Loaded hereNowForChannel data: occupancy: \(result.data.occupancy), uuids: \(result.data.uuids)") } }) // If you want to control the 'verbosity' of the server response -- restrict to (values are additive): // Occupancy : PNHereNowOccupancy // Occupancy + UUID : PNHereNowUUID // Occupancy + UUID + State : PNHereNowState self.client?.hereNowForChannel(channel1, withVerbosity: self.client.PNHereNowState, completion: { (result, status) -> Void in if (status) { handleStatus(status) } else if (result) { println("^^^^ Loaded hereNowForChannel data: occupancy: \(result.data.occupancy), uuids: \(result.data.uuids)") } }) //^# herenow state } func pubNubGlobalHereNow(){ self.client?.hereNowWithCompletion({ (result, status) -> Void in if ((status) != nil) { self.handleStatus(status) } else if ((result) != nil) { println("^^^^ Loaded Global hereNow data: channels: \(result.data.channels), total channels: \(result.data.totalChannels), total occupancy: \(result.data.totalOccupancy)") } }) // If you want to control the 'verbosity' of the server response -- restrict to (values are additive): // Occupancy : PNHereNowOccupancy // Occupancy + UUID : PNHereNowUUID // Occupancy + UUID + State : PNHereNowState self.client?.hereNowWithVerbosity(level: PNHereNowVerbosityLevel.self, completion: { (result, status) -> Void in if (status) { handleStatus(status) } else if (result) { println("^^^^ Loaded Global hereNow data: channels: \(result.data.channels), total channels: \(result.data.totalChannels), total occupancy: \(result.data.totalOccupancy)"); } }) //^# verbosity? } func pubNubHereNowForChannelGroups(){ /* [self.client hereNowForChannelGroup:<#(NSString *)group#> withCompletion:<#(PNChannelGroupHereNowCompletionBlock)block#>]; [self.client hereNowForChannelGroup:<#(NSString *)group#> withVerbosity:<#(PNHereNowVerbosityLevel)level#> completion:<#(PNChannelGroupHereNowCompletionBlock)block#>]; */ } func pubNubHistory(){ // History self.client?.historyForChannel(channel1, withCompletion: { (result, status) -> Void in // For completion blocks that provide both result and status parameters, you will only ever // have a non-nil status or result. // If you have a result, the data you specifically requested (in this case, history response) is available in result.data // If you have a status, error or non-error status information is available regarding the call. if (status) { // As a status, this contains error or non-error information about the history request, but not the actual history data I requested. // Timeout Error, PAM Error, etc. handleStatus(status) } else if (result) { // As a result, this contains the messages, start, and end timetoken in the data attribute println("Loaded history data: \(result.data.messages) with start \(result.data.start) and end \(result.data.end)") } }) /* [self.client historyForChannel:<#(NSString *)channel#> start:<#(NSNumber *)startDate#> end:<#(NSNumber *)endDate#> includeTimeToken:<#(BOOL)shouldIncludeTimeToken#> withCompletion:<#(PNHistoryCompletionBlock)block#>]; [self.client historyForChannel:<#(NSString *)channel#> start:<#(NSNumber *)startDate#> end:<#(NSNumber *)endDate#> limit:<#(NSUInteger)limit#> includeTimeToken:<#(BOOL)shouldIncludeTimeToken#> withCompletion:<#(PNHistoryCompletionBlock)block#>]; [self.client historyForChannel:<#(NSString *)channel#> start:<#(NSNumber *)startDate#> end:<#(NSNumber *)endDate#> limit:<#(NSUInteger)limit#> reverse:<#(BOOL)shouldReverseOrder#> includeTimeToken:<#(BOOL)shouldIncludeTimeToken#> withCompletion:<#(PNHistoryCompletionBlock)block#>]; [self.client historyForChannel:<#(NSString *)channel#> start:<#(NSNumber *)startDate#> end:<#(NSNumber *)endDate#> limit:<#(NSUInteger)limit#> reverse:<#(BOOL)shouldReverseOrder#> withCompletion:<#(PNHistoryCompletionBlock)block#>]; [self.client historyForChannel:<#(NSString *)channel#> start:<#(NSNumber *)startDate#> end:<#(NSNumber *)endDate#> limit:<#(NSUInteger)limit#> withCompletion:<#(PNHistoryCompletionBlock)block#>]; [self.client historyForChannel:<#(NSString *)channel#> start:<#(NSNumber *)startDate#> end:<#(NSNumber *)endDate#> withCompletion:<#(PNHistoryCompletionBlock)block#>]; [self.client historyForChannel:<#(NSString *)channel#> withCompletion:<#(PNHistoryCompletionBlock)block#>]; */ } func pubNubTime(){ self.client?.timeWithCompletion({ (result, status) -> Void in if((result.data) != nil){ println("Result from Time: \(result.data.timetoken)") } else if((status) != nil){ self.handleStatus(status) } }) } func pubNubPublish(){ self.client?.publish("Connected! I'm here!", toChannel: channel1, withCompletion: { (status) -> Void in if(!status.isError){ println("Message sent at TT: \(status.data.timetoken)") } else{ handleStatus(status) } }) /////^ # compressed /* [self.client publish:<#(id)message#> toChannel:<#(NSString *)channel#> compressed:<#(BOOL)compressed#> withCompletion:<#(PNPublishCompletionBlock)block#>]; [self.client publish:<#(id)message#> toChannel:<#(NSString *)channel#> withCompletion:<#(PNPublishCompletionBlock)block#>]; [self.client publish:<#(id)message#> toChannel:<#(NSString *)channel#> storeInHistory:<#(BOOL)shouldStore#> withCompletion:<#(PNPublishCompletionBlock)block#>]; [self.client publish:<#(id)message#> toChannel:<#(NSString *)channel#> storeInHistory:<#(BOOL)shouldStore#> compressed:<#(BOOL)compressed#> withCompletion:<#(PNPublishCompletionBlock)block#>]; [self.client publish:<#(id)message#> toChannel:<#(NSString *)channel#> mobilePushPayload:<#(NSDictionary *)payloads#> withCompletion:<#(PNPublishCompletionBlock)block#>]; [self.client publish:<#(id)message#> toChannel:<#(NSString *)channel#> mobilePushPayload:<#(NSDictionary *)payloads#> compressed:<#(BOOL)compressed#> withCompletion:<#(PNPublishCompletionBlock)block#>]; [self.client publish:<#(id)message#> toChannel:<#(NSString *)channel#> mobilePushPayload:<#(NSDictionary *)payloads#> storeInHistory:<#(BOOL)shouldStore#> withCompletion:<#(PNPublishCompletionBlock)block#>]; [self.client publish:<#(id)message#> toChannel:<#(NSString *)channel#> mobilePushPayload:<#(NSDictionary *)payloads#> storeInHistory:<#(BOOL)shouldStore#> compressed:<#(BOOL)compressed#> withCompletion:<#(PNPublishCompletionBlock)block#>]; */ } func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) { if ((message) != nil) { println("Received message: \(message.data.message) on channel \(message.data.subscribedChannel) at \(message.data.timetoken)") } } func client(client: PubNub!, didReceivePresenceEvent event: PNPresenceEventResult!) { println("^^^^^ Did receive presence event: \(event.data.presenceEvent)") } func client(client: PubNub!, didReceiveStatus status: PNSubscribeStatus!) { // This is where we'll find ongoing status events from our subscribe loop // Results (messages) from our subscribe loop will be found in didReceiveMessage // Results (presence events) from our subscribe loop will be found in didReceiveStatus handleStatus(status) } func handleStatus(status : PNStatus){ // Two types of status events are possible. Errors, and non-errors. Errors will prevent normal operation of your app. // // If this was a subscribe or presence PAM error, the system will continue to retry automatically. // If this was any other operation, you will need to manually retry the operation. // // You can always verify if an operation will auto retry by checking status.willAutomaticallyRetry // If the operation will not auto retry, you can manually retry by calling [status retry] // Retry attempts can be cancelled via [status cancelAutomaticRetry] if(status.error){ handleErrorStatus(status as! PNErrorStatus) // # ^ as! } else{ handleNonErrorStatus(status) } } func handleErrorStatus(status : PNErrorStatus){ println("Debug: \(status.debugDescription)") println("handleErrorStatus: PAM Error: for resource Will Auto Retry?: \(status.automaticallyRetry)") // # ^ ? YES OR NO if (status.category == PNAccessDeniedCategory) { self.handlePAMError(status) } else if (status.category == PNDecryptionErrorCategory) { println("Decryption error. Be sure the data is encrypted and/or encrypted with the correct cipher key.") println("You can find the raw data returned from the server in the status.data attribute: \(status.errorData)") } else if (status.category == PNMalformedResponseCategory) { println("We were expecting JSON from the server, but we got HTML, or otherwise not legal JSON.") println("This may happen when you connect to a public WiFi Hotspot that requires you to auth via your web browser first,") println("or if there is a proxy somewhere returning an HTML access denied error, or if there was an intermittent server issue.") } else if (status.category == PNTimeoutCategory) { println("For whatever reason, the request timed out. Temporary connectivity issues, etc.") } else { // Aside from checking for PAM, this is a generic catch-all if you just want to handle any error, regardless of reason // status.debugDescription will shed light on exactly whats going on println("Request failed... if this is an issue that is consistently interrupting the performance of your app,"); println("email the output of debugDescription to support along with all available log info: \(status.debugDescription)"); } } func handlePAMError(status : PNErrorStatus){ // Access Denied via PAM. Access status.data to determine the resource in question that was denied. // In addition, you can also change auth key dynamically if needed." var pamResourceName: AnyObject = (status.errorData.channels != nil) ? status.errorData.channels[0] : status.errorData.channelGroups var pamResourceType = (status.errorData.channels != nil) ? "channel" : "channel-groups" // # ^ println("PAM error on \(pamResourceType) \(pamResourceName)"); // If its a PAM error on subscribe, lets grab the channel name in question, and unsubscribe from it, and re-subscribe to a channel that we're authed to if (status.operation == PNSubscribeOperation) { if (pamResourceType.isEqualToString("channel")) { println("^^^^ Unsubscribing from \(pamResourceName)") self.reconfigOnPAMError(status) } else { self.client?.unsubscribeFromChannelGroups(pamResourceName, withPresence: true) // the case where we're dealing with CGs instead of CHs... follows the same pattern as above } } else if (status.operation == PNPublishOperation) { println("^^^^ Error publishing with authKey: \( _authKey) to channel \(pamResourceName)"); println("^^^^ Setting auth to an authKey that will allow for both sub and pub"); reconfigOnPAMError(status) } } func reconfigOnPamError(status : PNErrorStatus){ // If this is a subscribe PAM error if (status.operation == PNSubscribeOperation) { var subscriberStatus : PNSubscribeStatus = status as PNSubscribeStatus var currentChannels: NSArray = subscriberStatus.subscribedChannels; var currentChannelGroups: NSArray = subscriberStatus.subscribedChannelGroups; self.myConfig.authKey = "myAuthKey" self.client?.copyWithConfiguration(self.myConfig, completion: client) self.client = client self.client?.subscribeToChannels(currentChannels, withPresence: false) self.client?.subscribeToChannelGroups(currentChannelGroups, withPresence: false) } } func handleNonErrorStatus(status : PNStatus){ // This method demonstrates how to handle status events that are not errors -- that is, // status events that can safely be ignored, but if you do choose to handle them, you // can get increased functionality from the client if (status.category == PNAcknowledgmentCategory) { println("^^^^ Non-error status: ACK") // For methods like Publish, Channel Group Add|Remove|List, APNS Add|Remove|List // when the method is executed, and completes, you can receive the 'ack' for it here. // status.data will contain more server-provided information about the ack as well. } if (status.operation == PNSubscribeOperation) { var subscriberStatus: PNSubscribeStatus = status as PNSubscribeStatus // ^ # // Specific to the subscribe loop operation, you can handle connection events // These status checks are only available via the subscribe status completion block or // on the long-running subscribe loop listener didReceiveStatus // Connection events are never defined as errors via status.isError if (status.category == PNDisconnectedCategory) { // PNDisconnect happens as part of our regular operation // No need to monitor for this unless requested by support println("^^^^ Non-error status: Expected Disconnect, Channel Info: \(subscriberStatus.subscribedChannels)"); } else if (status.category == PNUnexpectedDisconnectCategory) { // PNUnexpectedDisconnect happens as part of our regular operation // This event happens when radio / connectivity is lost println("^^^^ Non-error status: Unexpected Disconnect, Channel Info: \(subscriberStatus.subscribedChannels)") } else if (status.category == PNConnectedCategory) { // Connect event. You can do stuff like publish, and know you'll get it. // Or just use the connected event to confirm you are subscribed for UI / internal notifications, etc // NSLog(@"Subscribe Connected to %@", status.data[@"channels"]); println("^^^^ Non-error status: Connected, Channel Info: \(subscriberStatus.subscribedChannels)"); self.pubNubPublish() } else if (status.category == PNReconnectedCategory) { // PNUnexpectedDisconnect happens as part of our regular operation // This event happens when radio / connectivity is lost println("^^^^ Non-error status: Reconnected, Channel Info: \(subscriberStatus.subscribedChannels)") } } } func updateClientConfiguration(){ // Set PubNub Configuration self.myConfig?.TLSEnabled = false self.myConfig?.uuid = randomString() as String self.myConfig?.origin = "pubsub.pubnub.com" self.myConfig?.authKey = self.authKey as! String // Presence Settings self.myConfig?.presenceHeartbeatValue = 120; self.myConfig?.presenceHeartbeatInterval = 60; // Cipher Key Settings //self.client.cipherKey = @"enigma"; // Time Token Handling Settings self.myConfig?.keepTimeTokenOnListChange = true self.myConfig?.restoreSubscription = true self.myConfig?.catchUpOnSubscriptionRestore = true } func randomString()->NSString{ var random = arc4random_uniform(74) var formatted = NSString(format:"%d", random) as NSString return formatted } func printClientConfiguration(){ // Get PubNub Options println("TLSEnabled: \(self.myConfig?.TLSEnabled) ") //^# yes or no println("Origin: \(self.myConfig!.origin)") println("authKey: \(self.myConfig!.authKey)") println("UUID: \(self.myConfig!.uuid)"); // Time Token Handling Settings println("keepTimeTokenOnChannelChange: \(self.myConfig?.keepTimeTokenOnListChange)" ) //#^ y/n println("resubscribeOnConnectionRestore: \(self.myConfig?.restoreSubscription)") //#^ y/n println("catchUpOnSubscriptionRestore: \(self.myConfig?.catchUpOnSubscriptionRestore)") // Get Presence Options println("Heartbeat value: \(self.myConfig!.presenceHeartbeatValue)") println("Heartbeat interval: \(self.myConfig!.presenceHeartbeatInterval)") // Get CipherKey println("Cipher key: \(self.myConfig!.cipherKey)") } 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
mruiz723/TODO
TODO/TODO/AppDelegate.swift
1
2142
// // AppDelegate.swift // TODO // // Created by Luis F Ruiz Arroyave on 10/23/16. // Copyright © 2016 UdeM. 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
josve05a/wikipedia-ios
Wikipedia/Code/DiffController.swift
2
10850
import Foundation enum DiffError: Error { case generateUrlFailure case missingDiffResponseFailure case missingUrlResponseFailure case fetchRevisionConstructTitleFailure case unrecognizedHardcodedIdsForIntermediateCounts case failureToPopulateModelsFromDeepLink case failureToVerifyRevisionIDs var localizedDescription: String { return CommonStrings.genericErrorDescription } } class DiffController { enum RevisionDirection { case next case previous } let diffFetcher: DiffFetcher let pageHistoryFetcher: PageHistoryFetcher? let globalUserInfoFetcher: GlobalUserInfoFetcher let diffThanker: DiffThanker let siteURL: URL let type: DiffContainerViewModel.DiffType private weak var revisionRetrievingDelegate: DiffRevisionRetrieving? let transformer: DiffTransformer init(siteURL: URL, diffFetcher: DiffFetcher = DiffFetcher(), pageHistoryFetcher: PageHistoryFetcher?, revisionRetrievingDelegate: DiffRevisionRetrieving?, type: DiffContainerViewModel.DiffType) { self.diffFetcher = diffFetcher self.pageHistoryFetcher = pageHistoryFetcher self.globalUserInfoFetcher = GlobalUserInfoFetcher() self.diffThanker = DiffThanker() self.siteURL = siteURL self.revisionRetrievingDelegate = revisionRetrievingDelegate self.type = type self.transformer = DiffTransformer(type: type, siteURL: siteURL) } func fetchEditCount(guiUser: String, completion: @escaping ((Result<Int, Error>) -> Void)) { globalUserInfoFetcher.fetchEditCount(guiUser: guiUser, siteURL: siteURL, completion: completion) } func fetchIntermediateCounts(for pageTitle: String, pageURL: URL, from fromRevisionID: Int , to toRevisionID: Int, completion: @escaping (Result<EditCountsGroupedByType, Error>) -> Void) { pageHistoryFetcher?.fetchEditCounts(.edits, .editors, for: pageTitle, pageURL: pageURL, from: fromRevisionID, to: toRevisionID, completion: completion) } func thankRevisionAuthor(toRevisionId: Int, completion: @escaping ((Result<DiffThankerResult, Error>) -> Void)) { diffThanker.thank(siteURL: siteURL, rev: toRevisionId, completion: completion) } func fetchFirstRevisionModel(articleTitle: String, completion: @escaping ((Result<WMFPageHistoryRevision, Error>) -> Void)) { guard let articleTitle = (articleTitle as NSString).wmf_normalizedPageTitle() else { completion(.failure(DiffError.fetchRevisionConstructTitleFailure)) return } diffFetcher.fetchFirstRevisionModel(siteURL: siteURL, articleTitle: articleTitle, completion: completion) } struct DeepLinkModelsResponse { let from: WMFPageHistoryRevision? let to: WMFPageHistoryRevision? let first: WMFPageHistoryRevision let articleTitle: String } func populateModelsFromDeepLink(fromRevisionID: Int?, toRevisionID: Int?, articleTitle: String?, completion: @escaping ((Result<DeepLinkModelsResponse, Error>) -> Void)) { if let articleTitle = articleTitle { populateModelsFromDeepLink(fromRevisionID: fromRevisionID, toRevisionID: toRevisionID, articleTitle: articleTitle, completion: completion) return } let maybeRevisionID = toRevisionID ?? fromRevisionID guard let revisionID = maybeRevisionID else { completion(.failure(DiffError.failureToVerifyRevisionIDs)) return } diffFetcher.fetchArticleTitle(siteURL: siteURL, revisionID: revisionID) { (result) in switch result { case .success(let title): self.populateModelsFromDeepLink(fromRevisionID: fromRevisionID, toRevisionID: toRevisionID, articleTitle: title, completion: completion) case .failure(let error): completion(.failure(error)) } } } private func populateModelsFromDeepLink(fromRevisionID: Int?, toRevisionID: Int?, articleTitle: String, completion: @escaping ((Result<DeepLinkModelsResponse, Error>) -> Void)) { guard let articleTitle = (articleTitle as NSString).wmf_normalizedPageTitle() else { completion(.failure(DiffError.fetchRevisionConstructTitleFailure)) return } var fromResponse: WMFPageHistoryRevision? var toResponse: WMFPageHistoryRevision? var firstResponse: WMFPageHistoryRevision? let group = DispatchGroup() if let fromRevisionID = fromRevisionID { group.enter() let fromRequest = DiffFetcher.FetchRevisionModelRequest.populateModel(revisionID: fromRevisionID) diffFetcher.fetchRevisionModel(siteURL, articleTitle: articleTitle, request: fromRequest) { (result) in switch result { case .success(let fetchResponse): fromResponse = fetchResponse case .failure: break } group.leave() } } if let toRevisionID = toRevisionID { group.enter() let toRequest = DiffFetcher.FetchRevisionModelRequest.populateModel(revisionID: toRevisionID) diffFetcher.fetchRevisionModel(siteURL, articleTitle: articleTitle, request: toRequest) { (result) in switch result { case .success(let fetchResponse): toResponse = fetchResponse case .failure: break } group.leave() } } group.enter() diffFetcher.fetchFirstRevisionModel(siteURL: siteURL, articleTitle: articleTitle) { (result) in switch result { case .success(let fetchResponse): firstResponse = fetchResponse case .failure: break } group.leave() } group.notify(queue: DispatchQueue.global(qos: .userInitiated)) { guard let firstResponse = firstResponse, (fromResponse != nil || toResponse != nil) else { completion(.failure(DiffError.failureToPopulateModelsFromDeepLink)) return } let response = DeepLinkModelsResponse(from: fromResponse, to: toResponse, first: firstResponse, articleTitle: articleTitle) completion(.success(response)) } } func fetchAdjacentRevisionModel(sourceRevision: WMFPageHistoryRevision, direction: RevisionDirection, articleTitle: String, completion: @escaping ((Result<WMFPageHistoryRevision, Error>) -> Void)) { if let revisionRetrievingDelegate = revisionRetrievingDelegate { //optimization - first try to grab a revision we might already have in memory from the revisionRetrievingDelegate switch direction { case .next: if let nextRevision = revisionRetrievingDelegate.retrieveNextRevision(with: sourceRevision) { completion(.success(nextRevision)) return } case .previous: if let previousRevision = revisionRetrievingDelegate.retrievePreviousRevision(with: sourceRevision) { completion(.success(previousRevision)) return } } } let direction: DiffFetcher.FetchRevisionModelRequestDirection = direction == .previous ? .older : .newer let request = DiffFetcher.FetchRevisionModelRequest.adjacent(sourceRevision: sourceRevision, direction: direction) diffFetcher.fetchRevisionModel(siteURL, articleTitle: articleTitle, request: request) { (result) in switch result { case .success(let response): completion(.success(response)) case .failure(let error): completion(.failure(error)) } } } func fetchFirstRevisionDiff(revisionId: Int, siteURL: URL, theme: Theme, traitCollection: UITraitCollection, completion: @escaping ((Result<[DiffListGroupViewModel], Error>) -> Void)) { diffFetcher.fetchWikitext(siteURL: siteURL, revisionId: revisionId) { (result) in switch result { case .success(let wikitext): do { let viewModels = try self.transformer.firstRevisionViewModels(from: wikitext, theme: theme, traitCollection: traitCollection) completion(.success(viewModels)) } catch (let error) { completion(.failure(error)) } case .failure(let error): completion(.failure(error)) } } } func fetchDiff(fromRevisionId: Int, toRevisionId: Int, theme: Theme, traitCollection: UITraitCollection, completion: @escaping ((Result<[DiffListGroupViewModel], Error>) -> Void)) { // let queue = DispatchQueue.global(qos: .userInitiated) // // queue.async { [weak self] in // // guard let self = self else { return } // // do { // // let url = Bundle.main.url(forResource: "DiffResponse", withExtension: "json")! // let data = try Data(contentsOf: url) // let diffResponse = try JSONDecoder().decode(DiffResponse.self, from: data) // // // do { // let viewModels = try self.transformer.viewModels(from: diffResponse, theme: theme, traitCollection: traitCollection) // // completion(.success(viewModels)) // } catch (let error) { // completion(.failure(error)) // } // // // } catch (let error) { // completion(.failure(error)) // } // } diffFetcher.fetchDiff(fromRevisionId: fromRevisionId, toRevisionId: toRevisionId, siteURL: siteURL) { [weak self] (result) in guard let self = self else { return } switch result { case .success(let diffResponse): do { let viewModels = try self.transformer.viewModels(from: diffResponse, theme: theme, traitCollection: traitCollection) completion(.success(viewModels)) } catch (let error) { completion(.failure(error)) } case .failure(let error): completion(.failure(error)) } } } }
mit
Edovia/SwiftPasscodeLock
PasscodeLock/Views/PasscodeSignPlaceholderView.swift
1
2164
// // PasscodeSignPlaceholderView.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/28/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import UIKit @IBDesignable public class PasscodeSignPlaceholderView: UIView { public enum State { case inactive case active case error } @IBInspectable public var inactiveColor: UIColor = UIColor.white { didSet { setupView() } } @IBInspectable public var activeColor: UIColor = UIColor.gray { didSet { setupView() } } @IBInspectable public var errorColor: UIColor = UIColor.red { didSet { setupView() } } public override init(frame: CGRect) { super.init(frame: frame) setupView() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override var intrinsicContentSize: CGSize { return CGSize(width: 16, height: 16) } private func setupView() { layer.cornerRadius = 8 layer.borderWidth = 1 layer.borderColor = activeColor.cgColor backgroundColor = inactiveColor } private func colorsForState(_ state: State) -> (backgroundColor: UIColor, borderColor: UIColor) { switch state { case .inactive: return (inactiveColor, activeColor) case .active: return (activeColor, activeColor) case .error: return (errorColor, errorColor) } } public func animateState(_ state: State) { let colors = colorsForState(state) UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { self.backgroundColor = colors.backgroundColor self.layer.borderColor = colors.borderColor.cgColor }, completion: nil ) } }
mit
combes/audio-weather
AudioWeather/AudioWeather/WeatherViewModel.swift
1
4370
// // WeatherViewModel.swift // AudioWeather // // Created by Christopher Combes on 6/25/17. // Copyright © 2017 Christopher Combes. All rights reserved. // import UIKit class WeatherViewModel: WeatherModelProtocol { // Protocol proprerties var city: String { get { return (cityText.characters.count == 0 ? "--" : cityText) } } var conditionText: String { get { return (conditionaryText.characters.count == 0 ? "--" : conditionaryText) } } var temperature: String { get { return UnitsViewModel.formattedTemperature(temperatureText) } } var windDirection: String { get { return windDirectionText.compassDirection() } } var windChill: String { get { return (windChillText.characters.count == 0 ? UnitsViewModel.formattedTemperature("-") : UnitsViewModel.formattedTemperature(windChillText)) } } var windSpeed: String { get { return UnitsViewModel.formattedSpeed(windSpeedText) } } var sunrise: String { get { return sunriseText.characters.count == 0 ? "-- am" : sunriseText } } var sunset: String { get { return sunsetText.characters.count == 0 ? "-- pm" : sunsetText } } var date: String // Private properties private var cityText: String private var temperatureText: String private var conditionaryText: String private var windDirectionText: String private var windChillText: String private var windSpeedText: String private var sunriseText: String private var sunsetText: String init(model: WeatherModel) { cityText = model.city conditionaryText = model.conditionText temperatureText = model.temperature windDirectionText = model.windDirection windChillText = model.windChill windSpeedText = model.windSpeed sunriseText = model.sunrise sunsetText = model.sunset date = model.date } func backgroundImage() -> UIImage { return backgroundImage(sunriseHour: hourUsingTimeFormat(timeText: sunrise), sunsetHour: hourUsingTimeFormat(timeText: sunset), currentHour: hourUsingWeatherFormat(dateText: date)) } /// Derive background image based on sunrise, day, sunset, night /// /// - Returns: Image name based on current time func backgroundImage(sunriseHour: Int, sunsetHour: Int, currentHour: Int) -> UIImage { if (abs(sunriseHour - currentHour) <= 1) { return #imageLiteral(resourceName: "background-sunrise") } if (abs(sunsetHour - currentHour) <= 1) { return #imageLiteral(resourceName: "background-sunset") } if (currentHour > sunriseHour && currentHour < sunsetHour) { return #imageLiteral(resourceName: "background-day") } return #imageLiteral(resourceName: "background-evening") } // MARK: Helper methods func hourUsingWeatherFormat(dateText: String) -> Int { var hour = 0 var textComponents = dateText.components(separatedBy: " ") textComponents.removeLast() let newText = textComponents.joined(separator: " ") let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE, d MMM yyyy hh:mm a" if let checkDate = dateFormatter.date(from: newText) { let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian) let components = calendar?.components(NSCalendar.Unit.hour, from: checkDate) hour = components?.hour ?? 0 } return hour } func hourUsingTimeFormat(timeText: String) -> Int { var hour = 0 let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm a" if let checkDate = dateFormatter.date(from: timeText) { let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian) let components = calendar?.components(NSCalendar.Unit.hour, from: checkDate) hour = components?.hour ?? 0 } return hour } }
mit
JackLearning/Weibo
Weibo/Weibo/Classes/Module/Home/StatusCell/StatusPictureView.swift
1
5937
// // StatusPictureView.swift // Weibo // // Created by apple on 15/12/21. // Copyright © 2015年 apple. All rights reserved. // import UIKit private let pictureCellID = "pictureCellID" private let pictureCellMargin:CGFloat = 5 class StatusPictureView: UICollectionView { // MARK:定义外部模型属性 var imageURLs: [NSURL]? { didSet { //修改配图视图的大小 let pSize = caclePictureViewSize() //更新配图视图的大小 self.snp_updateConstraints { (make) -> Void in make.size.equalTo(pSize) } //修改测试的文案 testLabel.text = "\(imageURLs?.count ?? 0)" // 刷新列表 reloadData() } } // MARK:重写构造方法 override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { //实例化一个 流水布局 let flowLayout = UICollectionViewFlowLayout() // 设置间距 flowLayout.minimumInteritemSpacing = pictureCellMargin flowLayout.minimumLineSpacing = pictureCellMargin super.init(frame: frame, collectionViewLayout: flowLayout) backgroundColor = UIColor.whiteColor() self.registerClass(PictureCell.self, forCellWithReuseIdentifier:pictureCellID) // 设置数据源 self.dataSource = self //设置视图 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* 单图会按照图片等比例显示 多图的图片大小固定 多图如果是4张,会按照 2 * 2 显示 多图其他数量,按照 3 * 3 九宫格显示 */ //计算配图视图的大小 private func caclePictureViewSize() -> CGSize { //计算配图的大小 //1.获取配图的数量 let imageCount = imageURLs?.count ?? 0 //获取配图视图的最大宽度 let maxWidth = screenW - 2 * StatusCellMarigin let itemWidth = (maxWidth - 2 * pictureCellMargin) / 3 // 1,取出collectionView的流水布局 let layout = self.collectionViewLayout as! UICollectionViewFlowLayout // 设置itemSize layout.itemSize = CGSize(width: itemWidth, height: itemWidth) //没有图片 if imageCount == 0 { return CGSizeZero } //单张图片 if imageCount == 1 { //TODO: 单图会按照图片等比例显示 //先给定固定尺寸 let imageSize = CGSize(width: 180, height: 120) // 设置单张图片的 itemSize layout.itemSize = imageSize return imageSize } if imageCount == 4 { //多图如果是4张,会按照 2 * 2 显示 let w = itemWidth * 2 + pictureCellMargin return CGSize(width: w, height: w) } //如果程序走到这里 就是其他的多张图片 //1. 确定有多少行 /* 1,2,3 -> 1 4,5,6 -> 2 7,8,9 -> 3 先 整体 + 1 -> 修正 分子 -1 */ let row = CGFloat((imageCount - 1) / 3 + 1) return CGSize(width: maxWidth, height: row * itemWidth + (row - 1) * pictureCellMargin ) } // MARK:设置页面 和 布局 private func setupUI() { self.addSubview(testLabel) testLabel.snp_makeConstraints { (make) -> Void in make.center.equalTo(self.snp_center) } } // MARK:懒加载所有的子视图 private lazy var testLabel: UILabel = UILabel(title: "", color: UIColor.redColor(), fontSize: 30) } // 数据源方法 //MARK: 数据源方法 extension StatusPictureView: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageURLs?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { //使用这个方法 一定要注册cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! PictureCell // cell.backgroundColor = UIColor.randomColor() cell.imageURL = imageURLs![indexPath.item] return cell } } class PictureCell: UICollectionViewCell { // MARK:定义外部模型属性 var imageURL: NSURL? { didSet { iconView.sd_setImageWithURL(imageURL) } } // MARK:重写构造方法 override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:设置页面 和 布局 private func setupUI() { contentView.addSubview(iconView) //设置布局 iconView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(snp_edges) } } // MARK:懒加载所有的子视图 private lazy var iconView: UIImageView = { let iv = UIImageView() //ScaleAspectFill 显示图片的原比例 但是 图片会被裁减 一般采用这种方式 //ScaleToFill 图片默认的显示样式 但是 图片 会被压缩 或者拉伸 一般不推荐使用这种方式来显示 iv.contentMode = UIViewContentMode.ScaleAspectFill //在手码开发中 图片的默认的剪裁 是没有开启的 需要手动设置 iv.clipsToBounds = true return iv }() }
mit
mollywoodnini/ImageViewer
ImageViewer/ImageViewer.swift
1
13232
// // ImageViewer.swift // ImageViewer // // Created by Tan Nghia La on 30.04.15. // Copyright (c) 2015 Tan Nghia La. All rights reserved. // import UIKit final class ImageViewer: UIViewController { // MARK: - Properties fileprivate let kMinMaskViewAlpha: CGFloat = 0.3 fileprivate let kMaxImageScale: CGFloat = 2.5 fileprivate let kMinImageScale: CGFloat = 1.0 fileprivate let senderView: UIImageView fileprivate var originalFrameRelativeToScreen: CGRect! fileprivate var rootViewController: UIViewController! fileprivate let imageView = UIImageView() fileprivate var panGesture: UIPanGestureRecognizer! fileprivate var panOrigin: CGPoint! fileprivate var isAnimating = false fileprivate var isLoaded = false fileprivate var closeButton = UIButton() fileprivate let windowBounds = UIScreen.main.bounds fileprivate let scrollView = UIScrollView() fileprivate let maskView = UIView() // MARK: - Lifecycle methods init(senderView: UIImageView, backgroundColor: UIColor) { self.senderView = senderView rootViewController = UIApplication.shared.keyWindow!.rootViewController! maskView.backgroundColor = backgroundColor super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configureView() configureMaskView() configureScrollView() configureCloseButton() configureImageView() configureConstraints() } // MARK: - View configuration fileprivate func configureScrollView() { scrollView.frame = windowBounds scrollView.delegate = self scrollView.minimumZoomScale = kMinImageScale scrollView.maximumZoomScale = kMaxImageScale scrollView.zoomScale = 1 view.addSubview(scrollView) } fileprivate func configureMaskView() { maskView.frame = windowBounds maskView.alpha = 0.0 view.insertSubview(maskView, at: 0) } fileprivate func configureCloseButton() { closeButton.alpha = 0.0 let image = UIImage(named: "Close", in: Bundle(for: ImageViewer.self), compatibleWith: nil) closeButton.setImage(image, for: UIControlState()) closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.addTarget(self, action: #selector(ImageViewer.closeButtonTapped(_:)), for: UIControlEvents.touchUpInside) view.addSubview(closeButton) view.setNeedsUpdateConstraints() } fileprivate func configureView() { var originalFrame = senderView.convert(windowBounds, to: nil) originalFrame.origin = CGPoint(x: originalFrame.origin.x, y: originalFrame.origin.y) originalFrame.size = senderView.frame.size originalFrameRelativeToScreen = originalFrame UIApplication.shared.setStatusBarHidden(true, with: UIStatusBarAnimation.slide) } fileprivate func configureImageView() { senderView.alpha = 0.0 imageView.frame = originalFrameRelativeToScreen imageView.isUserInteractionEnabled = true imageView.contentMode = UIViewContentMode.scaleAspectFit imageView.image = senderView.image scrollView.addSubview(imageView) animateEntry() addPanGestureToView() addGestures() centerScrollViewContents() } fileprivate func configureConstraints() { var constraints: [NSLayoutConstraint] = [] let views: [String: UIView] = [ "closeButton": closeButton ] constraints.append(NSLayoutConstraint(item: closeButton, attribute: .centerX, relatedBy: .equal, toItem: closeButton.superview, attribute: .centerX, multiplier: 1.0, constant: 0)) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[closeButton(==64)]-40-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[closeButton(==64)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) NSLayoutConstraint.activate(constraints) } // MARK: - Gestures fileprivate func addPanGestureToView() { panGesture = UIPanGestureRecognizer(target: self, action: #selector(ImageViewer.gestureRecognizerDidPan(_:))) panGesture.cancelsTouchesInView = false panGesture.delegate = self imageView.addGestureRecognizer(panGesture) } fileprivate func addGestures() { let singleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageViewer.didSingleTap(_:))) singleTapRecognizer.numberOfTapsRequired = 1 singleTapRecognizer.numberOfTouchesRequired = 1 scrollView.addGestureRecognizer(singleTapRecognizer) let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageViewer.didDoubleTap(_:))) doubleTapRecognizer.numberOfTapsRequired = 2 doubleTapRecognizer.numberOfTouchesRequired = 1 scrollView.addGestureRecognizer(doubleTapRecognizer) singleTapRecognizer.require(toFail: doubleTapRecognizer) } fileprivate func zoomInZoomOut(_ point: CGPoint) { let newZoomScale = scrollView.zoomScale > (scrollView.maximumZoomScale / 2) ? scrollView.minimumZoomScale : scrollView.maximumZoomScale let scrollViewSize = scrollView.bounds.size let w = scrollViewSize.width / newZoomScale let h = scrollViewSize.height / newZoomScale let x = point.x - (w / 2.0) let y = point.y - (h / 2.0) let rectToZoomTo = CGRect(x: x, y: y, width: w, height: h) scrollView.zoom(to: rectToZoomTo, animated: true) } // MARK: - Animation fileprivate func animateEntry() { guard let image = imageView.image else { fatalError("no image provided") } UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() -> Void in self.imageView.frame = self.centerFrameFromImage(image) }, completion: nil) UIView.animate(withDuration: 0.4, delay: 0.03, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() -> Void in self.closeButton.alpha = 1.0 self.maskView.alpha = 1.0 }, completion: nil) UIView.animate(withDuration: 0.4, delay: 0.1, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() -> Void in self.view.transform = CGAffineTransform.identity.scaledBy(x: 1.1, y: 1.1) self.rootViewController.view.transform = CGAffineTransform.identity.scaledBy(x: 0.95, y: 0.95) }, completion: nil) } fileprivate func centerFrameFromImage(_ image: UIImage) -> CGRect { var newImageSize = imageResizeBaseOnWidth(windowBounds.size.width, oldWidth: image.size.width, oldHeight: image.size.height) newImageSize.height = min(windowBounds.size.height, newImageSize.height) return CGRect(x: 0, y: windowBounds.size.height / 2 - newImageSize.height / 2, width: newImageSize.width, height: newImageSize.height) } fileprivate func imageResizeBaseOnWidth(_ newWidth: CGFloat, oldWidth: CGFloat, oldHeight: CGFloat) -> CGSize { let scaleFactor = newWidth / oldWidth let newHeight = oldHeight * scaleFactor return CGSize(width: newWidth, height: newHeight) } // MARK: - Actions func gestureRecognizerDidPan(_ recognizer: UIPanGestureRecognizer) { if scrollView.zoomScale != 1.0 || isAnimating { return } senderView.alpha = 0.0 scrollView.bounces = false let windowSize = maskView.bounds.size let currentPoint = panGesture.translation(in: scrollView) let y = currentPoint.y + panOrigin.y imageView.frame.origin = CGPoint(x: currentPoint.x + panOrigin.x, y: y) let yDiff = abs((y + imageView.frame.size.height / 2) - windowSize.height / 2) maskView.alpha = max(1 - yDiff / (windowSize.height / 0.95), kMinMaskViewAlpha) closeButton.alpha = max(1 - yDiff / (windowSize.height / 0.95), kMinMaskViewAlpha) / 2 if (panGesture.state == UIGestureRecognizerState.ended || panGesture.state == UIGestureRecognizerState.cancelled) && scrollView.zoomScale == 1.0 { maskView.alpha < 0.85 ? dismissViewController() : rollbackViewController() } } func didSingleTap(_ recognizer: UITapGestureRecognizer) { scrollView.zoomScale == 1.0 ? dismissViewController() : scrollView.setZoomScale(1.0, animated: true) } func didDoubleTap(_ recognizer: UITapGestureRecognizer) { let pointInView = recognizer.location(in: imageView) zoomInZoomOut(pointInView) } func closeButtonTapped(_ sender: UIButton) { if scrollView.zoomScale != 1.0 { scrollView.setZoomScale(1.0, animated: true) } dismissViewController() } // MARK: - Misc. fileprivate func centerScrollViewContents() { let boundsSize = rootViewController.view.bounds.size var contentsFrame = imageView.frame if contentsFrame.size.width < boundsSize.width { contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } imageView.frame = contentsFrame } fileprivate func rollbackViewController() { guard let image = imageView.image else { fatalError("no image provided") } isAnimating = true UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() in self.imageView.frame = self.centerFrameFromImage(image) self.maskView.alpha = 1.0 self.closeButton.alpha = 1.0 }, completion: {(finished) in self.isAnimating = false }) } fileprivate func dismissViewController() { isAnimating = true DispatchQueue.main.async(execute: { self.imageView.clipsToBounds = true UIView.animate(withDuration: 0.2, animations: {() in self.closeButton.alpha = 0.0 }) UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() in self.imageView.frame = self.originalFrameRelativeToScreen self.rootViewController.view.transform = CGAffineTransform.identity.scaledBy(x: 1.0, y: 1.0) self.view.transform = CGAffineTransform.identity.scaledBy(x: 1.0, y: 1.0) self.maskView.alpha = 0.0 UIApplication.shared.setStatusBarHidden(false, with: UIStatusBarAnimation.none) }, completion: {(finished) in self.willMove(toParentViewController: nil) self.view.removeFromSuperview() self.removeFromParentViewController() self.senderView.alpha = 1.0 self.isAnimating = false }) }) } func presentFromRootViewController() { willMove(toParentViewController: rootViewController) rootViewController.view.addSubview(view) rootViewController.addChildViewController(self) didMove(toParentViewController: rootViewController) } } // MARK: - GestureRecognizer delegate extension ImageViewer: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { panOrigin = imageView.frame.origin gestureRecognizer.isEnabled = true return !isAnimating } } // MARK: - ScrollView delegate extension ImageViewer: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { isAnimating = true centerScrollViewContents() } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { isAnimating = false } }
mit
joerocca/GitHawk
Classes/Utility/DeleteSwipeAction.swift
2
508
// // DeleteSwipeAction.swift // Freetime // // Created by Hesham Salman on 10/24/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import SwipeCellKit func DeleteSwipeAction(callback: ((SwipeAction, IndexPath) -> Void)? = nil) -> SwipeAction { let action = SwipeAction(style: .destructive, title: Constants.Strings.delete, handler: callback) action.backgroundColor = Styles.Colors.Red.medium.color action.textColor = .white action.tintColor = .white return action }
mit
prebid/prebid-mobile-ios
Example/PrebidDemo/PrebidDemoSwift/Examples/MAX/MAXNativeViewController.swift
1
5347
/* Copyright 2019-2022 Prebid.org, 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 PrebidMobile import PrebidMobileMAXAdapters import AppLovinSDK fileprivate let nativeStoredImpression = "imp-prebid-banner-native-styles" fileprivate let nativeStoredResponse = "response-prebid-banner-native-styles" fileprivate let maxRenderingNativeAdUnitId = "e4375fdcc7c5e56c" class MAXNativeViewController: BannerBaseViewController, MANativeAdDelegate { // Prebid private var maxMediationNativeAdUnit: MediationNativeAdUnit! private var maxMediationDelegate: MAXMediationNativeUtils! private var nativeRequestAssets: [NativeAsset] { let image = NativeAssetImage(minimumWidth: 200, minimumHeight: 50, required: true) image.type = ImageAsset.Main let icon = NativeAssetImage(minimumWidth: 20, minimumHeight: 20, required: true) icon.type = ImageAsset.Icon let title = NativeAssetTitle(length: 90, required: true) let body = NativeAssetData(type: DataAsset.description, required: true) let cta = NativeAssetData(type: DataAsset.ctatext, required: true) let sponsored = NativeAssetData(type: DataAsset.sponsored, required: true) return [title, icon, image, sponsored, body, cta] } private var eventTrackers: [NativeEventTracker] { [NativeEventTracker(event: EventType.Impression, methods: [EventTracking.Image,EventTracking.js])] } // MAX private var maxNativeAdLoader: MANativeAdLoader! private weak var maxLoadedNativeAd: MAAd! override func loadView() { super.loadView() Prebid.shared.storedAuctionResponse = nativeStoredResponse createAd() } deinit { if let maxLoadedNativeAd = maxLoadedNativeAd { maxNativeAdLoader?.destroy(maxLoadedNativeAd) } } func createAd() { // 1. Create a MANativeAdLoader maxNativeAdLoader = MANativeAdLoader(adUnitIdentifier: maxRenderingNativeAdUnitId) maxNativeAdLoader.nativeAdDelegate = self // 2. Create the MAXMediationNativeUtils maxMediationDelegate = MAXMediationNativeUtils(nativeAdLoader: maxNativeAdLoader) // 3. Create the MediationNativeAdUnit maxMediationNativeAdUnit = MediationNativeAdUnit(configId: nativeStoredImpression, mediationDelegate: maxMediationDelegate) // 4. Configure the MediationNativeAdUnit maxMediationNativeAdUnit.addNativeAssets(nativeRequestAssets) maxMediationNativeAdUnit.setContextType(.Social) maxMediationNativeAdUnit.setPlacementType(.FeedContent) maxMediationNativeAdUnit.setContextSubType(.Social) maxMediationNativeAdUnit.addEventTracker(eventTrackers) // 5. Create a MAXNativeAdView let nativeAdViewNib = UINib(nibName: "MAXNativeAdView", bundle: Bundle.main) let maNativeAdView = nativeAdViewNib.instantiate(withOwner: nil, options: nil).first! as! MANativeAdView? // 6. Create a MANativeAdViewBinder let adViewBinder = MANativeAdViewBinder.init(builderBlock: { (builder) in builder.iconImageViewTag = 1 builder.titleLabelTag = 2 builder.bodyLabelTag = 3 builder.advertiserLabelTag = 4 builder.callToActionButtonTag = 5 builder.mediaContentViewTag = 123 }) // 7. Bind views maNativeAdView!.bindViews(with: adViewBinder) // 7. Make a bid request to Prebid Server maxMediationNativeAdUnit.fetchDemand { [weak self] result in // 8. Load the native ad self?.maxNativeAdLoader.loadAd(into: maNativeAdView!) } } // MARK: - MANativeAdDelegate func didLoadNativeAd(_ nativeAdView: MANativeAdView?, for ad: MAAd) { if let nativeAd = maxLoadedNativeAd { maxNativeAdLoader?.destroy(nativeAd) } maxLoadedNativeAd = ad bannerView.backgroundColor = .clear nativeAdView?.translatesAutoresizingMaskIntoConstraints = false bannerView.addSubview(nativeAdView!) bannerView.heightAnchor.constraint(equalTo: nativeAdView!.heightAnchor).isActive = true bannerView.topAnchor.constraint(equalTo: nativeAdView!.topAnchor).isActive = true bannerView.leftAnchor.constraint(equalTo: nativeAdView!.leftAnchor).isActive = true bannerView.rightAnchor.constraint(equalTo: nativeAdView!.rightAnchor).isActive = true } func didFailToLoadNativeAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) { PrebidDemoLogger.shared.error("\(error.message)") } func didClickNativeAd(_ ad: MAAd) {} }
apache-2.0
thomaskamps/SlideFeedback
SlideFeedback/SlideFeedback/HistoryTableViewCell.swift
1
494
// // LecturerHistoryTableViewCell.swift // // // Created by Thomas Kamps on 22-06-17. // // import UIKit class HistoryTableViewCell: UITableViewCell { @IBOutlet weak var label: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
unlicense
ihomway/RayWenderlichCourses
Beginning Swift 3/Beginning Swift 3.playground/Pages/Tuples.xcplaygroundpage/Contents.swift
1
435
//: [Previous](@previous) import Foundation var str = "Hello, playground" var monster = ("Reaper", 100, true) monster.0 monster.1 monster.2 var anotherMonster: (String, Int, Bool) anotherMonster = ("Savager", 100, false) var yetAnotherMonster = (name: "Blobby", hitPoints: 200, isAggroed: true) yetAnotherMonster.hitPoints yetAnotherMonster.name yetAnotherMonster.isAggroed var (name, hp, _) = monster name hp //: [Next](@next)
mit