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
divita-lorenzo/ios-encapsulated
QapaEncapsulated/QapaEncapsulatedTests/QapaEncapsulatedTests.swift
1
938
// // QapaEncapsulatedTests.swift // QapaEncapsulatedTests // // Created by Lorenzo DI VITA on 06/10/2014. // Copyright (c) 2014 Lorenzo DI VITA. All rights reserved. // import UIKit import XCTest class QapaEncapsulatedTests: 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
IngmarStein/swift
validation-test/compiler_crashers_fixed/28318-swift-constraints-constraintgraphnode-getmembertype.swift
5
469
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse // REQUIRES: asserts protocol A{ protocol A typealias e:A}struct c<I:A for c
apache-2.0
MFaarkrog/swift-snippets
code/ss-uiviewcontroller.swift
1
242
import UIKit class <#controller-name#>: UIViewController { // MARK: - Properties // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() } // MARK: - IBActions // MARK: - Helper Functions }
gpl-3.0
xumx/ditto
Ditto/DittoStore.swift
2
12419
import UIKit import CoreData class DittoStore : NSObject { let MAX_CATEGORIES = 8 let PRESET_CATEGORIES = ["Instructions", "Driving", "Business", "Dating 🔥❤️"] let PRESET_DITTOS = [ "Instructions": [ "Welcome to Ditto! 👋", "Add Ditto in Settings > General > Keyboard > Keyboards.", "You must allow full access for Ditto to work properly. After you've added the Ditto keyboard, select it, and turn on Allow Full Access.", "We DO NOT access ANYTHING that you type on the keyboard.", "Everything is saved privately on your device. 🔒", "Use the Ditto app to customize your dittos.", "Add a triple underscore ___ to your ditto to control where your cursor lands.", "You can expand long dittos within the keyboard by holding them down. Go ahead and give this one a try! You can expand long dittos within the keyboard by holding them down. Go ahead and give this one a try! You can expand long dittos within the keyboard by holding them down. Go ahead and give this one a try! You can expand long dittos within the keyboard by holding them down. Go ahead and give this one a try!", "Hold down a keyboard tab to expand the category title, and swipe on the tab bar for quick access." ], "Driving": [ "I'm driving, can you call me?", "I'll be there in ___ minutes!", "What's the address?", "Can't text, I'm driving 🚘" ], "Business": [ "Hi ___,\n\nIt was great meeting you today. I'd love to chat in more detail about possible business opportunities. Please let me know your availability.\n\nBest,\nAsaf Avidan Antonir", "My name is Asaf, and I work at Shmoogle on the search team. We are always looking for talented candidates to join our team, and with your impressive background, we think you could be a great fit. Please let me know if you are interested, and if so, your availability to chat this week." ], "Dating 🔥❤️": [ "I'm not a photographer, but I can picture us together. 📷", "Was your dad a thief? Because someone stole the stars from the sky and put them in your eyes ✨👀✨.", "Do you have a Band-Aid? Because I just scraped my knee falling for you." ] ] let defaults = NSUserDefaults(suiteName: "group.io.kern.ditto")! static var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource("Ditto", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() static var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let directory = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.io.kern.ditto") let storeURL = directory?.URLByAppendingPathComponent("Ditto.sqlite") let options = [ NSMigratePersistentStoresAutomaticallyOption: NSNumber(bool: true), NSInferMappingModelAutomaticallyOption: NSNumber(bool: true) ] let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) var err: NSError? = nil do { try persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options) } catch var error as NSError { err = error fatalError(err!.localizedDescription) } catch { fatalError() } return persistentStoreCoordinator }() static var managedObjectContext: NSManagedObjectContext = { var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator return managedObjectContext }() //=================== // MARK: Persistence lazy var context: NSManagedObjectContext = { return DittoStore.managedObjectContext }() func save() { var err: NSError? = nil do { try DittoStore.managedObjectContext.save() } catch let error as NSError { err = error fatalError(err!.localizedDescription) } } func createProfile() -> Profile { let profile = NSEntityDescription.insertNewObjectForEntityForName("Profile", inManagedObjectContext: DittoStore.managedObjectContext) as! Profile for categoryName in PRESET_CATEGORIES { let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: DittoStore.managedObjectContext) as! Category category.profile = profile category.title = categoryName for dittoText in PRESET_DITTOS[categoryName]! { let ditto = NSEntityDescription.insertNewObjectForEntityForName("Ditto", inManagedObjectContext: DittoStore.managedObjectContext) as! Ditto ditto.category = category ditto.text = dittoText } } // Migrate dittos from V1 defaults.synchronize() if let dittos = defaults.arrayForKey("dittos") as? [String] { let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: DittoStore.managedObjectContext) as! Category category.profile = profile category.title = "General" for dittoText in dittos { let ditto = NSEntityDescription.insertNewObjectForEntityForName("Ditto", inManagedObjectContext: DittoStore.managedObjectContext) as! Ditto ditto.category = category ditto.text = dittoText } } defaults.removeObjectForKey("dittos") defaults.synchronize() save() return profile } func getProfile() -> Profile { let fetchRequest = NSFetchRequest(entityName: "Profile") var error: NSError? do { let profiles = try DittoStore.managedObjectContext.executeFetchRequest(fetchRequest) if profiles.count > 0 { return profiles[0] as! Profile } else { return self.createProfile() } } catch let error1 as NSError { error = error1 fatalError(error!.localizedDescription) } } //=============== // MARK: Getters func getCategories() -> [String] { return Array(getProfile().categories).map({ (category) in let c = category as! Category return c.title }) } func getCategory(categoryIndex: Int) -> String { let category = getProfile().categories[categoryIndex] as! Category return category.title } func getDittosInCategory(categoryIndex: Int) -> [String] { let category = getProfile().categories[categoryIndex] as! Category let dittos = Array(category.dittos) return dittos.map({ (ditto) in let d = ditto as! Ditto return d.text }) } func getDittoInCategory(categoryIndex: Int, index dittoIndex: Int) -> String { let category = getProfile().categories[categoryIndex] as! Category let ditto = category.dittos[dittoIndex] as! Ditto return ditto.text } func getDittoPreviewInCategory(categoryIndex: Int, index dittoIndex: Int) -> String { return preview(getDittoInCategory(categoryIndex, index: dittoIndex)) } //================== // MARK: - Counting func isEmpty() -> Bool { return countCategories() == 0 } func oneCategory() -> Bool { return countCategories() == 1 } func countInCategory(categoryIndex: Int) -> Int { let category = getProfile().categories[categoryIndex] as! Category return category.dittos.count } func countCategories() -> Int { return getProfile().categories.count } //============================= // MARK: - Category Management func canCreateNewCategory() -> Bool { return countCategories() < MAX_CATEGORIES } func addCategoryWithName(name: String) { let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: context) as! Category category.profile = getProfile() category.title = name save() } func removeCategoryAtIndex(categoryIndex: Int) { let category = getProfile().categories[categoryIndex] as! Category context.deleteObject(category) save() } func moveCategoryFromIndex(fromIndex: Int, toIndex: Int) { let categories = getProfile().categories.mutableCopy() as! NSMutableOrderedSet let category = categories[fromIndex] as! Category categories.removeObjectAtIndex(fromIndex) categories.insertObject(category, atIndex: toIndex) getProfile().categories = categories as NSOrderedSet save() } func editCategoryAtIndex(index: Int, name: String) { let category = getProfile().categories[index] as! Category category.title = name save() } //========================== // MARK: - Ditto Management func addDittoToCategory(categoryIndex: Int, text: String) { let ditto = NSEntityDescription.insertNewObjectForEntityForName("Ditto", inManagedObjectContext: context) as! Ditto ditto.category = getProfile().categories[categoryIndex] as! Category ditto.text = text save() } func removeDittoFromCategory(categoryIndex: Int, index dittoIndex: Int) { let category = getProfile().categories[categoryIndex] as! Category let ditto = category.dittos[dittoIndex] as! Ditto context.deleteObject(ditto) save() } func moveDittoFromCategory(fromCategoryIndex: Int, index fromDittoIndex: Int, toCategory toCategoryIndex: Int, index toDittoIndex: Int) { if fromCategoryIndex == toCategoryIndex { let category = getProfile().categories[fromCategoryIndex] as! Category let dittos = category.dittos.mutableCopy() as! NSMutableOrderedSet let ditto = dittos[fromDittoIndex] as! Ditto dittos.removeObjectAtIndex(fromDittoIndex) dittos.insertObject(ditto, atIndex: toDittoIndex) category.dittos = dittos as NSOrderedSet } else { let fromCategory = getProfile().categories[fromCategoryIndex] as! Category let toCategory = getProfile().categories[toCategoryIndex] as! Category let fromDittos = fromCategory.dittos.mutableCopy() as! NSMutableOrderedSet let toDittos = toCategory.dittos.mutableCopy() as! NSMutableOrderedSet let ditto = fromDittos[fromDittoIndex] as! Ditto fromDittos.removeObjectAtIndex(fromDittoIndex) toDittos.insertObject(ditto, atIndex: toDittoIndex) fromCategory.dittos = fromDittos as NSOrderedSet toCategory.dittos = toDittos as NSOrderedSet } save() } func moveDittoFromCategory(fromCategoryIndex: Int, index dittoIndex: Int, toCategory toCategoryIndex: Int) { moveDittoFromCategory(fromCategoryIndex, index: dittoIndex, toCategory: toCategoryIndex, index: countInCategory(toCategoryIndex)) } func editDittoInCategory(categoryIndex: Int, index dittoIndex: Int, text: String) { let category = getProfile().categories[categoryIndex] as! Category let ditto = category.dittos[dittoIndex] as! Ditto ditto.text = text save() } //================= // MARK: - Helpers func preview(ditto: String) -> String { return ditto .stringByReplacingOccurrencesOfString("\n", withString: " ") .stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " ")) } }
bsd-3-clause
tadija/AEXML
Sources/AEXML/Error.swift
1
744
/** * https://github.com/tadija/AEXML * Copyright © Marko Tadić 2014-2021 * Licensed under the MIT license */ import Foundation #if canImport(FoundationXML) import FoundationXML #endif /// A type representing error value that can be thrown or inside `error` property of `AEXMLElement`. public enum AEXMLError: Error { /// This will be inside `error` property of `AEXMLElement` when subscript is used for not-existing element. case elementNotFound /// This will be inside `error` property of `AEXMLDocument` when there is no root element. case rootElementMissing /// `AEXMLDocument` can throw this error on `init` or `loadXMLData` if parsing with `XMLParser` was not successful. case parsingFailed }
mit
swift-lang/swift-k
tests/language/working/03102-var-decl.swift
2
45
int p[] = [1 : 9 : 2]; // numbers 1 3 5 7 9
apache-2.0
richardpiazza/XCServerCoreData
Sources/IntegrationStep.swift
1
989
import Foundation /// ### IntegrationStep /// Current state of the `Integration` as it moves through the lifecycle. public enum IntegrationStep: String { case unknown case pending = "pending" case checkout = "checkout" case beforeTriggers = "before-triggers" case building = "building" case testing = "testing" case archiving = "archiving" case processing = "processing" case uploading = "uploading" case completed = "completed" public var description: String { switch self { case .unknown: return "Unknown" case .pending: return "Pending" case .checkout: return "Checkout" case .beforeTriggers: return "Before Triggers" case .building: return "Building" case .testing: return "Testing" case .archiving: return "Archiving" case .processing: return "Processing" case .uploading: return "Uploading" case .completed: return "Completed" } } }
mit
codestergit/Design-Patterns-In-Swift
Design-Patterns.playground/section-8.swift
3
129
let fancyPoint = Point { point in point.x = 0.1 point.y = 0.2 point.z = 0.3 } fancyPoint.x fancyPoint.y fancyPoint.z
gpl-3.0
zjjzmw1/speedxSwift
speedxSwift/Pods/RealmSwift/RealmSwift/ObjectSchema.swift
21
2590
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm /** This class represents Realm model object schemas. When using Realm, `ObjectSchema` objects allow performing migrations and introspecting the database's schema. `ObjectSchema`s map to tables in the core database. */ public final class ObjectSchema: CustomStringConvertible { // MARK: Properties internal let rlmObjectSchema: RLMObjectSchema /// Array of persisted `Property` objects for an object. public var properties: [Property] { return rlmObjectSchema.properties.map { Property($0) } } /// The name of the class this schema describes. public var className: String { return rlmObjectSchema.className } /// The property that serves as the primary key, if there is a primary key. public var primaryKeyProperty: Property? { if let rlmProperty = rlmObjectSchema.primaryKeyProperty { return Property(rlmProperty) } return nil } /// Returns a human-readable description of the properties contained in this object schema. public var description: String { return rlmObjectSchema.description } // MARK: Initializers internal init(_ rlmObjectSchema: RLMObjectSchema) { self.rlmObjectSchema = rlmObjectSchema } // MARK: Property Retrieval /// Returns the property with the given name, if it exists. public subscript(propertyName: String) -> Property? { if let rlmProperty = rlmObjectSchema[propertyName] { return Property(rlmProperty) } return nil } } // MARK: Equatable extension ObjectSchema: Equatable {} /// Returns whether the two object schemas are equal. public func == (lhs: ObjectSchema, rhs: ObjectSchema) -> Bool { // swiftlint:disable:this valid_docs return lhs.rlmObjectSchema.isEqualToObjectSchema(rhs.rlmObjectSchema) }
mit
FabrizioBrancati/BFKit-Swift
Tests/BFKitTests/Linux/Foundation/FileManagerExtensionTests.swift
1
7464
// // FileManagerExtensionTests.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // 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. @testable import BFKit import Foundation import XCTest internal class FileManagerExtensionTests: XCTestCase { override internal func setUp() { super.setUp() try? FileManager.default.delete(file: "Test.txt", from: .documents) try? FileManager.default.delete(file: "Test.plist", from: .documents) try? FileManager.default.delete(file: "Test2.plist", from: .documents) try? FileManager.default.delete(file: "Test.plist", from: .library) } internal func testPathFor() { let mainBundlePath = FileManager.default.pathFor(.mainBundle) let documentsPath = FileManager.default.pathFor(.documents) let libraryPath = FileManager.default.pathFor(.library) let cachePath = FileManager.default.pathFor(.cache) let applicationSupportPath = FileManager.default.pathFor(.applicationSupport) XCTAssertNotEqual(mainBundlePath, "") XCTAssertNotEqual(documentsPath, "") XCTAssertNotEqual(libraryPath, "") XCTAssertNotEqual(cachePath, "") XCTAssertNotEqual(applicationSupportPath, "") } internal func testReadFileOfType() { do { try FileManager.default.save(file: "Test.txt", in: .temporary, content: "Test") let file = try FileManager.default.read(file: "Test.txt", from: .temporary) XCTAssertNotNil(file) } catch { XCTFail("`testReadFileOfType` error: \(error.localizedDescription)") } } internal func testSavePlistObjectInFilename() { let saved = FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .temporary, filename: "Test") XCTAssertTrue(saved) } internal func testReadPlistFromFilename() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .temporary, filename: "Test") let readed = FileManager.default.readPlist(from: .temporary, filename: "Test") XCTAssertNotNil(readed) } internal func testMainBundlePathFile() { let path = FileManager.default.mainBundlePath() XCTAssertNotNil(path) } internal func testDocumentsPathFile() { let path = FileManager.default.documentsPath() XCTAssertNotNil(path) } internal func testLibraryPathFile() { let path = FileManager.default.libraryPath() XCTAssertNotNil(path) } internal func testCachePathFile() { let path = FileManager.default.cachePath() XCTAssertNotNil(path) } internal func testApplicationSupportPathFile() { let path = FileManager.default.applicationSupportPath() XCTAssertNotNil(path) } internal func testTemporaryPathFile() { let path = FileManager.default.temporaryPath() XCTAssertNotNil(path) } internal func testSizeFileFrom() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .temporary, filename: "Test") do { let size = try FileManager.default.size(file: "Test.plist", from: .temporary) XCTAssertNotNil(size) let sizeNil = try FileManager.default.size(file: "TestNil.plist", from: .temporary) XCTAssertNil(sizeNil) } catch { XCTFail("`testSizeFileFrom` error") } } internal func testDeleteFileFrom() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.delete(file: "Test.plist", from: .documents) XCTAssertTrue(true) } catch { XCTFail("`testDeleteFileFrom` error") } } internal func testMoveFileFromTo() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.move(file: "Test.plist", from: .documents, to: .library) XCTAssertTrue(true) } catch { XCTFail("`testMoveFileFromTo` error") } } internal func testCopyFileFromTo() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.copy(file: "Test.plist", from: .documents, to: .library) XCTAssertTrue(true) } catch { XCTFail("`testCopyFileFromTo` error") } } internal func testCopyFileFromToMainBundle() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.copy(file: "Test.plist", from: .documents, to: .mainBundle) XCTFail("`testCopyFileFromToMainBundle` error") } catch { XCTAssertTrue(true) } } internal func testRenameFileInFromTo() { FileManager.default.savePlist(object: ["1", "2", "3", "4", "5"], in: .documents, filename: "Test") do { try FileManager.default.rename(file: "Test.plist", in: .documents, to: "Test2.plist") XCTAssertTrue(true) } catch { XCTFail("`testRenameFileInFromTo` error") } } internal func testSetSettingsFilenameObjectForKey() { let settings = FileManager.default.setSettings(filename: "Test", object: ["1", "2", "3", "4", "5"], forKey: "Test") XCTAssertTrue(settings) } internal func testGetSettingsFilenameForKey() { FileManager.default.setSettings(filename: "Test", object: ["1", "2", "3", "4", "5"], forKey: "Test") let settings = FileManager.default.getSettings(filename: "Test", forKey: "Test") XCTAssertNotNil(settings) } internal func testGetEmptySettingsFilenameForKey() { let settings = FileManager.default.getSettings(filename: "Test3", forKey: "Test") XCTAssertNil(settings) } }
mit
vhbit/MastodonKit
Sources/MastodonKit/Resources/Favourites.swift
1
565
import Foundation public struct Favourites { /// Fetches a user's favourites. /// /// - Parameter range: The bounds used when requesting data from Mastodon. /// - Returns: Resource for `[Status]`. public static func all(range: ResourceRange = .default) -> TimelineResource { let parameters = range.parameters(limit: between(1, and: 40, fallback: 20)) let method = HTTPMethod.get(Payload.parameters(parameters)) return TimelineResource(path: "/api/v1/favourites", method: method, parse: TimelineResource.parser) } }
mit
TJ-93/TestKitchen
TestKitchen/TestKitchen/classes/Ingredient/service(处理公共点击事件)/FoodmatchService.swift
1
197
// // FoodmatchService.swift // TestKitchen // // Created by qianfeng on 2016/11/3. // Copyright © 2016年 陶杰. All rights reserved. // import UIKit class FoodmatchService: NSObject { }
mit
sicardf/MyRide
MyRide/UI/Maps/UIView/MapKitView.swift
1
1703
// // ApplePlan.swift // MyRide // // Created by Flavien SICARD on 24/05/2017. // Copyright © 2017 sicardf. All rights reserved. // import UIKit import MapKit class MapKitView: MapView, MKMapViewDelegate { private var mapView: MKMapView! private var pinView: UIImageView! var _delegate: MapDelegate! override init(frame: CGRect) { super.init(frame: frame) self.setup() } override func displayPin() {} override func changeCenterCoordinate(coordinate: CLLocationCoordinate2D) { let region = MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) mapView.setRegion(region, animated: true) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } private func setup() { mapView = MKMapView(frame: self.bounds) mapView.delegate = self mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] mapView.showsUserLocation = true mapView.setUserTrackingMode(MKUserTrackingMode.follow, animated: false) addSubview(mapView) let pinView = UIImageView(frame: CGRect(x: self.frame.size.width / 2 - 25, y: self.frame.size.height / 2 - 50, width: 50, height: 50)) pinView.image = #imageLiteral(resourceName: "pinIcon") addSubview(pinView) } // MARK : MGLMapViewDelegate func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { displayPin() print(mapView.centerCoordinate) delegate.centerCoordinateMapChange(coordinate: mapView.centerCoordinate) } }
mit
StanZabroda/Hydra
Pods/Nuke/Nuke/Source/Core/ImageMemoryCache.swift
10
2547
// The MIT License (MIT) // // Copyright (c) 2015 Alexander Grebenyuk (github.com/kean). import UIKit public protocol ImageMemoryCaching { func cachedResponseForKey(key: AnyObject) -> ImageCachedResponse? func storeResponse(response: ImageCachedResponse, forKey key: AnyObject) func removeAllCachedImages() } public class ImageCachedResponse { public let image: UIImage public let userInfo: Any? public init(image: UIImage, userInfo: Any?) { self.image = image self.userInfo = userInfo } } public class ImageMemoryCache: ImageMemoryCaching { public let cache: NSCache deinit { #if os(iOS) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) #endif } public init(cache: NSCache) { self.cache = cache #if os(iOS) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didReceiveMemoryWarning:"), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) #endif } public convenience init() { let cache = NSCache() cache.totalCostLimit = ImageMemoryCache.recommendedCacheTotalLimit() self.init(cache: cache) } public func cachedResponseForKey(key: AnyObject) -> ImageCachedResponse? { let object: AnyObject? = self.cache.objectForKey(key) return object as? ImageCachedResponse } public func storeResponse(response: ImageCachedResponse, forKey key: AnyObject) { let cost = self.costForImage(response.image) self.cache.setObject(response, forKey: key, cost: cost) } public func costForImage(image: UIImage) -> Int { let imageRef = image.CGImage let bits = CGImageGetWidth(imageRef) * CGImageGetHeight(imageRef) * CGImageGetBitsPerPixel(imageRef) return bits / 8 } public class func recommendedCacheTotalLimit() -> Int { #if os(iOS) let physicalMemory = NSProcessInfo.processInfo().physicalMemory let ratio = physicalMemory <= (1024 * 1024 * 512 /* 512 Mb */) ? 0.1 : 0.2 return Int(Double(physicalMemory) * ratio) #else return 1024 * 1024 * 30 // 30 Mb #endif } public func removeAllCachedImages() { self.cache.removeAllObjects() } @objc private func didReceiveMemoryWarning(notification: NSNotification) { self.cache.removeAllObjects() } }
mit
kstaring/swift
test/DebugInfo/liverange-extension.swift
21
934
// RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s func use<T>(_ x: T) {} func getInt32() -> Int32 { return -1 } public func rangeExtension(_ b: Bool) { // CHECK: define {{.*}}rangeExtension let i = getInt32() // CHECK: llvm.dbg.value(metadata i32 [[I:.*]], i64 0, metadata use(i) if b { let j = getInt32() // CHECK: llvm.dbg.value(metadata i32 [[I]], i64 0, metadata // CHECK: llvm.dbg.value(metadata i32 [[J:.*]], i64 0, metadata use(j) // CHECK-DAG: {{(asm sideeffect "", "r".*)|(zext i32)}} [[J]] // CHECK-DAG: asm sideeffect "", "r" } let z = getInt32() use(z) // CHECK-NOT: llvm.dbg.value(metadata i32 [[J]], i64 0, metadata // CHECK-DAG: llvm.dbg.value(metadata i32 [[I]], i64 0, metadata // CHECK-DAG: llvm.dbg.value(metadata i32 [[Z:.*]], i64 0, metadata // CHECK-DAG: {{(asm sideeffect "", "r".*)|(zext i32)}} [[I]] // CHECK-DAG: asm sideeffect "", "r" }
apache-2.0
kristofer/anagram-go-java
anagram.swift
1
1262
//: Playground - noun: a place where people can play let string1 = "aab" let string2 = "aba" let string3 = "cab" let string4 = "kjfdhskdhfksdhk" let string5 = "Kjfdhskdhfksdhk" func anagram(_ x: String, _ y: String) -> Bool { if x == y { return true } if x.count != y.count { return false } var dictx = [String: Int]() var dicty = [String: Int]() for i in x { let ii = "\(i)" if dictx[ii] != nil { let n = dictx[ii]! + 1 dictx[ii] = n } else { dictx[ii] = 1 } } for i in y { let ii = "\(i)" if dicty[ii] != nil { // handles unwrapping Int? let n = dicty[ii]! + 1 dicty[ii] = n } else { dicty[ii] = 1 } } if dictx.count != dicty.count { return false } for (k, v) in dictx { if let vy = dicty[k] { // handles unwrapping Int? if v != vy { return false } } } return true } func main() { print(anagram(string1, string1)) print(anagram(string1, string2)) print(anagram(string1, string3)) print(anagram(string1, string4)) print(anagram(string4, string5)) } main()
mit
alexanderedge/Toolbelt
Toolbelt/ToolbeltTests/ToolbeltTestsCommon.swift
1
3030
// // ToolbeltTestsCommon.swift // Toolbelt // // The MIT License (MIT) // // Copyright (c) 09/05/2015 Alexander G Edge // // 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 XCTest import CoreGraphics @testable import Toolbelt class ToolbeltTestsCommon: 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 testEmailValidation () { let email = "alex@alexedge.co.uk" XCTAssert(email.isValidEmail(), "email is valid") } func testHexString () { let bytes: [UInt8] = [0x1a,0x2b,0x3c,0x4d,0x5e] let data = NSData(bytes: UnsafePointer<UInt8>(bytes), length: bytes.count) XCTAssertEqual(data.hexadecimalString, "1a2b3c4d5e") } func testImageGeneration () { let image = Image.imageWithColour(Colour.red, size: CGSize(width: 50, height: 50)) XCTAssertNotNil(image, "image shouldn't be nil") } func testColourCreationUsingHex () { let colour = Colour(hex: 0x00801e) XCTAssertEqual(colour, Colour(red: 0, green: 128 / 255, blue: 30 / 255, alpha: 1)) } func testColourCreationUsingHexString () { let colour = Colour(hexString: "00801e") XCTAssertEqual(colour, Colour(red: 0, green: 128 / 255, blue: 30 / 255, alpha: 1)) } func testHexFromColour () { let colour = Colour(red: 0, green: 128 / 255, blue: 30 / 255, alpha: 1) XCTAssertEqual(colour.hex, 0x00801e) } func testHexStringFromColour () { let colour = Colour(red: 0, green: 128 / 255, blue: 30 / 255, alpha: 1) print(colour.hexString) XCTAssertEqual(colour.hexString, "#00801e") } }
mit
russbishop/swift
test/multifile/typealias/two-modules/library.swift
1
145
// RUN: true public enum Result<T, U> { case success(T) case failure(U) } public typealias GenericResult<T> = Result<T, ErrorProtocol>
apache-2.0
mitchtreece/Spider
Spider/Classes/Core/SSE/EventBuffer.swift
1
2841
// // EventBuffer.swift // Spider-Web // // Created by Mitch Treece on 10/6/20. // import Foundation internal class EventBuffer { private var newlineCharacters: [String] private let buffer = NSMutableData() init(newlineCharacters: [String]) { self.newlineCharacters = newlineCharacters } func append(data: Data?) -> [String] { guard let data = data else { return [] } self.buffer.append(data) return parse() } private func parse() -> [String] { var events = [String]() var searchRange = NSRange(location: 0, length: self.buffer.length) while let foundRange = searchFirstEventDelimiter(in: searchRange) { // if we found a delimiter range that means that from the beggining of the buffer // until the beggining of the range where the delimiter was found we have an event. // The beggining of the event is: searchRange.location // The lenght of the event is the position where the foundRange was found. let chunk = self.buffer.subdata( with: NSRange( location: searchRange.location, length: foundRange.location - searchRange.location ) ) if let text = String(bytes: chunk, encoding: .utf8) { events.append(text) } // We move the searchRange start position (location) after the fundRange we just found and searchRange.location = foundRange.location + foundRange.length searchRange.length = self.buffer.length - searchRange.location } // We empty the piece of the buffer we just search in. self.buffer.replaceBytes( in: NSRange(location: 0, length: searchRange.location), withBytes: nil, length: 0 ) return events } private func searchFirstEventDelimiter(in range: NSRange) -> NSRange? { // This methods returns the range of the first delimiter found in the buffer. For example: // If in the buffer we have: `id: event-id-1\ndata:event-data-first\n\n` // This method will return the range for the `\n\n`. let delimiters = self.newlineCharacters.map { "\($0)\($0)".data(using: .utf8)! } for delimiter in delimiters { let foundRange = self.buffer.range( of: delimiter, options: NSData.SearchOptions(), in: range ) if foundRange.location != NSNotFound { return foundRange } } return nil } }
mit
wmcginty/Edits
Sources/Extensions/Sequence+Bifilter.swift
1
559
// // Sequence+Bifilter.swift // Edits // // Created by William McGinty on 12/24/17. // import Foundation extension Sequence { func bifilter(_ isIncluded: (Element) throws -> Bool) rethrows -> (included: [Element], notIncluded: [Element]) { var included = [Element]() var notIncluded = [Element]() for element in self { guard try isIncluded(element) else { notIncluded.append(element); continue } included.append(element) } return (included, notIncluded) } }
mit
ntaku/SwiftEssential
SwiftEssential/ExtString.swift
1
1804
import Foundation import UIKit public extension String { var length: Int { return count } func split(by separator: String) -> [String] { return components(separatedBy: separator) } func gsub(from: String, to: String) -> String { return replacingOccurrences(of: from, with: to) } func boundingRect(with font: UIFont, size: CGSize) -> CGRect { return (self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil) } func height(with font: UIFont) -> CGFloat { return boundingRect(with: font, size: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)).size.height } func width(with font: UIFont) -> CGFloat { return boundingRect(with: font, size: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)).size.width } func boundingHeight(with font: UIFont, width: CGFloat) -> CGFloat { return boundingRect(with: font, size: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)).size.height } func boundingWidth(with font: UIFont, height: CGFloat) -> CGFloat { return boundingRect(with: font, size: CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)).size.width } }
mit
milot/Pendulum
PendulumTests/PendulumTests.swift
1
2824
// // PendulumTests.swift // PendulumTests // // Created by Milot Shala on 3/24/16. // Copyright © 2016 Milot Shala. All rights reserved. // import XCTest import Pendulum class PendulumTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testStart() { let stopwatch = PendulumStopwatch() stopwatch.start() while stopwatch.timePassedSince < 1 {} XCTAssert(stopwatch.isActive, "Should be active and running") XCTAssert(stopwatch.startTime != nil, "Should not be nil") XCTAssert(stopwatch.timePassedSince > 1, "Should be running already") } func testStop() { let stopwatch = PendulumStopwatch() stopwatch.start() stopwatch.stop() XCTAssert(stopwatch.isActive == false, "Should not be active") XCTAssert(stopwatch.startTime == nil, "Date should be nil") XCTAssert(stopwatch.timePassedSince == 0, "No time interval should be present") } func testStartIfPreviouslyRunning() { let stopwatch = PendulumStopwatch() stopwatch.continueIfPreviouslyRunning() XCTAssert(stopwatch.isActive, "Should be active!") stopwatch.stop() XCTAssert(stopwatch.isActive == false, "Should not be active after stop!") } func testPause() { let stopwatch = PendulumStopwatch() stopwatch.start() while stopwatch.timePassedSince < 1 {} stopwatch.pause() XCTAssert(stopwatch.isPaused, "isPaused should be true") XCTAssert(stopwatch.startTime == nil, "Start date should be nil") XCTAssert(stopwatch.timePassedSince > 0, "Time passed should be greater than 0") XCTAssert(stopwatch.timePassedWhileOnPause > 0, "Time passed while on pause should be greater than 0") } func testContinuity() { let stopwatch = PendulumStopwatch() stopwatch.continueIfPreviouslyRunning() let startTime1 = UserDefaults.standard.object(forKey: "pendulumStartTime") as! Date! XCTAssert(startTime1 != nil, "pendulumStartTime should not be nil at this point") XCTAssert(stopwatch.isActive, "Active") while stopwatch.timePassedSince < 10 {} XCTAssert(stopwatch.timePassedSince > 10, "Should be running already") stopwatch.stop() } func testIsActive() { let stopwatch = PendulumStopwatch() stopwatch.start() XCTAssert(stopwatch.isActive, "Should be active and running") XCTAssert(stopwatch.startTime != nil, "Should not be nil") XCTAssert(stopwatch.timePassedSince > 0, "Should be greater than 0, as it was running for 0.2 milliseconds") } 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
eeschimosu/LicensingViewController
LicensingViewControllerTests/LicensingViewControllerTests.swift
2
957
// // LicensingViewControllerTests.swift // LicensingViewControllerTests // // Created by Tiago Henriques on 15/07/15. // Copyright (c) 2015 Tiago Henriques. All rights reserved. // import UIKit import XCTest class LicensingViewControllerTests: 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
IvanVorobei/Sparrow
sparrow/modules/request-permissions/data/SPRequestPermissionDataColors.swift
2
1816
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by) // // 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 SPRequestPermissionData { struct colors { static func mainColor() -> UIColor { return SPStyleKit.baseColor() } static func secondColor() -> UIColor { return UIColor.white } struct gradient { struct dark { static func lightColor() -> UIColor { return UIColor.init(hex: "#171C1E") } static func darkColor() -> UIColor { return UIColor.init(hex: "#000000") } } } } }
mit
NikitaAsabin/pdpDecember
DayPhoto/FlipDismissAnimationController.swift
1
2477
// // FlipDismissAnimationController.swift // DayPhoto // // Created by Nikita Asabin on 14.01.16. // Copyright © 2016 Flatstack. All rights reserved. // import UIKit class FlipDismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning { var destinationFrame = CGRectZero func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.6 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey), let containerView = transitionContext.containerView(), let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else { return } let finalFrame = destinationFrame let snapshot = fromVC.view.snapshotViewAfterScreenUpdates(false) snapshot.layer.cornerRadius = 25 snapshot.layer.masksToBounds = true containerView.addSubview(toVC.view) containerView.addSubview(snapshot) fromVC.view.hidden = true AnimationHelper.perspectiveTransformForContainerView(containerView) toVC.view.layer.transform = AnimationHelper.yRotation(-M_PI_2) let duration = transitionDuration(transitionContext) UIView.animateKeyframesWithDuration( duration, delay: 0, options: .CalculationModeCubic, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1/3, animations: { snapshot.frame = finalFrame }) UIView.addKeyframeWithRelativeStartTime(1/3, relativeDuration: 1/3, animations: { snapshot.layer.transform = AnimationHelper.yRotation(M_PI_2) }) UIView.addKeyframeWithRelativeStartTime(2/3, relativeDuration: 1/3, animations: { toVC.view.layer.transform = AnimationHelper.yRotation(0.0) }) }, completion: { _ in fromVC.view.hidden = false snapshot.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } }
mit
coppercash/Anna
Anna_iOS_Tests/FocusTests.swift
1
10078
// // FocusTests.swift // Anna_iOS_Tests // // Created by William on 2018/5/19. // import XCTest import Anna class FocusTests: XCTestCase { func test_button() { let test = PathTestCaseBuilder(with: self) test.task = """ match( 'master/bt/detail/ana-appeared', function() { return 42; } ); """ class Controller : PathTestingViewController { var button :UIButton? = nil override func viewDidLoad() { super.viewDidLoad() self.analyzer.enable(naming: "master") self.button = { let button = PathTestingButton() self.analyzer.setSubAnalyzer( button.analyzer, for: "bt" ) button.addTarget( self, action: #selector(handleControlEvent), for: .touchUpInside ) return button }() self.view.addSubview(self.button!) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.button?.sendActions(for: .touchUpInside) } @objc func handleControlEvent() { let detail = PathTestingViewController() detail.analyzer.enable(naming: "detail") self.navigationController?.pushViewController( detail, animated: false ) } } let navigation = PathTestingNavigationController(rootViewController: Controller()) navigation.analyzer.enable(naming: "nv") test.rootViewController = navigation test.expect() test.launch() self.wait( for: test.expectations, timeout: 1.0 ) XCTAssertEqual(test[0] as? Int, 42) } func test_table() { let test = PathTestCaseBuilder(with: self) test.task = """ match( 'master/table/19/row/detail/ana-appeared', function() { return 42; } ); """ class Controller : PathTestingViewController, UITableViewDelegate, UITableViewDataSource, SectionAnalyzableTableViewDelegate { lazy var table :PathTestingTableView = { let superview = self.view! let table = PathTestingTableView(frame: superview.bounds) table.delegate = self table.dataSource = self return table }() override func viewDidLoad() { super.viewDidLoad() self.analyzer.enable(naming: "master") self.view.addSubview(self.table) self.analyzer.setSubAnalyzer( self.table.analyzer, for: "table" ) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let indexPath = IndexPath(row: 0, section: 19) self.table.scrollToRow( at: indexPath, at: .bottom, animated: false ) self.table.selectRow( at: indexPath, animated: false, scrollPosition: .none ) self.table.delegate?.tableView?( self.table, didSelectRowAt: indexPath ) } func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell { let cell = (tableView.dequeueReusableCell(withIdentifier: "r") as? PathTestingTableViewCell) ?? { let cell = PathTestingTableViewCell( style: .default, reuseIdentifier: "r" ) cell.analyzer.enable(naming: "row") return cell }() return cell } func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int ) -> Int { return 1 } func numberOfSections( in tableView: UITableView ) -> Int { return 20 } func tableView( _ tableView: UITableView, didSelectRowAt indexPath: IndexPath ) { let detail = PathTestingViewController() detail.analyzer.enable(naming: "detail") self.navigationController?.pushViewController( detail, animated: false ) } func tableView( _ tableView: UITableView & AnalyzerReadable, analyticNameFor section :Int ) -> String? { return "\(section)" } } let navigation = PathTestingNavigationController(rootViewController: Controller()) navigation.analyzer.enable(naming: "nv") test.rootViewController = navigation test.expect() test.launch() self.wait( for: test.expectations, timeout: 1.0 ) XCTAssertEqual(test[0] as? Int, 42) } func test_analyzer_activiated_with_standalone_name_should_handle_focus_marking_properly() { let test = PathTestCaseBuilder(with: self) test.task = (""" match( 'master/table/cell/button/detail/ana-appeared', function(node) { return 42; } ); """) class Controller : PathTestingViewController, UITableViewDelegate, UITableViewDataSource { class Cell : PathTestingTableViewCell { override init( style: UITableViewCellStyle, reuseIdentifier: String? ) { super.init( style: style, reuseIdentifier: reuseIdentifier ) let cell = self, button = PathTestingButton(frame: cell.contentView.bounds) cell.contentView.addSubview(button) button.analyzer.enable(naming: "button") button.addTarget( nil, action: #selector(Controller.handleControlEvent), for: .touchUpInside ) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } var counter = 10 lazy var table :PathTestingTableView = { let superview = self.view!; let table = PathTestingTableView(frame: superview.bounds) table.delegate = self table.dataSource = self table.register( Cell.self, forCellReuseIdentifier: "r" ) return table }() override func viewDidLoad() { super.viewDidLoad() self.analyzer.enable(naming: "master") self.view.addSubview(self.table) self.table.analyzer.enable(naming: "table") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let cell = self.table.cellForRow( at: IndexPath(row: 9, section: 0) ), button = cell?.contentView.subviews[0] as! PathTestingButton button.analyzer.markFocused() button.sendActions(for: .touchUpInside) } func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: "r", for: indexPath ) as! PathTestingTableViewCell cell.analyzer.enable(naming: "cell") return cell } func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int ) -> Int { return 10 } @objc func handleControlEvent() { let detail = PathTestingViewController() detail.analyzer.enable(naming: "detail") self.navigationController?.pushViewController(detail, animated: false) } } let navigation = UINavigationController(rootViewController: Controller()) test.rootViewController = navigation test.expect(for: 1) test.launch() self.wait( for: test.expectations, timeout: 1.0 ) XCTAssertEqual(test[0] as? Int, 42) } }
mit
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Home/View/CollectionGameCell.swift
1
2053
// // CollectionGameCell.swift // MGDYZB // // Created by ming on 16/10/26. // Copyright © 2016年 ming. All rights reserved. // 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles // github: https://github.com/LYM-mg // import UIKit class CollectionGameCell: UICollectionViewCell { // MARK: 控件属性 @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var lineView: UIView! // MARK: 定义模型属性 var baseGame : BaseGameModel? { didSet { titleLabel.text = baseGame?.tag_name // iconImageView.image = UIImage(named: "home_more_btn") if let iconURL = URL(string: baseGame?.icon_url ?? "") { iconImageView.kf.setImage(with: iconURL) } else { iconImageView.image = UIImage(named: "home_more_btn") } // titleLabel.text = baseGame?.tag_name // if let iconURL = URL(string: baseGame?.icon_url ?? "") { // if baseGame?.tag_name == "更多" { // iconImageView.image = #imageLiteral(resourceName: "home_more_btn") // }else { // iconImageView.kf.setImage(with: (with: iconURL), placeholder: #imageLiteral(resourceName: "placehoderImage")) //// iconImageView.kf.setImage(with: iconURL, placeholder: #imageLiteral(resourceName: "placehoderImage")) //// iconImageView.kf.setImage(with: iconURL) // } // } else { // iconImageView.image = UIImage(named: "home_more_btn") // } } } override func awakeFromNib() { super.awakeFromNib() self.layoutIfNeeded() iconImageView.layer.cornerRadius = self.iconImageView.frame.size.height*0.5 iconImageView.clipsToBounds = true frame = CGRect(x: 0, y: 0, width: 80, height: 90) lineView.isHidden = true // backgroundColor = UIColor.orangeColor() } }
mit
wireapp/wire-ios
Wire-iOS/Sources/Helpers/syncengine/ZMMessage+Likes.swift
1
2553
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireDataModel extension ZMConversationMessage { var canBeLiked: Bool { guard let conversation = conversationLike else { return false } let participatesInConversation = conversation.localParticipantsContain(user: SelfUser.current) let sentOrDelivered = deliveryState.isOne(of: .sent, .delivered, .read) let likableType = isNormal && !isKnock return participatesInConversation && sentOrDelivered && likableType && !isObfuscated && !isEphemeral } var liked: Bool { get { return likers.contains { $0.isSelfUser } } set { if newValue { ZMMessage.addReaction(.like, toMessage: self) } else { ZMMessage.removeReaction(onMessage: self) } } } func hasReactions() -> Bool { return self.usersReaction.map { (_, users) in return users.count }.reduce(0, +) > 0 } var likers: [UserType] { return usersReaction.filter { (reaction, _) -> Bool in reaction == MessageReaction.like.unicodeValue }.map { (_, users) in return users }.first ?? [] } var sortedLikers: [UserType] { return likers.sorted { $0.name < $1.name } } var sortedReadReceipts: [ReadReceipt] { return readReceipts.sorted { $0.userType.name < $1.userType.name } } } extension Message { static func setLikedMessage(_ message: ZMConversationMessage, liked: Bool) { return message.liked = liked } static func isLikedMessage(_ message: ZMConversationMessage) -> Bool { return message.liked } static func hasReactions(_ message: ZMConversationMessage) -> Bool { return message.hasReactions() } }
gpl-3.0
gregomni/swift
test/Generics/rdar75656022.swift
2
3288
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=verify // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=verify 2>&1 | %FileCheck %s protocol P1 { associatedtype T } protocol P2 { associatedtype T : P1 } struct S1<A, B, C> : P2 where A : P1, C : P2, B == A.T.T, C.T == A.T { typealias T = C.T } struct S2<D : P1> : P2 { typealias T = D } // Make sure that we can resolve the nested type A.T // in the same-type requirement 'A.T == B.T'. // // A is concrete, and S1<C, E, S2<D>>.T resolves to // S2<D>.T, which is D. The typealias S1.T has a // structural type 'C.T'; since C is concrete, we // have to handle the case of an unresolved member // type with a concrete base. struct UnresolvedWithConcreteBase<A, B> { // CHECK-LABEL: Generic signature: <A, B, C, D, E where A == S1<C, E, S2<D>>, B : P2, C : P1, D == B.[P2]T, E == D.[P1]T, B.[P2]T == C.[P1]T> init<C, D, E>(_: C) where A == S1<C, E, S2<D>>, B : P2, A.T == B.T, C : P1, D == C.T, E == D.T { } } // Make sure that we drop the conformance requirement // 'A : P2' and rebuild the generic signature with the // correct same-type requirements. // // The original test case in the bug report (correctly) // produces two warnings about redundant requirements. struct OriginalExampleWithWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C, D, E where A == S1<C, E, S2<D>>, B : P2, C : P1, D == B.[P2]T, E == D.[P1]T, B.[P2]T == C.[P1]T> init<C, D, E>(_: C) where C : P1, D : P1, // expected-warning {{redundant conformance constraint 'D' : 'P1'}} C.T : P1, // expected-warning {{redundant conformance constraint 'D' : 'P1'}} // expected-note@-1 {{conformance constraint 'D' : 'P1' implied here}} A == S1<C, C.T.T, S2<C.T>>, C.T == D, E == D.T { } } // Same as above but without the warnings. struct OriginalExampleWithoutWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C, D, E where A == S1<C, E, S2<D>>, B : P2, C : P1, D == B.[P2]T, E == D.[P1]T, B.[P2]T == C.[P1]T> init<C, D, E>(_: C) where C : P1, A == S1<C, C.T.T, S2<C.T>>, C.T == D, E == D.T { } } // Same as above but without unnecessary generic parameters. struct WithoutBogusGenericParametersWithWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C where A == S1<C, B.[P2]T.[P1]T, S2<B.[P2]T>>, B : P2, C : P1, B.[P2]T == C.[P1]T> init<C>(_: C) where C : P1, C.T : P1, // expected-warning {{redundant conformance constraint 'C.T' : 'P1'}} A == S1<C, C.T.T, S2<C.T>> {} } // Same as above but without unnecessary generic parameters // or the warning. struct WithoutBogusGenericParametersWithoutWarning<A, B> where A : P2, B : P2, A.T == B.T { // CHECK-LABEL: Generic signature: <A, B, C where A == S1<C, B.[P2]T.[P1]T, S2<B.[P2]T>>, B : P2, C : P1, B.[P2]T == C.[P1]T> init<C>(_: C) where C : P1, A == S1<C, C.T.T, S2<C.T>> {} }
apache-2.0
aigarssilavs/SwiftOCR
example/OS X/SwiftOCR Debug OS X/SwiftOCR Debug OS X/AppDelegate.swift
4
527
// // AppDelegate.swift // SwiftOCR Debug OS X // // Created by Nicolas Camenisch on 24.05.16. // Copyright © 2016 Nicolas Camenisch. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
apache-2.0
jenasubodh/tasky-ios
Tasky/TaskTableViewCell.swift
1
1360
// // TaskTableViewCell.swift // Tasky // // Created by Subodh Jena on 02/05/17. // Copyright © 2017 Subodh Jena. All rights reserved. // import UIKit class TaskTableViewCell: UITableViewCell { @IBOutlet weak var labelTitle: UILabel! @IBOutlet weak var labelDateTime: UILabel! @IBOutlet weak var labelDescription: 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 } func setUpCell(task: Task) { labelTitle.text = task.title labelDescription.text = task.description let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy, HH:mm" labelDateTime.text = dateFormatter.string(from: self.getFormattedDate(string: task.updatedAt!)) } func getFormattedDate(string: String) -> Date { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" formatter.timeZone = TimeZone(secondsFromGMT: 0) let date = formatter.date(from: string)! return date } }
mit
kickstarter/Kickstarter-Prelude
Prelude.playground/Pages/05-UIKit-Lenses.xcplaygroundpage/Contents.swift
1
1652
import CoreGraphics import Prelude import Prelude_UIKit import UIKit import PlaygroundSupport func rounded <A: UIViewProtocol> (radius: CGFloat) -> ((A) -> A) { return A.lens.layer.masksToBounds .~ true • A.lens.layer.cornerRadius .~ radius } // Hack to get around the fact that playgrounds dont render views that are // initialized like `UIView()` func createLabel() -> UILabel { return UILabel(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) } let titleStyle = UILabel.lens.textAlignment .~ .center <> UILabel.lens.font .~ .preferredFont(forTextStyle: .title1) let baseStyle = UILabel.lens.frame.size .~ .init(width: 160.0, height: 48.0) <> UILabel.lens.backgroundColor .~ .red <> UILabel.lens.textColor .~ .white <> rounded(radius: 6) // Create some labels and style them. let labels = ["Hello", "UIKit", "Lenses"] .map { createLabel() |> UILabel.lens.text .~ $0 |> baseStyle |> titleStyle } labels let button = UIButton() |> UIButton.lens.title(for: .normal) .~ "To lens" |> UIButton.lens.titleColor(for: .normal) .~ .white |> UIButton.lens.title(for: .disabled) .~ "Or not to lens" |> UIButton.lens.titleColor(for: .disabled) .~ .init(white: 1.0, alpha: 0.5) |> UIButton.lens.titleLabel.font .~ .preferredFont(forTextStyle: .headline) |> UIButton.lens.frame.size .~ .init(width: 200, height: 40) |> UIButton.lens.contentHorizontalAlignment .~ .left |> UIButton.lens.contentEdgeInsets .~ UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16) |> UIButton.lens.backgroundColor(for: .normal) .~ .blue |> UIButton.lens.backgroundColor(for: .disabled) .~ .gray |> rounded(radius: 6)
apache-2.0
getwagit/Baya
Baya/BayaLayout.swift
1
3532
// // Copyright (c) 2016-2017 wag it GmbH. // License: MIT // import Foundation import UIKit /** Protocol for any layout. */ public protocol BayaLayout: BayaLayoutable {} /** Methods just for the layout! */ public extension BayaLayout { /** Kick off the layout routine of the root element. Only call this method on the root element. Measures child layoutables but tries to keep them within the frame. */ mutating public func startLayout(with frame: CGRect) { let origin = CGPoint( x: frame.origin.x + self.bayaMargins.left, y: frame.origin.y + self.bayaMargins.top) let combinedSize = Self.combineSizeForLayout( for: self, wrappingSize: self.sizeThatFitsWithMargins(frame.size), matchingSize: frame.size.subtractMargins(ofElement: self)) let size = CGSize( width: min(frame.width, combinedSize.width), height: min(frame.height, combinedSize.height)) self.layoutWith(frame: CGRect( origin: origin, size: size)) } /** Start a dedicated measure pass. Note: You do NOT need to call this method under common conditions. Only if you need to measure your layouts for e.g. a UICollectionViewCell's sizeThatFits method, use this convenience helper. */ mutating public func startMeasure(with size: CGSize) -> CGSize { guard self.bayaModes.width == .wrapContent || self.bayaModes.height == .wrapContent else { return size } let measuredSize = self.sizeThatFitsWithMargins(size) let adjustedSize = measuredSize.addMargins(ofElement: self) return CGSize( width: self.bayaModes.width == .wrapContent ? adjustedSize.width : size.width, height: self.bayaModes.height == .wrapContent ? adjustedSize.height : size.height) } } /** Internal helper. */ internal extension BayaLayout { /** Measure or remeasure the size of a child element. - Parameter forChildElement: The element to measure. This element will be modified in the process. - Parameter cachedMeasuredSize: If available supply the size that was measured and cached during the measure pass. - Parameter availableSize: The size available, most of time the size of the frame. */ func calculateSizeForLayout( forChild element: inout BayaLayoutable, cachedSize measuredSize: CGSize?, ownSize availableSize: CGSize) -> CGSize { return Self.combineSizeForLayout( for: element, wrappingSize: measuredSize ?? element.sizeThatFitsWithMargins(availableSize), matchingSize: availableSize.subtractMargins(ofElement: element)) } /** Combines two sizes based on the measure modes defined by the element. - Parameter forElement: The element that holds the relevant measure modes. - Parameter wrappingSize: The measured size of the element. - Parameter matchingSize: The size of the element when matching the parent. */ static func combineSizeForLayout( `for` element: BayaLayoutable, wrappingSize: CGSize, matchingSize: CGSize) -> CGSize { return CGSize( width: element.bayaModes.width == .matchParent ? matchingSize.width : wrappingSize.width, height: element.bayaModes.height == .matchParent ? matchingSize.height : wrappingSize.height) } }
mit
kNeerajPro/EcommerceApp
ECommerceApp/TestClass.swift
1
437
// // TestClass.swift // ECommerceApp // // Created by Neeraj Kumar on 22/12/14. // Copyright (c) 2014 Neeraj Kumar. All rights reserved. // import UIKit class TestClass: NSObject { func testMethod() { // Tests. // Detail. let detailTest:Detail = Detail(id: "detail id", name: "detail name") print(detailTest) print(detailTest.name) //ProductDetail } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/13736-swift-declcontext-lookupqualified.swift
11
228
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { class c { class a<T where g: C { typealias e = b
mit
xuxulll/XLPickerNode
XLPickerNode.swift
1
25821
// // XLPickerNode.swift // createpickerNode // // Created by 徐磊 on 15/7/3. // Copyright (c) 2015年 xuxulll. All rights reserved. // import SpriteKit /** * Data Source */ @objc protocol XLPickerNodeDataSource: NSObjectProtocol { /** * Number of component in picker node * Default value is set to 1 if not implemented */ optional func numberOfComponentsInPickerNode(pickerNode: XLPickerNode) -> Int /** * Number of rows in component */ func pickerNode(pickerNode: XLPickerNode, numberOfRowsInComponent component: Int) -> Int /** * Cell for row in component */ func pickerNode(pickerNode: XLPickerNode, cellForRow row: Int, inComponent component: Int) -> SKNode } /** * Delegate */ @objc protocol XLPickerNodeDelegate: NSObjectProtocol { /** * Called after user dragged on the picker node or manually set selectedRow */ optional func pickerNode(pickerNode: XLPickerNode, didSelectRow row: Int, inComponent component: Int) /** * customize component width and row height for each component */ optional func pickerNode(pickerNode: XLPickerNode, widthForComponent component: Int) -> CGFloat optional func pickerNode(pickerNode: XLPickerNode, rowHeightForComponent components: Int) -> CGFloat /** * called before display cell */ optional func pickerNode(pickerNode: XLPickerNode, willDisplayCell cell: SKNode, forRow row: Int, forComponent component: Int) } // MARK: - Extension for SKNode private var cellIdentifier: NSString? extension SKNode { var identifier: String? { get { return objc_getAssociatedObject(self, &cellIdentifier) as? String } set { objc_setAssociatedObject(self, &cellIdentifier, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_COPY_NONATOMIC)) } } func prepareForReuse() { /** * Clear all action */ self.removeAllActions() for child in self.children { (child as! SKNode).removeAllActions() } } } // MARK: - XLPickerNode @availability(iOS, introduced=7.0) class XLPickerNode: SKNode, UIGestureRecognizerDelegate { weak var dataSource: XLPickerNodeDataSource? weak var delegate: XLPickerNodeDelegate? /// general config of row height for each component /// will be overrided if delegate methods are implemented var rowHeight: CGFloat = 44.0 //MARK: Computed Data /// Methods /** * info fetched from the data source and will be cached */ func numberOfComponents() -> Int { if _numberOfComponents == -1 { _numberOfComponents = dataSource?.numberOfComponentsInPickerNode?(self) ?? 1 } return _numberOfComponents } func numberOfRowsInComponent(Component: Int) -> Int { return dataSource!.pickerNode(self, numberOfRowsInComponent: Component) } func contentSizeForComponent(component: Int) -> CGSize { return contentNodes[component].frame.size } func rowHeightForComponent(component: Int) -> CGFloat { return componentRowHeights[component] } func widthForComponent(component: Int) -> CGFloat { return componentWidths[component] } /// Computed properties private var _maxRowHeight: CGFloat { var maxHeight: CGFloat = 0.0 for height in componentRowHeights { maxHeight = max(maxHeight, height) } return maxHeight } //MARK: Data affecting UI /// set during initialization, read-only to public private(set) var size: CGSize /// default to show indicator var showsSelectionIndicator: Bool = true { didSet { if showsSelectionIndicator { /** * Re-initialize indicator node since we deinit it when hiding indicator */ indicatorNode = SKSpriteNode(color: indicatorColor, size: CGSizeMake(size.width, _maxRowHeight)) backgroundNode.addChild(indicatorNode!) } else { /** * Release indicator node when hide indicator */ indicatorNode?.removeFromParent() indicatorNode = nil } } } var indicatorColor: UIColor = UIColor.whiteColor() { didSet { indicatorNode?.color = indicatorColor } } /// Set background color or texture var backgroundColor: UIColor = UIColor.clearColor() { didSet { if backgroundColor == UIColor.clearColor() { colorNode?.removeFromParent() colorNode = nil } else { if colorNode == nil { colorNode = SKSpriteNode(color: backgroundColor, size: size) self.addChild(colorNode!) } else { colorNode?.color = backgroundColor } } } } var backgroundTexture: SKTexture? { didSet { if backgroundTexture == nil { colorNode?.removeFromParent() colorNode = nil } else { if colorNode == nil { colorNode = SKSpriteNode(texture: backgroundTexture, size: size) self.addChild(colorNode!) } else { colorNode?.texture = backgroundTexture } } } } /// default to enable scroll var scrollEnabled: Bool = true { didSet { if scrollEnabled { /** * re-initialize pan gesture and add to view since we released it for avoid crash for scene transit */ if panGesture == nil { panGesture = UIPanGestureRecognizer(target: self, action: "panGestureDiDTriggered:") panGesture!.delegate = self self.scene?.view?.addGestureRecognizer(panGesture!) } self.userInteractionEnabled = true } else { /** * Remove gesture from view for disable scroll and avoid crash after new scene is presented */ if panGesture != nil { self.scene!.view!.removeGestureRecognizer(panGesture!) panGesture = nil } self.userInteractionEnabled = false } } } //MARK: Nested nodes private var maskedNode: SKCropNode! private var colorNode: SKSpriteNode? private var backgroundNode: SKNode! private var contentNodes = [SKSpriteNode]() private var indicatorNode: SKSpriteNode? /// bound to current drag node private weak var currentActionNode: SKSpriteNode? //MARK: Stored properties private var identifiers = [String: String]() private var reusableCells = [String: [SKNode]]() private var visibleItems = [Int: [Int: SKNode]]() private var componentWidths = [CGFloat]() private var componentRowHeights = [CGFloat]() private var maxRows = [Int]() private var _numberOfComponents: Int = -1 /* Gesture handler */ private var panGesture: UIPanGestureRecognizer? private var kScrollDuration: NSTimeInterval = 5.0 //MARK: - Initializers init(position: CGPoint, size: CGSize) { self.size = size super.init() self.position = position } convenience override init() { self.init(position: CGPointZero, size: CGSizeZero) } required init?(coder aDecoder: NSCoder) { self.size = CGSizeZero super.init(coder: aDecoder) } /** Register class for reusable cell. :param: className Class that will be registered to XLPickerNode. The Class should be SKNode or its subclass :param: identifier Reusable identifier */ func registerClass(className: AnyClass, withReusableIdentifer identifier: String) { identifiers[identifier] = "\(NSStringFromClass(className))" } //MARK: - Deinitializers deinit { println("XLPickerNode: deinit.") removeGestures() } override func removeFromParent() { /** * Remove gesture to avoid crash when picker node is deinited while pan gesture still refers to the node. */ removeGestures() super.removeFromParent() } private func removeGestures() { if panGesture != nil { self.scene!.view!.removeGestureRecognizer(panGesture!) panGesture = nil //println("XLPickerNode: Pan gesture is successfully removed.") } } //MARK: - Methods //MARK: Cell reuse func dequeueReusableCellWithIdentifier(identifier: String) -> AnyObject? { if identifiers.isEmpty { fatalError("XLPickerNode: No class is registered for reusable cell.") } if let array = reusableCells[identifier] { if var element = array.last { reusableCells[identifier]!.removeLast() element.prepareForReuse() return element } } let nodeClass = NSClassFromString(identifiers[identifier]) as! SKNode.Type return nodeClass() } private func enqueueReusableCell(cell: SKNode) { if let identifer = cell.identifier { var array = reusableCells[identifer] ?? [SKNode]() if array.isEmpty { reusableCells[identifer] = array } array.append(cell) //println("reusable count: \(array.count)") } } private func layoutCellsForComponent(component: Int) { let visibleRect = visibleRectForComponent(component) let oldVisibleRows = rowsForVisibleCellsInComponent(component) let newVisibleRows = rowsForCellInRect(visibleRect, forComponent: component) var rowsToRemove = NSMutableArray(array: oldVisibleRows) rowsToRemove.removeObjectsInArray(newVisibleRows) var rowsToAdd = NSMutableArray(array: newVisibleRows) rowsToAdd.removeObjectsInArray(oldVisibleRows) for row in rowsToRemove { if let cell = cellForRow(row as! Int, forComponent: component) { enqueueReusableCell(cell) cell.removeFromParent() visibleItems[component]?.removeValueForKey(row as! Int) } } let size = CGSizeMake(widthForComponent(component), rowHeightForComponent(component)) for row in rowsToAdd { var node = dataSource?.pickerNode(self, cellForRow: row as! Int, inComponent: component) assert(node != nil, "XLPickerNode: Unexpected to find optional nil in content cell. At lease one delegate method for returning picker cell.") contentNodes[component].addChild(node!) let n = Array(identifiers.keys)[0] node?.identifier = Array(identifiers.keys)[0] let info = positionAndSizeForRow(row as! Int, forComponent: component) node!.position = info.position node?.zPosition = 100 delegate?.pickerNode?(self, willDisplayCell: node!, forRow: row as! Int, forComponent: component) if visibleItems[component] == nil { visibleItems[component] = [Int: SKNode]() } visibleItems[component]![row as! Int] = node! } } //MARK: - Data Handler func reloadData() { if dataSource == nil { return } prepareForPickerNode() for component in 0 ..< numberOfComponents() { layoutCellsForComponent(component) updateAlphaForRow(0, forComponent: component) } } /** * called when reloadData() */ private func prepareForPickerNode() { /** * Nested methods. Only called when prepareForPickerNode() is called. */ func reloadParentNodes() { backgroundNode.removeAllChildren() componentWidths = [] componentRowHeights = [] contentNodes = [] maxRows = [] if delegate != nil && delegate!.respondsToSelector("pickerNode:widthForComponent:") { for s in 0 ..< numberOfComponents() { componentWidths.append(delegate!.pickerNode!(self, widthForComponent: s)) } } else { let fixedWidth = size.width / CGFloat(numberOfComponents()) for s in 0 ..< numberOfComponents() { componentWidths.append(fixedWidth) } } if delegate != nil && delegate!.respondsToSelector("pickerNode:rowHeightForComponent:") { for s in 0 ..< numberOfComponents() { let height = delegate!.pickerNode!(self, rowHeightForComponent: s) componentRowHeights.append(height) } } else { for _ in 0 ..< numberOfComponents() { componentRowHeights.append(rowHeight) } } for height in componentRowHeights { let rows = ceil(size.height / height) maxRows.append(Int(rows)) } for (index, componentWidth) in enumerate(componentWidths) { let contentNode = SKSpriteNode( color: UIColor.clearColor(), size: CGSizeMake( componentWidth, componentRowHeights[index] * CGFloat(numberOfRowsInComponent(index) ) ) ) contentNode.anchorPoint = CGPointMake(0, 1) var accuWidth: CGFloat = -size.width / 2 for i in 0 ..< index { accuWidth += componentWidths[i] } contentNode.position = CGPointMake(accuWidth, rowHeightForComponent(index) / 2) contentNode.identifier = "_contentNode" contentNode.userData = NSMutableDictionary(dictionary: ["_component": index]) backgroundNode.addChild(contentNode) contentNodes.append(contentNode) } } if maskedNode == nil { maskedNode = SKCropNode() self.addChild(maskedNode) backgroundNode = SKNode() maskedNode.addChild(backgroundNode) backgroundNode.zPosition = -1000 } /** * Re-mask */ let mask = SKSpriteNode(color: UIColor.blackColor(), size: size) maskedNode.maskNode = mask /** * reload all components in self */ reloadParentNodes() if showsSelectionIndicator && indicatorNode == nil { indicatorNode = SKSpriteNode(color: indicatorColor, size: CGSizeMake(size.width, _maxRowHeight)) backgroundNode.addChild(indicatorNode!) indicatorNode?.size = CGSizeMake(size.width, _maxRowHeight) } if scrollEnabled && panGesture == nil { panGesture = UIPanGestureRecognizer(target: self, action: "panGestureDiDTriggered:") panGesture!.delegate = self self.scene!.view!.addGestureRecognizer(panGesture!) } } // selection. in this case, it means showing the appropriate row in the middle // scrolls the specified row to center. func selectRow(row: Int, forComponent component: Int, animated: Bool) { currentActionNode = contentNodes[component] if animated { let rawPnt = contentNodes[component].position let newPosition = positionAndSizeForRow(row, forComponent: component).position currentNodeAnimateMoveToPosition(CGPointMake(rawPnt.x, -newPosition.y), fromPoint: rawPnt, duration: kScrollDuration) } else { let rawPnt = contentNodes[component].position let newPosition = positionAndSizeForRow(row, forComponent: component).position currentActionNode!.position = CGPointMake(rawPnt.x, -newPosition.y) delegate?.pickerNode?(self, didSelectRow: row, inComponent: component) } } // returns selected row. -1 if nothing selected func selectedRowForComponent(component: Int) -> Int { return max(0, min(Int((contentNodes[component].position.y/* + contentNodes[component].size.height / 2*/) / rowHeightForComponent(component)), numberOfRowsInComponent(component) - 1)) } //MARK: - Data calculations //MARK: Reusable private func visibleRectForComponent(component: Int) -> CGRect { let node = contentNodes[component] return CGRectMake(0, node.position.y - rowHeightForComponent(component) / 2 - size.height / 2, widthForComponent(component), size.height) } private func rowsForVisibleCellsInComponent(component: Int) -> [Int] { var rows = [Int]() if let comps = visibleItems[component] { for (key, _) in comps { rows.append(key) } return rows } return [Int]() } private func rowsForCellInRect(rect: CGRect, forComponent component: Int) -> [Int] { var rows = [Int]() for row in 0 ..< numberOfRowsInComponent(component) { var cellRect = rectForCellAtRow(row, inComponent: component) if CGRectIntersectsRect(cellRect, rect) { rows.append(row) } } return rows } private func rectForCellAtRow(row: Int, inComponent component: Int) -> CGRect { return CGRectMake(0, rowHeightForComponent(component) * CGFloat(row), widthForComponent(component), rowHeightForComponent(component)) } private func cellForRow(row: Int, forComponent component: Int) -> SKNode? { if let componentCells = visibleItems[component] { return componentCells[row] } return nil } //MARK: Position and size /** Position and size for a specific row and component :param: row row :param: component component :returns: Cell Info<Tuple> (position, size) */ private func positionAndSizeForRow(row: Int, forComponent component: Int) -> (position: CGPoint, size: CGSize) { func positionForRow(row: Int, forComponent component: Int) -> CGPoint { let rowHeight = -rowHeightForComponent(component) let totalHeight = CGFloat(row) * rowHeight + rowHeight * 0.5 return CGPointMake(widthForComponent(component) / 2, totalHeight) } func sizeForRow(row: Int, forComponent component: Int) -> CGSize { return CGSizeMake(widthForComponent(component), rowHeightForComponent(component)) } return (positionForRow(row, forComponent: component), sizeForRow(row, forComponent: component)) } /** Nearest anchor of cell for current drag location :param: point drag location :param: component component number for calculation :returns: nearest anchor point */ private func contentOffsetNearPoint(point: CGPoint, inComponent component: Int) -> CGPoint { var mult = round((point.y + rowHeightForComponent(component) / 2) / rowHeightForComponent(component)) let info = positionAndSizeForRow(Int(mult) - 1, forComponent: component) return CGPointMake(info.position.x, -info.position.y) } private func calculateThresholdYOffsetWithPoint(point: CGPoint, forComponent component: Int) -> CGPoint { var retVal = point retVal.x = contentNodes[component].position.x retVal.y = max(retVal.y, minYOffsetForComponents(component)) retVal.y = min(retVal.y, maxYOffsetForComponent(component)) return retVal } private func minYOffsetForComponents(component: Int) -> CGFloat { return rowHeightForComponent(component) / 2 } private func maxYOffsetForComponent(component: Int) -> CGFloat { return contentSizeForComponent(component).height - rowHeightForComponent(component) / 2 } //MARK: - Gesture Handler func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { let touchLocation = touch.locationInNode(self) weak var tNode: SKSpriteNode? for node in (self.nodesAtPoint(touchLocation) as! [SKNode]) { if node.identifier == "_contentNode" { currentActionNode = node as? SKSpriteNode return true } } return false } func panGestureDiDTriggered(recognizer: UIPanGestureRecognizer) { if recognizer.state == .Began { currentActionNode!.removeAllActions() } else if recognizer.state == .Changed { var translation = recognizer.translationInView(recognizer.view!) translation.y = -translation.y let pos = CGPointMake(currentActionNode!.position.x, currentActionNode!.position.y + translation.y) currentActionNode!.position = pos recognizer.setTranslation(CGPointZero, inView: recognizer.view!) let component = currentActionNode!.userData!.valueForKey("_component")!.integerValue layoutCellsForComponent(component) let row = round((pos.y + rowHeightForComponent(component) / 2) / rowHeightForComponent(component)) - 1 updateAlphaForRow(Int(row), forComponent: component) } else if recognizer.state == .Ended { if let component = find(contentNodes, currentActionNode!) { let velocity = recognizer.velocityInView(recognizer.view!) let rawPnt = currentActionNode!.position var newPosition = CGPointMake(rawPnt.x, rawPnt.y - velocity.y) newPosition = contentOffsetNearPoint(newPosition, inComponent: component) let endPoint = calculateThresholdYOffsetWithPoint(newPosition, forComponent: component) var duration = kScrollDuration if !CGPointEqualToPoint(newPosition, endPoint) { duration = 0.5 } currentNodeAnimateMoveToPosition(endPoint, fromPoint: rawPnt, duration: duration) } } } //MARK: - UI Update private func currentNodeAnimateMoveToPosition(endPoint: CGPoint, fromPoint startPoint: CGPoint, duration: NSTimeInterval) { let component = currentActionNode!.userData!.valueForKey("_component")!.integerValue let moveBlock = SKAction.customActionWithDuration(duration, actionBlock: { [unowned self](node, elapsedTime) -> Void in func easeStep(p: CGFloat) -> CGFloat { let f: CGFloat = (p - 1) return f * f * f * (1 - p) + 1 } let t = CGFloat(elapsedTime) / CGFloat(duration) let x = startPoint.x + easeStep(t) * (endPoint.x - startPoint.x); let y = startPoint.y + easeStep(t) * (endPoint.y - startPoint.y); let targetPoint = CGPointMake(x, y) node.position = targetPoint self.layoutCellsForComponent(component) let row = Int(round((node.position.y + self.rowHeightForComponent(component) / 2) / self.rowHeightForComponent(component))) - 1 self.updateAlphaForRow(row, forComponent: component) }) let finishBlock = SKAction.runBlock({ [unowned self]() -> Void in dispatch_async(dispatch_get_main_queue(), { [unowned self]() -> Void in self.delegate?.pickerNode?(self, didSelectRow: selectedRowForComponent(component), inComponent: component) }) }) currentActionNode!.runAction(SKAction.sequence([moveBlock, finishBlock])) } private func updateAlphaForRow(row: Int, forComponent component: Int) { let scope = CGFloat(maxRows[component] - 1) / 2 let reloadRow = CGFloat(maxRows[component] + 1) / 2 let step: CGFloat = 1.0 / reloadRow var currentStep: CGFloat = step for cRow in (row - Int(scope))...(row + Int(scope)) { cellForRow(cRow, forComponent: component)?.alpha = currentStep currentStep += cRow < row ? step : -step } } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/15809-swift-sourcemanager-getmessage.swift
11
224
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { func a { case { for { class for { class case ,
mit
felixjendrusch/Matryoshka
MatryoshkaPlayground/MatryoshkaPlayground/Networking/HTTPStatusCode.swift
1
8369
// http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml public enum HTTPStatusCode: Equatable { // Informational case Continue case SwitchingProtocols case Processing // Success case OK case Created case Accepted case NonAuthoritativeInformation case NoContent case ResetContent case PartialContent case MultiStatus case AlreadyReported case IMUsed // Redirection case MultipleChoices case MovedPermanently case Found case SeeOther case NotModified case UseProxy case TemporaryRedirect case PermanentRedirect // Client Error case BadRequest case Unauthorized case PaymentRequired case Forbidden case NotFound case MethodNotAllowed case NotAcceptable case ProxyAuthenticationRequired case RequestTimeout case Conflict case Gone case LengthRequired case PreconditionFailed case PayloadTooLarge case URITooLong case UnsupportedMediaType case RangeNotSatisfiable case ExceptionFailed case MisdirectedRequest case UnprocessableEntity case Locked case FailedDependency case UpgradeRequired case PreconditionRequired case TooManyRequests case RequestHeaderFieldsTooLarge // Server Error case InternalServerError case NotImplemented case BadGateway case ServiceUnavailable case GatewayTimeout case HTTPVersionNotSupported case VariantAlsoNegotiates case InsufficientStorage case LoopDetected case NotExtended case NetworkAuthenticationRequired // Unknown case Unknown(Int) } public func == (lhs: HTTPStatusCode, rhs: HTTPStatusCode) -> Bool { return lhs.rawValue == rhs.rawValue } extension HTTPStatusCode: Printable { public var description: String { return String(rawValue) } } extension HTTPStatusCode: RawRepresentable { public var rawValue: Int { switch self { case .Continue: return 100 case .SwitchingProtocols: return 101 case .Processing: return 102 case .OK: return 200 case .Created: return 201 case .Accepted: return 202 case .NonAuthoritativeInformation: return 203 case .NoContent: return 204 case .ResetContent: return 205 case .PartialContent: return 206 case .MultiStatus: return 207 case .AlreadyReported: return 208 case .IMUsed: return 226 case .MultipleChoices: return 300 case .MovedPermanently: return 301 case .Found: return 302 case .SeeOther: return 303 case .NotModified: return 304 case .UseProxy: return 305 case .TemporaryRedirect: return 307 case .PermanentRedirect: return 308 case .BadRequest: return 400 case .Unauthorized: return 401 case .PaymentRequired: return 402 case .Forbidden: return 403 case .NotFound: return 404 case .MethodNotAllowed: return 405 case .NotAcceptable: return 406 case .ProxyAuthenticationRequired: return 407 case .RequestTimeout: return 408 case .Conflict: return 409 case .Gone: return 410 case .LengthRequired: return 411 case .PreconditionFailed: return 412 case .PayloadTooLarge: return 413 case .URITooLong: return 414 case .UnsupportedMediaType: return 415 case .RangeNotSatisfiable: return 416 case .ExceptionFailed: return 417 case .MisdirectedRequest: return 421 case .UnprocessableEntity: return 422 case .Locked: return 423 case .FailedDependency: return 424 case .UpgradeRequired: return 426 case .PreconditionRequired: return 428 case .TooManyRequests: return 429 case .RequestHeaderFieldsTooLarge: return 431 case .InternalServerError: return 500 case .NotImplemented: return 501 case .BadGateway: return 502 case .ServiceUnavailable: return 503 case .GatewayTimeout: return 504 case .HTTPVersionNotSupported: return 505 case .VariantAlsoNegotiates: return 506 case .InsufficientStorage: return 507 case .LoopDetected: return 508 case .NotExtended: return 510 case .NetworkAuthenticationRequired: return 511 case let .Unknown(statusCode): return statusCode } } public init(rawValue: Int) { switch rawValue { case 100: self = .Continue case 101: self = .SwitchingProtocols case 102: self = .Processing case 200: self = .OK case 201: self = .Created case 202: self = .Accepted case 203: self = .NonAuthoritativeInformation case 204: self = .NoContent case 205: self = .ResetContent case 206: self = .PartialContent case 207: self = .MultiStatus case 208: self = .AlreadyReported case 226: self = .IMUsed case 300: self = .MultipleChoices case 301: self = .MovedPermanently case 302: self = .Found case 303: self = .SeeOther case 304: self = .NotModified case 305: self = .UseProxy case 307: self = .TemporaryRedirect case 308: self = .PermanentRedirect case 400: self = .BadRequest case 401: self = .Unauthorized case 402: self = .PaymentRequired case 403: self = .Forbidden case 404: self = .NotFound case 405: self = .MethodNotAllowed case 406: self = .NotAcceptable case 407: self = .ProxyAuthenticationRequired case 408: self = .RequestTimeout case 409: self = .Conflict case 410: self = .Gone case 411: self = .LengthRequired case 412: self = .PreconditionFailed case 413: self = .PayloadTooLarge case 414: self = .URITooLong case 415: self = .UnsupportedMediaType case 416: self = .RangeNotSatisfiable case 417: self = .ExceptionFailed case 421: self = .MisdirectedRequest case 422: self = .UnprocessableEntity case 423: self = .Locked case 424: self = .FailedDependency case 426: self = .UpgradeRequired case 428: self = .PreconditionRequired case 429: self = .TooManyRequests case 431: self = .RequestHeaderFieldsTooLarge case 500: self = .InternalServerError case 501: self = .NotImplemented case 502: self = .BadGateway case 503: self = .ServiceUnavailable case 504: self = .GatewayTimeout case 505: self = .HTTPVersionNotSupported case 506: self = .VariantAlsoNegotiates case 507: self = .InsufficientStorage case 508: self = .LoopDetected case 510: self = .NotExtended case 511: self = .NetworkAuthenticationRequired case let statusCode: self = .Unknown(statusCode) } } }
mit
tdscientist/ShelfView-iOS
Example/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift
1
3229
// // ImageDataProcessor.swift // Kingfisher // // Created by Wei Wang on 2018/10/11. // // Copyright (c) 2018年 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation private let sharedProcessingQueue: CallbackQueue = .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) // Handles image processing work on an own process queue. class ImageDataProcessor { let data: Data let callbacks: [SessionDataTask.TaskCallback] let queue: CallbackQueue // Note: We have an optimization choice there, to reduce queue dispatch by checking callback // queue settings in each option... let onImageProcessed = Delegate<(Result<Image, KingfisherError>, SessionDataTask.TaskCallback), Void>() init(data: Data, callbacks: [SessionDataTask.TaskCallback], processingQueue: CallbackQueue?) { self.data = data self.callbacks = callbacks self.queue = processingQueue ?? sharedProcessingQueue } func process() { queue.execute(doProcess) } private func doProcess() { var processedImages = [String: Image]() for callback in callbacks { let processor = callback.options.processor var image = processedImages[processor.identifier] if image == nil { image = processor.process(item: .data(data), options: callback.options) processedImages[processor.identifier] = image } let result: Result<Image, KingfisherError> if let image = image { let imageModifier = callback.options.imageModifier var finalImage = imageModifier.modify(image) if callback.options.backgroundDecode { finalImage = finalImage.kf.decoded } result = .success(finalImage) } else { let error = KingfisherError.processorError( reason: .processingFailed(processor: processor, item: .data(data))) result = .failure(error) } onImageProcessed.call((result, callback)) } } }
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01034-swift-constraints-constraintsystem-getfixedtyperecursive.swift
1
229
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A { protocol a : a { func a } } let start = "ab" A
mit
chrisamanse/CheckboxButton
CheckboxButton-exampleTests/CheckboxButton_exampleTests.swift
1
1047
// // CheckboxButton_exampleTests.swift // CheckboxButton-exampleTests // // Created by Joe Amanse on 30/11/2015. // Copyright © 2015 Joe Christopher Paul Amanse. All rights reserved. // import XCTest @testable import CheckboxButton_example class CheckboxButton_exampleTests: 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
cpascoli/WeatherHype
WeatherHype/Classes/API/DataTransformer/SearchResultsTransformer.swift
1
800
// // SearchResultsTransformer.swift // WeatherHype // // Created by Carlo Pascoli on 27/09/2016. // Copyright © 2016 Carlo Pascoli. All rights reserved. // import UIKit import SwiftyJSON class SearchResultsTransformer: NSObject { func parse(json:JSON) -> SearchResults { var results = [City]() let list = json["list"].arrayValue for item in list { let cityId = item["id"].stringValue let name = item["name"].stringValue let country = item["sys"]["country"].stringValue let city = City(cityId: cityId, name: name, country: country) results.append(city) } let searchReults = SearchResults(results:results) return searchReults } }
apache-2.0
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01138-void.swift
12
314
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func i(c: ( ) -> ( class a { var _ = i( ) { class b<h , i where h = i> : a { } { } { } { } { } { } { } { } { } { } } { { } } } import Foundation
mit
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Flows/PaymentFlow/PXPaymentFlowModel.swift
1
6669
import Foundation final class PXPaymentFlowModel: NSObject { var amountHelper: PXAmountHelper? var checkoutPreference: PXCheckoutPreference? let paymentPlugin: PXSplitPaymentProcessor? let mercadoPagoServices: MercadoPagoServices var paymentResult: PaymentResult? var instructionsInfo: PXInstruction? var pointsAndDiscounts: PXPointsAndDiscounts? var businessResult: PXBusinessResult? var productId: String? var shouldSearchPointsAndDiscounts: Bool = true var postPaymentStatus: PostPaymentStatus? let ESCBlacklistedStatus: [String]? init(paymentPlugin: PXSplitPaymentProcessor?, mercadoPagoServices: MercadoPagoServices, ESCBlacklistedStatus: [String]?) { self.paymentPlugin = paymentPlugin self.mercadoPagoServices = mercadoPagoServices self.ESCBlacklistedStatus = ESCBlacklistedStatus } enum Steps: String { case createPaymentPlugin case createDefaultPayment case goToPostPayment case getPointsAndDiscounts case createPaymentPluginScreen case finish } func nextStep() -> Steps { if needToCreatePaymentForPaymentPlugin() { return .createPaymentPlugin } else if needToShowPaymentPluginScreenForPaymentPlugin() { return .createPaymentPluginScreen } else if needToCreatePayment() { return .createDefaultPayment } else if needToGoToPostPayment() { return .goToPostPayment } else if needToGetPointsAndDiscounts() { return .getPointsAndDiscounts } else { return .finish } } func needToCreatePaymentForPaymentPlugin() -> Bool { if paymentPlugin == nil { return false } if !needToCreatePayment() { return false } if hasPluginPaymentScreen() { return false } assignToCheckoutStore() paymentPlugin?.didReceive?(checkoutStore: PXCheckoutStore.sharedInstance) if let shouldSupport = paymentPlugin?.support() { return shouldSupport } return false } func needToCreatePayment() -> Bool { return paymentResult == nil && businessResult == nil } func needToGoToPostPayment() -> Bool { let hasPostPaymentFlow = postPaymentStatus?.isPending ?? false let paymentResultIsApproved = paymentResult?.isApproved() == true let isBusinessApproved = businessResult?.isApproved() == true let isBusinessAccepted = businessResult?.isAccepted() == true let businessResultIsApprovedAndAccepted = isBusinessApproved && isBusinessAccepted return hasPostPaymentFlow && (paymentResultIsApproved || businessResultIsApprovedAndAccepted) } func needToGetPointsAndDiscounts() -> Bool { if postPaymentStatus == .continuing && shouldSearchPointsAndDiscounts { return true } if let paymentResult = paymentResult, shouldSearchPointsAndDiscounts, (paymentResult.isApproved() || needToGetInstructions()) { return true } else if let businessResult = businessResult, shouldSearchPointsAndDiscounts, businessResult.isApproved(), businessResult.isAccepted() { return true } return false } func needToGetInstructions() -> Bool { guard let paymentResult = self.paymentResult else { return false } guard !String.isNullOrEmpty(paymentResult.paymentId) else { return false } return isOfflinePayment() && instructionsInfo == nil } func needToShowPaymentPluginScreenForPaymentPlugin() -> Bool { if !needToCreatePayment() { return false } return hasPluginPaymentScreen() } func isOfflinePayment() -> Bool { guard let paymentTypeId = amountHelper?.getPaymentData().paymentMethod?.paymentTypeId else { return false } let id = amountHelper?.getPaymentData().paymentMethod?.id return !PXPaymentTypes.isOnlineType(paymentTypeId: paymentTypeId, paymentMethodId: id) } func assignToCheckoutStore(programId: String? = nil) { if let amountHelper = amountHelper { PXCheckoutStore.sharedInstance.paymentDatas = [amountHelper.getPaymentData()] if let splitAccountMoney = amountHelper.splitAccountMoney { PXCheckoutStore.sharedInstance.paymentDatas.append(splitAccountMoney) } } PXCheckoutStore.sharedInstance.validationProgramId = programId PXCheckoutStore.sharedInstance.checkoutPreference = checkoutPreference } func cleanData() { paymentResult = nil businessResult = nil instructionsInfo = nil } } extension PXPaymentFlowModel { func hasPluginPaymentScreen() -> Bool { guard let paymentPlugin = paymentPlugin else { return false } assignToCheckoutStore() paymentPlugin.didReceive?(checkoutStore: PXCheckoutStore.sharedInstance) let processorViewController = paymentPlugin.paymentProcessorViewController() return processorViewController != nil } } // MARK: Manage ESC extension PXPaymentFlowModel { func handleESCForPayment(status: String, statusDetails: String, errorPaymentType: String?) { guard let token = amountHelper?.getPaymentData().getToken() else { return } if let paymentStatus = PXPaymentStatus(rawValue: status), paymentStatus == PXPaymentStatus.APPROVED { // If payment was approved if let esc = token.esc { PXConfiguratorManager.escProtocol.saveESC(config: PXConfiguratorManager.escConfig, token: token, esc: esc) } } else { guard let errorPaymentType = errorPaymentType else { return } // If it has error Payment Type, check if the error was from a card if let isCard = PXPaymentTypes(rawValue: errorPaymentType)?.isCard(), isCard { if let ESCBlacklistedStatus = ESCBlacklistedStatus, ESCBlacklistedStatus.contains(statusDetails) { PXConfiguratorManager.escProtocol.deleteESC(config: PXConfiguratorManager.escConfig, token: token, reason: .REJECTED_PAYMENT, detail: statusDetails) } } } } } extension PXPaymentFlowModel { func generateIdempotecyKey() -> String { return String(arc4random()) + String(Date().timeIntervalSince1970) } }
mit
abaca100/Nest
iOS-NestDK/ConditionCell.swift
1
4977
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `ConditionCell` displays characteristic and location conditions. */ import UIKit import HomeKit /// A `UITableViewCell` subclass that displays a trigger condition. class ConditionCell: UITableViewCell { /// A static, short date formatter. static let dateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .NoStyle dateFormatter.timeStyle = .ShortStyle dateFormatter.locale = NSLocale.currentLocale() return dateFormatter }() /// Ignores the passed-in style and overrides it with .Subtitle. override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier) selectionStyle = .None detailTextLabel?.textColor = UIColor.lightGrayColor() accessoryType = .None } /// Required because we overwrote a designated initializer. required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** Sets the cell's text to represent a characteristic and target value. For example, "Brightness → 60%" Sets the subtitle to the service and accessory that this characteristic represents. - parameter characteristic: The characteristic this cell represents. - parameter targetValue: The target value from this action. */ func setCharacteristic(characteristic: HMCharacteristic, targetValue: AnyObject) { let targetDescription = "\(characteristic.localizedDescription) → \(characteristic.localizedDescriptionForValue(targetValue))" textLabel?.text = targetDescription let contextDescription = NSLocalizedString("%@ in %@", comment: "Service in Accessory") if let service = characteristic.service, accessory = service.accessory { detailTextLabel?.text = String(format: contextDescription, service.name, accessory.name) } else { detailTextLabel?.text = NSLocalizedString("Unknown Characteristic", comment: "Unknown Characteristic") } } /** Sets the cell's text to represent an ordered time with a set context string. - parameter order: A `TimeConditionOrder` which will map to a localized string. - parameter timeString: The localized time string. - parameter contextString: A localized string describing the time type. */ private func setOrder(order: TimeConditionOrder, timeString: String, contextString: String) { let formatString: String switch order { case .Before: formatString = NSLocalizedString("Before %@", comment: "Before Time") case .After: formatString = NSLocalizedString("After %@", comment: "After Time") case .At: formatString = NSLocalizedString("At %@", comment: "At Time") } textLabel?.text = String(format: formatString, timeString) detailTextLabel?.text = contextString } /** Sets the cell's text to represent an exact time condition. - parameter order: A `TimeConditionOrder` which will map to a localized string. - parameter dateComponents: The date components of the exact time. */ func setOrder(order: TimeConditionOrder, dateComponents: NSDateComponents) { let date = NSCalendar.currentCalendar().dateFromComponents(dateComponents) let timeString = ConditionCell.dateFormatter.stringFromDate(date!) setOrder(order, timeString: timeString, contextString: NSLocalizedString("Relative to Time", comment: "Relative to Time")) } /** Sets the cell's text to represent a solar event time condition. - parameter order: A `TimeConditionOrder` which will map to a localized string. - parameter sunState: A `TimeConditionSunState` which will map to localized string. */ func setOrder(order: TimeConditionOrder, sunState: TimeConditionSunState) { let timeString: String switch sunState { case .Sunrise: timeString = NSLocalizedString("Sunrise", comment: "Sunrise") case .Sunset: timeString = NSLocalizedString("Sunset", comment: "Sunset") } setOrder(order, timeString: timeString , contextString: NSLocalizedString("Relative to sun", comment: "Relative to Sun")) } /// Sets the cell's text to indicate the given condition is not handled by the app. func setUnknown() { let unknownString = NSLocalizedString("Unknown Condition", comment: "Unknown Condition") detailTextLabel?.text = unknownString textLabel?.text = unknownString } }
apache-2.0
DarlingXIe/WeiBoProject
WeiBo/WeiBo/Classes/View/Main/XDLTabBar.swift
1
2710
// // XDLTabBar.swift // WeiBo // // Created by DalinXie on 16/9/11. // Copyright © 2016年 itcast. All rights reserved. // import UIKit class XDLTabBar: UITabBar { // var composeButtonClosure:(()->())? override init(frame:CGRect){ super.init(frame:frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ backgroundImage = #imageLiteral(resourceName: "tabbar_background") addSubview(composeButton) } override func layoutSubviews() { super.layoutSubviews() //set composeButton Width composeButton.center = CGPoint(x: self.bounds.size.width * 0.5, y: self.bounds.size.height * 0.5) //set index to change x of subviews var index = 0 //calculate all subviews button's itemW let itemW = UIScreen.main.bounds.size.width/5 //for in function--- to set postion of subviews for subview in self.subviews{ //judge that the value of subview is "UITabBarButton" if subview.isKind(of: NSClassFromString("UITabBarButton")!){ // according to index to calculate each button width let itemX = CGFloat(index) * itemW // update values of each button frame subview.frame.origin.x = itemX subview.frame.size.width = itemW // index +1 index = index + 1 if index == 2{ index = index + 1 } } } } lazy var composeButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside) button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal) button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for:.highlighted) button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal) button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted) button.sizeToFit() return button }() @objc private func composeButtonClick(){ composeButtonClosure?() } }
mit
jCho23/MobileAzureDevDays
Swift/MobileAzureDevDays/MobileAzureDevDaysUITests/Tests/MobileAzureDevDaysUITests.swift
1
2240
// // MobileAzureDevDaysUITests.swift // MobileAzureDevDaysUITests // // Edited by Brandon Minnick on 02 February 2018. // Created by Sweekriti Satpathy on 11 October 2017. // Copyright © 2017 Colby Williams. All rights reserved. // import XCTest import AppCenterXCUITestExtensions class MobileAzureDevDaysUITests: XCTestCase { let app = XCUIApplication() var sentimentPage: SentimentPage! override func setUp() { super.setUp() continueAfterFailure = false ACTLaunch.launch(app) sentimentPage = SentimentPage(app: app) ACTLabel.labelStep("App Launched") } override func tearDown() { super.tearDown() } func test_LauncheApp_TakeNoAction_ConfirmAppLaunches(){ } func test_SentimentPage_SubmitHappyText_ResultShouldBeHappyEmoji() { //Arrange let happyText = "Happy" //Act sentimentPage.enterText(text: happyText) sentimentPage.tapSubmitButton() sentimentPage.waitForNoActivityIndicator(timeout: 10) //Assert let result = sentimentPage.getResults() XCTAssertTrue(result == "😃") ACTLabel.labelStep("Correct Result Present") } func test_SentimentPage_SubmitSadText_ResultShouldBeSadEmoji() { //Arrange let sadText = "Sad" //Act sentimentPage.enterText(text: sadText) sentimentPage.tapSubmitButton() sentimentPage.waitForNoActivityIndicator(timeout: 10) //Assert let result = sentimentPage.getResults() XCTAssertTrue(result == "☹️") ACTLabel.labelStep("Correct Result Present") } func test_SentimentPage_SubmitSadText_ResultShouldBeNeutralEmoji() { //Arrange let neutralText = "Mitigations in Seattle" //Act sentimentPage.enterText(text: neutralText) sentimentPage.tapSubmitButton() sentimentPage.waitForNoActivityIndicator(timeout: 10) //Assert let result = sentimentPage.getResults() XCTAssertTrue(result == "😐") ACTLabel.labelStep("Correct Result Present") } }
mit
BoxJeon/funjcam-ios
Platform/HTTPNetwork/Tests/HTTPNetworkImpTests.swift
1
1384
import XCTest import HTTPNetwork @testable import HTTPNetworkImp final class HTTPNetworkTests: XCTestCase { private func sut(session: URLSessionProtocol) -> HTTPNetwork { return HTTPNetworkImp(session: session) } func testGet() async throws { let stub = HTTPNetworkResponse(body: "stub".data(using: .utf8)!) let session = URLSessionMock(response: stub) let sut = self.sut(session: session) let params = HTTPGetParams( url: URL(string: "https://test.com"), headers: ["Authroization": "Bearer lsdkj23j"], queries: ["query": "someWord", "num": 3] ) _ = try await sut.get(with: params) XCTAssert(session.request?.url?.host == params.url?.host) XCTAssert(session.request?.url?.path == params.url?.path) XCTAssert(session.request?.httpMethod == HTTPMethod.get.rawValue) XCTAssert(session.request?.allHTTPHeaderFields == params.headers) params.queries?.forEach { key, value in XCTAssert(session.request?.url?.queries[key] == String(describing: value)) } } } private extension URL { var queries: [String: String] { guard let urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: false) else { return [:] } var queries = [String: String]() urlComponents.queryItems?.forEach { queryItem in queries[queryItem.name] = queryItem.value } return queries } }
mit
mtgto/GPM
GPM/Column.swift
1
338
// // Column.swift // GPM // // Created by mtgto on 2016/09/19. // Copyright © 2016 mtgto. All rights reserved. // import Cocoa struct Column: Hashable, Equatable { let id: Int let name: String var hashValue: Int { return id } } func == (lhs: Column, rhs: Column) -> Bool { return lhs.id == rhs.id }
mit
sebastianludwig/Koloda
Pod/Classes/KolodaView/KolodaView.swift
2
18197
// // KolodaView.swift // TinderCardsSwift // // Created by Eugene Andreyev on 4/24/15. // Copyright (c) 2015 Eugene Andreyev. All rights reserved. // import UIKit import pop public enum SwipeResultDirection { case None case Left case Right } //Default values private let defaultCountOfVisibleCards = 3 private let backgroundCardsTopMargin: CGFloat = 4.0 private let backgroundCardsScalePercent: CGFloat = 0.95 private let backgroundCardsLeftMargin: CGFloat = 8.0 private let backgroundCardFrameAnimationDuration: NSTimeInterval = 0.2 //Opacity values private let alphaValueOpaque: CGFloat = 1.0 private let alphaValueTransparent: CGFloat = 0.0 private let alphaValueSemiTransparent: CGFloat = 0.7 //Animations constants private let revertCardAnimationName = "revertCardAlphaAnimation" private let revertCardAnimationDuration: NSTimeInterval = 1.0 private let revertCardAnimationToValue: CGFloat = 1.0 private let revertCardAnimationFromValue: CGFloat = 0.0 private let kolodaAppearScaleAnimationName = "kolodaAppearScaleAnimation" private let kolodaAppearScaleAnimationFromValue = CGPoint(x: 0.1, y: 0.1) private let kolodaAppearScaleAnimationToValue = CGPoint(x: 1.0, y: 1.0) private let kolodaAppearScaleAnimationDuration: NSTimeInterval = 0.8 private let kolodaAppearAlphaAnimationName = "kolodaAppearAlphaAnimation" private let kolodaAppearAlphaAnimationFromValue: CGFloat = 0.0 private let kolodaAppearAlphaAnimationToValue: CGFloat = 1.0 private let kolodaAppearAlphaAnimationDuration: NSTimeInterval = 0.8 public protocol KolodaViewDataSource:class { func kolodaNumberOfCards(koloda: KolodaView) -> UInt func kolodaViewForCardAtIndex(koloda: KolodaView, index: UInt) -> UIView func kolodaViewForCardOverlayAtIndex(koloda: KolodaView, index: UInt) -> OverlayView? } public protocol KolodaViewDelegate:class { func kolodaDidSwipedCardAtIndex(koloda: KolodaView,index: UInt, direction: SwipeResultDirection) func kolodaDidRunOutOfCards(koloda: KolodaView) func kolodaDidSelectCardAtIndex(koloda: KolodaView, index: UInt) func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool } public class KolodaView: UIView, DraggableCardDelegate { public weak var dataSource: KolodaViewDataSource! { didSet { setupDeck() } } public weak var delegate: KolodaViewDelegate? private(set) public var currentCardNumber = 0 private(set) public var countOfCards = 0 var countOfVisibleCards = defaultCountOfVisibleCards private var visibleCards = [DraggableCardView]() private var animating = false private var configured = false //MARK: Lifecycle override public func layoutSubviews() { super.layoutSubviews() if !self.configured { if self.visibleCards.isEmpty { reloadData() } else { layoutDeck() } self.configured = true } } private func setupDeck() { countOfCards = Int(dataSource!.kolodaNumberOfCards(self)) if countOfCards - currentCardNumber > 0 { let countOfNeededCards = min(countOfVisibleCards, countOfCards - currentCardNumber) for index in 0..<countOfNeededCards { if let nextCardContentView = dataSource?.kolodaViewForCardAtIndex(self, index: UInt(index)) { let nextCardView = DraggableCardView(frame: frameForCardAtIndex(UInt(index))) nextCardView.delegate = self nextCardView.alpha = index == 0 ? alphaValueOpaque : alphaValueSemiTransparent nextCardView.userInteractionEnabled = index == 0 let overlayView = overlayViewForCardAtIndex(UInt(index)) nextCardView.configure(nextCardContentView, overlayView: overlayView!) visibleCards.append(nextCardView) index == 0 ? addSubview(nextCardView) : insertSubview(nextCardView, belowSubview: visibleCards[index - 1]) } } } } private func layoutDeck() { for (index, card) in enumerate(self.visibleCards) { card.frame = frameForCardAtIndex(UInt(index)) } } //MARK: Frames private func frameForCardAtIndex(index: UInt) -> CGRect { let bottomOffset:CGFloat = 0 let topOffset = backgroundCardsTopMargin * CGFloat(self.countOfVisibleCards - 1) let xOffset = backgroundCardsLeftMargin * CGFloat(index) let scalePercent = backgroundCardsScalePercent let width = CGRectGetWidth(self.frame) * pow(scalePercent, CGFloat(index)) let height = (CGRectGetHeight(self.frame) - bottomOffset - topOffset) * pow(scalePercent, CGFloat(index)) let multiplier: CGFloat = index > 0 ? 1.0 : 0.0 let previousCardFrame = index > 0 ? frameForCardAtIndex(max(index - 1, 0)) : CGRectZero let yOffset = (CGRectGetHeight(previousCardFrame) - height + previousCardFrame.origin.y + backgroundCardsTopMargin) * multiplier let frame = CGRect(x: xOffset, y: yOffset, width: width, height: height) return frame } private func moveOtherCardsWithFinishPercent(percent: CGFloat) { if visibleCards.count > 1 { for index in 1..<visibleCards.count { let previousCardFrame = frameForCardAtIndex(UInt(index - 1)) var frame = frameForCardAtIndex(UInt(index)) let distanceToMoveY: CGFloat = (frame.origin.y - previousCardFrame.origin.y) * (percent / 100) frame.origin.y -= distanceToMoveY let distanceToMoveX: CGFloat = (previousCardFrame.origin.x - frame.origin.x) * (percent / 100) frame.origin.x += distanceToMoveX let widthScale = (previousCardFrame.size.width - frame.size.width) * (percent / 100) let heightScale = (previousCardFrame.size.height - frame.size.height) * (percent / 100) frame.size.width += widthScale frame.size.height += heightScale let card = visibleCards[index] card.frame = frame card.layoutIfNeeded() //For fully visible next card, when moving top card if index == 1 { card.alpha = alphaValueOpaque } } } } //MARK: Animations public func applyAppearAnimation() { userInteractionEnabled = false animating = true let kolodaAppearScaleAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY) kolodaAppearScaleAnimation.duration = kolodaAppearScaleAnimationDuration kolodaAppearScaleAnimation.fromValue = NSValue(CGPoint: kolodaAppearScaleAnimationFromValue) kolodaAppearScaleAnimation.toValue = NSValue(CGPoint: kolodaAppearScaleAnimationToValue) kolodaAppearScaleAnimation.completionBlock = { (_, _) in self.userInteractionEnabled = true self.animating = false } let kolodaAppearAlphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) kolodaAppearAlphaAnimation.fromValue = NSNumber(float: Float(kolodaAppearAlphaAnimationFromValue)) kolodaAppearAlphaAnimation.toValue = NSNumber(float: Float(kolodaAppearAlphaAnimationToValue)) kolodaAppearAlphaAnimation.duration = kolodaAppearAlphaAnimationDuration pop_addAnimation(kolodaAppearAlphaAnimation, forKey: kolodaAppearAlphaAnimationName) pop_addAnimation(kolodaAppearScaleAnimation, forKey: kolodaAppearScaleAnimationName) } func applyRevertAnimation(card: DraggableCardView) { animating = true let firstCardAppearAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) firstCardAppearAnimation.toValue = NSNumber(float: Float(revertCardAnimationToValue)) firstCardAppearAnimation.fromValue = NSNumber(float: Float(revertCardAnimationFromValue)) firstCardAppearAnimation.duration = revertCardAnimationDuration firstCardAppearAnimation.completionBlock = { (_, _) in self.animating = false } card.pop_addAnimation(firstCardAppearAnimation, forKey: revertCardAnimationName) } //MARK: DraggableCardDelegate func cardDraggedWithFinishPercent(card: DraggableCardView, percent: CGFloat) { animating = true moveOtherCardsWithFinishPercent(percent) } func cardSwippedInDirection(card: DraggableCardView, direction: SwipeResultDirection) { swipedAction(direction) } func cardWasReset(card: DraggableCardView) { if visibleCards.count > 1 { UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveLinear, animations: { self.moveOtherCardsWithFinishPercent(0) }, completion: { _ in self.animating = false for index in 1..<self.visibleCards.count { let card = self.visibleCards[index] card.alpha = alphaValueSemiTransparent } }) } else { animating = false } } func cardTapped(card: DraggableCardView) { let index = currentCardNumber + find(visibleCards, card)! delegate?.kolodaDidSelectCardAtIndex(self, index: UInt(index)) } //MARK: Private private func clear() { currentCardNumber = 0 for card in visibleCards { card.removeFromSuperview() } visibleCards.removeAll(keepCapacity: true) } private func overlayViewForCardAtIndex(index: UInt) -> OverlayView? { return dataSource.kolodaViewForCardOverlayAtIndex(self, index: index) } //MARK: Actions private func swipedAction(direction: SwipeResultDirection) { animating = true visibleCards.removeAtIndex(0) currentCardNumber++ let shownCardsCount = currentCardNumber + countOfVisibleCards if shownCardsCount - 1 < countOfCards { if let dataSource = self.dataSource { let lastCardContentView = dataSource.kolodaViewForCardAtIndex(self, index: UInt(shownCardsCount - 1)) let lastCardOverlayView = dataSource.kolodaViewForCardOverlayAtIndex(self, index: UInt(shownCardsCount - 1)) let lastCardFrame = frameForCardAtIndex(UInt(currentCardNumber + visibleCards.count)) let lastCardView = DraggableCardView(frame: lastCardFrame) lastCardView.hidden = true lastCardView.userInteractionEnabled = true lastCardView.configure(lastCardContentView, overlayView: lastCardOverlayView) lastCardView.delegate = self insertSubview(lastCardView, belowSubview: visibleCards.last!) visibleCards.append(lastCardView) } } if !visibleCards.isEmpty { for (index, currentCard) in enumerate(visibleCards) { let frameAnimation = POPBasicAnimation(propertyNamed: kPOPViewFrame) frameAnimation.duration = backgroundCardFrameAnimationDuration if index != 0 { currentCard.alpha = alphaValueSemiTransparent } else { frameAnimation.completionBlock = {(_, _) in self.visibleCards.last?.hidden = false self.animating = false self.delegate?.kolodaDidSwipedCardAtIndex(self, index: UInt(self.currentCardNumber - 1), direction: direction) } currentCard.alpha = alphaValueOpaque } currentCard.userInteractionEnabled = index == 0 frameAnimation.toValue = NSValue(CGRect: frameForCardAtIndex(UInt(index))) currentCard.pop_addAnimation(frameAnimation, forKey: "frameAnimation") } } else { delegate?.kolodaDidSwipedCardAtIndex(self, index: UInt(currentCardNumber - 1), direction: direction) animating = false self.delegate?.kolodaDidRunOutOfCards(self) } } public func revertAction() { if currentCardNumber > 0 && animating == false { if countOfCards - currentCardNumber >= countOfVisibleCards { if let lastCard = visibleCards.last { lastCard.removeFromSuperview() visibleCards.removeLast() } } currentCardNumber-- if let dataSource = self.dataSource { let firstCardContentView = dataSource.kolodaViewForCardAtIndex(self, index: UInt(currentCardNumber)) let firstCardOverlayView = dataSource.kolodaViewForCardOverlayAtIndex(self, index: UInt(currentCardNumber)) let firstCardView = DraggableCardView() firstCardView.alpha = alphaValueTransparent firstCardView.configure(firstCardContentView, overlayView: firstCardOverlayView) firstCardView.delegate = self addSubview(firstCardView) visibleCards.insert(firstCardView, atIndex: 0) firstCardView.frame = frameForCardAtIndex(0) applyRevertAnimation(firstCardView) } for index in 1..<visibleCards.count { let currentCard = visibleCards[index] let frameAnimation = POPBasicAnimation(propertyNamed: kPOPViewFrame) frameAnimation.duration = backgroundCardFrameAnimationDuration currentCard.alpha = alphaValueSemiTransparent frameAnimation.toValue = NSValue(CGRect: frameForCardAtIndex(UInt(index))) currentCard.userInteractionEnabled = false currentCard.pop_addAnimation(frameAnimation, forKey: "frameAnimation") } } } private func loadMissingCards(missingCardsCount: Int) { if missingCardsCount > 0 { let cardsToAdd = min(missingCardsCount, countOfCards - currentCardNumber) for index in 1...cardsToAdd { let nextCardIndex = countOfVisibleCards - cardsToAdd + index - 1 let nextCardView = DraggableCardView(frame: frameForCardAtIndex(UInt(index))) nextCardView.alpha = alphaValueSemiTransparent nextCardView.delegate = self visibleCards.append(nextCardView) insertSubview(nextCardView, belowSubview: visibleCards[index - 1]) } } reconfigureCards() } private func reconfigureCards() { for index in 0..<visibleCards.count { if let dataSource = self.dataSource { let currentCardContentView = dataSource.kolodaViewForCardAtIndex(self, index: UInt(currentCardNumber + index)) let overlayView = dataSource.kolodaViewForCardOverlayAtIndex(self, index: UInt(currentCardNumber + index)) let currentCard = visibleCards[index] currentCard.configure(currentCardContentView, overlayView: overlayView) } } } public func reloadData() { countOfCards = Int(dataSource!.kolodaNumberOfCards(self)) let missingCards = min(countOfVisibleCards - visibleCards.count, countOfCards - (currentCardNumber + 1)) if countOfCards == 0 { return } if currentCardNumber == 0 { clear() } if countOfCards - (currentCardNumber + visibleCards.count) > 0 { if !visibleCards.isEmpty { loadMissingCards(missingCards) } else { setupDeck() layoutDeck() if let shouldApply = delegate?.kolodaShouldApplyAppearAnimation(self) where shouldApply == true { applyAppearAnimation() } } } else { reconfigureCards() } } public func swipe(direction: SwipeResultDirection) { if (animating == false) { if let frontCard = visibleCards.first { animating = true switch direction { case SwipeResultDirection.None: return case SwipeResultDirection.Left: frontCard.swipeLeft() case SwipeResultDirection.Right: frontCard.swipeRight() } if visibleCards.count > 1 { let nextCard = visibleCards[1] nextCard.alpha = alphaValueOpaque } } } } public func resetCurrentCardNumber() { clear() reloadData() } }
mit
nickynick/Visuals
Visuals/SpaceToken.swift
1
515
// // SpaceToken.swift // Visuals // // Created by Nick Tymchenko on 05/07/14. // Copyright (c) 2014 Nick Tymchenko. All rights reserved. // import Foundation protocol SpaceToken { func append(itemToken: ItemToken) -> ItemToken } @infix func - (lhs: SpaceToken, rhs: ItemToken) -> ItemToken { return lhs.append(rhs) } @infix func - (lhs: SpaceToken, rhs: View[]) -> ItemToken { return lhs-Item(view: rhs[0]) } @infix func - (lhs: SpaceToken, rhs: Item[]) -> ItemToken { return lhs-rhs[0] }
mit
Tantalum73/PermissionController
PermissionController/PermissionController.swift
1
12904
// // PermissionController.swift // ClubNews // // Created by Andreas Neusüß on 28.04.15. // Copyright (c) 2015 Cocoawah. All rights reserved. // import UIKit import MapKit import EventKit import UserNotifications /** Enum to express types of permission in that you are interested in. - Location: Location permission - Calendar: Calendar permission - Notification: Notification permission */ public enum PermissionInterestedIn { case location, calendar, notification } /// Exposes the interface for persenting the permission dialog and handles the actions. open class PermissionController: NSObject, CLLocationManagerDelegate { fileprivate var locationManager : CLLocationManager? fileprivate var eventStore : EKEventStore? fileprivate var currentViewControllerView: UIView? fileprivate var calendarSuccessBlock : (()->())? fileprivate var calendarFailureBlock: (()->())? fileprivate var successBlock : (()->())? fileprivate var failureBlock: (()->())? /** Use this method to present the permission view. The user will be asked to give permissions by a dialog. When the user already granted a permission, the button is not enabled and a checkmark reflects it. By specifying a `interestedInPermission` you register the completion and failure blocks to be executed when the user finfished the interaction with the dialog. If the operation you want to start depends on a permission, you can continue or cancel it in those blocks if you registered in that permission. - returns: Bool that is true, when requested permission is already granted. If other permissions are missing, the PermissionView will be displayed and false is returned. - parameter viewController: The UIViewController on which the PermissionView shall be presented. - parameter interestedInPermission: Indicates in which action the reuest is interested in. This value decides, whether the permission requesting was successful or not and therefore which completion block will be called. If you are only interested in the location permission to continue an operation, you can rely on the successBlock/failureBlock to be executed after the user was asked and continue or cancel the operation. - parameter successBlock: This block will be executed on the main thread if the user dismissed the PermissionView and gave the desired permission. - parameter failureBlock: This block will be executed on the main thread if the user dismissed the PermissionView and did not gave the desired permission. */ open func presentPermissionViewIfNeededInViewController(_ viewController: UIViewController, interestedInPermission: PermissionInterestedIn?, successBlock: (()->())?, failureBlock: (()->())? ) -> Bool { let status = stateOfPermissions() let allPermissionsGranted = status.permissionLocationGranted && status.permissionCalendarGranted && status.permissionNotificationGranted self.successBlock = successBlock self.failureBlock = failureBlock self.locationManager = CLLocationManager() self.locationManager?.delegate = self if !allPermissionsGranted { //presenting let explanationViewController = ModalExplanationViewController() explanationViewController.permissionActionHandler = self explanationViewController.presentExplanationViewControllerOnViewController(viewController, nameOfNibs: ["PermissionView"], completion: { (_: Bool) -> () in if let interest = interestedInPermission { let currentState = self.stateOfPermissions() DispatchQueue.main.async(execute: { //TODO: maybe in the future: accept more than one desiredPermission switch interest { case .location : if currentState.permissionLocationGranted { successBlock?() } else { failureBlock?() } break case .calendar: if currentState.permissionCalendarGranted { successBlock?() } else { failureBlock?() } break case .notification: if currentState.permissionNotificationGranted { successBlock?() } else { failureBlock?() } break } }) } }) //return something so that the calling code an continue. return false } successBlock?() return true } //MARK: - CLLocationManagerDelegate /** Receives CLLocationManagerDelegate authorization calls and writes them to the `NSUserDefaults`. Then, a notification is posted that tells the displayed dialog to update the UI accordingly. */ open func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { let defaults = UserDefaults.standard switch status { case .authorizedAlways: defaults.set(true, forKey: "LocationPermission") defaults.set(false, forKey: "LocationPermissionAskedOnce") break case .authorizedWhenInUse: defaults.set(false, forKey: "LocationPermission") defaults.set(false, forKey: "LocationPermissionAskedOnce") break case .denied: defaults.set(false, forKey: "LocationPermission") defaults.set(true, forKey: "LocationPermissionAskedOnce") break case .notDetermined: defaults.set(false, forKey: "LocationPermission") defaults.set(false, forKey: "LocationPermissionAskedOnce") break case .restricted: defaults.set(false, forKey: "LocationPermission") defaults.set(true, forKey: "LocationPermissionAskedOnce") break } defaults.synchronize() NotificationCenter.default.post(name: Notification.Name(rawValue: "LocalizationAuthorizationStatusChanged"), object: manager) NotificationCenter.default.post(name: Notification.Name(rawValue: "AuthorizationStatusChanged"), object: nil) } /** Open the Settings.app on the users device because he already declined the permission and it needs to be changed from there. */ fileprivate func sendUserToSettings() { let url = URL(string: UIApplicationOpenSettingsURLString)! if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } } extension PermissionController: PermissionAskingProtocol { func stateOfPermissions() -> StatusOfPermissions { var status = StatusOfPermissions() let defaults = UserDefaults.standard if defaults.bool(forKey: "LocationPermission") == true || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways { status.permissionLocationGranted = true } if UserDefaults.standard.bool(forKey: "CalendarPermission") == true || EKEventStore.authorizationStatus(for: EKEntityType.event) == EKAuthorizationStatus.authorized { status.permissionCalendarGranted = true } let registeredNotificationSettigns = UIApplication.shared.currentUserNotificationSettings if registeredNotificationSettigns?.types.rawValue != 0 || defaults.bool(forKey: "NotificationPermission") == true { //Some notifications are registered or already asked (probably both) status.permissionNotificationGranted = true } return status } func permissionButtonLocationPressed() { let status = CLLocationManager.authorizationStatus() let userWasAskedOnce = UserDefaults.standard.bool(forKey: "LocationPermissionAskedOnce") if userWasAskedOnce && status != CLAuthorizationStatus.authorizedAlways && status != CLAuthorizationStatus.authorizedWhenInUse { sendUserToSettings() return } self.locationManager?.requestAlwaysAuthorization() } func permissionButtonCalendarPressed() { let status = EKEventStore.authorizationStatus(for: EKEntityType.event) if status == EKAuthorizationStatus.denied { sendUserToSettings() return } UserDefaults.standard.set(true, forKey: "CalendarPermissionWasAskedOnce") self.eventStore = EKEventStore() let accessCompletionHandler : EKEventStoreRequestAccessCompletionHandler = {(granted:Bool , error: Error?) in let defaults = UserDefaults.standard if granted { defaults.set(true, forKey: "CalendarPermission") } else { defaults.set(false, forKey: "CalendarPermission") } defaults.synchronize() DispatchQueue.main.async(execute: { NotificationCenter.default.post(name: Notification.Name(rawValue: "AuthorizationStatusChanged"), object: nil) }) } self.eventStore?.requestAccess(to: .event, completion: accessCompletionHandler) } func permissionButtonNotificationPressed() { // NSNotificationCenter.defaultCenter().postNotificationName("AuthorizationStatusChanged", object: nil) let defaults = UserDefaults.standard let registeredNotificationSettigns = UIApplication.shared.currentUserNotificationSettings if registeredNotificationSettigns?.types.rawValue == 0 && defaults.bool(forKey: "NotificationPermissionWasAskedOnce") == true { //Some notifications are registered or already asked (probably both) sendUserToSettings() return } defaults.set(true, forKey: "NotificationPermissionWasAskedOnce") //iOS 10 changed this a little if #available(iOS 10.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) { (granted, error) in if(granted){ let defaults = UserDefaults.standard defaults.set(true, forKey: "NotificationPermission") } DispatchQueue.main.async(execute: { NotificationCenter.default.post(name: Notification.Name(rawValue: "AuthorizationStatusChanged"), object: nil) }) } } else { let desiredNotificationSettigns = UIUserNotificationSettings(types: [UIUserNotificationType.alert, .badge, .sound] , categories: nil) UIApplication.shared.registerUserNotificationSettings(desiredNotificationSettigns) } } } extension UIColor { /** returns UIColor from given hex value. - parameter hex: the hex value to be converted to uicolor - parameter alpha: the alpha value of the color - returns: the UIColor corresponding to the given hex and alpha value */ class func colorFromHex (_ hex: Int, alpha: Double = 1.0) -> UIColor { let red = Double((hex & 0xFF0000) >> 16) / 255.0 let green = Double((hex & 0xFF00) >> 8) / 255.0 let blue = Double((hex & 0xFF)) / 255.0 let color: UIColor = UIColor( red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha:CGFloat(alpha) ) return color } /** returns UIColor from rgb value. - parameter red: the r value - parameter green: the g value - parameter blue: the b value */ class func colorFromRGB (_ red: Int, green: Int, blue: Int) -> UIColor { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") return self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } }
mit
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Structs/MSPack.swift
1
581
// // MSPack.swift // MoyskladiOSRemapSDK // // Created by Vladislav on 18.10.17. // Copyright © 2017 Andrey Parshakov. All rights reserved. // import Foundation public class MSPack { public let id: MSID public var quantity: Double public var uom: MSEntity<MSUOM>? public init(id: MSID, quantity: Double, uom: MSEntity<MSUOM>?) { self.id = id self.quantity = quantity self.uom = uom } public func copy() -> MSPack { return MSPack(id: id, quantity: quantity, uom: uom) } }
mit
harenbrs/swix
swixUseCases/swix-OSX/swix/matrix/helper-functions.swift
2
2334
// // helper-functions.swift // swix // // Created by Scott Sievert on 8/9/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation func println(x: matrix, prefix:String="matrix([", postfix:String="])", newline:String="\n", format:String="%.3f", printWholeMatrix:Bool=false){ print(prefix) var suffix = ", " var pre:String var post:String var printedSpacer = false for i in 0..<x.shape.0{ // pre and post nice -- internal variables if i==0 {pre = ""} else {pre = " "} if i==x.shape.0-1{post=""} else {post = "],\n"} if printWholeMatrix || x.shape.0 < 16 || i<4-1 || i>x.shape.0-4{ print(x[i, 0..<x.shape.1], prefix:pre, postfix:post, format: format, printWholeMatrix:printWholeMatrix) } else if printedSpacer==false{ printedSpacer=true println(" ...,") } } print(postfix) print(newline) } func print(x: matrix, prefix:String="matrix([", postfix:String="])", newline:String="\n", format:String="%.3f", printWholeMatrix:Bool=false){ println(x, prefix:prefix, postfix:postfix, newline:"", format:format, printWholeMatrix:printWholeMatrix) } func argwhere(idx: matrix) -> ndarray{ return argwhere(idx.flat) } func flipud(x:matrix)->matrix{ var y = x.copy() CVWrapper.flip(!x, into:!y, how:"ud", m:x.shape.0.cint, n:x.shape.1.cint) return y } func fliplr(x:matrix)->matrix{ var y = x.copy() CVWrapper.flip(!x, into:!y, how:"lr", m:x.shape.0.cint, n:x.shape.1.cint) return y } func transpose (x: matrix) -> matrix{ var m = x.shape.1 var n = x.shape.0 var y = zeros((m, n)) vDSP_mtransD(!x, 1.cint, !y, 1.cint, vDSP_Length(m), vDSP_Length(n)) return y } func write_csv(x:matrix, #filename:String, prefix:String=S2_PREFIX){ var seperator="," var str = "" for i in 0..<x.shape.0{ for j in 0..<x.shape.1{ seperator = j == x.shape.1-1 ? "" : "," str += String(format: "\(x[i, j])"+seperator) } str += "\n" } var error:NSError? str.writeToFile(prefix+"../"+filename, atomically: false, encoding: NSUTF8StringEncoding, error: &error) if let error=error{ println("File probably wasn't recognized \n\(error)") } }
mit
ahoppen/swift
test/Sema/fixed_ambiguities/rdar35625473.swift
36
169
// RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s // CHECK: function_ref @$sSlsE9dropFirsty11SubSequenceQzSiF _ = [1, 2, 3].dropFirst(1).dropFirst(1)
apache-2.0
mlibai/OMKit
OMKit/Classes/OMKit.swift
1
766
// // OMKit.swift // Pods // // Created by mlibai on 2017/6/28. // // import Foundation extension Bundle { private class OMKitBundleClass {} public static let OMKit: Bundle = Bundle(for: OMKitBundleClass.self) } extension UIImage { /// 读取 OMKit 中的资源图片。 public convenience init?(OMKit name: String, compatibleWith traitCollection: UITraitCollection? = nil) { #if COCOAPODS let resourceBundle = Bundle(url: Bundle.OMKit.url(forResource: "OMKit", withExtension: "bundle")!)! self.init(named: name, in: resourceBundle, compatibleWith: traitCollection) #else self.init(named: name, in: Bundle.OMKit, compatibleWith: traitCollection) #endif } }
mit
Dreamersoul/Appz
Appz/AppzTests/AppsTests/InstagramTests.swift
1
2375
// // InstagramTests.swift // Appz // // Created by Suraj Shirvankar on 12/6/15. // Copyright © 2015 kitz. All rights reserved. // import XCTest @testable import Appz class InstagramTests: XCTestCase { let appCaller = ApplicationCallerMock() func testConfiguration() { let instagram = Applications.Instagram() XCTAssertEqual(instagram.scheme, "instagram:") XCTAssertEqual(instagram.fallbackURL, "https://instagram.com/") } func testOpen() { let action = Applications.Instagram.Action.open XCTAssertEqual(action.paths.app.pathComponents, ["app"]) XCTAssertEqual(action.paths.app.queryParameters, [:]) XCTAssertEqual(action.paths.web, Path()) } func testCamera() { let action = Applications.Instagram.Action.camera XCTAssertEqual(action.paths.app.pathComponents, ["camera"]) XCTAssertEqual(action.paths.app.queryParameters, [:]) XCTAssertEqual(action.paths.web, Path()) } func testMedia() { let action = Applications.Instagram.Action.media(id: "1") XCTAssertEqual(action.paths.app.pathComponents, ["media"]) XCTAssertEqual(action.paths.app.queryParameters, ["id":"1"]) XCTAssertEqual(action.paths.web.pathComponents, ["p", "1"]) } func testUsername() { let action = Applications.Instagram.Action.username(username: "test") XCTAssertEqual(action.paths.app.pathComponents, ["user"]) XCTAssertEqual(action.paths.app.queryParameters, ["id":"test"]) XCTAssertEqual(action.paths.web.pathComponents, ["test"]) } func testLocation() { let action = Applications.Instagram.Action.location(id: "111") XCTAssertEqual(action.paths.app.pathComponents, ["location"]) XCTAssertEqual(action.paths.app.queryParameters, ["id":"111"]) XCTAssertEqual(action.paths.web, Path()) } func testTag() { let action = Applications.Instagram.Action.tag(name: "tag") XCTAssertEqual(action.paths.app.pathComponents, ["tag"]) XCTAssertEqual(action.paths.app.queryParameters, ["name":"tag"]) XCTAssertEqual(action.paths.web.pathComponents, ["explore", "tags", "tag"]) } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/00753-swift-type-transform.swift
1
460
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func g<T) { struct B<f = { struct D : P { protocol P { init()
apache-2.0
iOS-mamu/SS
P/Library/Eureka/Source/Rows/Common/DecimalFormatter.swift
1
1295
// // DecimalFormatter.swift // Eureka // // Created by Martin Barreto on 2/24/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation open class DecimalFormatter : NumberFormatter, FormatterProtocol { public override init() { super.init() locale = .current numberStyle = .decimal minimumFractionDigits = 2 maximumFractionDigits = 2 } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, range rangep: UnsafeMutablePointer<NSRange>?) throws { guard obj != nil else { return } let str = string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "") obj?.pointee = NSNumber(value: (Double(str) ?? 0.0)/Double(pow(10.0, Double(minimumFractionDigits)))) } open func getNewPosition(forPosition position: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition { return textInput.position(from: position, offset:((newValue?.characters.count ?? 0) - (oldValue?.characters.count ?? 0))) ?? position } }
mit
sergiosilvajr/ToDoList-Assignment-iOS
ToDoList/ToDoList/ToDoTableViewCell.swift
1
661
// // ToDoTableViewCell.swift // ToDoList // // Created by Luis Sergio da Silva Junior on 11/27/15. // Copyright © 2015 Luis Sergio. All rights reserved. // import UIKit class ToDoTableViewCell: UITableViewCell { @IBOutlet weak var nameItem: UILabel! @IBOutlet weak var descriptionItem: UILabel! @IBOutlet weak var dateLabelInfo: UILabel! @IBOutlet weak var isImportantLabel: UILabel! weak var currentDateItem : NSDate? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
apache-2.0
mrdepth/Neocom
Legacy/Neocom/Neocom/DgmTypePicker.swift
2
557
// // DgmTypePicker.swift // Neocom // // Created by Artem Shimanski on 11/30/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures enum DgmTypePicker: Assembly { typealias View = DgmTypePickerViewController case `default` func instantiate(_ input: View.Input) -> Future<View> { switch self { case .default: let controller = UIStoryboard.fitting.instantiateViewController(withIdentifier: "DgmTypePickerViewController") as! View controller.input = input return .init(controller) } } }
lgpl-2.1
authme-org/authme
authme-iphone/AuthMe/Src/MasterPassword.swift
1
25117
/* * * Copyright 2015 Berin Lautenbach * * 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. * */ // // MasterPassword.swift // AuthMe // // Created by Berin Lautenbach on 2/03/2015. // Copyright (c) 2015 Berin Lautenbach. All rights reserved. // import Foundation import CoreData import UIKit import LocalAuthentication // MARK: Callback protocol protocol MasterPasswordCallback { func onServiceInitialised() func onServiceDeinitialised() } class MasterPassword : NSObject { let _AUTHME_DEVICE_RSA_KEY_TAG = "com.authme.iphone.new2" let _AUTHME_DEVICE_PASSWORD_TAG = "com.authme.iphone.password" let _AUTHME_RSA_KEY_LENGTH : Int32 = 256 /* Key size in bytes. 256 = 2048 bit key */ let masterPasswordSalt : [UInt8] = [0x56, 0x14, 0x4f, 0x01, 0x5b, 0x8d, 0x44, 0x23] as [UInt8] let configCheckArray : [UInt8] = [0x6a, 0x6a, 0x6a] as [UInt8] enum PasswordState : Int { case open_STORE case create_PASS1 case create_PASS2 } let logger = Log() var managedObjectContext: NSManagedObjectContext? = nil var cachedConfig: Configuration? var passwordState = PasswordState.open_STORE var passwordFirstPass = "" var storePassword = "" var useTouchID = false var RSAGenAlert: UIAlertController? = nil var serviceActive = false var callbacks : [MasterPasswordCallback] = [] // Keys var deviceRSAKey : RSAKey? = nil var storeKey : AESKey? = nil var serviceKey : AESKey? = nil var serviceKeyPair : RSAKey? = nil var authController: AuthListController? = nil override init() { logger.log(.debug, message: "Master Password initialising") } // MARK: Startup loading func requestStorePassword(_ prompt: String) { // Use an alert dialog to get password let alert = UIAlertController(title: "Master Password", message: prompt, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {(UIAlertAction) in self.passwordEntered((alert.textFields![0] as UITextField).text!) })) alert.addTextField(configurationHandler: {(textField: UITextField) in textField.placeholder = "Password" }) UIApplication.shared.keyWindow!.rootViewController!.present(alert, animated: true, completion: nil) } func startup() { logger.log(.debug, message: "Master password commencing load") /* Open the master key data */ // First load the Store Check Value so we can validate the password let request = NSFetchRequest<NSFetchRequestResult>() let entity = NSEntityDescription.entity(forEntityName: "Configuration", in: managedObjectContext!) request.entity = entity // Fetch var fetchResult : [AnyObject] = [] do { fetchResult = try managedObjectContext!.fetch(request) as [AnyObject]! } catch _ { } /* Can we fetch the required class from the store? */ if fetchResult.count == 0 { // Oh dear - need to create from scratch logger.log(.info, message: "Creating default configuration") cachedConfig = NSEntityDescription.insertNewObject(forEntityName: "Configuration", into: managedObjectContext!) as? Configuration do { try managedObjectContext?.save() } catch _ { } } else { cachedConfig = (fetchResult[0] as! Configuration) } // Load the configuration up AppConfiguration.getInstance().managedObjectContext = managedObjectContext // Find out if we have a TouchID that we want to enable let context = LAContext() let haveTouchId = context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: nil) // Now load the password if (cachedConfig!.checkString != nil) { passwordState = .open_STORE if haveTouchId && (cachedConfig!.useTouchID == NSNumber(value: 1 as Int32)) { requestTouchIDPassword() } else { requestStorePassword("Open Store - Enter Password") } } else { passwordState = .create_PASS1 if haveTouchId { requestTouchIDSetup() } else { requestStorePassword("Initialise Store - Enter Password") } } } func requestTouchIDSetup() { // Use an alert dialog to ask the user whether to use TouchID let alert = UIAlertController(title: "Use Touch ID?", message: "Touch ID is active on this device. Do you wish to use your fingerprint to secure this app?\n\nNOTE: You will still enter a password that can also be used in an emergency.", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: {(UIAlertAction) in self.useTouchID = true self.requestStorePassword("Initialise Store - Enter Password") })) alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: {(UIAlertAction) in self.requestStorePassword("Initialise Store - Enter Password") })) UIApplication.shared.keyWindow!.rootViewController!.present(alert, animated: true, completion: nil) } func storePasswordToTouchID() { let keyChainStore = KeyChainPassword(identifier: _AUTHME_DEVICE_PASSWORD_TAG) keyChainStore?.setPassword(storePassword) if !(keyChainStore?.storeKey())! { logger.log(.warn, message: "Error storing password to keychain") useTouchID = false } } func requestTouchIDPassword() { let keyChainStore = KeyChainPassword(identifier: _AUTHME_DEVICE_PASSWORD_TAG) if (keyChainStore?.loadKey())! { storePassword = (keyChainStore?.getPassword())! logger.log(.debug, message: "Got Key: \(storePassword)") if !checkStore() { // We failed to get the correct password! // Invalidate current keys and reset //memset(key, 0, _AUTHME_ENCRYPT_KEY_LENGTH); storePassword = "" requestStorePassword("Touch ID failed to load - Enter Password") return } startInit() } else { logger.log(.warn, message: "Error loading password from Touch ID") requestStorePassword("Open Store - Enter Password") } } func passwordEntered(_ password: String) { logger.log(.finest, message: "Password = \(password)") // First of all - did someone type "RESET!" to get this to reset? if password == "RESET!" { logger.log(.debug, message: "User requested database reset") if let persistentStoreCoordinator = managedObjectContext?.persistentStoreCoordinator { // Do the shut down of the store var errorCode : NSError? if let store = persistentStoreCoordinator.persistentStores.last as NSPersistentStore? { do { try persistentStoreCoordinator.remove(store) logger.log(.debug, message: "Store removed OK") } catch let error as NSError { errorCode = error logger.log(.debug, message: "Store removal Error: \(errorCode as Optional), \(errorCode?.userInfo as Optional)"); } // Now delete the file // FIXME: dirty. If there are many stores... // Delete file if FileManager.default.fileExists(atPath: store.url!.path) { do { try FileManager.default.removeItem(atPath: store.url!.path) logger.log(.debug, message:"Unresolved error \(errorCode as Optional), \(errorCode?.userInfo as Optional)") } catch let error as NSError { errorCode = error logger.log(.debug, message: "Store file deleted OK") } } } } abort(); } // Is this first entry or later? switch passwordState { case .create_PASS1: passwordFirstPass = password // Now load password screen again requestStorePassword("Initialise Store - Repeat Password") passwordState = .create_PASS2 return case .create_PASS2: // This is second time entered - check and done! if passwordFirstPass == password { storePassword = password logger.log(.debug, message: "Initial entry of password succeeded") if useTouchID { logger.log(.debug, message: "Storing password to keychain") storePasswordToTouchID() } // Use the password to build the createStore() return } else { logger.log(.debug, message: "Initial entry of password failed") passwordFirstPass = "" passwordState = .create_PASS1 requestStorePassword("Initialise Mismatch - Enter Password") return } case .open_STORE: storePassword = password // Now validate if !checkStore() { // We failed to get the correct password! // Invalidate current keys and reset //memset(key, 0, _AUTHME_ENCRYPT_KEY_LENGTH); storePassword = "" requestStorePassword("Incorrect Password - Enter Password") return } } startInit() } // MARK: Store management @objc func createStoreWorker() { /* Used to generate the RSA key in the background and then switch back to the * main thread to close the alert window */ logger.log(.debug, message:"rsaGEnThreadMain now generating keys") if deviceRSAKey != nil { deviceRSAKey!.destroy(true) deviceRSAKey = nil; } deviceRSAKey = RSAKey(identifier: _AUTHME_DEVICE_RSA_KEY_TAG) if !deviceRSAKey!.generate(_AUTHME_RSA_KEY_LENGTH * 8) { logger.log(.warn, message: "Error generating RSA key"); return; } logger.log(.debug, message: "ceateStoreWorker creating configuration"); /* Create the AES wrapper using the password */ let pwKey = AESKey() pwKey.setKeyFromPassword(storePassword, withSalt: Data(bytes: UnsafePointer<UInt8>(masterPasswordSalt), count: 8), ofLength: 8) /* Create the store key */ storeKey = AESKey() if !storeKey!.generateKey() { logger.log(.warn, message: "Error generating store key") return } /* Encrypt the check value, RSA Key pair and the store key to save */ let encodedCheckValue = storeKey!.encrypt(Data(bytes: UnsafePointer<UInt8>(configCheckArray), count: 3), plainLength: 3) let rawStoreKey = Data(bytes: UnsafePointer<UInt8>(storeKey!.key), count: 32) let encryptedStoreKey = pwKey.encrypt(rawStoreKey, plainLength: 32) let rawPublicKey = deviceRSAKey?.getPublicKey() let rawPrivateKey = deviceRSAKey?.getPrivateKey() let encryptedPrivateKey = storeKey!.encrypt(rawPrivateKey) let checkStringRSA = deviceRSAKey?.encrypt(Data(bytes: UnsafePointer<UInt8>(configCheckArray), count: 3), plainLength: 3) // Take the encoded result and store cachedConfig!.checkString = encodedCheckValue cachedConfig!.nextId = NSNumber(value: 1 as Int32) cachedConfig!.storeKey = encryptedStoreKey cachedConfig!.deviceKeyPrivate = encryptedPrivateKey cachedConfig!.deviceKeyPublic = rawPublicKey cachedConfig!.checkStringRSA = checkStringRSA cachedConfig!.useTouchID = NSNumber(value: useTouchID ? 1 : 0 as Int32) cachedConfig!.deviceUUID = UIDevice.current.identifierForVendor!.uuidString do { try managedObjectContext!.save() } catch _ { logger.log(.error, message:"Problem saving the configuration") abort(); } logger.log(.debug, message: "createStoreWorker finalising"); UIApplication.shared.keyWindow!.rootViewController!.dismiss(animated: true, completion: nil) DispatchQueue.main.async(execute: {self.startInit()} ) } func startInit() { // Only get here if things are OK let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) UIApplication.shared.registerForRemoteNotifications() let initialiser = AuthMeServiceInitialiser() initialiser.doInit() } func createStore() { /* This takes a lot of CPU so we put up a message with and delay the work * while it goes up */ //[self performSelector:@selector(createStoreWorker) withObject:nil afterDelay:.5]; logger.log(.debug, message: "Starting RSA") RSAGenAlert = UIAlertController(title: "Generating Key", message: "Generating RSA Key\nPlease wait...", preferredStyle: UIAlertControllerStyle.alert) let alertFrame = RSAGenAlert!.view.frame let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge) activityIndicator.frame = CGRect(x: 125,y: alertFrame.size.height+115, width: 30,height: 30); activityIndicator.isHidden = false; activityIndicator.contentMode = UIViewContentMode.center activityIndicator.startAnimating() RSAGenAlert!.view.addSubview(activityIndicator) UIApplication.shared.keyWindow!.rootViewController!.present(RSAGenAlert!, animated: true, completion: nil) let createStoreWorkerThread = Thread(target: self, selector: #selector(MasterPassword.createStoreWorker), object: nil) createStoreWorkerThread.start() } func checkStore() -> Bool { /* Know we have all the basic store values - need to validate them using the entered password */ let pwKey = AESKey() pwKey.setKeyFromPassword(storePassword, withSalt: Data(bytes: UnsafePointer<UInt8>(masterPasswordSalt), count: 8), ofLength: 8) /* Can we load the store key? */ if let decryptedStoreKey = pwKey.decrypt(cachedConfig!.storeKey!, cipherLength: 0) { // Decrypt worked for store Key storeKey = AESKey() if storeKey!.loadKey(decryptedStoreKey as Data!) { // Key loaded OK - check the check value if let decryptedCheckValue = storeKey?.decrypt(cachedConfig!.checkString!, cipherLength: 0) { var good = true let checkBytes = decryptedCheckValue.bytes.bindMemory(to: UInt8.self, capacity: decryptedCheckValue.length) for i in 0..<configCheckArray.count { if configCheckArray[i] != checkBytes[i] { good = false } } if good { // Load the RSA Key logger.log(.debug, message:"Loading RSA ley") if deviceRSAKey != nil { deviceRSAKey!.destroy(true) deviceRSAKey = nil; } deviceRSAKey = RSAKey(identifier: _AUTHME_DEVICE_RSA_KEY_TAG) // This is an internal test - we don't want the keys persisting // in the keychain if deviceRSAKey!.loadKeysFromKeychain() { // Want to make sure this *NEVER* happens logger.log(.error, message: "Error KEY FOUND IN KEY CHAIN"); abort(); //return false } // Now do decrypts against check values and then do an // encrypt/decrypt to see it works good = false if let decryptedPrivateKey = storeKey?.decrypt(cachedConfig!.deviceKeyPrivate!, cipherLength: 0) { if deviceRSAKey!.loadPrivateKey(NSString(data: decryptedPrivateKey as Data, encoding: String.Encoding.utf8.rawValue)! as String) { if deviceRSAKey!.loadPublicKey(cachedConfig!.deviceKeyPublic) { logger.log(.debug, message: "RSA Key loaded") // Quick internal tests if let decRSACheck = deviceRSAKey?.decrypt(cachedConfig!.checkStringRSA) { let decRSACheckBytes = (decRSACheck as NSData).bytes.bindMemory(to: UInt8.self, capacity: decRSACheck.count) let encTest = deviceRSAKey?.encrypt(Data(bytes: UnsafePointer<UInt8>(configCheckArray), count: 3), plainLength: 3) if let decTest = deviceRSAKey?.decrypt(encTest) { let decTestBytes = (decTest as NSData).bytes.bindMemory(to: UInt8.self, capacity: decTest.count) good = true for i in 0..<configCheckArray.count { if (configCheckArray[i] != checkBytes[i]) || (configCheckArray[i] != decRSACheckBytes[i]) || (configCheckArray[i] != decTestBytes[i]) { good = false } } } else { good = false } } } } } if !good { logger.log(.debug, message: "RSA Test failed") } else { logger.log(.debug, message: "All RSA tests passed") return true } } } } } return false } // MARK: Secret wrapping / unwrapping /* * A secret is made up of a Base64 encoded byte array * bytes 1-4 is the length of the encrypted AES key (LEN) * bytes 5-(5+LEN) is the AES key encrypted in the service public key * bytes (5+LEN) - (5+LEN+16) is the AES IV - 16 BYTES * bytes (5+LEN+16) - (END) is the secret we are actually unwrapping encrypted with teh AES key */ func unwrapSecret(_ wrappedSecret: String) -> String? { /* Sanity checks */ if (wrappedSecret == "" || serviceKeyPair == nil) { return nil } /* Have to decode first */ let wrappedLength = wrappedSecret.count if let rawSecret = Base64().base64decode(wrappedSecret, length: Int32(wrappedLength)) { let rawBytes = UnsafeMutablePointer<UInt8>(mutating: rawSecret.bytes.bindMemory(to: UInt8.self, capacity: rawSecret.length)) // Size of WrapBufLen var wrapBufLen = 0 for i in 0..<4 { wrapBufLen = wrapBufLen << 8 let orVal = rawBytes[i] wrapBufLen = wrapBufLen | Int(orVal) } /* Create the right NSData so we can decrypt using private key */ let wrapBufBytes = UnsafeMutableRawPointer(rawBytes.advanced(by: 4)) if let aesKey = serviceKeyPair?.decryptData(Data(bytesNoCopy: wrapBufBytes, count: wrapBufLen, deallocator: .none)) { logger.log(.finest, message: "Public key decrypt in unwrap worked"); /* Now get the last part of the buffer */ let aesBytes = UnsafeMutableRawPointer(rawBytes.advanced(by: 4 + wrapBufLen)) let aes = AESKey() if aes.loadKey(aesKey) { if let decrypt = aes.decryptData(Data(bytesNoCopy: aesBytes, count: rawSecret.length - 4 - wrapBufLen, deallocator: .none)) { logger.log(.finest, message: "AES decrypt in unwrap worked"); let ret = Base64().base64encode(decrypt as Data, length: Int32(decrypt.length)) return String(describing: ret) } } } } return nil } // MARK: Helper functions func getUniqueDeviceId() -> String { if cachedConfig?.deviceUUID != nil { return cachedConfig!.deviceUUID! } // This is a fail safe - not a good idea as this can change return UIDevice.current.identifierForVendor!.uuidString } func getDeviceName() -> String { return UIDevice.current.name } // MARK: Service handling func checkServiceActive(_ callback: MasterPasswordCallback?, registerCallback: Bool) -> Bool { if registerCallback && callback != nil { callbacks.append(callback!) } return serviceActive } // Called by the service initialiser when done func serviceActivated() { logger.log(.debug, message: "Service activation completed successfully - starting callbacks") serviceActive = true for i in callbacks { i.onServiceInitialised() } } // If username/password changes func serviceDeactivated() { if serviceActive { logger.log(.debug, message: "Service activation reversed - destroying service details") serviceActive = false /* Destroy keys */ serviceKey = nil if serviceKeyPair != nil { /* Remove key from key chain as well as deleting our copy */ serviceKeyPair?.destroy(true) serviceKeyPair = nil } /* Tell anyone using service info we're out for the count */ for i in callbacks { i.onServiceDeinitialised() } } } // MARK: TouchID KeyChain handling // MARK: Singleton Handling class func getInstance() -> MasterPassword { return sharedInstance } class var sharedInstance: MasterPassword { struct Static { static let instance: MasterPassword = MasterPassword() } return Static.instance } }
apache-2.0
liuxuan30/SwiftCharts
SwiftCharts/AxisValues/ChartAxisValueFloat.swift
2
1317
// // ChartAxisValueFloat.swift // swift_charts // // Created by ischuetz on 15/03/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartAxisValueFloat: ChartAxisValue { public let formatter: NSNumberFormatter let labelSettings: ChartLabelSettings public var float: CGFloat { return self.scalar } override public var text: String { return self.formatter.stringFromNumber(self.float)! } public init(_ float: CGFloat, formatter: NSNumberFormatter = ChartAxisValueFloat.defaultFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) { self.formatter = formatter self.labelSettings = labelSettings super.init(scalar: float) } override public var labels: [ChartAxisLabel] { let axisLabel = ChartAxisLabel(text: self.text, settings: self.labelSettings) return [axisLabel] } override public func copy(scalar: CGFloat) -> ChartAxisValueFloat { return ChartAxisValueFloat(scalar, formatter: self.formatter, labelSettings: self.labelSettings) } static var defaultFormatter: NSNumberFormatter = { let formatter = NSNumberFormatter() formatter.maximumFractionDigits = 2 return formatter }() }
apache-2.0
khizkhiz/swift
test/Parse/init_deinit.swift
8
3120
// RUN: %target-parse-verify-swift struct FooStructConstructorA { init // expected-error {{expected '('}} } struct FooStructConstructorB { init() // expected-error {{initializer requires a body}} } struct FooStructConstructorC { init {} // expected-error {{expected '('}}{{8-8=() }} } struct FooStructDeinitializerA { deinit // expected-error {{expected '{' for deinitializer}} } struct FooStructDeinitializerB { deinit // expected-error {{expected '{' for deinitializer}} } struct FooStructDeinitializerC { deinit {} // expected-error {{deinitializers may only be declared within a class}} } class FooClassDeinitializerA { deinit(a : Int) {} // expected-error{{no parameter clause allowed on deinitializer}}{{9-18=}} } class FooClassDeinitializerB { deinit { } } init {} // expected-error {{initializers may only be declared within a type}} expected-error {{expected '('}} {{6-6=() }} init() // expected-error {{initializers may only be declared within a type}} init() {} // expected-error {{initializers may only be declared within a type}} deinit {} // expected-error {{deinitializers may only be declared within a class}} deinit // expected-error {{expected '{' for deinitializer}} deinit {} // expected-error {{deinitializers may only be declared within a class}} struct BarStruct { init() {} deinit {} // expected-error {{deinitializers may only be declared within a class}} } extension BarStruct { init(x : Int) {} // When/if we allow 'var' in extensions, then we should also allow dtors deinit {} // expected-error {{deinitializers may only be declared within a class}} } enum BarUnion { init() {} deinit {} // expected-error {{deinitializers may only be declared within a class}} } extension BarUnion { init(x : Int) {} deinit {} // expected-error {{deinitializers may only be declared within a class}} } class BarClass { init() {} deinit {} } extension BarClass { convenience init(x : Int) { self.init() } deinit {} // expected-error {{deinitializers may only be declared within a class}} } protocol BarProtocol { init() {} // expected-error {{protocol initializers may not have bodies}} deinit {} // expected-error {{deinitializers may only be declared within a class}} } extension BarProtocol { init(x : Int) {} deinit {} // expected-error {{deinitializers may only be declared within a class}} } func fooFunc() { init() {} // expected-error {{initializers may only be declared within a type}} deinit {} // expected-error {{deinitializers may only be declared within a class}} } func barFunc() { var x : () = { () -> () in init() {} // expected-error {{initializers may only be declared within a type}} return } () var y : () = { () -> () in deinit {} // expected-error {{deinitializers may only be declared within a class}} return } () } // SR-852 class Aaron { init(x: Int) {} convenience init() { init(x: 1) } // expected-error {{missing 'self.' at initializer invocation}} } class Theodosia: Aaron { init() { init(x: 2) // expected-error {{missing 'super.' at initializer invocation}} } }
apache-2.0
khizkhiz/swift
validation-test/stdlib/Assert.swift
1
6260
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/Assert_Debug // RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/Assert_Release -O // RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/Assert_Unchecked -Ounchecked // // RUN: %target-run %t/Assert_Debug // RUN: %target-run %t/Assert_Release // RUN: %target-run %t/Assert_Unchecked // REQUIRES: executable_test import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate import SwiftPrivatePthreadExtras #if _runtime(_ObjC) import ObjectiveC #endif //===--- // Tests. //===--- func testTrapsAreNoreturn(i: Int) -> Int { // Don't need a return statement in 'case' statements because these functions // are @noreturn. switch i { case 2: preconditionFailure("cannot happen") case 3: _preconditionFailure("cannot happen") case 4: _stdlibAssertionFailure("cannot happen") case 5: _sanityCheckFailure("cannot happen") default: return 0 } } var Assert = TestSuite("Assert") Assert.test("assert") .xfail(.custom( { !_isDebugAssertConfiguration() }, reason: "assertions are disabled in Release and Unchecked mode")) .crashOutputMatches("this should fail") .code { var x = 2 assert(x * 21 == 42, "should not fail") expectCrashLater() assert(x == 42, "this should fail") } Assert.test("assert/StringInterpolation") .xfail(.custom( { !_isDebugAssertConfiguration() }, reason: "assertions are disabled in Release and Unchecked mode")) .crashOutputMatches("this should fail") .code { var should = "should" var x = 2 assert(x * 21 == 42, "\(should) not fail") expectCrashLater() assert(x == 42, "this \(should) fail") } Assert.test("assertionFailure") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches("this should fail") .code { expectCrashLater() assertionFailure("this should fail") } Assert.test("assertionFailure/StringInterpolation") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches("this should fail") .code { var should = "should" expectCrashLater() assertionFailure("this \(should) fail") } Assert.test("precondition") .xfail(.custom( { _isFastAssertConfiguration() }, reason: "preconditions are disabled in Unchecked mode")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var x = 2 precondition(x * 21 == 42, "should not fail") expectCrashLater() precondition(x == 42, "this should fail") } Assert.test("precondition/StringInterpolation") .xfail(.custom( { _isFastAssertConfiguration() }, reason: "preconditions are disabled in Unchecked mode")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var should = "should" var x = 2 precondition(x * 21 == 42, "\(should) not fail") expectCrashLater() precondition(x == 42, "this \(should) fail") } Assert.test("preconditionFailure") .skip(.custom( { _isFastAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { expectCrashLater() preconditionFailure("this should fail") } Assert.test("preconditionFailure/StringInterpolation") .skip(.custom( { _isFastAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var should = "should" expectCrashLater() preconditionFailure("this \(should) fail") } Assert.test("fatalError") .crashOutputMatches("this should fail") .code { expectCrashLater() fatalError("this should fail") } Assert.test("fatalError/StringInterpolation") .crashOutputMatches("this should fail") .code { var should = "should" expectCrashLater() fatalError("this \(should) fail") } Assert.test("_precondition") .xfail(.custom( { _isFastAssertConfiguration() }, reason: "preconditions are disabled in Unchecked mode")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var x = 2 _precondition(x * 21 == 42, "should not fail") expectCrashLater() _precondition(x == 42, "this should fail") } Assert.test("_preconditionFailure") .skip(.custom( { _isFastAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { expectCrashLater() _preconditionFailure("this should fail") } Assert.test("_stdlibAssert") .xfail(.custom( { !_isDebugAssertConfiguration() }, reason: "debug preconditions are disabled in Release and Unchecked mode")) .crashOutputMatches(_isDebugAssertConfiguration() ? "this should fail" : "") .code { var x = 2 _stdlibAssert(x * 21 == 42, "should not fail") expectCrashLater() _stdlibAssert(x == 42, "this should fail") } Assert.test("_stdlibAssertionFailure") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches("this should fail") .code { expectCrashLater() _stdlibAssertionFailure("this should fail") } Assert.test("_sanityCheck") .xfail(.custom( { !_isStdlibInternalChecksEnabled() }, reason: "sanity checks are disabled in this build of stdlib")) .crashOutputMatches("this should fail") .code { var x = 2 _sanityCheck(x * 21 == 42, "should not fail") expectCrashLater() _sanityCheck(x == 42, "this should fail") } Assert.test("_sanityCheckFailure") .skip(.custom( { !_isStdlibInternalChecksEnabled() }, reason: "optimizer assumes that the code path is unreachable")) .crashOutputMatches("this should fail") .code { expectCrashLater() _sanityCheckFailure("this should fail") } runAllTests()
apache-2.0
srn214/Floral
Floral/Floral/Classes/Expand/Extensions/Device+Hardware.swift
1
4130
// // Device+Hardware.swift // JianZhongBang // // Created by Apple on 2018/8/26. // Copyright © 2018年 文刂Rn. All rights reserved. // import UIKit import DeviceKit // MARK: - 手机系列判断 extension Device { /// 是否是iPhone 4.7系列手机 public static var isPhone4_7Serier: Bool { return (((Device.current.diagonal ) == 4.7) ? true: false) } /// 是否是iPhone 5.5系列手机 public static var isPhone5_5Series: Bool { return (((Device.current.diagonal ) >= 5.5) ? true: false) } /// 是否是iPhone 5 以下 系列手机 public static var isPhone5Earlier: Bool { return (((Device.current.diagonal ) <= 4.0) ? true: false) } /// 是否是iPhone X手机 public static var isPhoneXSerise: Bool { let device = Device.current var _bool = false if Device.allXSeriesDevices.contains(device) { _bool = true } else if Device.allSimulatorXSeriesDevices.contains(device) { _bool = true } return _bool } } // MARK: - 手机信息 extension Device { /// 设备系统名称 public static var deviceSystemName: String { return UIDevice.current.systemName } /// 设备名称 public static var deviceName: String { return UIDevice.current.name } /// 设备版本 public static var deviceSystemVersion: String { return UIDevice.current.systemVersion } /// App版本 public static var appVersion: String { guard let dict = Bundle.main.infoDictionary else { return "unknown" } guard let version = dict["CFBundleShortVersionString"] as? String else { return "unknown" } return version } } extension Device { /// 设备型号 public static var machineModelName: String { switch Device.current { case .iPodTouch5: return "iPod_Touch_5" case .iPodTouch6: return "iPod_Touch_6" case .iPhone4: return "iPhone_4" case .iPhone4s: return "iPhone_4s" case .iPhone5: return "iPhone_5" case .iPhone5c: return "iPhone_5c" case .iPhone5s: return "iPhone_5s" case .iPhone6: return "iPhone_6" case .iPhone6Plus: return "iPhone_6_Plus" case .iPhone6s: return "iPhone_6s" case .iPhone6sPlus: return "iPhone_6s_Plus" case .iPhone7: return "iPhone_7" case .iPhone7Plus: return "iPhone_7_Plus" case .iPhoneSE: return "iPhone_SE" case .iPhone8: return "iPhone_8" case .iPhone8Plus: return "iPhone_8_Plus" case .iPhoneX: return "iPhone_X" case .iPhoneXS: return "iPhone_Xs" case .iPhoneXSMax: return "iPhone_Xs_Max" case .iPhoneXR: return "iPhone_Xr" case .iPad2: return "iPad_2" case .iPad3: return "iPad_3" case .iPad4: return "iPad_4" case .iPadAir: return "iPad_Air" case .iPadAir2: return "iPad_Air2" case .iPad5: return "iPad_5" case .iPad6: return "iPad_6" case .iPadMini: return "iPad_Mini" case .iPadMini2: return "iPad_Mini2" case .iPadMini3: return "iPad_Mini3" case .iPadMini4: return "iPad_Mini4" case .iPadPro9Inch: return "iPad_Pro_9Inch" case .iPadPro12Inch: return "iPad_Pro_12Inch" case .iPadPro12Inch2: return "iPad_Pro_12Inch2" case .iPadPro10Inch: return "iPad_Pro_10Inch" case .iPadPro11Inch: return "iPad_Pro_11Inch" case .iPadPro12Inch3: return "iPad_Pro_12Inch3" default: return "其他型号" } } }
mit
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift
5
5637
// // GitHubSearchRepositoriesAPI.swift // RxExample // // Created by Krunoslav Zaher on 10/18/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif import struct Foundation.URL import struct Foundation.Data import struct Foundation.URLRequest import struct Foundation.NSRange import class Foundation.HTTPURLResponse import class Foundation.URLSession import class Foundation.NSRegularExpression import class Foundation.JSONSerialization import class Foundation.NSString /** Parsed GitHub repository. */ struct Repository: CustomDebugStringConvertible { var name: String var url: URL init(name: String, url: URL) { self.name = name self.url = url } } extension Repository { var debugDescription: String { return "\(name) | \(url)" } } enum GitHubServiceError: Error { case offline case githubLimitReached case networkError } typealias SearchRepositoriesResponse = Result<(repositories: [Repository], nextURL: URL?), GitHubServiceError> class GitHubSearchRepositoriesAPI { // ***************************************************************************************** // !!! This is defined for simplicity sake, using singletons isn't advised !!! // !!! This is just a simple way to move services to one location so you can see Rx code !!! // ***************************************************************************************** static let sharedAPI = GitHubSearchRepositoriesAPI(reachabilityService: try! DefaultReachabilityService()) fileprivate let _reachabilityService: ReachabilityService private init(reachabilityService: ReachabilityService) { _reachabilityService = reachabilityService } } extension GitHubSearchRepositoriesAPI { public func loadSearchURL(_ searchURL: URL) -> Observable<SearchRepositoriesResponse> { return URLSession.shared .rx.response(request: URLRequest(url: searchURL)) .retry(3) .observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler) .map { pair -> SearchRepositoriesResponse in if pair.0.statusCode == 403 { return .failure(.githubLimitReached) } let jsonRoot = try GitHubSearchRepositoriesAPI.parseJSON(pair.0, data: pair.1) guard let json = jsonRoot as? [String: AnyObject] else { throw exampleError("Casting to dictionary failed") } let repositories = try Repository.parse(json) let nextURL = try GitHubSearchRepositoriesAPI.parseNextURL(pair.0) return .success((repositories: repositories, nextURL: nextURL)) } .retryOnBecomesReachable(.failure(.offline), reachabilityService: _reachabilityService) } } // MARK: Parsing the response extension GitHubSearchRepositoriesAPI { private static let parseLinksPattern = "\\s*,?\\s*<([^\\>]*)>\\s*;\\s*rel=\"([^\"]*)\"" private static let linksRegex = try! NSRegularExpression(pattern: parseLinksPattern, options: [.allowCommentsAndWhitespace]) fileprivate static func parseLinks(_ links: String) throws -> [String: String] { let length = (links as NSString).length let matches = GitHubSearchRepositoriesAPI.linksRegex.matches(in: links, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: length)) var result: [String: String] = [:] for m in matches { let matches = (1 ..< m.numberOfRanges).map { rangeIndex -> String in let range = m.range(at: rangeIndex) let startIndex = links.characters.index(links.startIndex, offsetBy: range.location) let endIndex = links.characters.index(links.startIndex, offsetBy: range.location + range.length) return String(links[startIndex ..< endIndex]) } if matches.count != 2 { throw exampleError("Error parsing links") } result[matches[1]] = matches[0] } return result } fileprivate static func parseNextURL(_ httpResponse: HTTPURLResponse) throws -> URL? { guard let serializedLinks = httpResponse.allHeaderFields["Link"] as? String else { return nil } let links = try GitHubSearchRepositoriesAPI.parseLinks(serializedLinks) guard let nextPageURL = links["next"] else { return nil } guard let nextUrl = URL(string: nextPageURL) else { throw exampleError("Error parsing next url `\(nextPageURL)`") } return nextUrl } fileprivate static func parseJSON(_ httpResponse: HTTPURLResponse, data: Data) throws -> AnyObject { if !(200 ..< 300 ~= httpResponse.statusCode) { throw exampleError("Call failed") } return try JSONSerialization.jsonObject(with: data, options: []) as AnyObject } } extension Repository { fileprivate static func parse(_ json: [String: AnyObject]) throws -> [Repository] { guard let items = json["items"] as? [[String: AnyObject]] else { throw exampleError("Can't find items") } return try items.map { item in guard let name = item["name"] as? String, let url = item["url"] as? String else { throw exampleError("Can't parse repository") } return Repository(name: name, url: try URL(string: url).unwrap()) } } }
mit
nodes-vapor/admin-panel-provider
Sources/AdminPanelProvider/Middlewares.swift
1
142
import Vapor public enum Middlewares { public static var unsecured: [Middleware] = [] public static var secured: [Middleware] = [] }
mit
yagihiro/swift-http-server-sample
Sources/main.swift
1
251
import Foundation print("Hello, world") do { let ip = try IP(port: 5555) let serverSocket = try TCPServerSocket(ip: ip) let clientSocket = try serverSocket.accept() let yo = try clientSocket.receiveString(untilDelimiter: "\n") } catch { }
mit
radex/swift-compiler-crashes
crashes-fuzzing/13772-swift-constraints-constraintsystem-opengeneric.swift
11
208
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true{var:Int=[{}class A{func b<T:A.b
mit
radex/swift-compiler-crashes
crashes-fuzzing/21599-swift-modulefile-maybereadpattern.swift
11
229
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing "" struct S { var d = a protocol a { typealias e : e func >
mit
vuthaihoa2402/OverlayOptionsSwift
OverlayOptions/SecondViewController.swift
1
515
// // SecondViewController.swift // OverlayOptions // // Created by Thaihoa on 9/24/15. // Copyright © 2015 Thaihoa. All rights reserved. // import UIKit class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
Bouke/HAP
Sources/HAP/Base/Predefined/Enums/Enums.TargetMediaState.swift
1
160
public extension Enums { enum TargetMediaState: UInt8, CharacteristicValueType { case play = 0 case pause = 1 case stop = 2 } }
mit
bugsnag/bugsnag-cocoa
features/fixtures/shared/scenarios/BreadcrumbCallbackCrashScenario.swift
1
1268
// // BreadcrumbCallbackCrashScenario.swift // iOSTestApp // // Created by Jamie Lynch on 27/05/2020. // Copyright © 2020 Bugsnag. All rights reserved. // import Foundation class BreadcrumbCallbackCrashScenario : Scenario { override func startBugsnag() { self.config.autoTrackSessions = false; self.config.enabledBreadcrumbTypes = [] self.config.addOnBreadcrumb { (crumb) -> Bool in crumb.metadata["addedInCallback"] = true // throw an exception to crash in the callback NSException(name: NSExceptionName("BreadcrumbCallbackCrashScenario"), reason: "Message: BreadcrumbCallbackCrashScenario", userInfo: nil).raise() crumb.metadata["shouldNotHappen"] = "it happened" return true } self.config.addOnBreadcrumb { (crumb) -> Bool in crumb.metadata["secondCallback"] = true return true } super.startBugsnag() } override func run() { Bugsnag.leaveBreadcrumb("Hello World", metadata: ["foo": "bar"], type: .manual) let error = NSError(domain: "BreadcrumbCallbackCrashScenario", code: 100, userInfo: nil) Bugsnag.notifyError(error) } }
mit
KEN-chan/RequestAlert
Demo/Demo/ViewController.swift
1
1902
// // ViewController.swift // Demo // // Created by HARA KENTA on 2016/03/07. // Copyright © 2016年 Hara Kenta. All rights reserved. // import UIKit import RequestAlert class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) RequestAlert.showAlert(id: RequestAlertType.pushNotification.id) { print("push OK button of Request Alert of type of push notification") } if RequestAlert.hasDisplayed(id: RequestAlertType.review.id) { print("review request alert has been displayed") } if RequestAlert.hasBeenPushedOKButton(id: RequestAlertType.share.id) { print("share request alert has been pushed OK Button") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func pushedPushNotificationButton(sender: AnyObject) { RequestAlert.incrementCount(id: RequestAlertType.pushNotification.id) { print("push OK button of Request Alert of type of push notification") } } @IBAction func pushedReviewButton(sender: AnyObject) { RequestAlert.incrementCount(id: RequestAlertType.review.id) { print("push OK button of Request Alert of type of review") } } @IBAction func pushedShareButton(sender: AnyObject) { RequestAlert.incrementCount(id: RequestAlertType.share.id) { print("push OK button of Request Alert of type of share") } } }
mit
brianjmoore/material-components-ios
components/TextFields/examples/TextFieldKitchenSinkExample.swift
1
27340
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // swiftlint:disable file_length // swiftlint:disable type_body_length // swiftlint:disable function_body_length import UIKit import MaterialComponents.MaterialTextFields import MaterialComponents.MaterialAppBar import MaterialComponents.MaterialButtons import MaterialComponents.MaterialTypography final class TextFieldKitchenSinkSwiftExample: UIViewController { let scrollView = UIScrollView() let controlLabel: UILabel = { let controlLabel = UILabel() controlLabel.translatesAutoresizingMaskIntoConstraints = false controlLabel.text = "Options" controlLabel.font = UIFont.preferredFont(forTextStyle: .headline) controlLabel.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity()) return controlLabel }() let singleLabel: UILabel = { let singleLabel = UILabel() singleLabel.translatesAutoresizingMaskIntoConstraints = false singleLabel.text = "Single-line Text Fields" singleLabel.font = UIFont.preferredFont(forTextStyle: .headline) singleLabel.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity()) singleLabel.numberOfLines = 0 return singleLabel }() let multiLabel: UILabel = { let multiLabel = UILabel() multiLabel.translatesAutoresizingMaskIntoConstraints = false multiLabel.text = "Multi-line Text Fields" multiLabel.font = UIFont.preferredFont(forTextStyle: .headline) multiLabel.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity()) multiLabel.numberOfLines = 0 return multiLabel }() let errorLabel: UILabel = { let errorLabel = UILabel() errorLabel.translatesAutoresizingMaskIntoConstraints = false errorLabel.text = "In Error:" errorLabel.font = UIFont.preferredFont(forTextStyle: .subheadline) errorLabel.textColor = UIColor(white: 0, alpha: MDCTypography.subheadFontOpacity()) errorLabel.numberOfLines = 0 return errorLabel }() let helperLabel: UILabel = { let helperLabel = UILabel() helperLabel.translatesAutoresizingMaskIntoConstraints = false helperLabel.text = "Show Helper Text:" helperLabel.font = UIFont.preferredFont(forTextStyle: .subheadline) helperLabel.textColor = UIColor(white: 0, alpha: MDCTypography.subheadFontOpacity()) helperLabel.numberOfLines = 0 return helperLabel }() var allInputControllers = [MDCTextInputController]() var allTextFieldControllers = [MDCTextInputController]() var allMultilineTextFieldControllers = [MDCTextInputController]() var controllersWithCharacterCount = [MDCTextInputController]() var controllersFullWidth = [MDCTextInputControllerFullWidth]() let unstyledTextField = MDCTextField() let unstyledMultilineTextField = MDCMultilineTextField() lazy var textInsetsModeButton: MDCButton = self.setupButton() lazy var characterModeButton: MDCButton = self.setupButton() lazy var clearModeButton: MDCButton = self.setupButton() lazy var underlineButton: MDCButton = self.setupButton() deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() setupExampleViews() } func setupFilledTextFields() -> [MDCTextInputControllerFilled] { let textFieldFilled = MDCTextField() textFieldFilled.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldFilled) textFieldFilled.delegate = self let textFieldControllerFilled = MDCTextInputControllerFilled(textInput: textFieldFilled) textFieldControllerFilled.isFloatingEnabled = false textFieldControllerFilled.placeholderText = "This is a filled text field" let textFieldFilledFloating = MDCTextField() textFieldFilledFloating.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldFilledFloating) textFieldFilledFloating.delegate = self let textFieldControllerFilledFloating = MDCTextInputControllerFilled(textInput: textFieldFilledFloating) textFieldControllerFilledFloating.placeholderText = "This is filled and floating" return [textFieldControllerFilled, textFieldControllerFilledFloating] } func setupDefaultTextFields() -> [MDCTextInputControllerDefault] { let textFieldDefault = MDCTextField() textFieldDefault.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldDefault) textFieldDefault.delegate = self textFieldDefault.clearButtonMode = .whileEditing let textFieldControllerDefault = MDCTextInputControllerDefault(textInput: textFieldDefault) textFieldControllerDefault.isFloatingEnabled = false let textFieldDefaultPlaceholder = MDCTextField() textFieldDefaultPlaceholder.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldDefaultPlaceholder) textFieldDefaultPlaceholder.delegate = self textFieldDefaultPlaceholder.clearButtonMode = .whileEditing let textFieldControllerDefaultPlaceholder = MDCTextInputControllerDefault(textInput: textFieldDefaultPlaceholder) textFieldControllerDefaultPlaceholder.isFloatingEnabled = false textFieldControllerDefaultPlaceholder.placeholderText = "This is a text field w/ inline placeholder" let textFieldDefaultCharMax = MDCTextField() textFieldDefaultCharMax.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldDefaultCharMax) textFieldDefaultCharMax.delegate = self textFieldDefaultCharMax.clearButtonMode = .whileEditing let textFieldControllerDefaultCharMax = MDCTextInputControllerDefault(textInput: textFieldDefaultCharMax) textFieldControllerDefaultCharMax.characterCountMax = 50 textFieldControllerDefaultCharMax.isFloatingEnabled = false textFieldControllerDefaultCharMax.placeholderText = "This is a text field w/ character count" controllersWithCharacterCount.append(textFieldControllerDefaultCharMax) return [textFieldControllerDefault, textFieldControllerDefaultPlaceholder, textFieldControllerDefaultCharMax] } func setupFullWidthTextFields() -> [MDCTextInputControllerFullWidth] { let textFieldFullWidthPlaceholder = MDCTextField() textFieldFullWidthPlaceholder.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldFullWidthPlaceholder) textFieldFullWidthPlaceholder.delegate = self textFieldFullWidthPlaceholder.clearButtonMode = .whileEditing let textFieldControllerFullWidthPlaceholder = MDCTextInputControllerFullWidth(textInput: textFieldFullWidthPlaceholder) textFieldControllerFullWidthPlaceholder.placeholderText = "This is a full width text field" let textFieldFullWidthCharMax = MDCTextField() textFieldFullWidthCharMax.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldFullWidthCharMax) textFieldFullWidthCharMax.delegate = self textFieldFullWidthCharMax.clearButtonMode = .whileEditing let textFieldControllerFullWidthCharMax = MDCTextInputControllerFullWidth(textInput: textFieldFullWidthCharMax) textFieldControllerFullWidthCharMax.characterCountMax = 50 textFieldControllerFullWidthCharMax.placeholderText = "This is a full width text field with character count and a very long placeholder" controllersWithCharacterCount.append(textFieldControllerFullWidthCharMax) return [textFieldControllerFullWidthPlaceholder, textFieldControllerFullWidthCharMax] } func setupFloatingTextFields() -> [MDCTextInputControllerDefault] { let textFieldFloating = MDCTextField() textFieldFloating.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldFloating) textFieldFloating.delegate = self textFieldFloating.clearButtonMode = .whileEditing let textFieldControllerFloating = MDCTextInputControllerDefault(textInput: textFieldFloating) textFieldControllerFloating.placeholderText = "This is a text field w/ floating placeholder" let textFieldFloatingCharMax = MDCTextField() textFieldFloatingCharMax.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldFloatingCharMax) textFieldFloatingCharMax.delegate = self textFieldFloatingCharMax.clearButtonMode = .whileEditing let textFieldControllerFloatingCharMax = MDCTextInputControllerDefault(textInput: textFieldFloatingCharMax) textFieldControllerFloatingCharMax.characterCountMax = 50 textFieldControllerFloatingCharMax.placeholderText = "This is floating with character count" controllersWithCharacterCount.append(textFieldControllerFloatingCharMax) return [textFieldControllerFloating, textFieldControllerFloatingCharMax] } func setupSpecialTextFields() -> [MDCTextInputControllerDefault] { let textFieldDisabled = MDCTextField() textFieldDisabled.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldDisabled) textFieldDisabled.delegate = self textFieldDisabled.isEnabled = false let textFieldControllerDefaultDisabled = MDCTextInputControllerDefault(textInput: textFieldDisabled) textFieldControllerDefaultDisabled.isFloatingEnabled = false textFieldControllerDefaultDisabled.placeholderText = "This is a disabled text field" let textFieldCustomFont = MDCTextField() textFieldCustomFont.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldCustomFont) textFieldCustomFont.font = UIFont.preferredFont(forTextStyle: .headline) textFieldCustomFont.delegate = self textFieldCustomFont.clearButtonMode = .whileEditing let textFieldControllerDefaultCustomFont = MDCTextInputControllerDefault(textInput: textFieldCustomFont) textFieldControllerDefaultCustomFont.inlinePlaceholderFont = UIFont.preferredFont(forTextStyle: .headline) textFieldControllerDefaultCustomFont.isFloatingEnabled = false textFieldControllerDefaultCustomFont.placeholderText = "This is a custom font" let textFieldCustomFontFloating = MDCTextField() textFieldCustomFontFloating.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldCustomFontFloating) textFieldCustomFontFloating.font = UIFont.preferredFont(forTextStyle: .headline) textFieldCustomFontFloating.delegate = self textFieldCustomFontFloating.clearButtonMode = .whileEditing textFieldCustomFontFloating.cursorColor = .orange let textFieldControllerDefaultCustomFontFloating = MDCTextInputControllerDefault(textInput: textFieldCustomFontFloating) textFieldControllerDefaultCustomFontFloating.characterCountMax = 40 textFieldControllerDefaultCustomFontFloating.placeholderText = "This is a custom font with the works" textFieldControllerDefaultCustomFontFloating.helperText = "Custom Font" textFieldControllerDefaultCustomFontFloating.activeColor = .green textFieldControllerDefaultCustomFontFloating.normalColor = .purple textFieldControllerDefaultCustomFontFloating.leadingUnderlineLabelTextColor = .cyan textFieldControllerDefaultCustomFontFloating.trailingUnderlineLabelTextColor = .magenta textFieldControllerDefaultCustomFontFloating.leadingUnderlineLabelFont = UIFont.preferredFont(forTextStyle: .headline) textFieldControllerDefaultCustomFontFloating.inlinePlaceholderFont = UIFont.preferredFont(forTextStyle: .headline) textFieldControllerDefaultCustomFontFloating.trailingUnderlineLabelFont = UIFont.preferredFont(forTextStyle: .subheadline) textFieldCustomFontFloating.clearButton.tintColor = MDCPalette.red.accent400 let bundle = Bundle(for: TextFieldKitchenSinkSwiftExample.self) let leadingViewImage = UIImage(named: "ic_search", in: bundle, compatibleWith: nil)! let textFieldLeadingView = MDCTextField() textFieldLeadingView.leadingViewMode = .always textFieldLeadingView.leadingView = UIImageView(image:leadingViewImage) textFieldLeadingView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldLeadingView) textFieldLeadingView.delegate = self textFieldLeadingView.clearButtonMode = .whileEditing let textFieldControllerDefaultLeadingView = MDCTextInputControllerDefault(textInput: textFieldLeadingView) textFieldControllerDefaultLeadingView.isFloatingEnabled = false textFieldControllerDefaultLeadingView.placeholderText = "This has a leading view" let textFieldLeadingViewFloating = MDCTextField() textFieldLeadingViewFloating.leadingViewMode = .always textFieldLeadingViewFloating.leadingView = UIImageView(image:leadingViewImage) textFieldLeadingViewFloating.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldLeadingViewFloating) textFieldLeadingViewFloating.delegate = self textFieldLeadingViewFloating.clearButtonMode = .whileEditing let textFieldControllerDefaultLeadingViewFloating = MDCTextInputControllerDefault(textInput: textFieldLeadingViewFloating) textFieldControllerDefaultLeadingViewFloating.placeholderText = "This has a leading view and floats" let trailingViewImage = UIImage(named: "ic_done", in: bundle, compatibleWith: nil)! let textFieldTrailingView = MDCTextField() textFieldTrailingView.trailingViewMode = .always textFieldTrailingView.trailingView = UIImageView(image:trailingViewImage) textFieldTrailingView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldTrailingView) textFieldTrailingView.delegate = self textFieldTrailingView.clearButtonMode = .whileEditing let textFieldControllerDefaultTrailingView = MDCTextInputControllerDefault(textInput: textFieldTrailingView) textFieldControllerDefaultTrailingView.isFloatingEnabled = false textFieldControllerDefaultTrailingView.placeholderText = "This has a trailing view" let textFieldTrailingViewFloating = MDCTextField() textFieldTrailingViewFloating.trailingViewMode = .always textFieldTrailingViewFloating.trailingView = UIImageView(image:trailingViewImage) textFieldTrailingViewFloating.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldTrailingViewFloating) textFieldTrailingViewFloating.delegate = self textFieldTrailingViewFloating.clearButtonMode = .whileEditing let textFieldControllerDefaultTrailingViewFloating = MDCTextInputControllerDefault(textInput: textFieldTrailingViewFloating) textFieldControllerDefaultTrailingViewFloating.placeholderText = "This has a trailing view and floats" let textFieldLeadingTrailingView = MDCTextField() textFieldLeadingTrailingView.leadingViewMode = .whileEditing textFieldLeadingTrailingView.leadingView = UIImageView(image: leadingViewImage) textFieldLeadingTrailingView.trailingViewMode = .unlessEditing textFieldLeadingTrailingView.trailingView = UIImageView(image:trailingViewImage) textFieldLeadingTrailingView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldLeadingTrailingView) textFieldLeadingTrailingView.delegate = self textFieldLeadingTrailingView.clearButtonMode = .whileEditing let textFieldControllerDefaultLeadingTrailingView = MDCTextInputControllerDefault(textInput: textFieldLeadingTrailingView) textFieldControllerDefaultLeadingTrailingView.isFloatingEnabled = false textFieldControllerDefaultLeadingTrailingView.placeholderText = "This has leading & trailing views and a very long placeholder that should be truncated" let textFieldLeadingTrailingViewFloating = MDCTextField() textFieldLeadingTrailingViewFloating.leadingViewMode = .always textFieldLeadingTrailingViewFloating.leadingView = UIImageView(image: leadingViewImage) textFieldLeadingTrailingViewFloating.trailingViewMode = .whileEditing textFieldLeadingTrailingViewFloating.trailingView = UIImageView(image:trailingViewImage) textFieldLeadingTrailingViewFloating.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldLeadingTrailingViewFloating) textFieldLeadingTrailingViewFloating.delegate = self textFieldLeadingTrailingViewFloating.clearButtonMode = .whileEditing let textFieldControllerDefaultLeadingTrailingViewFloating = MDCTextInputControllerDefault(textInput: textFieldLeadingTrailingViewFloating) textFieldControllerDefaultLeadingTrailingViewFloating.placeholderText = "This has leading & trailing views and floats and a very long placeholder that should be truncated" unstyledTextField.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(unstyledTextField) unstyledTextField.placeholder = "This is an unstyled text field (no controller)" unstyledTextField.leadingUnderlineLabel.text = "Leading label" unstyledTextField.trailingUnderlineLabel.text = "Trailing label" unstyledTextField.delegate = self unstyledTextField.clearButtonMode = .whileEditing unstyledTextField.leadingView = UIImageView(image: leadingViewImage) unstyledTextField.leadingViewMode = .always unstyledTextField.trailingView = UIImageView(image: trailingViewImage) unstyledTextField.trailingViewMode = .always return [textFieldControllerDefaultDisabled, textFieldControllerDefaultCustomFont, textFieldControllerDefaultCustomFontFloating, textFieldControllerDefaultLeadingView, textFieldControllerDefaultLeadingViewFloating, textFieldControllerDefaultTrailingView, textFieldControllerDefaultTrailingViewFloating, textFieldControllerDefaultLeadingTrailingView, textFieldControllerDefaultLeadingTrailingViewFloating] } // MARK: - Multi-line func setupAreaTextFields() -> [MDCTextInputControllerOutlinedTextArea] { let textFieldArea = MDCMultilineTextField() textFieldArea.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(textFieldArea) textFieldArea.textView?.delegate = self let textFieldControllerArea = MDCTextInputControllerOutlinedTextArea(textInput: textFieldArea) textFieldControllerArea.placeholderText = "This is a text area" return [textFieldControllerArea] } func setupDefaultMultilineTextFields() -> [MDCTextInputControllerDefault] { let multilineTextFieldDefault = MDCMultilineTextField() multilineTextFieldDefault.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(multilineTextFieldDefault) multilineTextFieldDefault.textView?.delegate = self let multilineTextFieldControllerDefault = MDCTextInputControllerDefault(textInput: multilineTextFieldDefault) multilineTextFieldControllerDefault.isFloatingEnabled = false let multilineTextFieldDefaultPlaceholder = MDCMultilineTextField() multilineTextFieldDefaultPlaceholder.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(multilineTextFieldDefaultPlaceholder) multilineTextFieldDefaultPlaceholder.textView?.delegate = self let multilineTextFieldControllerDefaultPlaceholder = MDCTextInputControllerDefault(textInput: multilineTextFieldDefaultPlaceholder) multilineTextFieldControllerDefaultPlaceholder.isFloatingEnabled = false multilineTextFieldControllerDefaultPlaceholder.placeholderText = "This is a multi-line text field with placeholder" let multilineTextFieldDefaultCharMax = MDCMultilineTextField() multilineTextFieldDefaultCharMax.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(multilineTextFieldDefaultCharMax) multilineTextFieldDefaultCharMax.textView?.delegate = self let multilineTextFieldControllerDefaultCharMax = MDCTextInputControllerDefault(textInput: multilineTextFieldDefaultCharMax) multilineTextFieldControllerDefaultCharMax.characterCountMax = 140 multilineTextFieldControllerDefaultCharMax.isFloatingEnabled = false multilineTextFieldControllerDefaultCharMax.placeholderText = "This is a multi-line text field with placeholder" controllersWithCharacterCount.append(multilineTextFieldControllerDefaultCharMax) return [multilineTextFieldControllerDefault, multilineTextFieldControllerDefaultPlaceholder, multilineTextFieldControllerDefaultCharMax] } func setupFullWidthMultilineTextFields() -> [MDCTextInputControllerFullWidth] { let multilineTextFieldFullWidth = MDCMultilineTextField() multilineTextFieldFullWidth.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(multilineTextFieldFullWidth) multilineTextFieldFullWidth.textView?.delegate = self let multilineTextFieldControllerFullWidth = MDCTextInputControllerFullWidth(textInput: multilineTextFieldFullWidth) multilineTextFieldControllerFullWidth.placeholderText = "This is a full width multi-line text field" let multilineTextFieldFullWidthCharMax = MDCMultilineTextField() multilineTextFieldFullWidthCharMax.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(multilineTextFieldFullWidthCharMax) multilineTextFieldFullWidthCharMax.textView?.delegate = self let multilineTextFieldControllerFullWidthCharMax = MDCTextInputControllerFullWidth(textInput: multilineTextFieldFullWidthCharMax) multilineTextFieldControllerFullWidthCharMax.placeholderText = "This is a full width multi-line text field with character count" controllersWithCharacterCount.append(multilineTextFieldControllerFullWidthCharMax) multilineTextFieldControllerFullWidthCharMax.characterCountMax = 140 return [multilineTextFieldControllerFullWidth, multilineTextFieldControllerFullWidthCharMax] } func setupFloatingMultilineTextFields() -> [MDCTextInputControllerDefault] { let multilineTextFieldFloating = MDCMultilineTextField() multilineTextFieldFloating.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(multilineTextFieldFloating) multilineTextFieldFloating.textView?.delegate = self let multilineTextFieldControllerFloating = MDCTextInputControllerDefault(textInput: multilineTextFieldFloating) multilineTextFieldControllerFloating.placeholderText = "This is a multi-line text field with a floating placeholder" let multilineTextFieldFloatingCharMax = MDCMultilineTextField() multilineTextFieldFloatingCharMax.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(multilineTextFieldFloatingCharMax) multilineTextFieldFloatingCharMax.textView?.delegate = self let multilineTextFieldControllerFloatingCharMax = MDCTextInputControllerDefault(textInput: multilineTextFieldFloatingCharMax) multilineTextFieldControllerFloatingCharMax.placeholderText = "This is a multi-line text field with a floating placeholder and character count" controllersWithCharacterCount.append(multilineTextFieldControllerFloatingCharMax) return [multilineTextFieldControllerFloating, multilineTextFieldControllerFloatingCharMax] } func setupSpecialMultilineTextFields() -> [MDCTextInputController] { let bundle = Bundle(for: TextFieldKitchenSinkSwiftExample.self) let trailingViewImage = UIImage(named: "ic_done", in: bundle, compatibleWith: nil)! let multilineTextFieldTrailingView = MDCMultilineTextField() multilineTextFieldTrailingView.trailingViewMode = .always multilineTextFieldTrailingView.trailingView = UIImageView(image:trailingViewImage) multilineTextFieldTrailingView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(multilineTextFieldTrailingView) multilineTextFieldTrailingView.textView?.delegate = self multilineTextFieldTrailingView.clearButtonMode = .whileEditing let multilineTextFieldControllerDefaultTrailingView = MDCTextInputControllerDefault(textInput: multilineTextFieldTrailingView) multilineTextFieldControllerDefaultTrailingView.isFloatingEnabled = false multilineTextFieldControllerDefaultTrailingView.placeholderText = "This has a trailing view" let multilineTextFieldCustomFont = MDCMultilineTextField() multilineTextFieldCustomFont.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(multilineTextFieldCustomFont) let multilineTextFieldControllerDefaultCustomFont = MDCTextInputControllerDefault(textInput: multilineTextFieldCustomFont) multilineTextFieldControllerDefaultCustomFont.placeholderText = "This has a custom font" multilineTextFieldCustomFont.placeholderLabel.font = UIFont.preferredFont(forTextStyle: .headline) multilineTextFieldCustomFont.font = UIFont.preferredFont(forTextStyle: .headline) scrollView.addSubview(unstyledMultilineTextField) unstyledMultilineTextField.translatesAutoresizingMaskIntoConstraints = false unstyledMultilineTextField.placeholder = "This multi-line text field has no controller (unstyled)" unstyledMultilineTextField.leadingUnderlineLabel.text = "Leading label" unstyledMultilineTextField.trailingUnderlineLabel.text = "Trailing label" unstyledMultilineTextField.textView?.delegate = self return [multilineTextFieldControllerDefaultTrailingView, multilineTextFieldControllerDefaultCustomFont] } @objc func tapDidTouch(sender: Any) { self.view.endEditing(true) } @objc func errorSwitchDidChange(errorSwitch: UISwitch) { allInputControllers.forEach { controller in if errorSwitch.isOn { controller.setErrorText("Uh oh! Try something else.", errorAccessibilityValue: nil) } else { controller.setErrorText(nil, errorAccessibilityValue: nil) } } } @objc func helperSwitchDidChange(helperSwitch: UISwitch) { allInputControllers.forEach { controller in controller.helperText = helperSwitch.isOn ? "This is helper text." : nil } } } extension TextFieldKitchenSinkSwiftExample: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } } extension TextFieldKitchenSinkSwiftExample: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { print(textView.text) } } extension TextFieldKitchenSinkSwiftExample { @objc func contentSizeCategoryDidChange(notif: Notification) { controlLabel.font = UIFont.preferredFont(forTextStyle: .headline) singleLabel.font = UIFont.preferredFont(forTextStyle: .headline) errorLabel.font = UIFont.preferredFont(forTextStyle: .subheadline) helperLabel.font = UIFont.preferredFont(forTextStyle: .subheadline) } }
apache-2.0
wrld3d/wrld-example-app
ios/Include/WrldSDK/iphoneos12.0/WrldNavWidget.framework/Headers/WRLDNavWidgetTablet.swift
4
12093
import UIKit import WrldUtils import WrldNav @objc public class WRLDNavWidgetTablet: WRLDNavWidgetBase { @IBOutlet var view: UIView! //-- Top - Current & Next Instructions --------------------------------------------------------- @IBOutlet var topPanelView: UIView! @IBOutlet weak var currentDirectionView: WRLDNavCurrentDirectionView! @IBOutlet weak var nextDirectionView: WRLDNavNextDirectionView! @IBOutlet weak var stepByStepDirectionsView: WRLDNavDirectionsView! //-- Left hand side - Directions --------------------------------------------------------------- @IBOutlet var leftPanelView: UIView! @IBOutlet weak var leftInfoViews: UIView! @IBOutlet weak var directionsStack: UIStackView! @IBOutlet weak var setupJourneyView: WRLDNavSetupJourneyView! @IBOutlet weak var leftTimeToDestinationView: WRLDNavTimeToDestinationView! @IBOutlet weak var directionsView: WRLDNavDirectionsView! //-- Bottom - Time to Destination -------------------------------------------------------------- @IBOutlet var bottomPanelView: UIView! @IBOutlet weak var bottomStack: UIStackView! @IBOutlet weak var bottomTimeToDestinationView: WRLDNavTimeToDestinationView! var m_bottomPanelHeight: CGFloat = 0 var m_isStepByStepNavListShowing: Bool = false; var _hideViews: Bool = false public override init(frame: CGRect) { super.init(frame: frame) initCommon() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initCommon() } private func initCommon() { observer.registerObserver(observerKey: navModeKeyPath) let bundle = Bundle(for: WRLDNavWidgetTablet.self) let nib = UINib(nibName: "WRLDNavWidgetTablet", bundle: bundle) let view: UIView! = nib.instantiate(withOwner: self, options: nil)[0] as! UIView view.frame = bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(view) applyShadow(view: nextDirectionView) applyShadow(view: leftInfoViews) applyShadow(view: directionsView) applyShadow(view: stepByStepDirectionsView) leftPanelView.translatesAutoresizingMaskIntoConstraints = true view.addSubview(leftPanelView) topPanelView.translatesAutoresizingMaskIntoConstraints = true view.addSubview(topPanelView) bottomPanelView.translatesAutoresizingMaskIntoConstraints = true view.addSubview(bottomPanelView) m_bottomPanelHeight = bottomPanelView.frame.size.height; } func applyShadow(view: UIView) { view.layer.shadowColor = UIColor.darkGray.cgColor view.layer.shadowRadius = 11 view.layer.shadowOffset = CGSize(width: 0, height: 0) view.layer.shadowOpacity = 0.5 view.layer.masksToBounds = false } public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let leftViewPoint = view.convert(point, to: leftPanelView) let pointInsideLeftView = (leftInfoViews.frame.contains(leftViewPoint) || directionsView.frame.contains(leftViewPoint)) let bottomViewPoint = view.convert(point, to: bottomPanelView) let pointInsideBottomView = bottomStack.frame.contains(bottomViewPoint) let topViewPoint = view.convert(point, to: topPanelView) let pointInsideTopView = (stepByStepDirectionsView.frame.contains(topViewPoint) || currentDirectionView.frame.contains(topViewPoint) || nextDirectionView.frame.contains(topViewPoint)) return (pointInsideLeftView || pointInsideBottomView || pointInsideTopView); } public func modelSet() { if let navModel = observer.navModel() { setupJourneyView .observer.setNavModel(navModel) //Left leftTimeToDestinationView .observer.setNavModel(navModel) //Left directionsView .observer.setNavModel(navModel) //Left currentDirectionView .observer.setNavModel(navModel) //Top nextDirectionView .observer.setNavModel(navModel) //Top stepByStepDirectionsView .observer.setNavModel(navModel) //Top bottomTimeToDestinationView.observer.setNavModel(navModel) //Bottom } updateNavMode(animate: false) updateBottomStack() } public override func eventReceived(key: WRLDNavEvent) { if key == .showHideListButtonClicked { setStepByStepDirectionsVisibility(visible: !m_isStepByStepNavListShowing, animate: true) } super.eventReceived(key: key) } func setLeftVisibility(visible: Bool, animate: Bool) { let frameWidth: Int = 371 let frameHeight: Int = Int(view.frame.size.height) let openFrame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight) let closedFrame = CGRect(x: -frameWidth, y: 0, width: frameWidth, height: frameHeight) let block = { self.leftPanelView.frame = (visible) ? (openFrame) : (closedFrame) self.view.setNeedsLayout() self.view.layoutIfNeeded() }; if(animate == true) { UIView.animate(withDuration: 0.3, animations:block) } else { block() } } func setDirectionsVisibility(visible: Bool, animate: Bool) { let frameWidth: Int = Int(directionsView.frame.width) let frameHeight: Int = Int(directionsView.frame.height) let yPos = Int(directionsView.frame.minY) let openFrame = CGRect(x: 0, y: yPos, width: frameWidth, height: frameHeight) let closedFrame = CGRect(x: -frameWidth, y: yPos, width: frameWidth, height: frameHeight) let block = { self.directionsView.frame = (visible) ? (openFrame) : (closedFrame) self.view.setNeedsLayout() self.view.layoutIfNeeded() }; if(animate == true) { UIView.animate(withDuration: 0.3, animations:block) } else { block() } } func setTopVisibility(visible: Bool, animate: Bool) { let frameWidth: Int = Int(view.frame.size.width) let frameHeight: Int = Int(view.frame.size.height - bottomStack.frame.size.height) let openFrame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight) let closedFrame = CGRect(x: 0, y: -(frameHeight+11), width: frameWidth, height: frameHeight) let block = { self.topPanelView.frame = (visible) ? (openFrame) : (closedFrame) self.view.setNeedsLayout() self.view.layoutIfNeeded() self.topPanelVisibleHeight = visible ? self.currentDirectionView.bounds.size.height : 0 }; if(animate == true) { UIView.animate(withDuration: 0.3, animations:block) } else { block() } } func setBottomVisibility(visible: Bool, animate: Bool) { let ht = Int(view.frame.size.height) let frameWidth: Int = Int(view.frame.size.width) let frameHeight: Int = Int(m_bottomPanelHeight) let openFrame = CGRect(x: 0, y: ht-frameHeight, width: frameWidth, height: frameHeight) let closedFrame = CGRect(x: 0, y: ht, width: frameWidth, height: frameHeight) let block = { self.bottomPanelView.frame = (visible) ? (openFrame) : (closedFrame) self.view.setNeedsLayout() self.view.layoutIfNeeded() self.bottomPanelVisibleHeight = visible ? self.bottomPanelView.bounds.size.height : 0 }; if(animate == true) { UIView.animate(withDuration: 0.3, animations:block) } else { block() } } func setStepByStepDirectionsVisibility(visible: Bool, animate: Bool) { m_isStepByStepNavListShowing = visible nextDirectionView.setShowHideListButtonState(visible) let frameWidth: Int = Int(stepByStepDirectionsView.frame.width) let frameHeight: Int = Int(stepByStepDirectionsView.frame.height) let yPos = Int(nextDirectionView.frame.maxY) let openFrame = CGRect(x: 0, y: yPos, width: frameWidth, height: frameHeight) let closedFrame = CGRect(x: 0, y: -frameHeight, width: frameWidth, height: frameHeight) let block = { self.stepByStepDirectionsView.frame = (visible) ? (openFrame) : (closedFrame) self.view.setNeedsLayout() self.view.layoutIfNeeded() self.updateTopPanel() }; if(animate == true) { UIView.animate(withDuration: 0.3, animations:block) } else { block() } } //This shows/hides the various UI elements based on the current navigation mode. override open func updateNavMode(animate: Bool) { if(_hideViews) { setLeftVisibility (visible: false, animate: animate) setTopVisibility (visible: false, animate: animate) setBottomVisibility(visible: false, animate: animate) } else if let navModel = observer.navModel() { switch(navModel.navMode) { case .notReady: setLeftVisibility (visible: true, animate: animate) setTopVisibility (visible: false, animate: animate) setBottomVisibility(visible: false, animate: animate) setDirectionsVisibility(visible: false, animate: animate) setStepByStepDirectionsVisibility(visible: false, animate: animate) break; case .ready, .readyNoTurnByTurn: setLeftVisibility (visible: true, animate: animate) setTopVisibility (visible: false, animate: animate) setBottomVisibility(visible: false, animate: animate) setDirectionsVisibility(visible: true, animate: animate) setStepByStepDirectionsVisibility(visible: false, animate: false) break; case .active: setLeftVisibility (visible: false, animate: animate) setTopVisibility (visible: true, animate: animate) setBottomVisibility(visible: true, animate: animate) setStepByStepDirectionsVisibility(visible: false, animate: false) break; } } } //Show/hide the time to destination view when the user clicks the toggle button. func updateBottomStack() { UIView.animate(withDuration: 0.3, animations: { self.view.setNeedsLayout() self.view.layoutIfNeeded() self.bottomPanelVisibleHeight = self.bottomStack.bounds.size.height self.updateTopPanel() }) } //Update top panel's size according to bottom stack size change func updateTopPanel() { if m_isStepByStepNavListShowing { let bottomHeight = m_bottomPanelHeight let frameHeight: Int = Int(self.view.frame.size.height - bottomHeight) let frameWidth: Int = Int(self.view.frame.size.width) let newFrame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight) self.topPanelView.frame = newFrame self.topPanelView.setNeedsLayout() } } @objc public override func setViewVisibility(animate: Bool, hideViews: Bool) { _hideViews = hideViews updateNavMode(animate: animate) } }
bsd-2-clause
MxABC/oclearning
swiftLearning/Pods/Kingfisher/Kingfisher/UIButton+Kingfisher.swift
12
31710
// // UIButton+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/13. // // Copyright (c) 2015 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /** * Set image to use from web for a specified state. */ public extension UIButton { /** Set an image to use for a specified state with a resource. It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state. The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState) -> RetrieveImageTask { return kf_setImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a URL. It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state. The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use. If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a resource and a placeholder image. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a URL and a placeholder image. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a resource, a placeholder image and options. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a URL, a placeholder image and options. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a resource, a placeholder image, options and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image to use for a specified state with a URL, a placeholder image, options and completion handler. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { setImage(placeholderImage, forState: state) kf_setWebURL(resource.downloadURL, forState: state) let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { receivedSize, totalSize in if let progressBlock = progressBlock { dispatch_async(dispatch_get_main_queue(), { () -> Void in progressBlock(receivedSize: receivedSize, totalSize: totalSize) }) } }, completionHandler: {[weak self] image, error, cacheType, imageURL in dispatch_async_safely_main_queue { if let sSelf = self { if imageURL == sSelf.kf_webURLForState(state) && image != nil { sSelf.setImage(image, forState: state) } completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) } } } ) return task } /** Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(Resource(downloadURL: URL), forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler) } } private var lastURLKey: Void? public extension UIButton { /** Get the image URL binded to this button for a specified state. - parameter state: The state that uses the specified image. - returns: Current URL for image. */ public func kf_webURLForState(state: UIControlState) -> NSURL? { return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL } private func kf_setWebURL(URL: NSURL, forState state: UIControlState) { kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL } private var kf_webURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() kf_setWebURLs(dictionary!) } return dictionary! } private func kf_setWebURLs(URLs: NSMutableDictionary) { objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** * Set background image to use from web for a specified state. */ public extension UIButton { /** Set the background image to use for a specified state with a resource. It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state. The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a URL. It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state. The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use. If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a resource and a placeholder image. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a URL and a placeholder image. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a resource, a placeholder image and options. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a URL, a placeholder image and options. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a resource, a placeholder image, options and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set the background image to use for a specified state with a URL, a placeholder image, options and completion handler. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set the background image to use for a specified state with a resource, a placeholder image, options progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { setBackgroundImage(placeholderImage, forState: state) kf_setBackgroundWebURL(resource.downloadURL, forState: state) let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { receivedSize, totalSize in if let progressBlock = progressBlock { dispatch_async(dispatch_get_main_queue(), { () -> Void in progressBlock(receivedSize: receivedSize, totalSize: totalSize) }) } }, completionHandler: { [weak self] image, error, cacheType, imageURL in dispatch_async_safely_main_queue { if let sSelf = self { if imageURL == sSelf.kf_backgroundWebURLForState(state) && image != nil { sSelf.setBackgroundImage(image, forState: state) } completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) } } } ) return task } /** Set the background image to use for a specified state with a URL, a placeholder image, options progress handler and completion handler. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(Resource(downloadURL: URL), forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler) } } private var lastBackgroundURLKey: Void? public extension UIButton { /** Get the background image URL binded to this button for a specified state. - parameter state: The state that uses the specified background image. - returns: Current URL for background image. */ public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? { return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL } private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) { kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL } private var kf_backgroundWebURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() kf_setBackgroundWebURLs(dictionary!) } return dictionary! } private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) { objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated public extension UIButton { @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo: instead.") public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: nil) } @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: completionHandler) } @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler) } @available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo: instead.") public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: nil) } @available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.") public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: completionHandler) } @available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.") public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler) } }
mit
MadAppGang/SmartLog
iOS/Pods/CoreStore/Sources/CSCoreStore+Migrating.swift
2
5881
// // CSCoreStore+Migrating.swift // CoreStore // // Copyright © 2016 John Rommel Estropia // // 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 CoreData // MARK: - CSCoreStore public extension CSCoreStore { /** Asynchronously adds a `CSInMemoryStore` to the `defaultStack`. Migrations are also initiated by default. ``` NSError *error; NSProgress *migrationProgress = [dataStack addInMemoryStorage:[CSInMemoryStore new] completion:^(CSSetupResult *result) { if (result.isSuccess) { // ... } } error: &error]; ``` - parameter storage: the `CSInMemoryStore` instance - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `CSSetupResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a failure `CSSetupResult` result if an error occurs asynchronously. */ public static func addInMemoryStorage(_ storage: CSInMemoryStore, completion: @escaping (CSSetupResult) -> Void) { self.defaultStack.addInMemoryStorage(storage, completion: completion) } /** Asynchronously adds a `CSSQLiteStore` to the `defaultStack`. Migrations are also initiated by default. ``` NSError *error; NSProgress *migrationProgress = [dataStack addInMemoryStorage:[[CSSQLiteStore alloc] initWithFileName:@"core_data.sqlite" configuration:@"Config1"] completion:^(CSSetupResult *result) { if (result.isSuccess) { // ... } } error: &error]; ``` - parameter storage: the `CSSQLiteStore` instance - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `CSSetupResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a failure `CSSetupResult` result if an error occurs asynchronously. Note that the `CSLocalStorage` associated to the `-[CSSetupResult storage]` may not always be the same instance as the parameter argument if a previous `CSLocalStorage` was already added at the same URL and with the same configuration. - parameter error: the `NSError` pointer that indicates the reason in case of an failure - returns: an `NSProgress` instance if a migration has started. `nil` if no migrations are required or if `error` was set. */ public static func addSQLiteStorage(_ storage: CSSQLiteStore, completion: @escaping (CSSetupResult) -> Void, error: NSErrorPointer) -> Progress? { return self.defaultStack.addSQLiteStorage(storage, completion: completion, error: error) } /** Migrates a `CSSQLiteStore` to match the `defaultStack`'s managed object model version. This method does NOT add the migrated store to the data stack. - parameter storage: the `CSSQLiteStore` instance - parameter completion: the closure to be executed on the main queue when the migration completes, either due to success or failure. The closure's `CSMigrationResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a failure `CSSetupResult` result if an error occurs asynchronously. - parameter error: the `NSError` pointer that indicates the reason in case of an failure - returns: an `NSProgress` instance if a migration has started. `nil` if no migrations are required or if `error` was set. */ @objc public static func upgradeStorageIfNeeded(_ storage: CSSQLiteStore, completion: @escaping (CSMigrationResult) -> Void, error: NSErrorPointer) -> Progress? { return self.defaultStack.upgradeStorageIfNeeded(storage, completion: completion, error: error) } /** Checks the migration steps required for the `CSSQLiteStore` to match the `defaultStack`'s managed object model version. - parameter storage: the `CSSQLiteStore` instance - parameter error: the `NSError` pointer that indicates the reason in case of an failure - returns: a `CSMigrationType` array indicating the migration steps required for the store, or an empty array if the file does not exist yet. Otherwise, `nil` is returned and the `error` argument is set if either inspection of the store failed, or if no mapping model was found/inferred. */ @objc public static func requiredMigrationsForSQLiteStore(_ storage: CSSQLiteStore, error: NSErrorPointer) -> [CSMigrationType]? { return self.defaultStack.requiredMigrationsForSQLiteStore(storage, error: error) } }
mit
spire-inc/Bond
Sources/UIKit/UIButton.swift
6
1679
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import ReactiveKit public extension UIButton { public var bnd_title: Bond<UIButton, String?> { return Bond(target: self) { $0.setTitle($1, for: .normal) } } public var bnd_tap: Signal<Void, NoError> { return bnd_controlEvents(.touchUpInside) } public var bnd_isSelected: Bond<UIButton, Bool> { return Bond(target: self) { $0.isSelected = $1 } } public var bnd_isHighlighted: Bond<UIButton, Bool> { return Bond(target: self) { $0.isHighlighted = $1 } } }
mit
tismart/TSMLib
TSMLib/TSMLibrary.swift
1
466
// // TSMLibrary.swift // TSMLibrary // // Created by Franco Castellano on 3/11/16. // Copyright © 2016 Tismart. All rights reserved. // import UIKit import Foundation import MagicalRecord public class TSMLibrary { public var networkManager = NetworkManager() public var databaseManager = DatabaseManager() public class func initializeDataBaseWithName(name name : String) { MagicalRecord.setupCoreDataStackWithStoreNamed(name) } }
mit
jverdi/URLQueue
URLQueue/AppDelegate.swift
1
2580
// // AppDelegate.swift // URLQueue // // Created by Jared Verdi on 6/9/14. // Copyright (c) 2014 Eesel LLC. 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. reloadList() } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - func reloadList() { let tabController = window!.rootViewController as! UITabBarController if let navController = tabController.selectedViewController as? UINavigationController { if let listController = navController.viewControllers[0] as? URLListViewController { listController.reload() } } } }
mit
lsirbu/BelerLibrary
Pod/Classes/Utils.swift
1
302
// // Utils.swift // MyFramework // // Created by Liliana on 26/01/16. // Copyright (c) 2016 Liliana Sirbu. All rights reserved. // import UIKit @objc public protocol CustomNavigationBarDelegate { optional func reloadTable() optional func downloadData() } class Utils: NSObject { }
mit
ahyattdev/OrangeIRC
OrangeIRC Core/Message.swift
1
7277
// This file of part of the Swift IRC client framework OrangeIRC Core. // // Copyright © 2016 Andrew Hyatt // // 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 let SPACE = " " let SLASH = "/" let COLON = ":" let EXCLAMATION_MARK = "!" let AT_SYMBOL = "@" let CARRIAGE_RETURN = "\r\n" let EMPTY = "" internal class Message { internal typealias Tag = (key: String, value: String?, vendor: String?) internal struct Prefix { internal var prefix: String internal var servername: String? internal var nickname: String? internal var user: String? internal var host: String? internal init?(_ string: String) { self.prefix = string if string.contains(EXCLAMATION_MARK) && string.contains(AT_SYMBOL) { // One of the msgto formats let exclamationMark = string.range(of: EXCLAMATION_MARK)! let atSymbol = string.range(of: AT_SYMBOL)! self.nickname = String(string[string.startIndex ..< exclamationMark.lowerBound]) self.user = String(string[exclamationMark.upperBound ..< atSymbol.lowerBound]) self.host = String(string[atSymbol.upperBound ..< string.endIndex]) } else { self.servername = prefix } } internal func toString() -> String { if let nickname = self.nickname, let user = self.user, let host = self.host { return nickname + EXCLAMATION_MARK + user + AT_SYMBOL + host } else { guard let servername = self.servername else { return "PREFIX UNKNOWN" } return servername } } } internal var message: String internal var prefix: Prefix? internal var command: String internal var target: [String] internal var parameters: String? internal var tags = [Tag]() internal init?(_ string: String) { var trimmedString = string.replacingOccurrences(of: CARRIAGE_RETURN, with: EMPTY) self.message = trimmedString guard let firstSpaceIndex = trimmedString.range(of: " ")?.lowerBound else { // The message is invalid if there isn't a single space return nil } var possibleTags = trimmedString[trimmedString.startIndex ..< firstSpaceIndex] if !possibleTags.isEmpty && possibleTags.hasPrefix("@") { // There are tags present // Remove the @ symbol possibleTags.remove(at: possibleTags.startIndex) // Seperate by ; for tag in possibleTags.components(separatedBy: ";") { /* <tag> ::= <key> ['=' <escaped value>] <key> ::= [ <vendor> '/' ] <sequence of letters, digits, hyphens (`-`)> */ guard let equalSignIndex = tag.range(of: "=")?.lowerBound else { print("Invalid tag: \(tag)") continue } var key = tag[tag.startIndex ..< equalSignIndex] var vendor: String? if key.contains("/") { // A vendor is present let slash = key.range(of: "/")!.lowerBound vendor = String(key[key.startIndex ..< slash]) key = key[key.index(after: slash) ..< key.endIndex] } var value: String? = String(tag[tag.index(after: equalSignIndex) ..< tag.endIndex]) if value!.isEmpty { value = nil } guard !key.isEmpty else { print("Unexpected empty key: \(tag)") continue } tags.append((key: String(key), value: value, vendor: vendor)) } // Remove the tags so the old code works trimmedString.removeSubrange(trimmedString.startIndex ... firstSpaceIndex) } if trimmedString[trimmedString.startIndex] == Character(COLON) { // There is a prefix, and we must handle and trim it let indexAfterColon = trimmedString.index(after: trimmedString.startIndex) let indexOfSpace = trimmedString.range(of: SPACE)!.lowerBound let prefixString = trimmedString[indexAfterColon ..< indexOfSpace] guard let prefix = Prefix(String(prefixString)) else { // Present but invalid prefix. // The whole message may be corrupt, so let's give up 🤡. return nil } self.prefix = prefix // Trim off the prefix trimmedString = String(trimmedString[trimmedString.index(after: indexOfSpace) ..< trimmedString.endIndex]) } if let colonSpaceRange = trimmedString.range(of: " :") { // There are parameters let commandAndTargetString = trimmedString[trimmedString.startIndex ..< colonSpaceRange.lowerBound] // Space seperated array var commandAndTargetComponents = commandAndTargetString.components(separatedBy: " ") self.command = commandAndTargetComponents.remove(at: 0) self.target = commandAndTargetComponents // If the command is a 3-didgit numeric, the first target must go if let cmd = Int(command) { if cmd >= 0 && cmd < 1000 && target.count > 0 { target.remove(at: 0) } } // If this check if not performed, this code could crash if the last character of trimmedString is a colon if colonSpaceRange.upperBound != trimmedString.endIndex { var parametersStart = trimmedString.index(after: colonSpaceRange.upperBound) // Fixes a bug where the first character of the parameters is cut off parametersStart = trimmedString.index(before: parametersStart) self.parameters = String(trimmedString[parametersStart ..< trimmedString.endIndex]) } } else { // There are no parameters var spaceSeperatedArray = trimmedString.components(separatedBy: " ") self.command = spaceSeperatedArray.remove(at: 0) self.target = spaceSeperatedArray } } }
apache-2.0
schurik/AppVentory
AppVentory/ApiClient.swift
1
200
// // ApiClient.swift // AppVentory // // Created by Alexander Buss on 09.02.16. // Copyright © 2016 Alexander Buss. All rights reserved. // import Foundation internal struct ApiClient { }
mit
bugnitude/SamplePDFViewer
SamplePDFViewer/CGSize+Extension.swift
1
918
import UIKit extension CGSize { enum RoundType { case none case down case up case off } func aspectFitSize(within size: CGSize, roundType: RoundType = .none) -> CGSize { if self.width == 0.0 || self.height == 0.0 { return CGSize.zero } let widthRatio = size.width / self.width let heightRatio = size.height / self.height let aspectFitRatio = min(widthRatio, heightRatio) var aspectFitSize = CGSize(width: self.width * aspectFitRatio, height: self.height * aspectFitRatio) switch roundType { case .down: aspectFitSize = CGSize(width: floor(aspectFitSize.width), height: floor(aspectFitSize.height)) case .up: aspectFitSize = CGSize(width: ceil(aspectFitSize.width), height: ceil(aspectFitSize.height)) case .off: aspectFitSize = CGSize(width: round(aspectFitSize.width), height: round(aspectFitSize.height)) default: break } return aspectFitSize } }
mit
radvansky-tomas/SwiftBLEPeripheral
BLEPeriferal/BLEPeriferalServer.swift
1
6069
// // BLEPeriferalServer.swift // BLEPeriferal // // Created by Tomas Radvansky on 20/10/2015. // Copyright © 2015 Radvansky Solutions. All rights reserved. // import UIKit import CoreBluetooth protocol BLEPeriferalServerDelegate { func periferalServer(periferal:BLEPeriferalServer, centralDidSubscribe:CBCentral) func periferalServer(periferal:BLEPeriferalServer, centralDidUnsubscribe:CBCentral) } class BLEPeriferalServer: NSObject,CBPeripheralManagerDelegate { //MARK:-Public var serviceName:String? var serviceUUID:CBUUID? var characteristicUUID:CBUUID? var delegate:BLEPeriferalServerDelegate? //MARK:-Private var peripheral:CBPeripheralManager? var characteristic:CBMutableCharacteristic? var serviceRequiresRegistration:Bool? var service:CBMutableService? var pendingData:NSData? init(withDelegate delegate:BLEPeriferalServerDelegate) { super.init() self.peripheral = CBPeripheralManager(delegate: self, queue: nil) self.delegate = delegate } class func isBluetoothSupported()->Bool { if (NSClassFromString("CBPeripheralManager")==nil) { return false } return true } func sendToSubscribers(data:NSData) { if (self.peripheral?.state != CBPeripheralManagerState.PoweredOn) { print("sendToSubscribers: peripheral not ready for sending state: %d", self.peripheral!.state.rawValue) return } if let success:Bool = (self.peripheral?.updateValue(data, forCharacteristic: self.characteristic!, onSubscribedCentrals: nil))! { if !success { print("Failed to send data, buffering data for retry once ready.") self.pendingData = data return } } } func applicationDidEnterBackground() { } func applicationWillEnterForeground() { print("applicationWillEnterForeground") } func startAdvertising() { if self.peripheral?.isAdvertising == true { self.peripheral?.stopAdvertising() } let advertisement:[String:AnyObject]? = [CBAdvertisementDataServiceUUIDsKey:[self.serviceUUID!], CBAdvertisementDataLocalNameKey:self.serviceName!] self.peripheral?.startAdvertising(advertisement) } func stopAdvertising() { self.peripheral?.stopAdvertising() } func isAdvertising()->Bool? { return self.peripheral?.isAdvertising } func disableService() { self.peripheral?.removeService(self.service!) self.service = nil self.stopAdvertising() } func enableService() { if (self.service != nil) { self.peripheral?.removeService(self.service!) } self.service = CBMutableService(type: self.serviceUUID!, primary: true) self.characteristic = CBMutableCharacteristic (type: self.characteristicUUID!, properties: CBCharacteristicProperties.Notify, value: nil, permissions: CBAttributePermissions.Readable) var characteristics = [CBMutableCharacteristic]() characteristics.append( self.characteristic!) self.service?.characteristics = characteristics self.peripheral?.addService(self.service!) let runAfter : dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))) dispatch_after(runAfter, dispatch_get_main_queue()) { () -> Void in self.startAdvertising() } } //MARK:-CBPeripheralManagerDelegate func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) { //self.startAdvertising() } func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { switch (peripheral.state) { case CBPeripheralManagerState.PoweredOn: print("peripheralStateChange: Powered On") // As soon as the peripheral/bluetooth is turned on, start initializing // the service. self.enableService() case CBPeripheralManagerState.PoweredOff: print("peripheralStateChange: Powered Off") self.disableService() self.serviceRequiresRegistration = true case CBPeripheralManagerState.Resetting: print("peripheralStateChange: Resetting"); self.serviceRequiresRegistration = true case CBPeripheralManagerState.Unauthorized: print("peripheralStateChange: Deauthorized"); self.disableService() self.serviceRequiresRegistration = true case CBPeripheralManagerState.Unsupported: print("peripheralStateChange: Unsupported"); self.serviceRequiresRegistration = true // TODO: Give user feedback that Bluetooth is not supported. case CBPeripheralManagerState.Unknown: print("peripheralStateChange: Unknown") } } func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) { self.delegate?.periferalServer(self, centralDidSubscribe: central) } func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic) { self.delegate?.periferalServer(self, centralDidUnsubscribe: central) } func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) { print(error?.localizedDescription) } func peripheralManagerIsReadyToUpdateSubscribers(peripheral: CBPeripheralManager) { print("isReadyToUpdateSubscribers") if let data:NSData = self.pendingData { self.sendToSubscribers(data) } } }
mit
igormatyushkin014/Baggage
Demo/BaggageDemo/BaggageDemo/Flows/Main/MainViewController/MainViewController.swift
1
2290
// // MainViewController.swift // BaggageDemo // // Created by Igor Matyushkin on 25.01.16. // Copyright © 2016 Igor Matyushkin. All rights reserved. // import UIKit class MainViewController: UIViewController, UITextFieldDelegate { // MARK: Class variables & properties // MARK: Class methods // MARK: Initializers // MARK: Deinitializer deinit { } // MARK: Outlets @IBOutlet private weak var sourceTextField: UITextField! @IBOutlet private weak var resultTextField: UITextField! @IBOutlet private weak var copyAndPasteButton: UIButton! // MARK: Variables & properties override var prefersStatusBarHidden: Bool { get { return true } } // MARK: Public methods override func viewDidLoad() { super.viewDidLoad() // Initialize source text field sourceTextField.delegate = self // Initialize copy and paste button copyAndPasteButton.isEnabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Private methods // MARK: Actions @IBAction func copyAndPasteButtonTapped(sender: AnyObject) { // Copy source text to clipboard sourceTextField.bg.copy() // Paste source text to result text field resultTextField.bg.paste() } // MARK: Protocol methods func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == sourceTextField { let currentText = textField.text ?? "" let textAfterReplacement = (currentText as NSString).replacingCharacters(in: range, with: string) let textAfterReplacementIsEmpty = textAfterReplacement.isEmpty let shouldEnableCopyAndPasteButton = !textAfterReplacementIsEmpty copyAndPasteButton.isEnabled = shouldEnableCopyAndPasteButton return true } else { return true } } }
mit
Vanlol/MyYDW
SwiftCocoa/Resource/Mine/Controller/XYMainViewController.swift
1
5912
// // XYMainViewController.swift // SwiftCocoa // // Created by 祁小峰 on 2017/9/13. // Copyright © 2017年 admin. All rights reserved. // import UIKit class XYMainViewController: BaseViewController { @IBOutlet weak var contentScrollView: UIScrollView! static let dynamicTVTag = 1 static let photoTVTag = 2 let floatViHeight:CGFloat = 38 let headerViHeight:CGFloat = 400 fileprivate lazy var headerView:XYHeaderView = { let vi = UINib(nibName: "XYHeaderView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! XYHeaderView vi.frame = CGRect(x: 0, y: 0, width: C.SCREEN_WIDTH, height: 400) return vi }() override func viewDidLoad() { super.viewDidLoad() initNav() addSubViews() } /** * 初始化nav */ fileprivate func initNav() { navigationController?.navigationBar.isTranslucent = false setUpSystemNav(title: "个人中心", hexColorBg: 0xffffff) navigationItem.leftBarButtonItem = UIBarButtonItem.backItemWithImage(image: "4_nav_return_icon", target: self, action: #selector(backButtonClick)) } //MARK: 返回按钮点击事件 func backButtonClick() { navigationController?.popViewController(animated: true) } //MARK: 添加子试图 fileprivate func addSubViews() { view.addSubview(headerView) contentScrollView.contentOffset = CGPoint.zero contentScrollView.contentSize = CGSize(width: 2*C.SCREEN_WIDTH, height: 0) let dynamicVC = UIStoryboard(name: "Mine", bundle: nil).instantiateViewController(withIdentifier: "XYDynamicViewControllerID") as! XYDynamicViewController addChildViewController(dynamicVC) dynamicVC.tableView.tag = XYMainViewController.dynamicTVTag dynamicVC.tableView.contentInset = UIEdgeInsets(top: headerViHeight - 64, left: 0, bottom: 64, right: 0) dynamicVC.tableView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil) let photoVC = UIStoryboard(name: "Mine", bundle: nil).instantiateViewController(withIdentifier: "XYPhotoViewControllerID") as! XYPhotoViewController addChildViewController(photoVC) photoVC.tableView.tag = XYMainViewController.photoTVTag photoVC.tableView.contentInset = UIEdgeInsets(top: headerViHeight - 64, left: 0, bottom: 64, right: 0) photoVC.tableView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil) contentScrollView.addSubview(dynamicVC.tableView) contentScrollView.addSubview(photoVC.tableView) } //MARK: 重新布局子视图 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() Print.dlog("viewDidLayoutSubviews") for subVC in childViewControllers { if subVC.isKind(of: XYDynamicViewController.classForCoder()) { subVC.view.frame = CGRect(x: 0, y: 0, width: C.SCREEN_WIDTH, height: C.SCREEN_HEIGHT) }else if subVC.isKind(of: XYPhotoViewController.classForCoder()) { subVC.view.frame = CGRect(x: C.SCREEN_WIDTH, y: 0, width: C.SCREEN_WIDTH, height: C.SCREEN_HEIGHT) } } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let tabVi = object as! UITableView /* 没什么卵用的判断 */ if (contentScrollView.contentOffset.x == 0 && tabVi.tag == XYMainViewController.photoTVTag) || (contentScrollView.contentOffset.x == C.SCREEN_WIDTH && tabVi.tag == XYMainViewController.dynamicTVTag) { return } Print.dlog(tabVi.contentOffset.y)//-336 if tabVi.contentOffset.y >= -floatViHeight { headerView.frame.origin.y = -headerViHeight + floatViHeight + 64 if tabVi.tag == XYMainViewController.dynamicTVTag { let anotherTabVi = view.viewWithTag(XYMainViewController.photoTVTag) as! UITableView if anotherTabVi.contentOffset.y < -floatViHeight { anotherTabVi.contentOffset = CGPoint(x: 0, y: -floatViHeight) } }else{ let anotherTabVi = view.viewWithTag(XYMainViewController.dynamicTVTag) as! UITableView if anotherTabVi.contentOffset.y < -floatViHeight { anotherTabVi.contentOffset = CGPoint(x: 0, y: -floatViHeight) } } }else{ headerView.frame.origin.y = -headerViHeight + 64 - tabVi.contentOffset.y if (tabVi.contentOffset.y < -floatViHeight && tabVi.contentOffset.y >= -headerViHeight) { let tag = tabVi.tag == XYMainViewController.dynamicTVTag ? XYMainViewController.photoTVTag : XYMainViewController.dynamicTVTag let anotherTabVi = view.viewWithTag(tag) as! UITableView anotherTabVi.contentOffset = tabVi.contentOffset } } } /* * 注销观察者模式 */ deinit { for subVC in childViewControllers { if subVC.isKind(of: XYDynamicViewController.classForCoder()) { (subVC as! XYDynamicViewController).tableView.removeObserver(self, forKeyPath: "contentOffset", context: nil) }else if subVC.isKind(of: XYPhotoViewController.classForCoder()) { (subVC as! XYPhotoViewController).tableView.removeObserver(self, forKeyPath: "contentOffset", context: nil) } } } } extension XYMainViewController:UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.isKind(of: UITableView.classForCoder()) { return } } }
apache-2.0
IvanVorobei/RequestPermission
Example/SPPermission/SPPermission/Frameworks/SparrowKit/Animation/SPAnimation.swift
1
2533
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by) // // 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 enum SPAnimation { static func animate(_ duration: TimeInterval, animations: (() -> Void)!, delay: TimeInterval = 0, options: UIView.AnimationOptions = [], withComplection completion: (() -> Void)! = {}) { UIView.animate( withDuration: duration, delay: delay, options: options, animations: { animations() }, completion: { finished in completion() }) } static func animateWithRepeatition(_ duration: TimeInterval, animations: (() -> Void)!, delay: TimeInterval = 0, options: UIView.AnimationOptions = [], withComplection completion: (() -> Void)! = {}) { var optionsWithRepeatition = options optionsWithRepeatition.insert([.autoreverse, .repeat, .allowUserInteraction]) self.animate( duration, animations: { animations() }, delay: delay, options: optionsWithRepeatition, withComplection: { completion() }) } }
mit
samburnstone/Mealie
Mealie/AppDelegate.swift
1
2148
// // AppDelegate.swift // Mealie // // Created by Sam Burnstone on 12/03/2016. // Copyright © 2016 Sam Burnstone. 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:. } }
gpl-3.0
kennethcc2005/Sharity
Sharity/HomeTableViewCell.swift
1
780
// // HomeTableViewCell.swift // Sharity // // Created by Zoesh on 10/24/15. // Copyright © 2015 Zoesh. All rights reserved. // import UIKit protocol HomeCellDelegate { func didTappedBuyButton () -> Void } class HomeTableViewCell: UITableViewCell { var delegate: HomeCellDelegate? @IBOutlet weak var productImage: UIImageView! @IBOutlet weak var label: UILabel! @IBAction func buyAction(sender: AnyObject) { delegate?.didTappedBuyButton() } 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 } }
mit
siyana/SwiftMaps
PhotoMaps/PhotoMaps/CoreDataManager.swift
1
4087
// // CoreDataManager.swift // PhotoMaps // // Created by Siyana Slavova on 3/24/15. // Copyright (c) 2015 Siyana Slavova. All rights reserved. // import Foundation import CoreData class CoreDataManager: NSObject { // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "PM.PhotoMaps" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("PhotoMaps", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PhotoMaps.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
belatrix/iOSAllStars
AllStarsV2/AllStarsV2/iPhone/Classes/Login/ChangePasswordViewController.swift
1
5850
// // ChangePasswordViewController.swift // AllStarsV2 // // Created by Kenyi Rodriguez Vergara on 25/07/17. // Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved. // import UIKit class ChangePasswordViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var constraintBottomViewLogo : NSLayoutConstraint! @IBOutlet weak var constraintTopViewLogo : NSLayoutConstraint! @IBOutlet weak var constraintCenterForm : NSLayoutConstraint! @IBOutlet weak var viewLogo : UIView! @IBOutlet weak var viewFormUser : UIView! @IBOutlet weak var txtCurrentPassword : UITextField! @IBOutlet weak var txtNewPassword : UITextField! @IBOutlet weak var txtRepeatNewPassword : UITextField! @IBOutlet weak var activityPassword : UIActivityIndicatorView! var initialValueConstraintCenterForm : CGFloat = 0 var objSession : SessionBE! //MARK: - UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == self.txtCurrentPassword { self.txtNewPassword.becomeFirstResponder() }else if textField == self.txtNewPassword { self.txtRepeatNewPassword.becomeFirstResponder() }else if textField == self.txtRepeatNewPassword { self.clickBtnChangePassword(nil) } return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{ let result = string.replace(" ", withString: "") return result.count == string.count } //MARK: - WebService func changePassword(){ self.starLoading() UserBC.resetUserPassword(withSession: self.objSession, currentPassword: self.txtCurrentPassword.text, newPassword: self.txtNewPassword.text, repeatNewPassword: self.txtRepeatNewPassword.text, withSuccessful: { (objSession) in self.objSession = objSession self.stopLoading() if self.objSession.session_base_profile_complete.boolValue == false{ self.performSegue(withIdentifier: "CompleteProfileViewController", sender: nil) }else{ UserBC.saveSession(self.objSession) self.performSegue(withIdentifier: "RevealViewController", sender: nil) } }) { (title, message) in self.stopLoading() CDMUserAlerts.showSimpleAlert(title: title, withMessage: message, withAcceptButton: "ok".localized, withController: self, withCompletion: nil) } } //MARK: - func starLoading(){ self.view.isUserInteractionEnabled = false self.activityPassword.startAnimating() } func stopLoading(){ self.view.isUserInteractionEnabled = true self.activityPassword.stopAnimating() } //MARK: - IBAction methods @IBAction func clickBtnChangePassword(_ sender: Any?) { self.tapToCloseKeyboard(nil) self.changePassword() } @IBAction func tapToCloseKeyboard(_ sender: Any?) { self.view.endEditing(true) } //MARK: - Keyboard Notifications @objc func keyboardWillShown(notification : NSNotification) -> Void{ let kbSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let finalForm = self.viewFormUser.frame.size.height / 2 + self.initialValueConstraintCenterForm let sizeScreen = UIScreen.main.bounds.size.height / 2 let availableArea = sizeScreen - (kbSize?.height)! if finalForm > availableArea { UIView.animate(withDuration: 0.35, animations: { self.constraintCenterForm.constant = self.initialValueConstraintCenterForm - (finalForm - availableArea) - 2 self.view.layoutIfNeeded() }) } } @objc func keyboardWillBeHidden(notification : NSNotification) -> Void { UIView.animate(withDuration: 0.35, animations: { self.constraintCenterForm.constant = self.initialValueConstraintCenterForm self.view.layoutIfNeeded() }) } //MARK: - override func viewDidLoad() { super.viewDidLoad() self.initialValueConstraintCenterForm = self.constraintCenterForm.constant } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShown(notification:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeHidden(notification:)), name: .UIKeyboardWillHide, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } 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. } */ }
apache-2.0
skedgo/tripkit-ios
Sources/TripKit/server/TKRealTime.swift
1
933
// // TKRealTime.swift // TripKit // // Created by Adrian Schönig on 25.06.18. // Copyright © 2018 SkedGo Pty Ltd. All rights reserved. // import Foundation public enum TKRealTimeUpdateProgress<E> { case idle case updating case updated(E) } /// :nodoc: @objc public protocol TKRealTimeUpdatable { /// Whether the particular objects should be updated at all @objc var wantsRealTimeUpdates: Bool { get } } extension TKRealTimeUpdatable { func wantsRealTimeUpdates(forStart start: Date, end: Date, forPreplanning: Bool) -> Bool { if forPreplanning { return start.timeIntervalSinceNow < 12 * 60 * 60 // half a day in advance && end.timeIntervalSinceNow > -60 * 60 // an hour ago } else { return start.timeIntervalSinceNow < 45 * 60 // start isn't more than 45 minutes from now && end.timeIntervalSinceNow > -30 * 60 // end isn't more than 30 minutes ago } } }
apache-2.0
appplemac/ios9-examples
iOS9Sampler/Common/FilterHelper.swift
6
2252
// // FilterHelper.swift // iOS9Sampler // // Created by Shuichi Tsutsumi on 2015/08/21. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import UIKit class FilterHelper: NSObject { class func filterNamesFor_iOS9(category: String?) -> [String]! { return FilterHelper.filterNamesFor_iOS9(category, exceptCategories: nil) } class func filterNamesFor_iOS9(category: String?, exceptCategories: [String]?) -> [String]! { var filterNames:[String] = [] let all = CIFilter.filterNamesInCategory(category) for aFilterName in all { let attributes = CIFilter(name: aFilterName)!.attributes if exceptCategories?.count > 0 { var needExcept = false let categories = attributes[kCIAttributeFilterCategories] as! [String] for aCategory in categories { if (exceptCategories?.contains(aCategory) == true) { needExcept = true break } } if needExcept { continue } } let availability = attributes[kCIAttributeFilterAvailable_iOS] // print("filtername:\(aFilterName), availability:\(availability)") if availability != nil && availability as! String == "9" { filterNames.append(aFilterName) } } return filterNames } } extension CIFilter { func categoriesStringForFilter() -> String { var categories = self.attributes[kCIAttributeFilterCategories]!.description categories = categories.stringByReplacingOccurrencesOfString("(", withString: "") categories = categories.stringByReplacingOccurrencesOfString(")", withString: "") categories = categories.stringByReplacingOccurrencesOfString("\n", withString: "") categories = categories.stringByReplacingOccurrencesOfString(" ", withString: "") categories = categories.stringByReplacingOccurrencesOfString("CICategory", withString: "") return categories } }
mit
kinetic-fit/sensors-swift-trainers
Sources/SwiftySensorsTrainers/WahooTrainerSerializer.swift
1
5484
// // WahooTrainerSerializer.swift // SwiftySensorsTrainers // // https://github.com/kinetic-fit/sensors-swift-trainers // // Copyright © 2017 Kinetic. All rights reserved. // import Foundation import SwiftySensors /** Message Serializer / Deserializer for Wahoo Trainers. Work In Progress! */ open class WahooTrainerSerializer { open class Response { fileprivate(set) var operationCode: OperationCode! } public enum OperationCode: UInt8 { case unlock = 32 case setResistanceMode = 64 case setStandardMode = 65 case setErgMode = 66 case setSimMode = 67 case setSimCRR = 68 case setSimWindResistance = 69 case setSimGrade = 70 case setSimWindSpeed = 71 case setWheelCircumference = 72 } public static func unlockCommand() -> [UInt8] { return [ WahooTrainerSerializer.OperationCode.unlock.rawValue, 0xee, // unlock code 0xfc // unlock code ] } public static func setResistanceMode(_ resistance: Float) -> [UInt8] { let norm = UInt16((1 - resistance) * 16383) return [ WahooTrainerSerializer.OperationCode.setResistanceMode.rawValue, UInt8(norm & 0xFF), UInt8(norm >> 8 & 0xFF) ] } public static func setStandardMode(level: UInt8) -> [UInt8] { return [ WahooTrainerSerializer.OperationCode.setStandardMode.rawValue, level ] } public static func seErgMode(_ watts: UInt16) -> [UInt8] { return [ WahooTrainerSerializer.OperationCode.setErgMode.rawValue, UInt8(watts & 0xFF), UInt8(watts >> 8 & 0xFF) ] // response: 0x01 0x42 0x01 0x00 watts1 watts2 } public static func seSimMode(weight: Float, rollingResistanceCoefficient: Float, windResistanceCoefficient: Float) -> [UInt8] { // Weight units are Kg // TODO: Throw Error if weight, rrc or wrc are not within "sane" values let weightN = UInt16(max(0, min(655.35, weight)) * 100) let rrcN = UInt16(max(0, min(65.535, rollingResistanceCoefficient)) * 1000) let wrcN = UInt16(max(0, min(65.535, windResistanceCoefficient)) * 1000) return [ WahooTrainerSerializer.OperationCode.setSimMode.rawValue, UInt8(weightN & 0xFF), UInt8(weightN >> 8 & 0xFF), UInt8(rrcN & 0xFF), UInt8(rrcN >> 8 & 0xFF), UInt8(wrcN & 0xFF), UInt8(wrcN >> 8 & 0xFF) ] } public static func setSimCRR(_ rollingResistanceCoefficient: Float) -> [UInt8] { // TODO: Throw Error if rrc is not within "sane" value range let rrcN = UInt16(max(0, min(65.535, rollingResistanceCoefficient)) * 1000) return [ WahooTrainerSerializer.OperationCode.setSimCRR.rawValue, UInt8(rrcN & 0xFF), UInt8(rrcN >> 8 & 0xFF) ] } public static func setSimWindResistance(_ windResistanceCoefficient: Float) -> [UInt8] { // TODO: Throw Error if wrc is not within "sane" value range let wrcN = UInt16(max(0, min(65.535, windResistanceCoefficient)) * 1000) return [ WahooTrainerSerializer.OperationCode.setSimWindResistance.rawValue, UInt8(wrcN & 0xFF), UInt8(wrcN >> 8 & 0xFF) ] } public static func setSimGrade(_ grade: Float) -> [UInt8] { // TODO: Throw Error if grade is not between -1 and 1 let norm = UInt16((min(1, max(-1, grade)) + 1.0) * 65535 / 2.0) return [ WahooTrainerSerializer.OperationCode.setSimGrade.rawValue, UInt8(norm & 0xFF), UInt8(norm >> 8 & 0xFF) ] } public static func setSimWindSpeed(_ metersPerSecond: Float) -> [UInt8] { let norm = UInt16((max(-32.767, min(32.767, metersPerSecond)) + 32.767) * 1000) return [ WahooTrainerSerializer.OperationCode.setSimWindSpeed.rawValue, UInt8(norm & 0xFF), UInt8(norm >> 8 & 0xFF) ] } public static func setWheelCircumference(_ millimeters: Float) -> [UInt8] { let norm = UInt16(max(0, millimeters) * 10) return [ WahooTrainerSerializer.OperationCode.setWheelCircumference.rawValue, UInt8(norm & 0xFF), UInt8(norm >> 8 & 0xFF) ] } public static func readReponse(_ data: Data) -> Response? { let bytes = data.map { $0 } if bytes.count > 1 { let result = bytes[0] // 01 = success let opCodeRaw = bytes[1] if let opCode = WahooTrainerSerializer.OperationCode(rawValue: opCodeRaw) { let response: Response switch opCode { default: response = Response() } response.operationCode = opCode return response } else { SensorManager.logSensorMessage?("Unrecognized Operation Code: \(opCodeRaw)") } if result == 1 { SensorManager.logSensorMessage?("Success for operation: \(opCodeRaw)") } } return nil } }
mit
delannoyk/ConfigurationKit
sources/ConfigurationKitTests/tests/parser/PListParser_TestCase.swift
1
1705
// // PListParser_TestCase.swift // ConfigurationKit // // Created by Kevin DELANNOY on 25/07/15. // Copyright (c) 2015 Kevin Delannoy. All rights reserved. // import XCTest @testable import ConfigurationKit class PListParser_TestCase: XCTestCase { //Test parsing func testSuccessParsing() { let URL = Bundle(for: type(of: self)).url(forResource: "SampleConfig", withExtension: "plist") let data = try! Data(contentsOf: URL!) let parser = PListParser() let result: [String: String] do { result = try parser.parse(data) } catch { XCTFail() return } XCTAssert(result["Foo1"] == "Bar1", "The parsing result isn't correct") XCTAssert(result["Foo2"] == "Bar2", "The parsing result isn't correct") XCTAssert(result["Foo3"] == "Bar3", "The parsing result isn't correct") XCTAssert(result["Foo4"] == "Bar4", "The parsing result isn't correct") XCTAssert(result["Foo5"] == "Bar5", "The parsing result isn't correct") XCTAssert(result["Foo6"] == "Bar6", "The parsing result isn't correct") XCTAssert(result["Foo7"] == "Bar7", "The parsing result isn't correct") XCTAssert(result["Foo8"] == "Bar8", "The parsing result isn't correct") XCTAssert(result["Foo9"] == "Bar9", "The parsing result isn't correct") } func testFailureParsing() { let URL = Bundle(for: type(of: self)).url(forResource: "SampleConfig", withExtension: "json") let data = try! Data(contentsOf: URL!) let parser = PListParser() do { let _ = try parser.parse(data) XCTFail() } catch {} } }
gpl-2.0
Bunn/firefox-ios
Extensions/Today/TodayViewController.swift
1
10766
/* 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 import NotificationCenter import Shared import SnapKit import XCGLogger private let log = Logger.browserLogger struct TodayStrings { static let NewPrivateTabButtonLabel = NSLocalizedString("TodayWidget.NewPrivateTabButtonLabel", tableName: "Today", value: "New Private Tab", comment: "New Private Tab button label") static let NewTabButtonLabel = NSLocalizedString("TodayWidget.NewTabButtonLabel", tableName: "Today", value: "New Tab", comment: "New Tab button label") static let GoToCopiedLinkLabel = NSLocalizedString("TodayWidget.GoToCopiedLinkLabel", tableName: "Today", value: "Go to copied link", comment: "Go to link on clipboard") } private struct TodayUX { static let privateBrowsingColor = UIColor(rgb: 0xcf68ff) static let backgroundHightlightColor = UIColor(white: 216.0/255.0, alpha: 44.0/255.0) static let linkTextSize: CGFloat = 10.0 static let labelTextSize: CGFloat = 14.0 static let imageButtonTextSize: CGFloat = 14.0 static let copyLinkImageWidth: CGFloat = 23 static let margin: CGFloat = 8 static let buttonsHorizontalMarginPercentage: CGFloat = 0.1 } @objc (TodayViewController) class TodayViewController: UIViewController, NCWidgetProviding { var copiedURL: URL? fileprivate lazy var newTabButton: ImageButtonWithLabel = { let imageButton = ImageButtonWithLabel() imageButton.addTarget(self, action: #selector(onPressNewTab), forControlEvents: .touchUpInside) imageButton.label.text = TodayStrings.NewTabButtonLabel let button = imageButton.button button.setImage(UIImage(named: "new_tab_button_normal")?.withRenderingMode(.alwaysTemplate), for: .normal) button.setImage(UIImage(named: "new_tab_button_highlight")?.withRenderingMode(.alwaysTemplate), for: .highlighted) let label = imageButton.label label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize) imageButton.sizeToFit() return imageButton }() fileprivate lazy var newPrivateTabButton: ImageButtonWithLabel = { let imageButton = ImageButtonWithLabel() imageButton.addTarget(self, action: #selector(onPressNewPrivateTab), forControlEvents: .touchUpInside) imageButton.label.text = TodayStrings.NewPrivateTabButtonLabel let button = imageButton.button button.setImage(UIImage(named: "new_private_tab_button_normal"), for: .normal) button.setImage(UIImage(named: "new_private_tab_button_highlight"), for: .highlighted) let label = imageButton.label label.tintColor = TodayUX.privateBrowsingColor label.textColor = TodayUX.privateBrowsingColor label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize) imageButton.sizeToFit() return imageButton }() fileprivate lazy var openCopiedLinkButton: ButtonWithSublabel = { let button = ButtonWithSublabel() button.setTitle(TodayStrings.GoToCopiedLinkLabel, for: .normal) button.addTarget(self, action: #selector(onPressOpenClibpoard), for: .touchUpInside) // We need to set the background image/color for .Normal, so the whole button is tappable. button.setBackgroundColor(UIColor.clear, forState: .normal) button.setBackgroundColor(TodayUX.backgroundHightlightColor, forState: .highlighted) button.setImage(UIImage(named: "copy_link_icon")?.withRenderingMode(.alwaysTemplate), for: .normal) button.label.font = UIFont.systemFont(ofSize: TodayUX.labelTextSize) button.subtitleLabel.font = UIFont.systemFont(ofSize: TodayUX.linkTextSize) return button }() fileprivate lazy var widgetStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.alignment = .fill stackView.spacing = TodayUX.margin / 2 stackView.distribution = UIStackView.Distribution.fill stackView.layoutMargins = UIEdgeInsets(top: TodayUX.margin, left: TodayUX.margin, bottom: TodayUX.margin, right: TodayUX.margin) stackView.isLayoutMarginsRelativeArrangement = true return stackView }() fileprivate lazy var buttonStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.alignment = .fill stackView.spacing = 0 stackView.distribution = UIStackView.Distribution.fillEqually return stackView }() fileprivate var scheme: String { guard let string = Bundle.main.object(forInfoDictionaryKey: "MozInternalURLScheme") as? String else { // Something went wrong/weird, but we should fallback to the public one. return "firefox" } return string } override func viewDidLoad() { super.viewDidLoad() let widgetView: UIView! self.extensionContext?.widgetLargestAvailableDisplayMode = .compact let effectView = UIVisualEffectView(effect: UIVibrancyEffect.widgetPrimary()) self.view.addSubview(effectView) effectView.snp.makeConstraints { make in make.edges.equalTo(self.view) } widgetView = effectView.contentView buttonStackView.addArrangedSubview(newTabButton) buttonStackView.addArrangedSubview(newPrivateTabButton) widgetStackView.addArrangedSubview(buttonStackView) widgetStackView.addArrangedSubview(openCopiedLinkButton) widgetView.addSubview(widgetStackView) widgetStackView.snp.makeConstraints { make in make.edges.equalTo(widgetView) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateCopiedLink() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { let edge = size.width * TodayUX.buttonsHorizontalMarginPercentage buttonStackView.layoutMargins = UIEdgeInsets(top: 0, left: edge, bottom: 0, right: edge) } func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets { return .zero } func updateCopiedLink() { UIPasteboard.general.asyncURL().uponQueue(.main) { res in if let copiedURL: URL? = res.successValue, let url = copiedURL { self.openCopiedLinkButton.isHidden = false self.openCopiedLinkButton.subtitleLabel.isHidden = SystemUtils.isDeviceLocked() self.openCopiedLinkButton.subtitleLabel.text = url.absoluteDisplayString self.copiedURL = url } else { self.openCopiedLinkButton.isHidden = true self.copiedURL = nil } } } // MARK: Button behaviour @objc func onPressNewTab(_ view: UIView) { openContainingApp("?private=false") } @objc func onPressNewPrivateTab(_ view: UIView) { openContainingApp("?private=true") } fileprivate func openContainingApp(_ urlSuffix: String = "") { let urlString = "\(scheme)://open-url\(urlSuffix)" self.extensionContext?.open(URL(string: urlString)!) { success in log.info("Extension opened containing app: \(success)") } } @objc func onPressOpenClibpoard(_ view: UIView) { if let url = copiedURL, let encodedString = url.absoluteString.escape() { openContainingApp("?url=\(encodedString)") } } } extension UIButton { func setBackgroundColor(_ color: UIColor, forState state: UIControl.State) { let colorView = UIView(frame: CGRect(width: 1, height: 1)) colorView.backgroundColor = color UIGraphicsBeginImageContext(colorView.bounds.size) if let context = UIGraphicsGetCurrentContext() { colorView.layer.render(in: context) } let colorImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setBackgroundImage(colorImage, for: state) } } class ImageButtonWithLabel: UIView { lazy var button = UIButton() lazy var label = UILabel() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) performLayout() } func performLayout() { addSubview(button) addSubview(label) button.snp.makeConstraints { make in make.top.left.centerX.equalTo(self) } label.snp.makeConstraints { make in make.top.equalTo(button.snp.bottom) make.leading.trailing.bottom.equalTo(self) } label.numberOfLines = 1 label.lineBreakMode = .byWordWrapping label.textAlignment = .center label.textColor = UIColor.white } func addTarget(_ target: AnyObject?, action: Selector, forControlEvents events: UIControl.Event) { button.addTarget(target, action: action, for: events) } } class ButtonWithSublabel: UIButton { lazy var subtitleLabel = UILabel() lazy var label = UILabel() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init() { self.init(frame: .zero) } override init(frame: CGRect) { super.init(frame: frame) performLayout() } fileprivate func performLayout() { let titleLabel = self.label self.titleLabel?.removeFromSuperview() addSubview(titleLabel) let imageView = self.imageView! let subtitleLabel = self.subtitleLabel subtitleLabel.textColor = UIColor.lightGray self.addSubview(subtitleLabel) imageView.snp.makeConstraints { make in make.centerY.left.equalTo(self) make.width.equalTo(TodayUX.copyLinkImageWidth) } titleLabel.snp.makeConstraints { make in make.left.equalTo(imageView.snp.right).offset(TodayUX.margin) make.trailing.top.equalTo(self) } subtitleLabel.lineBreakMode = .byTruncatingTail subtitleLabel.snp.makeConstraints { make in make.bottom.equalTo(self) make.top.equalTo(titleLabel.snp.bottom) make.leading.trailing.equalTo(titleLabel) } } override func setTitle(_ text: String?, for state: UIControl.State) { self.label.text = text super.setTitle(text, for: state) } }
mpl-2.0
zarkopopovski/IOS-Tutorials
UIAlertControllerTutorial/UIAlertControllerTutorial/AppDelegate.swift
1
2164
// // AppDelegate.swift // UIAlertControllerTutorial // // Created by Zarko Popovski on 8/11/16. // Copyright © 2016 ZPOTutorials. 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