repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
blitzagency/events
refs/heads/master
Events/TypedEventManager/TypedEventManager+PublisherCallback.swift.swift
mit
1
// // TypedEventManager+PublisherCallback.swift.swift // Events // // Created by Adam Venturella on 7/21/16. // Copyright © 2016 BLITZ. All rights reserved. // import Foundation extension TypedEventManager { public func listenTo<Event: RawRepresentable, Publisher: TypedEventManager<Event>>(_ publisher: Publisher, event: Event, callback: @escaping (Publisher) -> ()) where Event.RawValue == String { listenTo(publisher, event: event.rawValue, callback: callback) } func listenTo<Publisher: EventManagerBase>(_ publisher: Publisher, event: String, callback: @escaping (Publisher) -> ()){ let wrappedCallback = wrapCallback(callback) internalOn(publisher, event: event, callback: wrappedCallback) } func internalOn<Publisher: EventManagerBase>(_ publisher: Publisher, event: String, callback: @escaping (EventPublisher<Publisher>) -> ()){ let listener = publisherListener(publisher) let handler = HandlerPublisher<Publisher>( publisher: listener.publisher, subscriber: listener.subscriber, listener: listener, callback: callback ) self.addHandler(publisher, handler: handler, listener: listener, event: event) } func trigger<Publisher: EventManagerBase>(_ event: EventPublisher<Publisher>){ // when we trigger an event, we use buildEvent() which set's the publisher to // ourself on the EventPublisher<Publisher> model. // so event.publisher == self let handlers = publisherEventHandlers(event.publisher, event: event.name) handlers?.forEach{ handler in guard let handler = handler as? HandlerPublisher<Publisher> else { return } handler.callback(event) } } }
4c684634021c7bb75a44fb8d71bc8f00
31.491228
163
0.653348
false
false
false
false
AaronMT/firefox-ios
refs/heads/master
Client/Frontend/UIConstants.swift
mpl-2.0
8
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared extension UIColor { // These are defaults from http://design.firefox.com/photon/visuals/color.html struct Defaults { static let MobileGreyF = UIColor(rgb: 0x636369) static let iOSTextHighlightBlue = UIColor(rgb: 0xccdded) // This color should exactly match the ios text highlight static let Purple60A30 = UIColor(rgba: 0x8000d74c) static let MobilePrivatePurple = UIColor.Photon.Purple60 // Reader Mode Sepia static let LightBeige = UIColor(rgb: 0xf0e6dc) } } public struct UIConstants { static let DefaultPadding: CGFloat = 10 static let SnackbarButtonHeight: CGFloat = 57 static let TopToolbarHeight: CGFloat = 56 static var ToolbarHeight: CGFloat = 46 static var BottomToolbarHeight: CGFloat { get { var bottomInset: CGFloat = 0.0 if let window = UIApplication.shared.keyWindow { bottomInset = window.safeAreaInsets.bottom } return ToolbarHeight + bottomInset } } static let SystemBlueColor = UIColor.Photon.Blue40 // Static fonts static let DefaultChromeSize: CGFloat = 16 static let DefaultChromeSmallSize: CGFloat = 11 static let PasscodeEntryFontSize: CGFloat = 36 static let DefaultChromeFont = UIFont.systemFont(ofSize: DefaultChromeSize, weight: UIFont.Weight.regular) static let DefaultChromeSmallFontBold = UIFont.boldSystemFont(ofSize: DefaultChromeSmallSize) static let PasscodeEntryFont = UIFont.systemFont(ofSize: PasscodeEntryFontSize, weight: UIFont.Weight.bold) /// JPEG compression quality for persisted screenshots. Must be between 0-1. static let ScreenshotQuality: Float = 0.3 static let ActiveScreenshotQuality: CGFloat = 0.5 }
996da29c409f538d5a6eea746689e1fb
40.645833
122
0.714857
false
false
false
false
qq456cvb/DeepLearningKitForiOS
refs/heads/master
iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/ViewController.swift
apache-2.0
1
// // ViewController.swift // iOSDeepLearningKitApp // // Created by Amund Tveit on 13/02/16. // Copyright © 2016 DeepLearningKit. All rights reserved. // import UIKit import CoreGraphics import AVFoundation public class AtomicBoolean { private var val: UInt8 = 0 public init(initialValue: Bool) { self.val = (initialValue == false ? 0 : 1) } public func getAndSet(value: Bool) -> Bool { if value { return OSAtomicTestAndSet(7, &val) } else { return OSAtomicTestAndClear(7, &val) } } public func get() -> Bool { return val != 0 } } class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate { @IBOutlet weak var chooseBtn: UIButton! @IBOutlet weak var imageView: UIImageView! var deepNetwork: DeepNetwork! let imagePicker = UIImagePickerController() let path = Bundle.main.path(forResource: "yolo_tiny", ofType: "bson")! let imageShape:[Float] = [1.0, 3.0, 448.0, 448.0] let cameraSession = AVCaptureSession() let caching_mode = false var loaded = false var frame_done = AtomicBoolean.init(initialValue: true) @IBAction func start(_ sender: Any) { cameraSession.sessionPreset = AVCaptureSessionPresetMedium let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) as AVCaptureDevice do { let deviceInput = try AVCaptureDeviceInput(device: captureDevice) cameraSession.beginConfiguration() // 1 if (cameraSession.canAddInput(deviceInput) == true) { cameraSession.addInput(deviceInput) } let dataOutput = AVCaptureVideoDataOutput() // 2 dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString) : NSNumber(value: kCVPixelFormatType_32BGRA as UInt32)] // 3 dataOutput.alwaysDiscardsLateVideoFrames = true // 4 if (cameraSession.canAddOutput(dataOutput) == true) { cameraSession.addOutput(dataOutput) } cameraSession.commitConfiguration() //5 let queue = DispatchQueue(label: "video") // 6 dataOutput.setSampleBufferDelegate(self, queue: queue) // 7 cameraSession.startRunning() } catch let error as NSError { NSLog("\(error), \(error.localizedDescription)") } } func imageFromSampleBuffer(sampleBuffer : CMSampleBuffer) -> UIImage { // Get a CMSampleBuffer's Core Video image buffer for the media data let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); // Lock the base address of the pixel buffer CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags.readOnly); // Get the number of bytes per row for the pixel buffer let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer!); // Get the number of bytes per row for the pixel buffer let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!); // Get the pixel buffer width and height let width = CVPixelBufferGetWidth(imageBuffer!); let height = CVPixelBufferGetHeight(imageBuffer!); // Create a device-dependent RGB color space let colorSpace = CGColorSpaceCreateDeviceRGB(); // Create a bitmap graphics context with the sample buffer data var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Little.rawValue bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue & CGBitmapInfo.alphaInfoMask.rawValue //let bitmapInfo: UInt32 = CGBitmapInfo.alphaInfoMask.rawValue let context = CGContext.init(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) // Create a Quartz image from the pixel data in the bitmap graphics context let quartzImage = context?.makeImage(); // Unlock the pixel buffer CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags.readOnly); // Create an image object from the Quartz image let image = UIImage.init(cgImage: quartzImage!, scale: 1.0, orientation: .down); return (image); } func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) { if frame_done.get() { _ = self.frame_done.getAndSet(value: false) let captured = self.imageFromSampleBuffer(sampleBuffer: sampleBuffer) DispatchQueue.global().async { let resized = self.resizeImage(image: captured, newWidth: CGFloat(self.imageShape[3]), newHeight: CGFloat(self.imageShape[2])) let (r, g, b, _) = imageToMatrix(resized) var image = b + g + r for (i, _) in image.enumerated() { image[i] /= 255 } self.deepNetwork.loadDeepNetworkFromBSON(self.path, inputImage: image, inputShape: self.imageShape, caching_mode:self.caching_mode) // 1. classify image (of cat) self.deepNetwork.yoloDetect(captured, imageView: self.imageView) _ = self.frame_done.getAndSet(value: true) } } } func resizeImage(image: UIImage, newWidth: CGFloat, newHeight: CGFloat) -> UIImage { UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight)) image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } @IBAction func imageChoosen(_ sender: Any) { imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { print(info.debugDescription) if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { // imageView.contentMode = .scaleAspectFit imageView.image = pickedImage } // DispatchQueue.global().async { // let resized = self.resizeImage(image: self.imageView.image!, newWidth: CGFloat(self.imageShape[3]), newHeight: CGFloat(self.imageShape[2])) // // // print(resized.size.width) // // let (r, g, b, _) = imageToMatrix(resized) // var image = b + g + r // for (i, _) in image.enumerated() { // image[i] /= 255 // } // self.deepNetwork.loadDeepNetworkFromBSON(self.path, inputImage: image, inputShape: self.imageShape, caching_mode:self.caching_mode) // // // 1. classify image (of cat) // self.deepNetwork.yoloDetect(image, imageView: self.imageView) // } dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. imagePicker.delegate = self imageView.image = #imageLiteral(resourceName: "lena") deepNetwork = DeepNetwork() } override func viewDidAppear(_ animated: Bool) { // conv1.json contains a cifar 10 image of a cat // let conv1Layer = deepNetwork.loadJSONFile("conv1")! // let image: [Float] = conv1Layer["input"] as! [Float] // // _ = UIImage(named: "lena") // //shows a tiny (32x32) CIFAR 10 image on screen // showCIFARImage(image) // var randomimage = createFloatNumbersArray(image.count) // for i in 0..<randomimage.count { // randomimage[i] = Float(arc4random_uniform(1000)) // } // **********************comment out below to debug at launch time ******************// // let imageCount = Int(imageShape.reduce(1, *)) // // let resizeLena = resizeImage(image: #imageLiteral(resourceName: "lena"), newWidth: 448.0, newHeight: 448.0) // let (r, g, b, _) = imageToMatrix(resizeLena) // var image = b + g + r // for (i, _) in image.enumerated() { // image[i] /= 255 // } // print(image.max()!) // // var randomimage = createFloatNumbersArray(imageCount) // for i in 0..<randomimage.count { // randomimage[i] = Float(1.0) // } // // // 0. load network in network model // deepNetwork.loadDeepNetworkFromBSON(path, inputImage: image, inputShape: imageShape, caching_mode:caching_mode) // // // 1. classify image (of cat) // deepNetwork.yoloDetect(image, imageView: imageView) // deepNetwork.loadDeepNetworkFromBSON(path, inputImage: randomimage, inputShape: imageShape, caching_mode:caching_mode) // deepNetwork.classify(randomimage) // **********************comment out above to debug at launch time ******************// } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //*********************************************************************************** func showCIFARImage(_ cifarImageData:[Float]) { var cifarImageData = cifarImageData let size = CGSize(width: 32, height: 32) let rect = CGRect(origin: CGPoint(x: 0,y: 0), size: size) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIColor.white.setFill() // or custom color UIRectFill(rect) var image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // CIFAR 10 images are 32x32 in 3 channels - RGB // it is stored as 3 sequences of 32x32 = 1024 numbers in cifarImageData, i.e. // red: numbers from position 0 to 1024 (not inclusive) // green: numbers from position 1024 to 2048 (not inclusive) // blue: numbers from position 2048 to 3072 (not inclusive) for i in 0..<32 { for j in 0..<32 { let r = UInt8(cifarImageData[i*32 + j]) let g = UInt8(cifarImageData[32*32 + i*32 + j]) let b = UInt8(cifarImageData[2*32*32 + i*32 + j]) // used to set pixels - RGBA into an UIImage // for more info about RGBA check out https://en.wikipedia.org/wiki/RGBA_color_space image = image?.setPixelColorAtPoint(CGPoint(x: j,y: i), color: UIImage.RawColorType(r,g,b,255))! // used to read pixels - RGBA from an UIImage _ = image?.getPixelColorAtLocation(CGPoint(x:i, y:j)) } } print(image?.size ?? CGSize(width: 0, height: 0)) // Displaying original image. let originalImageView:UIImageView = UIImageView(frame: CGRect(x: 20, y: 20, width: image!.size.width, height: image!.size.height)) originalImageView.image = image self.view.addSubview(originalImageView) } }
d23c9236242595bfd977d6311a8eb217
40.174825
175
0.597826
false
false
false
false
jinSasaki/in-app-purchase
refs/heads/master
Tests/Stubs/StubPaymentTransaction.swift
mit
1
// // StubPaymentTransaction.swift // InAppPurchase // // Created by Jin Sasaki on 2017/04/11. // Copyright © 2017年 Jin Sasaki. All rights reserved. // import Foundation import StoreKit final class StubPaymentTransaction: SKPaymentTransaction { private let _transactionIdentifier: String? private let _transactionState: SKPaymentTransactionState private let _original: StubPaymentTransaction? private let _payment: SKPayment private let _error: Error? init(transactionIdentifier: String? = nil, transactionState: SKPaymentTransactionState = .purchasing, original: StubPaymentTransaction? = nil, payment: SKPayment = StubPayment(productIdentifier: ""), error: Error? = nil) { self._transactionIdentifier = transactionIdentifier self._transactionState = transactionState self._original = original self._payment = payment self._error = error } override var transactionIdentifier: String? { return _transactionIdentifier } override var transactionState: SKPaymentTransactionState { return _transactionState } override var original: SKPaymentTransaction? { return _original } override var payment: SKPayment { return _payment } override var error: Error? { return _error } }
0731ba865f43255aa72150ba4607e521
25.803922
67
0.685443
false
false
false
false
BPForEveryone/BloodPressureForEveryone
refs/heads/master
BPApp/BPProfessional/BPProGraphViewController.swift
mit
1
// // BPProGraphViewController.swift // BPForProfessionals // // Created by Andrew Hu on 10/16/17. // Copyright © 2017 BlackstoneBuilds. All rights reserved. // import UIKit import Charts class BPProGraphViewController: UIViewController, ChartViewDelegate { // Systolic and Diastolic Line Charts @IBOutlet weak var systolicLineChartView: LineChartView! @IBOutlet weak var diastolicLineChartView: LineChartView! var systolicDataEntry: [ChartDataEntry] = [] @IBAction func backPressed(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } // Patient Object passed from Analysis Results var patient: Patient? // Holds the BPNorms entries obtained by indexing Sex/Age var normsTable: [BPNormsEntry]? // Y-Axis - Height Percentile let heightPercentile = [5, 10, 25, 50, 75, 90, 95] // Systolic Chart Data var systolicNorms50: [Int] = [] var systolicNorms90: [Int] = [] var systolicNorms95: [Int] = [] var systolicNorms95plus: [Int] = [] // Diastolic Chart Data // Use Patient Object data from previous to index into norms table // Temporary Dummy Data let age = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] let BP = [86.0, 89.0, 90.0, 92.0, 94.0, 95.0, 97.0, 98.0, 99.0, 100.0, 102.0, 104.0, 105.0, 109.0, 113.0, 115.0, 117.0] // Prepare data before view loads override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) normsTable = patient?.normsArray // for index in 0...normsTable!.count { // systolicNorms50.append(normsTable![index].systolic50) // systolicNorms90.append(normsTable![index].systolic90) // systolicNorms95.append(normsTable![index].systolic95) // systolicNorms95plus.append(normsTable![index].systolic95plus) // } } // Present graphs once the view loads override func viewDidLoad() { super.viewDidLoad() lineChartSetup() } func lineChartSetup() { systolicLineChartView.delegate = self systolicLineChartView.backgroundColor = UIColor.white systolicLineChartView.translatesAutoresizingMaskIntoConstraints = false //Temporary so that the app does not break setLineChart(dataPoints: age, values: BP) //setLineChart(dataPoints: heightPercentile, values: systolicNorms50) } func setLineChart(dataPoints: [Int], values: [Double]) { //func setLineChart(dataPoints: [Int], values: [Int]) { // No Data Available Setup systolicLineChartView.noDataTextColor = UIColor.white systolicLineChartView.noDataText = "No graph data available" systolicLineChartView.backgroundColor = UIColor.white // Data Point Setup & Color Configuration for i in 0..<dataPoints.count { let dataPoint = ChartDataEntry(x: Double(dataPoints[i]), y: Double(values[i])) systolicDataEntry.append(dataPoint) } let fifty_DataSet = LineChartDataSet(values: systolicDataEntry, label: "50th Percentile Systolic BP") let fifty_Data = LineChartData() fifty_Data.addDataSet(fifty_DataSet) fifty_Data.setDrawValues(true) fifty_DataSet.colors = [UIColor.red] fifty_DataSet.setCircleColor(UIColor.red) fifty_DataSet.circleHoleColor = UIColor.red fifty_DataSet.circleRadius = 0.0 fifty_DataSet.lineWidth = 5.0 // Gradient Fill let gradientColors = [UIColor.red.cgColor, UIColor.red.cgColor] as CFArray let colorLocations: [CGFloat] = [1.0, 0.0] guard let red_gradient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations) else { print("Gradient error"); return } fifty_DataSet.fill = Fill.fillWithLinearGradient(red_gradient, angle: 90.0) fifty_DataSet.drawFilledEnabled = true // Axes Setup systolicLineChartView.chartDescription?.enabled = false systolicLineChartView.legend.enabled = true systolicLineChartView.xAxis.drawGridLinesEnabled = false systolicLineChartView.xAxis.granularity = 1.0 systolicLineChartView.xAxis.labelCount = dataPoints.count systolicLineChartView.xAxis.labelPosition = .bottom systolicLineChartView.xAxis.xOffset = 1.0 systolicLineChartView.rightAxis.enabled = true systolicLineChartView.rightAxis.drawGridLinesEnabled = false systolicLineChartView.leftAxis.drawGridLinesEnabled = false systolicLineChartView.leftAxis.drawLabelsEnabled = true systolicLineChartView.leftAxis.xOffset = 1.0 //systolicLineChartView.extraTopOffset = 10.0 //systolicLineChartView.extraLeftOffset = 35.0 systolicLineChartView.data = fifty_Data } }
b0466854ce3387c64e45172a4b2e63fd
39.300813
184
0.671777
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
Client/Frontend/Settings/SettingsNavigationController.swift
mpl-2.0
1
/* 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 class SettingsNavigationController: UINavigationController { var popoverDelegate: PresentingModalViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() self.navigationBar.barTintColor = UIColor.white let value = UIInterfaceOrientation.portrait.rawValue UIDevice.current.setValue(value, forKey: "orientation") } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } override var shouldAutorotate : Bool { return false } override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation { return UIInterfaceOrientation.portrait } func SELdone() { if let delegate = popoverDelegate { delegate.dismissPresentedModalViewController(self, animated: true) getApp().browserViewController.view.alpha = CGFloat(BraveUX.BrowserViewAlphaWhenShowingTabTray) } else { self.dismiss(animated: true, completion: { getApp().browserViewController.view.alpha = CGFloat(1.0) }) } getApp().browserViewController.urlBar.setNeedsLayout() getApp().browserViewController.urlBar.setNeedsUpdateConstraints() } } protocol PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) }
aca9ea909a66ffd54f7391406e3fecff
35.212766
107
0.704465
false
false
false
false
MjAbuz/SwiftHamcrest
refs/heads/master
Hamcrest/Hamcrest.swift
bsd-3-clause
1
import Foundation import Swift import XCTest /// Reporter function that is called whenever a Hamcrest assertion fails. /// By default this calls XCTFail, except in Playgrounds where it does nothing. /// This is intended for testing Hamcrest itself. public var HamcrestReportFunction: (_: String, file: String, line: UInt) -> () = HamcrestDefaultReportFunction public let HamcrestDefaultReportFunction = isPlayground() ? {(message, file, line) in} : {(message, file, line) in XCTFail(message, file: file, line: line)} // MARK: helpers func filterNotNil<T>(array: [T?]) -> [T] { return array.filter({$0 != nil}).map({$0!}) } func delegateMatching<T>(value: T, _ matcher: Matcher<T>, _ mismatchDescriber: String? -> String?) -> MatchResult { switch matcher.matches(value) { case .Match: return .Match case let .Mismatch(mismatchDescription): return .Mismatch(mismatchDescriber(mismatchDescription)) } } func equalToWithoutDescription<T: Equatable>(expectedValue: T) -> Matcher<T> { return describedAs(describe(expectedValue), equalTo(expectedValue)) } func isPlayground() -> Bool { let infoDictionary = NSBundle.mainBundle().infoDictionary let bundleIdentifier: AnyObject? = infoDictionary?["CFBundleIdentifier"] return (bundleIdentifier as? String)?.hasPrefix("com.apple.dt.playground.stub") ?? false } // MARK: assertThrows public func assertThrows<T>(@autoclosure value: () throws -> T, file: String = __FILE__, line: UInt = __LINE__) -> String { do { try value() return reportResult(describeExpectedError()) } catch { return reportResult(nil) } } public func assertThrows<S, T: ErrorType where T: Equatable>(@autoclosure value: () throws -> S, _ error: T, file: String = __FILE__, line: UInt = __LINE__) -> String { return assertThrows(value, equalToWithoutDescription(error), file: file, line: line) } public func assertThrows<S, T: ErrorType>(@autoclosure value: () throws -> S, _ matcher: Matcher<T>, file: String = __FILE__, line: UInt = __LINE__) -> String { return reportResult(applyErrorMatcher(matcher, toBlock: value)) } private func applyErrorMatcher<S, T: ErrorType>(matcher: Matcher<T>, @noescape toBlock: () throws -> S) -> String? { do { try toBlock() return describeExpectedError(matcher.description) } catch let error as T { let match = matcher.matches(error) switch match { case .Match: return nil case let .Mismatch(mismatchDescription): return describeErrorMismatch(error, matcher.description, mismatchDescription) } } catch let error { return describeErrorMismatch(error, matcher.description, nil) } } // MARK: assertThat public func assertThat<T>(@autoclosure value: () throws -> T, _ matcher: Matcher<T>, file: String = __FILE__, line: UInt = __LINE__) -> String { return reportResult(applyMatcher(matcher, toValue: value), file: file, line: line) } func applyMatcher<T>(matcher: Matcher<T>, @noescape toValue: () throws -> T) -> String? { do { let value = try toValue() let match = matcher.matches(value) switch match { case .Match: return nil case let .Mismatch(mismatchDescription): return describeMismatch(value, matcher.description, mismatchDescription) } } catch let error { return describeError(error) } } func reportResult(possibleResult: String?, file: String = __FILE__, line: UInt = __LINE__) -> String { if let result = possibleResult { HamcrestReportFunction(result, file: file, line: line) return result } else { // The return value is just intended for Playgrounds. return "✓" } }
6e1c05e2a9aa549032efc33a5e21ca41
34.839623
168
0.660437
false
false
false
false
armendo/CP-W3-Yelp
refs/heads/master
Yelp/Business.swift
apache-2.0
2
// // Business.swift // Yelp // // Created by Timothy Lee on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit class Business: NSObject { let name: String? let address: String? let imageURL: NSURL? let categories: String? let distance: String? let ratingImageURL: NSURL? let reviewCount: NSNumber? init(dictionary: NSDictionary) { name = dictionary["name"] as? String let imageURLString = dictionary["image_url"] as? String if imageURLString != nil { imageURL = NSURL(string: imageURLString!)! } else { imageURL = nil } let location = dictionary["location"] as? NSDictionary var address = "" if location != nil { let addressArray = location!["address"] as? NSArray if addressArray != nil && addressArray!.count > 0 { address = addressArray![0] as! String } let neighborhoods = location!["neighborhoods"] as? NSArray if neighborhoods != nil && neighborhoods!.count > 0 { if !address.isEmpty { address += ", " } address += neighborhoods![0] as! String } } self.address = address let categoriesArray = dictionary["categories"] as? [[String]] if categoriesArray != nil { var categoryNames = [String]() for category in categoriesArray! { let categoryName = category[0] categoryNames.append(categoryName) } categories = categoryNames.joinWithSeparator(", ") } else { categories = nil } let distanceMeters = dictionary["distance"] as? NSNumber if distanceMeters != nil { let milesPerMeter = 0.000621371 distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue) } else { distance = nil } let ratingImageURLString = dictionary["rating_img_url_large"] as? String if ratingImageURLString != nil { ratingImageURL = NSURL(string: ratingImageURLString!) } else { ratingImageURL = nil } reviewCount = dictionary["review_count"] as? NSNumber } class func businesses(array array: [NSDictionary]) -> [Business] { var businesses = [Business]() for dictionary in array { let business = Business(dictionary: dictionary) businesses.append(business) } return businesses } class func searchWithTerm(term: String, completion: ([Business]!, NSError!) -> Void) { YelpClient.sharedInstance.searchWithTerm(term, completion: completion) } class func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: ([Business]!, NSError!) -> Void) -> Void { YelpClient.sharedInstance.searchWithTerm(term, sort: sort, categories: categories, deals: deals, completion: completion) } }
5d2ca5181868e3eb812960114d4ded1f
32.861702
156
0.568646
false
false
false
false
schrismartin/dont-shoot-the-messenger
refs/heads/master
Sources/Library/Models/Items/Consumables/Misc.swift
mit
1
public class Cloth: Item { public override init(quantity: Int){ super.init(quantity: quantity) name = "cloth" pickupText = "You add \(quantity) \(name) to your inventory." desctiption = "I'd use it to blow my nose but I think it might come in handy later." keywords ["stick"] = "torch" } } public class Flint: Item { public override init(quantity: Int){ super.init(quantity: quantity) name = "flint" pickupText = "You add \(quantity) \(name) to your inventory." desctiption = "Striking it makes sparks. Useful to start fires." keywords ["torch"] = "lit_torch" } } public class Stick: Item { public override init(quantity: Int){ super.init(quantity: quantity) name = "stick" pickupText = "You add \(quantity) \(name) to your inventory." desctiption = "I've been told these will poke your eye out." keywords ["cloth"] = "torch" // keywords ["flint"] = "Campfire" } } public class Map: Item { public override init(quantity: Int){ super.init(quantity: quantity) name = "map" pickupText = "You add \(quantity) \(name) to your inventory." desctiption = "A map that details the surrounding area. Now i wont get lost!" } } public class Torch: Item { public override init(quantity: Int){ super.init(quantity: quantity) name = "torch" pickupText = "You add \(quantity) \(name) to your inventory." desctiption = "Now I just need something to light it and I'll have a portable light source." keywords ["flint"] = "lit_torch" } } public class LitTorch: Item { public override init(quantity: Int){ super.init(quantity: quantity) name = "lit_torch" pickupText = "You add \(quantity) \(name) to your inventory." desctiption = "This should help in those dark areas." } } /*-------------------------------------*/ public class Journal: Item { public override init(quantity: Int){ super.init(quantity: quantity) name = "journal" pickupText = "You add \(quantity) \(name) to your inventory." desctiption = "The journal tells you the door in the cave's name is Franky." } } public class Key: Item { public override init (quantity: Int){ super.init(quantity: quantity) name = "key" pickupText = "You add \(quantity) \(name) to your inventory." desctiption = "A small brass key." } } // Vines // Rock
82cd6f9c69a63c047502e5fc5d7944e2
27.222222
94
0.668854
false
false
false
false
zhangliangzhi/iosStudyBySwift
refs/heads/master
CoreToDo/CoreToDo/ViewController.swift
mit
1
// // ViewController.swift // CoreToDo // // Created by ZhangLiangZhi on 2016/12/6. // Copyright © 2016年 xigk. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var tasks:[Task] = [] override func viewWillAppear(_ animated: Bool) { getData() tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tasks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() let task = tasks[indexPath.row] if task.isimportant { cell.textLabel?.text = "😀"+task.name! }else{ cell.textLabel?.text = task.name } return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext do{ tasks = try context.fetch(Task.fetchRequest()) let task = tasks[indexPath.row] context.delete(task) tasks.remove(at: indexPath.row) (UIApplication.shared.delegate as! AppDelegate).saveContext() tableView.reloadData() }catch{ print("core data error") } } } func getData() { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext do{ tasks = try context.fetch(Task.fetchRequest()) }catch{ print("core data error") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
cdb3ca18561b9fabd20d78121f06975e
26.506173
127
0.590664
false
false
false
false
Instamojo/ios-sdk
refs/heads/master
Instamojo/PaymentViewController.swift
lgpl-3.0
1
// // PaymentView.swift // Instamojo // // Created by Sukanya Raj on 27/02/17. // Edited by Vaibhav Bhasin on 4/10/19 // Copyright © 2017 Sukanya Raj. All rights reserved. // import UIKit class PaymentViewController: UIViewController { var juspaySafeBrowser = JuspaySafeBrowser() var params: BrowserParams! var cancelled: Bool = false override func viewDidLoad() { super.viewDidLoad() Logger.logDebug(tag: "Juspay Request", message: "Juspay Request Starting juspay safe browser payment") self.juspaySafeBrowser.startpaymentWithJuspay(in: self.view, withParameters: self.params) { (status, error, _) in let transactionStatus = JPTransactionStatus() if (!status) { transactionStatus.paymentID = "TransactionID" let nsError = error! as NSError if (nsError.code == 101) { self.cancelled = true transactionStatus.paymentStatus = JPCANCELLED UserDefaults.standard.setValue(true, forKey: "USER-CANCELLED") UserDefaults.standard.setValue(nil, forKey: "ON-REDIRECT-URL") let controllers = self.navigationController?.viewControllers for vc in controllers! { if vc is PaymentOptionsView { _ = self.navigationController?.popToViewController(vc as! PaymentOptionsView, animated: true) } if(Instamojo.isNavigationStack() == false ){ vc.dismiss(animated: true, completion: nil) } } NotificationCenter.default.post(name: NSNotification.Name(rawValue: "INSTAMOJO"), object: nil) } else { transactionStatus.paymentStatus = JPUNKNOWNSTATUS } } JPLogger.sharedInstance().logPaymentStatus(transactionStatus) } } override func viewDidAppear(_ animated: Bool) { self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false } //the navigationShouldPopOnBackButton method to check if controller is allowed to pop. override func navigationShouldPopOnBackButton() -> Bool { self.juspaySafeBrowser.backButtonPressed() return self.juspaySafeBrowser.isControllerAllowedToPop } override func viewWillDisappear(_ animated: Bool) { //To renable interactive pop gesture. if !cancelled { UserDefaults.standard.setValue(nil, forKey: "USER-CANCELLED") UserDefaults.standard.setValue(true, forKey: "ON-REDIRECT-URL") let controllers = self.navigationController?.viewControllers for vc in controllers! { if vc is PaymentOptionsView { _ = self.navigationController?.popToViewController(vc as! PaymentOptionsView, animated: true) } if(Instamojo.isNavigationStack() == false ){ vc.dismiss(animated: true, completion: nil) } } NotificationCenter.default.post(name: NSNotification.Name(rawValue: "INSTAMOJO"), object: nil) } self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true } }
46bea890a2ec71807c89fc4e5bfc8554
42.538462
121
0.603946
false
false
false
false
Logicalshift/SwiftRebound
refs/heads/master
SwiftReboundTests/BindingContextTests.swift
apache-2.0
1
// // BindingContextTests.swift // SwiftRebound // // Created by Andrew Hunter on 10/07/2016. // // import Foundation import XCTest @testable import SwiftRebound class BindingContextTests : XCTestCase { func testCanSetContext() { XCTAssert(BindingContext.current == nil); BindingContext.withNewContext { XCTAssert(BindingContext.current != nil); } XCTAssert(BindingContext.current == nil); } func testNewContextPerformance() { self.measure { for _ in 0..<100000 { BindingContext.withNewContext { }; } } } func testNewContextPerformanceWithNesting() { BindingContext.withNewContext { self.measure { for _ in 0..<100000 { BindingContext.withNewContext { }; } } } } func testReadContextPerformance() { BindingContext.withNewContext { self.measure { for _ in 0..<100000 { if BindingContext.current == nil { XCTAssert(false); } } } } } }
c9788f7a3fbb38ac827ac1e8c8683a1c
22.075472
54
0.509403
false
true
false
false
xglofter/PicturePicker
refs/heads/master
PicturePicker/PickerManager.swift
mit
1
// // PickerManager.swift // // Created by Richard on 2017/4/20. // Copyright © 2017年 Richard. All rights reserved. // import UIKit import Photos public class PickerManager: NSObject { public static let shared = PickerManager() public typealias ChoosePhotosHandle = ([UIImage]) -> Void fileprivate(set) var callbackAfterFinish: ChoosePhotosHandle? fileprivate(set) var maxPhotos: Int = 0 fileprivate(set) lazy var choosedAssets = [PHAsset]() fileprivate(set) var fetchOutputImages: [UIImage]! /// 获取当前已选择图片的数目 public var currentNumber: Int { get { return choosedAssets.count } } /// 当前是否已经选满了 public var isMax: Bool { get { return choosedAssets.count == maxPhotos } } private override init() { super.init() } /// 开始选择图片 /// /// - Parameters: /// - number: 选择图片的最大数目 /// - handle: 回调处理 public func startChoosePhotos(with number: Int, completion handle: @escaping ChoosePhotosHandle) { guard number > 0 && number < 100 else { fatalError("choosePhotos with unexpected number.") } resetPicker() maxPhotos = number callbackAfterFinish = handle let library: PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus() if library == .notDetermined { PHPhotoLibrary.requestAuthorization { (status) in if status == PHAuthorizationStatus.authorized { DispatchQueue.main.async { [weak self] _ in self?.presentPicker() } } } } else if library == .denied || library == .restricted { let alert = UIAlertController(title: nil, message: "需要访问您的相册,请前往设置打开权限", preferredStyle: .alert) let okAction = UIAlertAction(title: "确定", style: .default, handler: nil) alert.addAction(okAction) topMostViewController()?.present(alert, animated: true, completion: nil) } else { presentPicker() } } /// 终止选择图片 /// /// - Parameter isFinish: 是否是完成了,false表示取消 public func endChoose(isFinish: Bool) { if isFinish { fetchOutputImages = [UIImage](repeating: UIImage(), count: choosedAssets.count) for asset in choosedAssets { PHImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .default, options: nil, resultHandler: { (img, _) in let tempIdx = self.choosedAssets.index(of: asset)! self.callbackAfterFetch(img: img!, index: tempIdx) }) } } else { resetPicker() } } /// 获取某图片的 flag 数字 /// /// - Returns: 0 表示未被选择,1 ~ maxPhotos 已被选择的序列号 public func getPhotoNumber(with id: String) -> Int { var idx = 1 for asset in choosedAssets { if asset.localIdentifier == id { return idx } idx += 1 } return 0 } /// 选择某图片 /// /// - Parameter asset: 图片 PHAsset 资源 public func choosePhoto(with asset: PHAsset) { choosedAssets.append(asset) } /// 取消选择某图片 /// /// - Parameter id: 图片 identity public func unchoosePhoto(with id: String) { let number = getPhotoNumber(with: id) if number != 0 { choosedAssets.remove(at: number - 1) } else { fatalError("错误!") } } /// 重置 PickerManager 参数 public func resetPicker() { choosedAssets.removeAll() maxPhotos = 0 callbackAfterFinish = nil fetchOutputImages?.removeAll() PickerManager.fetchImageNumber = 0 } } // MARK: - Private Function private extension PickerManager { static var fetchImageNumber = 0 func callbackAfterFetch(img: UIImage, index: Int) { fetchOutputImages[index] = img PickerManager.fetchImageNumber += 1 if PickerManager.fetchImageNumber == choosedAssets.count { callbackAfterFinish?(fetchOutputImages) } } func presentPicker() { let allPhotos = fetchAllPhotos()! let albumVC = AlbumTableViewController(with: allPhotos) let naviVC = UINavigationController(rootViewController: albumVC) let gridVC = PhotosGridViewController(with: allPhotos) gridVC.title = "所有照片" naviVC.viewControllers.append(gridVC) topMostViewController()?.present(naviVC, animated: true, completion: nil) } func topMostViewController() -> UIViewController? { var topController = UIApplication.shared.keyWindow?.rootViewController while topController?.presentedViewController != nil { topController = topController?.presentedViewController } return topController } func fetchAllPhotos() -> PHFetchResult<PHAsset>! { let allPhotoOptions = PHFetchOptions() allPhotoOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] allPhotoOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) return PHAsset.fetchAssets(with: allPhotoOptions) } }
455a2cc328db11c7696ca65a24255b83
29.96
170
0.592839
false
false
false
false
anthonypuppo/GDAXSwift
refs/heads/master
GDAXSwift/Classes/GDAXMarketOrderRequest.swift
mit
1
// // GDAXMarketOrderRequest.swift // GDAXSwift // // Created by Anthony on 6/9/17. // Copyright © 2017 Anthony Puppo. All rights reserved. // public struct GDAXMarketOrderRequest: GDAXOrderRequestProtocol { public let type: GDAXOrderType = .market public var clientOID: String? public var side: GDAXSide public var productID: String public var stp: GDAXSelfTradePrevention? public var size: Double? public var funds: Double? public init( clientOID: String? = nil, side: GDAXSide, productID: String, stp: GDAXSelfTradePrevention? = nil, size: Double? = nil, funds: Double? = nil) { self.clientOID = clientOID self.side = side self.productID = productID self.stp = stp self.size = size self.funds = funds } public func asJSON() -> [String : Any] { var json: [String: Any] = [ "type": type.rawValue, "side": side.rawValue, "product_id": productID ] if let clientOID = clientOID { json["client_oid"] = clientOID } if let stp = stp { json["stp"] = stp.rawValue } if let size = size { json["size"] = size } if let funds = funds { json["funds"] = funds } return json } }
896bc94613b5e9b3d51ab3ab3923ee59
17.951613
64
0.651064
false
false
false
false
PANDA-Guide/PandaGuideApp
refs/heads/master
Carthage/Checkouts/starscream/Source/WebSocket.swift
gpl-3.0
4
////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // // Created by Dalton Cherry on 7/16/14. // Copyright (c) 2014-2016 Dalton Cherry. // // 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 CoreFoundation import CommonCrypto public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification" public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification" public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName" public protocol WebSocketDelegate: class { func websocketDidConnect(socket: WebSocket) func websocketDidDisconnect(socket: WebSocket, error: NSError?) func websocketDidReceiveMessage(socket: WebSocket, text: String) func websocketDidReceiveData(socket: WebSocket, data: Data) } public protocol WebSocketPongDelegate: class { func websocketDidReceivePong(socket: WebSocket, data: Data?) } // A Delegate with more advanced info on messages and connection etc. public protocol WebSocketAdvancedDelegate: class { func websocketDidConnect(socket: WebSocket) func websocketDidDisconnect(socket: WebSocket, error: NSError?) func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse) func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse) func websocketHttpUpgrade(socket: WebSocket, request: CFHTTPMessage) func websocketHttpUpgrade(socket: WebSocket, response: CFHTTPMessage) } open class WebSocket : NSObject, StreamDelegate { public enum OpCode : UInt8 { case continueFrame = 0x0 case textFrame = 0x1 case binaryFrame = 0x2 // 3-7 are reserved. case connectionClose = 0x8 case ping = 0x9 case pong = 0xA // B-F reserved. } public enum CloseCode : UInt16 { case normal = 1000 case goingAway = 1001 case protocolError = 1002 case protocolUnhandledType = 1003 // 1004 reserved. case noStatusReceived = 1005 //1006 reserved. case encoding = 1007 case policyViolated = 1008 case messageTooBig = 1009 } public static let ErrorDomain = "WebSocket" enum InternalErrorCode: UInt16 { // 0-999 WebSocket status codes not used case outputStreamWriteError = 1 case compressionError = 2 case invalidSSLError = 3 case writeTimeoutError = 4 } // Where the callback is executed. It defaults to the main UI thread queue. public var callbackQueue = DispatchQueue.main var optionalProtocols: [String]? // MARK: - Constants let headerWSUpgradeName = "Upgrade" let headerWSUpgradeValue = "websocket" let headerWSHostName = "Host" let headerWSConnectionName = "Connection" let headerWSConnectionValue = "Upgrade" let headerWSProtocolName = "Sec-WebSocket-Protocol" let headerWSVersionName = "Sec-WebSocket-Version" let headerWSVersionValue = "13" let headerWSExtensionName = "Sec-WebSocket-Extensions" let headerWSKeyName = "Sec-WebSocket-Key" let headerOriginName = "Origin" let headerWSAcceptName = "Sec-WebSocket-Accept" let BUFFER_MAX = 4096 let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let RSV1Mask: UInt8 = 0x40 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 let httpSwitchProtocolCode = 101 let supportedSSLSchemes = ["wss", "https"] public class WSResponse { var isFin = false public var code: OpCode = .continueFrame var bytesLeft = 0 public var frameCount = 0 public var buffer: NSMutableData? public let firstFrame = { return Date() }() } // MARK: - Delegates /// Responds to callback about new messages coming in over the WebSocket /// and also connection/disconnect messages. public weak var delegate: WebSocketDelegate? /// The optional advanced delegate can be used insteadof of the delegate public weak var advancedDelegate: WebSocketAdvancedDelegate? /// Receives a callback for each pong message recived. public weak var pongDelegate: WebSocketPongDelegate? // MARK: - Block based API. public enum HTTPMethod { case get case post case put case connect case custom(value: String) var representation: String { switch self { case .get: return "GET" case .post: return "POST" case .put: return "PUT" case .connect: return "CONNECT" case .custom(let value): return value.capitalized } } } public var onConnect: (() -> Void)? public var onDisconnect: ((NSError?) -> Void)? public var onText: ((String) -> Void)? public var onData: ((Data) -> Void)? public var onPong: ((Data?) -> Void)? public var httpMethod: HTTPMethod = .get public var headers = [String: String]() public var disableSSLCertValidation = false public var enableCompression = true public var security: SSLTrustValidator? public var enabledSSLCipherSuites: [SSLCipherSuite]? public var origin: String? public var timeout = 5 public var isConnected: Bool { return connected } public var currentURL: URL { return url } // MARK: - Private private struct CompressionState { var supportsCompression = false var messageNeedsDecompression = false var serverMaxWindowBits = 15 var clientMaxWindowBits = 15 var clientNoContextTakeover = false var serverNoContextTakeover = false var decompressor:Decompressor? = nil var compressor:Compressor? = nil } private var url: URL private var inputStream: InputStream? private var outputStream: OutputStream? private var connected = false private var isConnecting = false private var compressionState = CompressionState() private var writeQueue = OperationQueue() private var readStack = [WSResponse]() private var inputQueue = [Data]() private var fragBuffer: Data? private var certValidated = false private var didDisconnect = false private var readyToWrite = false private var headerSecKey = "" private let mutex = NSLock() private let notificationCenter = NotificationCenter.default private var canDispatch: Bool { mutex.lock() let canWork = readyToWrite mutex.unlock() return canWork } /// The shared processing queue used for all WebSocket. private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) /// Used for setting protocols. public init(url: URL, protocols: [String]? = nil) { self.url = url self.origin = url.absoluteString if let hostUrl = URL (string: "/", relativeTo: url) { var origin = hostUrl.absoluteString origin.remove(at: origin.index(before: origin.endIndex)) self.origin = origin } writeQueue.maxConcurrentOperationCount = 1 optionalProtocols = protocols } // Used for specifically setting the QOS for the write queue. public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) { self.init(url: url, protocols: protocols) writeQueue.qualityOfService = writeQueueQOS } /** Connect to the WebSocket server on a background thread. */ open func connect() { guard !isConnecting else { return } didDisconnect = false isConnecting = true createHTTPRequest() } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. - Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket. */ open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) { guard isConnected else { return } switch forceTimeout { case .some(let seconds) where seconds > 0: let milliseconds = Int(seconds * 1_000) callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in self?.disconnectStream(nil) } fallthrough case .none: writeError(closeCode) default: disconnectStream(nil) break } } /** Write a string to the websocket. This sends it as a text frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter string: The string to write. - parameter completion: The (optional) completion handler. */ open func write(string: String, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion) } /** Write binary data to the websocket. This sends it as a binary frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter data: The data to write. - parameter completion: The (optional) completion handler. */ open func write(data: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(data, code: .binaryFrame, writeCompletion: completion) } /** Write a ping to the websocket. This sends it as a control frame. Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s */ open func write(ping: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(ping, code: .ping, writeCompletion: completion) } /** Private method that starts the connection. */ private func createHTTPRequest() { let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, httpMethod.representation as CFString, url as CFURL, kCFHTTPVersion1_1).takeRetainedValue() var port = url.port if port == nil { if supportedSSLSchemes.contains(url.scheme!) { port = 443 } else { port = 80 } } addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue) addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue) if let protocols = optionalProtocols { addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joined(separator: ",")) } headerSecKey = generateWebSocketKey() addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue) addHeader(urlRequest, key: headerWSKeyName, val: headerSecKey) if let origin = origin { addHeader(urlRequest, key: headerOriginName, val: origin) } if enableCompression { let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15" addHeader(urlRequest, key: headerWSExtensionName, val: val) } addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)") for (key, value) in headers { addHeader(urlRequest, key: key, val: value) } if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) { let serializedRequest = cfHTTPMessage.takeRetainedValue() initStreamsWithData(serializedRequest as Data, Int(port!)) self.advancedDelegate?.websocketHttpUpgrade(socket: self, request: urlRequest) } } /** Add a header to the CFHTTPMessage by using the NSString bridges to CFString */ private func addHeader(_ urlRequest: CFHTTPMessage, key: String, val: String) { CFHTTPMessageSetHeaderFieldValue(urlRequest, key as CFString, val as CFString) } /** Generate a WebSocket key as needed in RFC. */ private func generateWebSocketKey() -> String { var key = "" let seed = 16 for _ in 0..<seed { let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25))) key += "\(Character(uni!))" } let data = key.data(using: String.Encoding.utf8) let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return baseKey! } /** Start the stream connection and write the data to the output stream. */ private func initStreamsWithData(_ data: Data, _ port: Int) { //higher level API we will cut over to at some point //NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream) // Disconnect and clean up any existing streams before setting up a new pair disconnectStream(nil, runDelegate: false) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let h = url.host! as NSString CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() guard let inStream = inputStream, let outStream = outputStream else { return } inStream.delegate = self outStream.delegate = self if supportedSSLSchemes.contains(url.scheme!) { certValidated = false inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) if disableSSLCertValidation { let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false), kCFStreamSSLPeerName: kCFNull] inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) } if let cipherSuites = self.enabledSSLCipherSuites { if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?, let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) if resIn != errSecSuccess { let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn)) disconnectStream(error) return } if resOut != errSecSuccess { let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut)) disconnectStream(error) return } } } } else { certValidated = true //not a https session, so no need to check SSL pinning } CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue) CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue) inStream.open() outStream.open() self.mutex.lock() self.readyToWrite = true self.mutex.unlock() let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) var out = timeout * 1_000_000 // wait 5 seconds before giving up let operation = BlockOperation() operation.addExecutionBlock { [weak self, weak operation] in guard let sOperation = operation else { return } while !outStream.hasSpaceAvailable && !sOperation.isCancelled { usleep(100) // wait until the socket is ready guard !sOperation.isCancelled else { return } out -= 100 if out < 0 { WebSocket.sharedWorkQueue.async { self?.cleanupStream() } let errCode = InternalErrorCode.writeTimeoutError.rawValue self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: errCode)) return } else if outStream.streamError != nil { return // disconnectStream will be called. } } guard !sOperation.isCancelled, let s = self else { return } // Do the pinning now if needed if let sec = s.security, !s.certValidated { if let possibleTrust = outStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) { let domain = outStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String s.certValidated = sec.isValid(possibleTrust as! SecTrust, domain: domain) } else { s.certValidated = false } if !s.certValidated { WebSocket.sharedWorkQueue.async { let errCode = InternalErrorCode.invalidSSLError.rawValue let error = s.errorWithDetail("Invalid SSL certificate", code: errCode) s.disconnectStream(error) } return } } outStream.write(bytes, maxLength: data.count) } writeQueue.addOperation(operation) } /** Delegate for the stream methods. Processes incoming bytes */ open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { if eventCode == .hasBytesAvailable { if aStream == inputStream { processInputStream() } } else if eventCode == .errorOccurred { disconnectStream(aStream.streamError as NSError?) } else if eventCode == .endEncountered { disconnectStream(nil) } } /** Disconnect the stream object and notifies the delegate. */ private func disconnectStream(_ error: NSError?, runDelegate: Bool = true) { if error == nil { writeQueue.waitUntilAllOperationsAreFinished() } else { writeQueue.cancelAllOperations() } cleanupStream() connected = false if runDelegate { doDisconnect(error) } } /** cleanup the streams. */ private func cleanupStream() { outputStream?.delegate = nil inputStream?.delegate = nil if let stream = inputStream { CFReadStreamSetDispatchQueue(stream, nil) stream.close() } if let stream = outputStream { CFWriteStreamSetDispatchQueue(stream, nil) stream.close() } outputStream = nil inputStream = nil fragBuffer = nil } /** Handles the incoming bytes and sending them to the proper processing method. */ private func processInputStream() { let buf = NSMutableData(capacity: BUFFER_MAX) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) let length = inputStream!.read(buffer, maxLength: BUFFER_MAX) guard length > 0 else { return } var process = false if inputQueue.count == 0 { process = true } inputQueue.append(Data(bytes: buffer, count: length)) if process { dequeueInput() } } /** Dequeue the incoming input so it is processed in order. */ private func dequeueInput() { while !inputQueue.isEmpty { autoreleasepool { let data = inputQueue[0] var work = data if let buffer = fragBuffer { var combine = NSData(data: buffer) as Data combine.append(data) work = combine fragBuffer = nil } let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self) let length = work.count if !connected { processTCPHandshake(buffer, bufferLen: length) } else { processRawMessagesInBuffer(buffer, bufferLen: length) } inputQueue = inputQueue.filter{ $0 != data } } } } /** Handle checking the inital connection status */ private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) { let code = processHTTP(buffer, bufferLen: bufferLen) switch code { case 0: break case -1: fragBuffer = Data(bytes: buffer, count: bufferLen) break // do nothing, we are going to collect more data default: doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code))) } } /** Finds the HTTP Packet in the TCP stream, by looking for the CRLF. */ private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var k = 0 var totalSize = 0 for i in 0..<bufferLen { if buffer[i] == CRLFBytes[k] { k += 1 if k == 3 { totalSize = i + 1 break } } else { k = 0 } } if totalSize > 0 { let code = validateResponse(buffer, bufferLen: totalSize) if code != 0 { return code } isConnecting = false connected = true didDisconnect = false if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onConnect?() s.delegate?.websocketDidConnect(socket: s) s.advancedDelegate?.websocketDidConnect(socket: s) s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self) } } totalSize += 1 //skip the last \n let restSize = bufferLen - totalSize if restSize > 0 { processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize) } return 0 //success } return -1 // Was unable to find the full TCP header. } /** Validates the HTTP is a 101 as per the RFC spec. */ private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() CFHTTPMessageAppendBytes(response, buffer, bufferLen) let code = CFHTTPMessageGetResponseStatusCode(response) self.advancedDelegate?.websocketHttpUpgrade(socket: self, response: response) if code != httpSwitchProtocolCode { return code } if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { let headers = cfHeaders.takeRetainedValue() as NSDictionary if let extensionHeader = headers[headerWSExtensionName as NSString] as? String { processExtensionHeader(extensionHeader) } if let acceptKey = headers[headerWSAcceptName as NSString] as? NSString { if acceptKey.length > 0 { if headerSecKey.characters.count > 0 { let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64() if sha != acceptKey as String { return -1 } } return 0 } } } return -1 } /** Parses the extension header, setting up the compression parameters. */ func processExtensionHeader(_ extensionHeader: String) { let parts = extensionHeader.components(separatedBy: ";") for p in parts { let part = p.trimmingCharacters(in: .whitespaces) if part == "permessage-deflate" { compressionState.supportsCompression = true } else if part.hasPrefix("server_max_window_bits=") { let valString = part.components(separatedBy: "=")[1] if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { compressionState.serverMaxWindowBits = val } } else if part.hasPrefix("client_max_window_bits=") { let valString = part.components(separatedBy: "=")[1] if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { compressionState.clientMaxWindowBits = val } } else if part == "client_no_context_takeover" { compressionState.clientNoContextTakeover = true } else if part == "server_no_context_takeover" { compressionState.serverNoContextTakeover = true } } if compressionState.supportsCompression { compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits) compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits) } } /** Read a 16 bit big endian value from a buffer */ private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 { return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) } /** Read a 64 bit big endian value from a buffer */ private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 { var value = UInt64(0) for i in 0...7 { value = (value << 8) | UInt64(buffer[offset + i]) } return value } /** Write a 16-bit big endian value to a buffer. */ private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) { buffer[offset + 0] = UInt8(value >> 8) buffer[offset + 1] = UInt8(value & 0xff) } /** Write a 64-bit big endian value to a buffer. */ private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) { for i in 0...7 { buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) } } /** Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process. */ private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> { let response = readStack.last guard let baseAddress = buffer.baseAddress else {return emptyBuffer} let bufferLen = buffer.count if response != nil && bufferLen < 2 { fragBuffer = Data(buffer: buffer) return emptyBuffer } if let response = response, response.bytesLeft > 0 { var len = response.bytesLeft var extra = bufferLen - response.bytesLeft if response.bytesLeft > bufferLen { len = bufferLen extra = 0 } response.bytesLeft -= len response.buffer?.append(Data(bytes: baseAddress, count: len)) _ = processResponse(response) return buffer.fromOffset(bufferLen - extra) } else { let isFin = (FinMask & baseAddress[0]) let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0]) let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue) let isMasked = (MaskMask & baseAddress[1]) let payloadLen = (PayloadLenMask & baseAddress[1]) var offset = 2 if compressionState.supportsCompression && receivedOpcode != .continueFrame { compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0 } if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode)) writeError(errCode) return emptyBuffer } let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping) if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame && receivedOpcode != .textFrame && receivedOpcode != .pong) { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcodeRawValue)", code: errCode)) writeError(errCode) return emptyBuffer } if isControlFrame && isFin == 0 { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode)) writeError(errCode) return emptyBuffer } var closeCode = CloseCode.normal.rawValue if receivedOpcode == .connectionClose { if payloadLen == 1 { closeCode = CloseCode.protocolError.rawValue } else if payloadLen > 1 { closeCode = WebSocket.readUint16(baseAddress, offset: offset) if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1011 && closeCode < 3000) { closeCode = CloseCode.protocolError.rawValue } } if payloadLen < 2 { doDisconnect(errorWithDetail("connection closed by server", code: closeCode)) writeError(closeCode) return emptyBuffer } } else if isControlFrame && payloadLen > 125 { writeError(CloseCode.protocolError.rawValue) return emptyBuffer } var dataLength = UInt64(payloadLen) if dataLength == 127 { dataLength = WebSocket.readUint64(baseAddress, offset: offset) offset += MemoryLayout<UInt64>.size } else if dataLength == 126 { dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) offset += MemoryLayout<UInt16>.size } if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { fragBuffer = Data(bytes: baseAddress, count: bufferLen) return emptyBuffer } var len = dataLength if dataLength > UInt64(bufferLen) { len = UInt64(bufferLen-offset) } if receivedOpcode == .connectionClose && len > 0 { let size = MemoryLayout<UInt16>.size offset += size len -= UInt64(size) } let data: Data if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor { do { data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0) if isFin > 0 && compressionState.serverNoContextTakeover{ try decompressor.reset() } } catch { let closeReason = "Decompression failed: \(error)" let closeCode = CloseCode.encoding.rawValue doDisconnect(errorWithDetail(closeReason, code: closeCode)) writeError(closeCode) return emptyBuffer } } else { data = Data(bytes: baseAddress+offset, count: Int(len)) } if receivedOpcode == .connectionClose { var closeReason = "connection closed by server" if let customCloseReason = String(data: data, encoding: .utf8) { closeReason = customCloseReason } else { closeCode = CloseCode.protocolError.rawValue } doDisconnect(errorWithDetail(closeReason, code: closeCode)) writeError(closeCode) return emptyBuffer } if receivedOpcode == .pong { if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } let pongData: Data? = data.count > 0 ? data : nil s.onPong?(pongData) s.pongDelegate?.websocketDidReceivePong(socket: s, data: pongData) } } return buffer.fromOffset(offset + Int(len)) } var response = readStack.last if isControlFrame { response = nil // Don't append pings. } if isFin == 0 && receivedOpcode == .continueFrame && response == nil { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode)) writeError(errCode) return emptyBuffer } var isNew = false if response == nil { if receivedOpcode == .continueFrame { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("first frame can't be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } isNew = true response = WSResponse() response!.code = receivedOpcode! response!.bytesLeft = Int(dataLength) response!.buffer = NSMutableData(data: data) } else { if receivedOpcode == .continueFrame { response!.bytesLeft = Int(dataLength) } else { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } response!.buffer!.append(data) } if let response = response { response.bytesLeft -= Int(len) response.frameCount += 1 response.isFin = isFin > 0 ? true : false if isNew { readStack.append(response) } _ = processResponse(response) } let step = Int(offset + numericCast(len)) return buffer.fromOffset(step) } } /** Process all messages in the buffer if possible. */ private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) { var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen) repeat { buffer = processOneRawMessage(inBuffer: buffer) } while buffer.count >= 2 if buffer.count > 0 { fragBuffer = Data(buffer: buffer) } } /** Process the finished response of a buffer. */ private func processResponse(_ response: WSResponse) -> Bool { if response.isFin && response.bytesLeft <= 0 { if response.code == .ping { let data = response.buffer! // local copy so it is perverse for writing dequeueWrite(data as Data, code: .pong) } else if response.code == .textFrame { let str: NSString? = NSString(data: response.buffer! as Data, encoding: String.Encoding.utf8.rawValue) if str == nil { writeError(CloseCode.encoding.rawValue) return false } if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onText?(str! as String) s.delegate?.websocketDidReceiveMessage(socket: s, text: str! as String) s.advancedDelegate?.websocketDidReceiveMessage(socket: s, text: str! as String, response: response) } } } else if response.code == .binaryFrame { if canDispatch { let data = response.buffer! // local copy so it is perverse for writing callbackQueue.async { [weak self] in guard let s = self else { return } s.onData?(data as Data) s.delegate?.websocketDidReceiveData(socket: s, data: data as Data) s.advancedDelegate?.websocketDidReceiveData(socket: s, data: data as Data, response: response) } } } readStack.removeLast() return true } return false } /** Create an error */ private func errorWithDetail(_ detail: String, code: UInt16) -> NSError { var details = [String: String]() details[NSLocalizedDescriptionKey] = detail return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details) } /** Write an error to the socket */ private func writeError(_ code: UInt16) { let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) WebSocket.writeUint16(buffer, offset: 0, value: code) dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose) } /** Used to write things to the stream */ private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) { let operation = BlockOperation() operation.addExecutionBlock { [weak self, weak operation] in //stream isn't ready, let's wait guard let s = self else { return } guard let sOperation = operation else { return } var offset = 2 var firstByte:UInt8 = s.FinMask | code.rawValue var data = data if [.textFrame, .binaryFrame].contains(code), let compressor = s.compressionState.compressor { do { data = try compressor.compress(data) if s.compressionState.clientNoContextTakeover { try compressor.reset() } firstByte |= s.RSV1Mask } catch { // TODO: report error? We can just send the uncompressed frame. } } let dataLength = data.count let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize) let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self) buffer[0] = firstByte if dataLength < 126 { buffer[1] = CUnsignedChar(dataLength) } else if dataLength <= Int(UInt16.max) { buffer[1] = 126 WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) offset += MemoryLayout<UInt16>.size } else { buffer[1] = 127 WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) offset += MemoryLayout<UInt64>.size } buffer[1] |= s.MaskMask let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) _ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey) offset += MemoryLayout<UInt32>.size for i in 0..<dataLength { buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size] offset += 1 } var total = 0 while !sOperation.isCancelled { guard let outStream = s.outputStream else { break } let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self) let len = outStream.write(writeBuffer, maxLength: offset-total) if len < 0 { var error: Error? if let streamError = outStream.streamError { error = streamError } else { let errCode = InternalErrorCode.outputStreamWriteError.rawValue error = s.errorWithDetail("output stream error during write", code: errCode) } s.doDisconnect(error as NSError?) break } else { total += len } if total >= offset { if let queue = self?.callbackQueue, let callback = writeCompletion { queue.async { callback() } } break } } } writeQueue.addOperation(operation) } /** Used to preform the disconnect delegate */ private func doDisconnect(_ error: NSError?) { guard !didDisconnect else { return } didDisconnect = true isConnecting = false connected = false guard canDispatch else {return} callbackQueue.async { [weak self] in guard let s = self else { return } s.onDisconnect?(error) s.delegate?.websocketDidDisconnect(socket: s, error: error) s.advancedDelegate?.websocketDidDisconnect(socket: s, error: error) let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] } s.notificationCenter.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo) } } // MARK: - Deinit deinit { mutex.lock() readyToWrite = false mutex.unlock() cleanupStream() writeQueue.cancelAllOperations() } } private extension String { func sha1Base64() -> String { let data = self.data(using: String.Encoding.utf8)! var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) } return Data(bytes: digest).base64EncodedString() } } private extension Data { init(buffer: UnsafeBufferPointer<UInt8>) { self.init(bytes: buffer.baseAddress!, count: buffer.count) } } private extension UnsafeBufferPointer { func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> { return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset) } } private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
97ab0387638a2b8519120c594c4188c6
40.308929
226
0.581161
false
false
false
false
bradvandyk/OpenSim
refs/heads/master
OpenSim/Device.swift
mit
1
// // Device.swift // SimPholders // // Created by Luo Sheng on 11/9/15. // Copyright © 2015 Luo Sheng. All rights reserved. // import Foundation struct Device { enum State: String { case Shutdown = "Shutdown" case Unknown = "Unknown" case Booted = "Booted" } let UDID: String let type: String let name: String let runtime: Runtime let state: State let applications: [Application] init(UDID: String, type: String, name: String, runtime: String, state: State) { self.UDID = UDID self.type = type self.name = name self.runtime = Runtime(name: runtime) self.state = state let applicationPath = URLHelper.deviceURLForUDID(self.UDID).URLByAppendingPathComponent("data/Containers/Bundle/Application") do { let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(applicationPath, includingPropertiesForKeys: nil, options: [.SkipsSubdirectoryDescendants, .SkipsHiddenFiles]) self.applications = contents.map { Application(URL: $0) }.filter { $0 != nil }.map { $0! } } catch { self.applications = [] } } var fullName:String { get { return "\(self.name) (\(self.runtime))" } } func containerURLForApplication(application: Application) -> NSURL? { let URL = URLHelper.containersURLForUDID(UDID) do { let directories = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(URL, includingPropertiesForKeys: nil, options: .SkipsSubdirectoryDescendants) if let matchingURL = directories.filter({ dir -> Bool in if let contents = NSDictionary(contentsOfURL: dir.URLByAppendingPathComponent(".com.apple.mobile_container_manager.metadata.plist")), identifier = contents["MCMMetadataIdentifier"] as? String where identifier == application.bundleID { return true } return false }).first { return matchingURL } else { return nil } } catch { return nil } } }
c8b591d50e5c5412cfb9bab580ec315d
31.782609
197
0.593543
false
false
false
false
jwfriese/FrequentFlyer
refs/heads/master
FrequentFlyer/Time/ElapsedTimePrinter.swift
apache-2.0
1
import Foundation class ElapsedTimePrinter { var timepiece = Timepiece() func printTime(since timeSinceEpochInSeconds: TimeInterval?) -> String { guard let input = timeSinceEpochInSeconds else { return "--" } let inputAsDate = Date(timeIntervalSince1970: input) let now = timepiece.now() let timePassed = now.timeIntervalSince(inputAsDate) if timePassed < 0 { return "--" } if timePassed < 60 { return "\(UInt(timePassed))s ago" } let mins = timePassed / 60 let secondsInHour = TimeInterval(3600) if timePassed < secondsInHour { return "\(UInt(mins))m ago" } let hours = mins / 60 let secondsInDay = TimeInterval(86400) if timePassed < secondsInDay { return "\(UInt(hours))h ago" } let days = hours / 24 return "\(UInt(days))d ago" } }
f63a2cf403522802388ecdd425b9e663
23.846154
76
0.560372
false
false
false
false
DanielAsher/VIPER-SWIFT
refs/heads/master
Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/Control+RxTests+UIKit.swift
mit
2
// // Control+RxTests+UIKit.swift // RxTests // // Created by Ash Furrow on 4/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit import RxSwift import RxCocoa import XCTest extension ControlTests { func testSubscribeEnabledToTrue() { let subject = UIControl() let disposable = Observable.just(true).subscribe(subject.rx_enabled) defer { disposable.dispose() } XCTAssert(subject.enabled == true, "Expected enabled set to true") } func testSubscribeEnabledToFalse() { let subject = UIControl() let disposable = Observable.just(false).subscribe(subject.rx_enabled) defer { disposable.dispose() } XCTAssert(subject.enabled == false, "Expected enabled set to false") } func testSubscribedSelectedToTrue() { let subject = UIControl() let disposable = Observable.just(true).subscribe(subject.rx_selected) defer { disposable.dispose() } XCTAssert(subject.selected == true, "Expected selected set to true") } func testSubscribeSelectedToFalse() { let subject = UIControl() let disposable = Observable.just(false).subscribe(subject.rx_selected) defer { disposable.dispose() } XCTAssert(subject.selected == false, "Expected selected set to false") } } // UITextField extension ControlTests { func testTextField_TextCompletesOnDealloc() { ensurePropertyDeallocated({ UITextField() }, "a") { (view: UITextField) in view.rx_text } } } // Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UIAlertController: 0x7fc6820309c0>) // Don't know why can't use ActionSheet and AlertView inside unit tests // UIBarButtonItem extension ControlTests { func testBarButtonItem_DelegateEventCompletesOnDealloc() { ensureEventDeallocated({ UIBarButtonItem() }) { (view: UIBarButtonItem) in view.rx_tap } } } // UILabel extension ControlTests { func testLabel_HasWeakReference() { let variable = Variable<NSAttributedString?>(nil) ensureControlObserverHasWeakReference(UILabel(), { (label: UILabel) -> AnyObserver<NSAttributedString?> in label.rx_attributedText }, { variable.asObservable() }) } func testLabel_NextElementsSetsValue() { let subject = UILabel() let attributedTextSequence = Variable<NSAttributedString?>(nil) let disposable = attributedTextSequence.asObservable().bindTo(subject.rx_attributedText) defer { disposable.dispose() } attributedTextSequence.value = NSAttributedString(string: "Hello!") XCTAssert(subject.attributedText == attributedTextSequence.value, "Expected attributedText to have been set") } } // UIProgressView extension ControlTests { func testProgressView_HasWeakReference() { ensureControlObserverHasWeakReference(UIProgressView(), { (progressView: UIProgressView) -> AnyObserver<Float> in progressView.rx_progress }, { Variable<Float>(0.0).asObservable() }) } func testProgressView_NextElementsSetsValue() { let subject = UIProgressView() let progressSequence = Variable<Float>(0.0) let disposable = progressSequence.asObservable().bindTo(subject.rx_progress) defer { disposable.dispose() } progressSequence.value = 1.0 XCTAssert(subject.progress == progressSequence.value, "Expected progress to have been set") } } // UIControl extension ControlTests { func testControl_DelegateEventCompletesOnDealloc() { let createView: () -> UIControl = { UIControl(frame: CGRectMake(0, 0, 1, 1)) } ensureEventDeallocated(createView) { (view: UIControl) in view.rx_controlEvent(.AllEditingEvents) } } } // UIGestureRecognizer extension ControlTests { func testGestureRecognizer_DelegateEventCompletesOnDealloc() { let createView: () -> UIGestureRecognizer = { UIGestureRecognizer(target: nil, action: NSSelectorFromString("s")) } ensureEventDeallocated(createView) { (view: UIGestureRecognizer) in view.rx_event } } } // UIScrollView extension ControlTests { func testScrollView_DelegateEventCompletesOnDealloc() { let createView: () -> UIScrollView = { UIScrollView(frame: CGRectMake(0, 0, 1, 1)) } ensurePropertyDeallocated(createView, CGPoint(x: 1, y: 1)) { (view: UIScrollView) in view.rx_contentOffset } } } // UISegmentedControl extension ControlTests { func testSegmentedControl_DelegateEventCompletesOnDealloc() { let createView: () -> UISegmentedControl = { UISegmentedControl(items: ["a", "b", "c"]) } ensurePropertyDeallocated(createView, 1) { (view: UISegmentedControl) in view.rx_value } } } // UITextView extension ControlTests { func testText_DelegateEventCompletesOnDealloc() { let createView: () -> UITextView = { UITextView(frame: CGRectMake(0, 0, 1, 1)) } ensurePropertyDeallocated(createView, "text") { (view: UITextView) in view.rx_text } } } // UIActivityIndicatorView extension ControlTests { func testActivityIndicator_HasWeakReference() { ensureControlObserverHasWeakReference(UIActivityIndicatorView(), { (view: UIActivityIndicatorView) -> AnyObserver<Bool> in view.rx_animating }, { Variable<Bool>(true).asObservable() }) } func testActivityIndicator_NextElementsSetsValue() { let subject = UIActivityIndicatorView() let boolSequence = Variable<Bool>(false) let disposable = boolSequence.asObservable().bindTo(subject.rx_animating) defer { disposable.dispose() } boolSequence.value = true XCTAssertTrue(subject.isAnimating(), "Expected animation to be started") boolSequence.value = false XCTAssertFalse(subject.isAnimating(), "Expected animation to be stopped") } } #if os(iOS) // UIDatePicker extension ControlTests { func testDatePicker_DelegateEventCompletesOnDealloc() { let createView: () -> UIDatePicker = { UIDatePicker(frame: CGRectMake(0, 0, 1, 1)) } ensurePropertyDeallocated(createView, NSDate()) { (view: UIDatePicker) in view.rx_date } } } // UISlider extension ControlTests { func testSlider_DelegateEventCompletesOnDealloc() { let createView: () -> UISlider = { UISlider(frame: CGRectMake(0, 0, 1, 1)) } ensurePropertyDeallocated(createView, 0.5) { (view: UISlider) in view.rx_value } } } // UIStepper extension ControlTests { func testStepper_DelegateEventCompletesOnDealloc() { let createView: () -> UIStepper = { UIStepper(frame: CGRectMake(0, 0, 1, 1)) } ensurePropertyDeallocated(createView, 1) { (view: UIStepper) in view.rx_value } } } // UISwitch extension ControlTests { func testSwitch_DelegateEventCompletesOnDealloc() { let createView: () -> UISwitch = { UISwitch(frame: CGRectMake(0, 0, 1, 1)) } ensurePropertyDeallocated(createView, true) { (view: UISwitch) in view.rx_value } } } // UIButton extension ControlTests { func testButton_tapDeallocates() { let createView: () -> UIButton = { UIButton(frame: CGRectMake(0, 0, 1, 1)) } ensureEventDeallocated(createView) { (view: UIButton) in view.rx_tap } } } #elseif os(tvOS) // UIButton extension ControlTests { func testButton_tapDeallocates() { let createView: () -> UIButton = { UIButton(frame: CGRectMake(0, 0, 1, 1)) } ensureEventDeallocated(createView) { (view: UIButton) in view.rx_primaryAction } } } #endif
6ba59eb2d7be28b44e3fde777c3b7d49
34.00463
192
0.694485
false
true
false
false
IFTTT/RazzleDazzle
refs/heads/master
Example/RazzleDazzleTests/RAZRotationAnimationSpec.swift
mit
1
// // RotationAnimationSpec.swift // RazzleDazzle // // Created by Laura Skelton on 6/17/15. // Copyright (c) 2015 IFTTT. All rights reserved. // import RazzleDazzle import Nimble import Quick class RotationAnimationSpec: QuickSpec { override func spec() { var view: UIView! var animation: RotationAnimation! beforeEach { view = UIView() animation = RotationAnimation(view: view) } describe("RotationAnimation") { it("should add and retrieve keyframes") { animation[2] = 5 expect(animation[2]).to(equal(5)) } it("should add and retrieve negative keyframes") { animation[-2] = 5 expect(animation[-2]).to(equal(5)) } it("should add and retrieve multiple keyframes") { animation[-2] = 3 animation[2] = 5 expect(animation[-2]).to(equal(3)) expect(animation[2]).to(equal(5)) } it("should return the first value for times before the start time") { animation[2] = 3 animation[4] = 5 expect(animation[1]).to(equal(3)) expect(animation[0]).to(equal(3)) } it("should return the last value for times after the end time") { animation[2] = 3 animation[4] = 5 expect(animation[6]).to(equal(5)) expect(animation[10]).to(equal(5)) } it("should apply changes to the view's rotation transform") { animation[1] = 3 animation[3] = 5 let radiansOne = 3 * CGFloat(M_PI / -180.0) let radiansThree = 5 * CGFloat(M_PI / -180.0) animation.animate(1) expect(view.transform == CGAffineTransform(rotationAngle: radiansOne)).to(beTruthy()) animation.animate(3) expect(view.transform == CGAffineTransform(rotationAngle: radiansThree)).to(beTruthy()) } it("should do nothing if no keyframes have been set") { animation.animate(5) expect(view.transform == CGAffineTransform.identity).to(beTruthy()) } } } }
0ab94e926666279d548697b240487ada
34.666667
103
0.518267
false
false
false
false
Purdue-iOS-Dev-Club/Fall-2015-Tutorials
refs/heads/master
ServerClient/DiningCourt/DiningCourt/AppDelegate.swift
mit
1
// // AppDelegate.swift // DiningCourt // // Created by George Lo on 10/5/15. // Copyright © 2015 Purdue iOS Dev Club. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
81dbfd9363541bf362bf1b2352a11538
53.704918
285
0.764759
false
false
false
false
vsubrahmanian/iRemind
refs/heads/master
iRemind/AppDelegate.swift
apache-2.0
2
// // AppDelegate.swift // iRemind // // Created by Vijay Subrahmanian on 03/06/15. // Copyright (c) 2015 Vijay Subrahmanian. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var reminderList: Array<ReminderInfoModel> = [] func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Reading the saved list of reminders from User Defaults. if let aList: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("reminderList") { let unArchivedList: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(aList as! NSData) self.reminderList = unArchivedList as! Array } // Calling our local method to register for local notifications. self.registerForLocalNotifications() // Handle any action if the user opens the application throught the notification. i.e., by clicking on the notification when the application is killed/ removed from background. if let aLaunchOptions = launchOptions { // Checking if there are any launch options. // Check if there are any local notification objects. if let notification = (aLaunchOptions as NSDictionary).objectForKey("UIApplicationLaunchOptionsLocalNotificationKey") as? UILocalNotification { // Handle the notification action on opening. Like updating a table or showing an alert. UIAlertView(title: notification.alertTitle, message: notification.alertBody, delegate: nil, cancelButtonTitle: "OK").show() } } return true } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { // Point for handling the local notification when the app is open. // Showing reminder details in an alertview UIAlertView(title: notification.alertTitle, message: notification.alertBody, delegate: nil, cancelButtonTitle: "OK").show() } func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) { // Point for handling the local notification Action. Provided alongside creating the notification. if identifier == "ShowDetails" { // Showing reminder details in an alertview UIAlertView(title: notification.alertTitle, message: notification.alertBody, delegate: nil, cancelButtonTitle: "OK").show() } else if identifier == "Snooze" { // Snooze the reminder for 5 minutes notification.fireDate = NSDate().dateByAddingTimeInterval(60*5) UIApplication.sharedApplication().scheduleLocalNotification(notification) } else if identifier == "Confirm" { // Confirmed the reminder. Mark the reminder as complete maybe? } completionHandler() } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { let archivedReminderList = NSKeyedArchiver.archivedDataWithRootObject(self.reminderList) NSUserDefaults.standardUserDefaults().setObject(archivedReminderList, forKey: "reminderList") } func applicationWillEnterForeground(application: UIApplication) { } func applicationDidBecomeActive(application: UIApplication) { // Reset the application badge to zero when the application as launched. The notification is viewed. if application.applicationIconBadgeNumber > 0 { application.applicationIconBadgeNumber = 0 } } func applicationWillTerminate(application: UIApplication) { } func registerForLocalNotifications() { // Specify the notification actions. let reminderActionConfirm = UIMutableUserNotificationAction() reminderActionConfirm.identifier = "Confirm" reminderActionConfirm.title = "Confirm" reminderActionConfirm.activationMode = UIUserNotificationActivationMode.Background reminderActionConfirm.destructive = false reminderActionConfirm.authenticationRequired = false let reminderActionSnooze = UIMutableUserNotificationAction() reminderActionSnooze.identifier = "Snooze" reminderActionSnooze.title = "Snooze" reminderActionSnooze.activationMode = UIUserNotificationActivationMode.Background reminderActionSnooze.destructive = true reminderActionSnooze.authenticationRequired = false // Create a category with the above actions let shoppingListReminderCategory = UIMutableUserNotificationCategory() shoppingListReminderCategory.identifier = "reminderCategory" shoppingListReminderCategory.setActions([reminderActionConfirm, reminderActionSnooze], forContext: UIUserNotificationActionContext.Default) shoppingListReminderCategory.setActions([reminderActionConfirm, reminderActionSnooze], forContext: UIUserNotificationActionContext.Minimal) // Register for notification: This will prompt for the user's consent to receive notifications from this app. let notificationSettings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Sound | UIUserNotificationType.Badge, categories: Set(arrayLiteral: shoppingListReminderCategory)) //*NOTE* // Registering UIUserNotificationSettings more than once results in previous settings being overwritten. UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) } }
501650260e454364593b798930a65fc4
52.018349
224
0.733518
false
false
false
false
ole/Ampere
refs/heads/main
Sources/Ampere/Adopters/UnitProductConformances.swift
mit
1
import Foundation /// Speed = Length / Duration ⇔ Length = Speed * Duration /// 1 m/s = 1 m / 1 s extension UnitLength: UnitProduct { public typealias Factor1 = UnitSpeed public typealias Factor2 = UnitDuration public typealias Product = UnitLength public static func defaultUnitMapping() -> (Factor1, Factor2, Product) { return (.metersPerSecond, .seconds, .meters) } public static func preferredUnitMappings() -> [(Factor1, Factor2, Product)] { return [ (.kilometersPerHour, .hours, .kilometers), (.milesPerHour, .hours, .miles), (.knots, .hours, .nauticalMiles) ] } } /// Volume = Area * Length /// 1 m³ = 1 m² * 1 m extension UnitVolume: UnitProduct { public typealias Factor1 = UnitArea public typealias Factor2 = UnitLength public typealias Product = UnitVolume public static func defaultUnitMapping() -> (Factor1, Factor2, Product) { return (.squareMeters, .meters, .cubicMeters) } } /// Acceleration = Speed / Duration ⇔ Speed = Acceleration * Duration /// 1 m/s² = 1 m/s / 1 s extension UnitSpeed: UnitProduct { public typealias Factor1 = UnitAcceleration public typealias Factor2 = UnitDuration public typealias Product = UnitSpeed public static func defaultUnitMapping() -> (Factor1, Factor2, Product) { return (.metersPerSecondSquared, .seconds, .metersPerSecond) } } /// Density = Mass / Volume ⇔ Mass = Density * Volume /// 1 kg/m³ = 1 kg / 1 m³ extension UnitMass: UnitProduct { public typealias Factor1 = UnitConcentrationMass public typealias Factor2 = UnitVolume public typealias Product = UnitMass public static func defaultUnitMapping() -> (Factor1, Factor2, Product) { return (.gramsPerLiter, .liters, .grams) } } /// Resistance = Voltage / Current ⇔ Voltage = Resistance * Current /// 1 Ω = 1 V / 1 A extension UnitElectricPotentialDifference: UnitProduct { public typealias Factor1 = UnitElectricResistance public typealias Factor2 = UnitElectricCurrent public typealias Product = UnitElectricPotentialDifference public static func defaultUnitMapping() -> (Factor1, Factor2, Product) { return (.ohms, .amperes, .volts) } } /// Energy = Power * Duration /// 1 J = 1 W * 1 s extension UnitEnergy: UnitProduct { public typealias Factor1 = UnitPower public typealias Factor2 = UnitDuration public typealias Product = UnitEnergy public static func defaultUnitMapping() -> (Factor1, Factor2, Product) { return (.watts, .seconds, .joules) } } /// Charge = Current * Duration /// 1 C = 1 A * 1 s extension UnitElectricCharge: UnitProduct { public typealias Factor1 = UnitElectricCurrent public typealias Factor2 = UnitDuration public typealias Product = UnitElectricCharge public static func defaultUnitMapping() -> (Factor1, Factor2, Product) { return (.amperes, .seconds, .coulombs) } } /// Force = Mass * Acceleration /// 1 N = 1 kg * 1 m/s² extension UnitForce: UnitProduct { public typealias Factor1 = UnitMass public typealias Factor2 = UnitAcceleration public typealias Product = UnitForce public static func defaultUnitMapping() -> (Factor1, Factor2, Product) { return (.kilograms, .metersPerSecondSquared, .newtons) } } // FIXME: This is currently not expressible because `UnitForce` already conforms to `UnitProduct` for the relation Force = Mass * Acceleration. // Is it necessary to introduce another protocol (like `UnitRatio`) for this? // /// Pressure = Force / Area ⇔ Force = Pressure * Area /// 1 Pa = 1 N / 1 m² //extension UnitForce: UnitProduct { // public typealias Factor1 = UnitPressure // public typealias Factor2 = UnitArea // public typealias Product = UnitForce // // public static func defaultUnitMapping() -> (Factor1, Factor2, Product) { // return (.newtonsPerMetersSquared, .squareMeters, .newtons) // } //}
e3034b611f7a79576f69bc844c6f6b45
32.15
143
0.68552
false
false
false
false
mactive/rw-courses-note
refs/heads/master
your-second-swift-app/CheckList/Checklists/Checklists/ChecklistViewController.swift
mit
1
// // ViewController.swift // Checklists // // Created by Brian on 8/14/17. // Copyright © 2017 Razeware. All rights reserved. // import UIKit class ChecklistViewController: UITableViewController { var items: [ChecklistItem] @IBAction func addItem(_ sender: Any) { // let newRowIndex = items.count let item = ChecklistItem() var titles = ["Empty todo item", "Generic todo", "First todo: fill me out", "I need something to do", "Much todo about nothing"] let randomNumber = arc4random_uniform(UInt32(titles.count)) let title = titles[Int(randomNumber)] item.text = title item.checked = true // items.append(item) // insert at the begining items.insert(item, at: 0) let indexPath = IndexPath(row: 0, section: 0) let indexPaths = [indexPath] tableView.insertRows(at: indexPaths, with: .automatic) } required init?(coder aDecoder: NSCoder) { items = [ChecklistItem]() let row0Item = ChecklistItem() row0Item.text = "Walk the dog" row0Item.checked = false items.append(row0Item) let row1Item = ChecklistItem() row1Item.text = "Brush my teeth" row1Item.checked = false items.append(row1Item) let row2Item = ChecklistItem() row2Item.text = "Learn iOS development" row2Item.checked = false items.append(row2Item) let row3Item = ChecklistItem() row3Item.text = "Soccer pratice" row3Item.checked = false items.append(row3Item) let row4Item = ChecklistItem() row4Item.text = "Eat ice cream" row4Item.checked = false items.append(row4Item) let row5Item = ChecklistItem() row5Item.text = "Watch Game of Thrones" row5Item.checked = true items.append(row5Item) let row6Item = ChecklistItem() row6Item.text = "Read iOS Apprentice" row6Item.checked = true items.append(row6Item) let row7Item = ChecklistItem() row7Item.text = "Take a nap" row7Item.checked = false items.append(row7Item) super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationController?.navigationBar.prefersLargeTitles = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { items.remove(at: indexPath.row); let indexPaths = [indexPath] tableView.deleteRows(at: indexPaths, with: .automatic) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { let item = items[indexPath.row] item.toggleChecked() configureCheckmark(for: cell, with: item) } tableView.deselectRow(at: indexPath, animated: true) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistItem", for: indexPath) let item = items[indexPath.row] configureText(for: cell, with: item) configureCheckmark(for: cell, with: item) return cell } func configureText(for cell: UITableViewCell, with item: ChecklistItem) { let label = cell.viewWithTag(1000) as! UILabel label.text = item.text } func configureCheckmark(for cell: UITableViewCell, with item: ChecklistItem) { if item.checked { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } } }
d9cd0c7edf0db8976cc0d4062085c56e
26.524823
134
0.679464
false
false
false
false
mac-cain13/DocumentStore
refs/heads/master
DocumentStoreTests/Mocks/MockTransaction.swift
mit
1
// // MockTransaction.swift // DocumentStore // // Created by Mathijs Kadijk on 22-11-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation @testable import DocumentStore class MockTransaction: ReadWritableTransaction { var countCalls = 0 var fetchCalls = 0 var deleteQueryCalls = 0 var deleteDocumentCalls = 0 var saveCalls = 0 var persistChangesCalls = 0 var fetchLimitCallback: ((UInt?) -> Void)? func count<DocumentType>(matching query: Query<DocumentType>) throws -> Int { countCalls += 1 return 42 } func fetch<DocumentType>(matching query: Query<DocumentType>) throws -> [DocumentType] { fetchCalls += 1 fetchLimitCallback?(query.limit) guard let data = "{}".data(using: .utf8) else { fatalError("Failed to create data") } return [ try? DocumentType.decode(from: data), try? DocumentType.decode(from: data) ].compactMap { $0 } } @discardableResult func delete<DocumentType>(matching query: Query<DocumentType>) throws -> Int { deleteQueryCalls += 1 return 1 } func delete<DocumentType: Document>(document: DocumentType) throws -> Bool { deleteDocumentCalls += 1 return true } func insert<DocumentType: Document>(document: DocumentType, mode: InsertMode) throws -> Bool { saveCalls += 1 return true } func persistChanges() throws { persistChangesCalls += 1 } }
0f2dcbad50dd89d0cdf5643471d5698e
23.859649
96
0.689485
false
false
false
false
t4thswm/Course
refs/heads/master
Course/AssignmentDetailViewController.swift
gpl-3.0
1
// // AssignmentDetailViewController.swift // Course // // Created by Archie Yu on 2016/12/4. // Copyright © 2016年 Archie Yu. All rights reserved. // import UIKit class AssignmentDetailViewController : UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var assignmentNo = -1 var courseName = "" let max = 16384 var year = 0 var timePicker : UIPickerView? @IBOutlet weak var courseLabel: UILabel! @IBOutlet weak var assignmentContent: UILabel! @IBOutlet weak var assignmentNote: UILabel! @IBOutlet weak var battery: UILabel! @IBOutlet weak var remainingTime: UILabel! @IBOutlet weak var batteryTrailingConstraint: NSLayoutConstraint! var batteryWidth : CGFloat! var timer: Timer! override func viewDidLoad() { super.viewDidLoad() timePicker = UIPickerView() timePicker?.delegate = self timePicker?.dataSource = self batteryWidth = UIScreen.main.bounds.width - 96 fresh() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AssignmentDetailViewController.fresh), userInfo: nil, repeats: true) // 得到当前年份 let curTime = Date() let timeFormatter = DateFormatter() timeFormatter.dateFormat = "yyyy" year = Int(timeFormatter.string(from: curTime))! } override func viewWillAppear(_ animated: Bool) { courseLabel.text = assignmentList[assignmentNo].course assignmentContent.text = assignmentList[assignmentNo].content if assignmentList[assignmentNo].note == "" { assignmentNote.text = "备注" } else { assignmentNote.text = assignmentList[assignmentNo].note } } override func viewDidDisappear(_ animated: Bool) { timer.invalidate() } func fresh() { let current = Date() let end = assignmentList[assignmentNo].endTime let fromNow = end.timeIntervalSince(current) var ratio: CGFloat! // 处理过期任务 if fromNow < 0 { ratio = 0 remainingTime.text = "任务过期" } else { let begin = assignmentList[assignmentNo].beginTime let fromBegin = end.timeIntervalSince(begin) // 计算电量显示条长度和剩余时间 if fromNow > fromBegin { remainingTime.text = "任务还未开始" } else { ratio = CGFloat(fromNow / fromBegin) var sec = Int(fromNow) var min = sec / 60 sec %= 60 var hour = min / 60 min %= 60 let day = hour / 24 hour %= 24 if day > 0 { remainingTime.text = String(format: "剩余时间 %d:%02d:%02d:%02d", arguments: [day, hour, min, sec]) } else if hour > 0 { remainingTime.text = String(format: "剩余时间 %02d:%02d:%02d", arguments: [hour, min, sec]) } else { remainingTime.text = String(format: "剩余时间 %02d:%02d", arguments: [min, sec]) } } } batteryTrailingConstraint.constant = -8 - batteryWidth * (1 - ratio) } @IBAction func checkRemainingTime(_ sender: Any) { let editTimeController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // 编辑开始时间 let beginHandler = {(action:UIAlertAction!) -> Void in let editBeginTimeController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: .actionSheet) // 定义时间选择器占用的空间 let margin : CGFloat = 0.0 let rect = CGRect(x: 0, y: margin, width: editTimeController.view.bounds.size.width, height: 230) self.timePicker?.frame = rect // self.timePicker?.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 0.5) // 选择器初始值设置为开始时间 let beginTime = assignmentList[self.assignmentNo].beginTime let timeFormatter = DateFormatter() timeFormatter.dateFormat = "yyyy" let year = Int(timeFormatter.string(from: beginTime))! timeFormatter.dateFormat = "MM" let month = Int(timeFormatter.string(from: beginTime))! timeFormatter.dateFormat = "dd" let day = Int(timeFormatter.string(from: beginTime))! timeFormatter.dateFormat = "HH" let hour = Int(timeFormatter.string(from: beginTime))! timeFormatter.dateFormat = "mm" let minute = Int(timeFormatter.string(from: beginTime))! let middle = self.max / 2 let yearRow = middle - (middle % 9) + year - self.year + 4 let monthRow = middle - (middle % 12) + month - 1 let dayRow = middle - (middle % 31) + day - 1 let hourRow = middle - (middle % 24) + hour let minuteRow = middle - (middle % 60) + minute self.timePicker?.selectRow(yearRow, inComponent: 0, animated: true) self.timePicker?.selectRow(monthRow, inComponent: 1, animated: true) self.timePicker?.selectRow(dayRow, inComponent: 2, animated: true) self.timePicker?.selectRow(hourRow, inComponent: 3, animated: true) self.timePicker?.selectRow(minuteRow, inComponent: 4, animated: true) // 将时间选择器添加到AlertController的视图中 editBeginTimeController.view.addSubview(self.timePicker!) let confirmHandler = {(action:UIAlertAction!) -> Void in let year = self.year + (self.timePicker?.selectedRow(inComponent: 0))! % 9 - 4 let month = (self.timePicker?.selectedRow(inComponent: 1))! % 12 + 1 let day = (self.timePicker?.selectedRow(inComponent: 2))! % 31 + 1 let hour = (self.timePicker?.selectedRow(inComponent: 3))! % 24 let minute = (self.timePicker?.selectedRow(inComponent: 4))! % 60 var dateComponents = DateComponents() dateComponents.year = year dateComponents.month = month dateComponents.day = day dateComponents.hour = hour dateComponents.minute = minute dateComponents.second = 0 let calendar = Calendar.current let date = calendar.date(from: dateComponents)! assignmentList[self.assignmentNo].beginTime = date } let confirm = UIAlertAction(title: "确定", style: .default, handler: confirmHandler) let cancel = UIAlertAction(title: "取消", style: .default, handler: nil) editBeginTimeController.addAction(confirm) editBeginTimeController.addAction(cancel) self.present(editBeginTimeController, animated: true, completion: nil) } let begin = UIAlertAction(title: "开始时间", style: .default, handler: beginHandler) // 编辑结束时间 let endHandler = {(action:UIAlertAction!) -> Void in let editEndTimeController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: .actionSheet) // 定义时间选择器占用的空间 let margin : CGFloat = 0.0 let rect = CGRect(x: 0, y: margin, width: editTimeController.view.bounds.size.width, height: 230) self.timePicker?.frame = rect // self.timePicker?.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 0.5) // 选择器初始值设置为结束时间 let endTime = assignmentList[self.assignmentNo].endTime let timeFormatter = DateFormatter() timeFormatter.dateFormat = "yyyy" let year = Int(timeFormatter.string(from: endTime))! timeFormatter.dateFormat = "MM" let month = Int(timeFormatter.string(from: endTime))! timeFormatter.dateFormat = "dd" let day = Int(timeFormatter.string(from: endTime))! timeFormatter.dateFormat = "HH" let hour = Int(timeFormatter.string(from: endTime))! timeFormatter.dateFormat = "mm" let minute = Int(timeFormatter.string(from: endTime))! let middle = self.max / 2 let yearRow = middle - (middle % 9) + year - self.year + 4 let monthRow = middle - (middle % 12) + month - 1 let dayRow = middle - (middle % 31) + day - 1 let hourRow = middle - (middle % 24) + hour let minuteRow = middle - (middle % 60) + minute self.timePicker?.selectRow(yearRow, inComponent: 0, animated: true) self.timePicker?.selectRow(monthRow, inComponent: 1, animated: true) self.timePicker?.selectRow(dayRow, inComponent: 2, animated: true) self.timePicker?.selectRow(hourRow, inComponent: 3, animated: true) self.timePicker?.selectRow(minuteRow, inComponent: 4, animated: true) // 将时间选择器添加到AlertController的视图中 editEndTimeController.view.addSubview(self.timePicker!) let confirmHandler = {(action:UIAlertAction!) -> Void in let year = self.year + (self.timePicker?.selectedRow(inComponent: 0))! % 9 - 4 let month = (self.timePicker?.selectedRow(inComponent: 1))! % 12 + 1 let day = (self.timePicker?.selectedRow(inComponent: 2))! % 31 + 1 let hour = (self.timePicker?.selectedRow(inComponent: 3))! % 24 let minute = (self.timePicker?.selectedRow(inComponent: 4))! % 60 var dateComponents = DateComponents() dateComponents.year = year dateComponents.month = month dateComponents.day = day dateComponents.hour = hour dateComponents.minute = minute dateComponents.second = 0 let calendar = Calendar.current let date = calendar.date(from: dateComponents)! assignmentList[self.assignmentNo].endTime = date } let confirm = UIAlertAction(title: "确定", style: .default, handler: confirmHandler) let cancel = UIAlertAction(title: "取消", style: .default, handler: nil) editEndTimeController.addAction(confirm) editEndTimeController.addAction(cancel) self.present(editEndTimeController, animated: true, completion: nil) } let end = UIAlertAction(title: "结束时间", style: .default, handler: endHandler) let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil) editTimeController.addAction(begin) editTimeController.addAction(end) editTimeController.addAction(cancel) self.present(editTimeController, animated: true, completion: nil) } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 5 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return max } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let title = UILabel() title.textColor = UIColor.black title.textAlignment = NSTextAlignment.center switch component { case 0: title.text = String(row % 9 + year - 4) case 1: title.text = String(row % 12 + 1) case 2: title.text = String(row % 31 + 1) case 3: title.text = String(row % 24) case 4: title.text = String(row % 60) default: title.text = "" } return title } }
9e4054091e105eaa9ae3aea97cc7bb19
39.817881
156
0.563316
false
false
false
false
Jnosh/swift
refs/heads/master
stdlib/public/SDK/Foundation/Codable.swift
apache-2.0
4
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Errors //===----------------------------------------------------------------------===// // Adding the following extensions to EncodingError and DecodingError allows them to bridge to NSErrors implicitly. fileprivate let NSCodingPathErrorKey = "NSCodingPath" fileprivate let NSDebugDescriptionErrorKey = "NSDebugDescription" extension EncodingError : CustomNSError { public static var errorDomain: String = NSCocoaErrorDomain public var errorCode: Int { switch self { case .invalidValue(_, _): return CocoaError.coderInvalidValue.rawValue } } public var errorUserInfo: [String : Any] { let context: Context switch self { case .invalidValue(_, let c): context = c } return [NSCodingPathErrorKey: context.codingPath, NSDebugDescriptionErrorKey: context.debugDescription] } } extension DecodingError : CustomNSError { public static var errorDomain: String = NSCocoaErrorDomain public var errorCode: Int { switch self { case .valueNotFound(_, _): fallthrough case .keyNotFound(_, _): return CocoaError._coderValueNotFound.rawValue case .typeMismatch(_, _): fallthrough case .dataCorrupted(_): return CocoaError._coderReadCorrupt.rawValue } } public var errorUserInfo: [String : Any]? { let context: Context switch self { case .typeMismatch(_, let c): context = c case .valueNotFound(_, let c): context = c case .keyNotFound(_, let c): context = c case .dataCorrupted(let c): context = c } return [NSCodingPathErrorKey: context.codingPath, NSDebugDescriptionErrorKey: context.debugDescription] } } //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// internal extension DecodingError { /// Returns a `.typeMismatch` error describing the expected type. /// /// - parameter path: The path of `CodingKey`s taken to decode a value of this type. /// - parameter expectation: The type expected to be encountered. /// - parameter reality: The value that was encountered instead of the expected type. /// - returns: A `DecodingError` with the appropriate path and debug description. internal static func _typeMismatch(at path: [CodingKey?], expectation: Any.Type, reality: Any) -> DecodingError { let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead." return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description)) } /// Returns a description of the type of `value` appropriate for an error message. /// /// - parameter value: The value whose type to describe. /// - returns: A string describing `value`. /// - precondition: `value` is one of the types below. fileprivate static func _typeDescription(of value: Any) -> String { if value is NSNull { return "a null value" } else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ { return "a number" } else if value is String { return "a string/data" } else if value is [Any] { return "an array" } else if value is [String : Any] { return "a dictionary" } else { // This should never happen -- we somehow have a non-JSON type here. preconditionFailure("Invalid storage type \(type(of: value)).") } } }
d2e4a7947c060828a38acd097ac9b2ca
39.361111
175
0.583161
false
false
false
false
petester42/PMCoreDataStack
refs/heads/master
Pod/CoreDataViewModel.swift
mit
1
import UIKit import CoreData import ReactiveCocoa public class CoreDataViewModel: NSObject, NSFetchedResultsControllerDelegate { let willChangeContentSignal:RACSignal = RACSignal.empty() let didChangeObjectSignal:RACSignal = RACSignal.empty() let didChangeSectionSignal:RACSignal = RACSignal.empty() let didChangeContentSignal:RACSignal = RACSignal.empty() let managedObjectContext:NSManagedObjectContext let fetchedResultsController:NSFetchedResultsController public init(objectConext: NSManagedObjectContext, fetchController: NSFetchedResultsController) { managedObjectContext = objectConext fetchedResultsController = fetchController super.init() willChangeContentSignal = willChangeContent() didChangeObjectSignal = didChangeObject() didChangeSectionSignal = didChangeSection() didChangeContentSignal = didChangeContent() fetchedResultsController.delegate = self switch fetchedResultsController.performFetch() { case .Success: break case .Failure(let error): println(error) } } public func numberOfSections() -> Int { if let sections = fetchedResultsController.sections { return sections.count } return 0 } public func numberOfObjectsInSection(section: Int) -> Int { if let sections = fetchedResultsController.sections { let sectionInfo = sections[section] as NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } return 0 } public func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject { return fetchedResultsController.objectAtIndexPath(indexPath) } private func willChangeContent() -> RACSignal { return rac_signalForSelector(Selector("controllerWillChangeContent:"), fromProtocol: NSFetchedResultsControllerDelegate.self).map({ (_) -> AnyObject! in return nil }) } private func didChangeObject() -> RACSignal { return rac_signalForSelector(Selector("controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:"), fromProtocol: NSFetchedResultsControllerDelegate.self).map({ (protocolTuple) -> AnyObject! in let tuple = protocolTuple as RACTuple let indexPath = tuple[2] as NSIndexPath! ?? RACTupleNil() let type = tuple[3] as NSNumber let newIndexPath = tuple[4] as NSIndexPath! ?? RACTupleNil() return RACTuple(objectsFromArray: [indexPath, type, newIndexPath], convertNullsToNils: true) }) } private func didChangeSection() -> RACSignal { return rac_signalForSelector(Selector("controller:didChangeSection:atIndex:forChangeType:"), fromProtocol: NSFetchedResultsControllerDelegate.self).map({ (protocolTuple) -> AnyObject! in let tuple = protocolTuple as RACTuple let sectionIndex = tuple[2] as NSIndexPath! ?? RACTupleNil() let type = tuple[3] as NSNumber return RACTuple(objectsFromArray: [sectionIndex, type], convertNullsToNils: true) }) } private func didChangeContent() -> RACSignal { return rac_signalForSelector(Selector("controllerDidChangeContent:"), fromProtocol: NSFetchedResultsControllerDelegate.self).map({ (_) -> AnyObject! in return nil }) } }
1b63026a462b5739dfabf2e75258186f
33.698113
210
0.644916
false
false
false
false
zach-freeman/swift-localview
refs/heads/master
localview/FlickrConstants.swift
mit
1
// // FlickrConstants.swift // localview // // Created by Zach Freeman on 8/13/15. // Copyright (c) 2021 sparkwing. All rights reserved. // import UIKit class FlickrConstants: NSObject { static let kFlickrApiKey: String = "==redacted==" static let kFlickrUrl: String = "https://www.flickr.com/services/rest/" static let kSearchMethod: String = "flickr.photos.search" static let kFormatType: String = "json" static let kJsonCallback: Int = 1 static let kPrivacyFilter: Int = 1 static let kNumberOfPhotos: String = "100" static let kFlickrPhotoSourceHost: String = "static.flickr.com" static let kTitleNotAvailable: String = "Title not available" static let kSmallImageSize: FlickrApiUtils.FlickrPhotoSize = FlickrApiUtils.FlickrPhotoSize.photoSizeSmallSquare75 static let kBigImageSize: FlickrApiUtils.FlickrPhotoSize = FlickrApiUtils.FlickrPhotoSize.photoSizeLarge1024 static let kMaxTitleSize: String = """ UmjLyNul3eFoj5zVivYVfR18coNUSInD3rRO2ABzwSDzigNATEJTam0HlMVwcoY0LBeK4m4Zhwu0ZC7S24GrONKymeEXVUMDst97IN96caaZw44c94ClHK1X 6sIpSvoSqVejiTu6Fscq12zIi2zwHjROVYwhH4mcvUgGLz3Q06ZCq8fuxwUGBcK3n9h6SXqj3EnRjHF182yXoNN9eM4PW3ZUHgh0y449WnAHpTIex46ys8q3 itu9GTTSPXGeVLG """ }
2f2fa7c5df897d50989db34d67ebdd30
41.928571
120
0.810316
false
false
false
false
gu704823/huobanyun
refs/heads/master
huobanyun/guideViewController.swift
mit
1
// // guideViewController.swift // huobanyun // // Created by AirBook on 2017/6/26. // Copyright © 2017年 AirBook. All rights reserved. // import UIKit class guideViewController: UIViewController { //定义 var pagecontrol = UIPageControl() var startbtn = UIButton() fileprivate var scrollview:UIScrollView! fileprivate var numberofpages = 4 fileprivate let frame = UIScreen.main.bounds override func viewDidLoad() { super.viewDidLoad() scrollview = UIScrollView(frame: frame) scrollview.isPagingEnabled = true scrollview.showsHorizontalScrollIndicator = false scrollview.showsVerticalScrollIndicator = false scrollview.scrollsToTop = false scrollview.bounces = false scrollview.contentOffset = CGPoint.zero scrollview.contentSize = CGSize(width: frame.size.width*CGFloat(numberofpages), height: frame.size.height) scrollview.delegate = self for index in 0..<numberofpages{ let imageview = UIImageView(image: UIImage(named: "guideimage\(index+1)")) imageview.frame = CGRect(x: frame.size.width*CGFloat(index), y: 0, width: frame.size.width, height: frame.size.height) scrollview.addSubview(imageview) } self.view.insertSubview(scrollview, at: 0) //开始按钮 let btnW = 0.25*frame.size.width let btnx = frame.size.width/2 - btnW/2 let btny = 0.8*frame.size.height let btnH = btnW*0.4 startbtn.frame = CGRect(x: btnx, y:frame.size.height, width: btnW, height: btnH) startbtn.setTitle("开始体验", for: .normal) startbtn.backgroundColor = UIColor.gray startbtn.setTitleColor(UIColor.purple, for: .highlighted) startbtn.layer.cornerRadius = 10 startbtn.layer.masksToBounds = true startbtn.alpha = 0 startbtn.addTarget(self, action: #selector(btnclick), for: .touchUpInside) self.view.addSubview(startbtn) pagecontrol.frame = CGRect(x: btnx, y: btny*1.18, width: btnW, height: btnH) pagecontrol.numberOfPages = numberofpages pagecontrol.pageIndicatorTintColor = UIColor.black pagecontrol.currentPageIndicatorTintColor = UIColor.red self.view.addSubview(pagecontrol) } @objc fileprivate func btnclick(){ let vc = UIStoryboard(name: "loginanderegisiter", bundle: Bundle.main).instantiateInitialViewController()! show(vc, sender: nil) } //隐藏状态栏 override var prefersStatusBarHidden: Bool{ return true } } extension guideViewController:UIScrollViewDelegate{ func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset let a = Int(offset.x/view.bounds.width) pagecontrol.currentPage = a // print(a,offset.x,view.bounds.width) if a == numberofpages - 1{ UIView.animate(withDuration: 0.5, animations: { self.startbtn.frame.origin.y = (self.frame.height)*0.8 self.startbtn.alpha = 1 }) }else{ UIView.animate(withDuration: 0.2, animations: { self.startbtn.frame.origin.y = self.frame.height self.startbtn.alpha = 0 }) } } }
badad232044e3b2469177815856cf3d4
37.264368
130
0.642235
false
false
false
false
curoo/ConfidoIOS
refs/heads/master
ConfidoIOS/KeychainKey.swift
mit
3
// // KeychainKey.swift // ExpendSecurity // // Created by Rudolph van Graan on 21/08/2015. // // import Foundation import CommonCrypto extension SecIdentity { func certificateRef() throws -> SecCertificate { var certificateRef: SecCertificate? = nil try ensureOK(SecIdentityCopyCertificate(self, &certificateRef)) return certificateRef! } func privateKeyRef() throws -> SecKey { var keyRef: SecKey? = nil try ensureOK(SecIdentityCopyPrivateKey(self, &keyRef)) return keyRef! } } open class KeychainKey : KeychainItem, KeychainKeyClassProperties { open class func keychainKeyFromAttributes(SecItemAttributes attributes: SecItemAttributes) throws -> KeychainKey { let keyClass = KeyClass.keyClass(attributes[String(kSecAttrKeyClass)]) switch keyClass { case .privateKey: return try KeychainPrivateKey(SecItemAttributes: attributes) case .publicKey: return try KeychainPublicKey(SecItemAttributes: attributes) default: return try KeychainKey(SecItemAttributes: attributes) } } var keySecKey: SecKey? public init(descriptor: KeychainKeyDescriptor, keyRef: SecKey) { keySecKey = keyRef super.init(securityClass: .key, byCopyingAttributes: descriptor) } public init(SecItemAttributes attributes: SecItemAttributes) throws { super.init(securityClass: SecurityClass.key, SecItemAttributes: attributes) self.keySecKey = try KeychainKey.getKeySecKey(SecItemAttributes: attributes as NSDictionary) } class func getKeySecKey(SecItemAttributes attributes: NSDictionary) throws -> SecKey { if let valueRef = attributes[String(kSecValueRef)] { if CFGetTypeID(valueRef as CFTypeRef!) == SecKeyGetTypeID() { return (valueRef as! SecKey) } else if CFGetTypeID(valueRef as CFTypeRef!) == SecIdentityGetTypeID() { let secIdentity = (valueRef as! SecIdentity) return try secIdentity.privateKeyRef() } } fatalError("No SecKey Reference") } override open func specifierMatchingProperties() -> Set<String> { return kKeyItemMatchingProperties } func ensureRSAOrECKey() throws { if (self.keyType == KeyType.rsa) { return } if (self.keyType == KeyType.elypticCurve) { return } throw KeychainError.unimplementedKeyType(reason: "Not implemented for key types other than RSA or EC") } } /** An instance of an IOS Keychain Public Key */ open class KeychainSymmetricKey : KeychainKey, KeychainFindable, GenerateKeychainFind { //This specifies the argument type and return value for the generated functions public typealias QueryType = KeychainKeyDescriptor public typealias ResultType = KeychainSymmetricKey override public init(descriptor: KeychainKeyDescriptor, keyRef: SecKey) { super.init(descriptor: descriptor, keyRef: keyRef) attributes[String(kSecAttrKeyClass)] = KeyClass.kSecAttrKeyClass(.symmetricKey) } public override init(SecItemAttributes attributes: SecItemAttributes) throws { try super.init(SecItemAttributes: attributes) self.attributes[String(kSecAttrKeyClass)] = KeyClass.kSecAttrKeyClass(.symmetricKey) } open func withKeyDataDo(_ closure : (Data)-> Void ) throws { // this key's keyData is cryptographic key material and should not be passed around or stored. // Use this very carefully let keyData = try fetchKeyData(self) closure(keyData) } } func fetchKeyData(_ key: KeychainKey) throws -> Data { var query : KeyChainPropertiesData = [ : ] let descriptor = key.keychainMatchPropertyValues() query[String(kSecClass)] = SecurityClass.kSecClass(key.securityClass) query[String(kSecReturnData)] = kCFBooleanTrue query[String(kSecMatchLimit)] = kSecMatchLimitOne query += descriptor.keychainMatchPropertyValues() let keyData: Data = try SecurityWrapper.secItemCopyMatching(query) return keyData } extension KeychainSymmetricKey { }
7b72b518934c7886bd1bddc8626cc0d6
35.069565
118
0.702748
false
false
false
false
dangquochoi2007/cleancodeswift
refs/heads/master
CleanStore/CleanStore/App/Scenes/WatchLists/View/UIView/WatchListMoviesCollectionViewCell.swift
mit
1
// // WatchListMoviesCollectionViewCell.swift // CleanStore // // Created by hoi on 28/6/17. // Copyright © 2017 hoi. All rights reserved. // import UIKit class WatchListMoviesCollectionViewCell: UICollectionViewCell { lazy var moviesImageView:UIImageView = UIImageView(image: UIImage(named: "film")) override init(frame: CGRect) { super.init(frame: frame) configureViewWhenLoad() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code configureViewWhenLoad() } func configureViewWhenLoad() { [moviesImageView].forEach { $0.contentMode = .scaleAspectFill $0.translatesAutoresizingMaskIntoConstraints = false $0.clipsToBounds = true contentView.addSubview($0) } let attributes: [NSLayoutAttribute] = [.top, .left, .bottom, .right] for attribute in attributes { contentView.addConstraint(NSLayoutConstraint(item: moviesImageView, attribute: attribute, relatedBy: .equal, toItem: contentView, attribute: attribute, multiplier: 1, constant: 0)) } } }
0f60d1a28521e1b17c23d1ed1fd65491
26.375
192
0.631659
false
true
false
false
quickthyme/PUTcat
refs/heads/master
Tests/iOS/Environment/EnvironmentPresenterSpy.swift
apache-2.0
1
import UIKit class EnvironmentPresenterSpy : EnvironmentPresenter { var ucFetchEnvironmentListWasCalled = false var ucAddEnvironmentWasCalled = false var ucUpdateEnvironmentWasCalled = false var ucUpdateEnvironmentParameter_name: String? var ucUpdateEnvironmentParameter_id: String? var ucDeleteEnvironmentWasCalled = false var ucDeleteEnvironmentParameter_environmentID: String? var ucSortEnvironmentListWasCalled = false var ucSortEnvironmentListParameter_ordinality: [String]? var ucBuildFullyConstructedEnvironmentWasCalled = false var ucBuildFullyConstructedEnvironmentParameter_name: String? override func ucFetchEnvironmentList() -> Composed.Action<Any, PCList<PCEnvironment>> { ucFetchEnvironmentListWasCalled = true return createAction_EnvironmentList() } override func ucAddEnvironment() -> Composed.Action<Any, PCList<PCEnvironment>> { ucAddEnvironmentWasCalled = true return createAction_EnvironmentList() } override func ucUpdateEnvironment(name: String, id: String) -> Composed.Action<Any, PCList<PCEnvironment>> { ucUpdateEnvironmentWasCalled = true ucUpdateEnvironmentParameter_name = name ucUpdateEnvironmentParameter_id = id return createAction_EnvironmentList() } override func ucDeleteEnvironment(environmentID: String) -> Composed.Action<Any, PCList<PCEnvironment>> { ucDeleteEnvironmentWasCalled = true ucDeleteEnvironmentParameter_environmentID = environmentID return createAction_EnvironmentList() } override func ucSortEnvironmentList(ordinality ids: [String]) -> Composed.Action<Any, PCList<PCEnvironment>> { ucSortEnvironmentListWasCalled = true ucSortEnvironmentListParameter_ordinality = ids return createAction_EnvironmentList() } override func ucBuildFullyConstructedEnvironment(name: String) -> Composed.Action<Any, PCEnvironment> { ucBuildFullyConstructedEnvironmentWasCalled = true ucBuildFullyConstructedEnvironmentParameter_name = name return createAction_Environment() } // Fake Data func createAction_EnvironmentList() -> Composed.Action<Any, PCList<PCEnvironment>> { return Composed.Action<Any, PCList<PCEnvironment>> { _, completion in completion(.success(self.createEnvironmentList())) } } func createAction_Environment() -> Composed.Action<Any, PCEnvironment> { return Composed.Action<Any, PCEnvironment> { _, completion in completion(.success(self.createEnvironment())) } } func createEnvironmentList() -> PCList<PCEnvironment> { return PCList<PCEnvironment>(items: [ PCEnvironment(id: "987", name: "Environment 1"), PCEnvironment(id: "654", name: "Environment 2") ] ) } func createEnvironment() -> PCEnvironment { return PCEnvironment(id: "987", name: "Environment 1") } }
7163fe0eebb6202c67e4e3d24a0924f8
36.407407
114
0.711221
false
false
false
false
0gajun/mal
refs/heads/cpp14
swift3/Sources/step1_read_print/main.swift
mpl-2.0
15
import Foundation // read func READ(_ str: String) throws -> MalVal { return try read_str(str) } // eval func EVAL(_ ast: MalVal, _ env: String) throws -> MalVal { return ast } // print func PRINT(_ exp: MalVal) -> String { return pr_str(exp, true) } // repl func rep(_ str:String) throws -> String { return PRINT(try EVAL(try READ(str), "")) } while true { print("user> ", terminator: "") let line = readLine(strippingNewline: true) if line == nil { break } if line == "" { continue } do { print(try rep(line!)) } catch (MalError.Reader(let msg)) { print("Error: \(msg)") } }
b3eebdb1993a339149b3815dbf54e340
17.4
58
0.57764
false
false
false
false
wireapp/wire-ios-data-model
refs/heads/develop
Source/Model/Conversation/ZMConversation+Participants.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 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 WireProtos public enum ConversationRemoveParticipantError: Error { case unknown, invalidOperation, conversationNotFound } public enum ConversationAddParticipantsError: Error { case unknown, invalidOperation, accessDenied, notConnectedToUser, conversationNotFound, tooManyMembers, missingLegalHoldConsent } public class AddParticipantAction: EntityAction { public var resultHandler: ResultHandler? public typealias Result = Void public typealias Failure = ConversationAddParticipantsError public let userIDs: [NSManagedObjectID] public let conversationID: NSManagedObjectID public required init(users: [ZMUser], conversation: ZMConversation) { userIDs = users.map(\.objectID) conversationID = conversation.objectID } } public class RemoveParticipantAction: EntityAction { public var resultHandler: ResultHandler? public typealias Result = Void public typealias Failure = ConversationRemoveParticipantError public let userID: NSManagedObjectID public let conversationID: NSManagedObjectID public required init(user: ZMUser, conversation: ZMConversation) { userID = user.objectID conversationID = conversation.objectID } } extension ZMConversation { func sortedUsers(_ users: Set<ZMUser>) -> [ZMUser] { let nameDescriptor = NSSortDescriptor(key: "normalizedName", ascending: true) let sortedUser = (users as NSSet?)?.sortedArray(using: [nameDescriptor]) as? [ZMUser] return sortedUser ?? [] } @objc public var sortedActiveParticipants: [ZMUser] { return sortedUsers(localParticipants) } /// Whether the roles defined for this conversation should be re-downloaded @NSManaged public var needsToDownloadRoles: Bool @objc public var isSelfAnActiveMember: Bool { return self.participantRoles.contains(where: { (role) -> Bool in role.user?.isSelfUser == true }) } // MARK: - keyPathsForValuesAffecting static var participantRolesKeys: [String] { return [#keyPath(ZMConversation.participantRoles)] } @objc public class func keyPathsForValuesAffectingActiveParticipants() -> Set<String> { return Set(participantRolesKeys) } @objc public class func keyPathsForValuesAffectingLocalParticipants() -> Set<String> { return Set(participantRolesKeys) } @objc public class func keyPathsForValuesAffectingLocalParticipantRoles() -> Set<String> { return Set(participantRolesKeys + [#keyPath(ZMConversation.participantRoles.role)]) } @objc public class func keyPathsForValuesAffectingDisplayName() -> Set<String> { return Set([ZMConversationConversationTypeKey, "participantRoles.user.name", "connection.to.name", "connection.to.availability", ZMConversationUserDefinedNameKey] + ZMConversation.participantRolesKeys) } @objc public class func keyPathsForValuesAffectingLocalParticipantsExcludingSelf() -> Set<String> { return Set(ZMConversation.participantRolesKeys) } // MARK: - Participant actions public func addParticipants(_ participants: [UserType], completion: @escaping AddParticipantAction.ResultHandler) { guard let context = managedObjectContext else { return completion(.failure(ConversationAddParticipantsError.unknown)) } let users = participants.materialize(in: context) guard conversationType == .group, !users.isEmpty, !users.contains(ZMUser.selfUser(in: context)) else { return completion(.failure(ConversationAddParticipantsError.invalidOperation)) } var action = AddParticipantAction(users: users, conversation: self) action.onResult(resultHandler: completion) action.send(in: context.notificationContext) } public func removeParticipant(_ participant: UserType, completion: @escaping RemoveParticipantAction.ResultHandler) { guard let context = managedObjectContext else { return completion(.failure(ConversationRemoveParticipantError.unknown)) } guard conversationType == .group, let user = participant as? ZMUser else { return completion(.failure(ConversationRemoveParticipantError.invalidOperation)) } var action = RemoveParticipantAction(user: user, conversation: self) action.onResult(resultHandler: completion) action.send(in: context.notificationContext) } // MARK: - Participants methods /// Participants that are in the conversation, according to the local state, /// even if that state is not yet synchronized with the backend @objc public var localParticipantRoles: Set<ParticipantRole> { return participantRoles } /// Participants that are in the conversation, according to the local state /// even if that state is not yet synchronized with the backend @objc public var localParticipants: Set<ZMUser> { return Set(localParticipantRoles.compactMap { $0.user }) } /// Participants that are in the conversation, according to the local state /// even if that state is not yet synchronized with the backend @objc public var localParticipantsExcludingSelf: Set<ZMUser> { return self.localParticipants.filter { !$0.isSelfUser } } // MARK: - Participant operations /// Add participants to the conversation. The method will decide on its own whether /// this operation need to be synchronized to the backend or not based on the current context. /// If the operation is executed from the UI context, then the operation will be synchronized. /// If the operation is executed from the sync context, then the operation will not be synchronized. /// /// The method will handle the case when the participant is already there, so it's safe to call /// it multiple time for the same user. It will update the role if the user is already there with /// a different role. /// /// The method will also check if the addition of the users will change the verification status, the archive /// status, etc. @objc public func addParticipantAndUpdateConversationState(user: ZMUser, role: Role?) { self.addParticipantsAndUpdateConversationState(usersAndRoles: [(user, role)]) } /// Add participants to the conversation. The method will decide on its own whether /// this operation need to be synchronized to the backend or not based on the current context. /// If the operation is executed from the UI context, then the operation will be synchronized. /// If the operation is executed from the sync context, then the operation will not be synchronized. /// /// The method will handle the case when the participant is already there, so it's safe to call /// it multiple time for the same user. It will update the role if the user is already there with /// a different role. /// /// The method will also check if the addition of the users will change the verification status, the archive /// status, etc. @objc public func addParticipantsAndUpdateConversationState(users: Set<ZMUser>, role: Role?) { self.addParticipantsAndUpdateConversationState(usersAndRoles: users.map { ($0, role) }) } /// Add participants to the conversation. The method will decide on its own whether /// this operation need to be synchronized to the backend or not based on the current context. /// If the operation is executed from the UI context, then the operation will be synchronized. /// If the operation is executed from the sync context, then the operation will not be synchronized. /// /// The method will handle the case when the participant is already there, so it's safe to call /// it multiple time for the same user. It will update the role if the user is already there with /// a different role. /// /// The method will also check if the addition of the users will change the verification status, the archive /// status, etc. public func addParticipantsAndUpdateConversationState(usersAndRoles: [(ZMUser, Role?)]) { // Is this a new conversation, or an existing one that is being updated? let doesExistsOnBackend = self.remoteIdentifier != nil let addedRoles = usersAndRoles.compactMap { (user, role) -> ParticipantRole? in guard !user.isAccountDeleted else { return nil } // make sure the role is the right team/conversation role require( role == nil || (role!.team == self.team || role!.conversation == self), "Tried to add a role that does not belong to the conversation" ) guard let (result, pr) = updateExistingOrCreateParticipantRole(for: user, with: role) else { return nil } return (result == .created) ? pr : nil } let addedSelfUser = doesExistsOnBackend && addedRoles.contains(where: {$0.user?.isSelfUser == true}) if addedSelfUser { self.markToDownloadRolesIfNeeded() self.needsToBeUpdatedFromBackend = true } if !addedRoles.isEmpty { self.checkIfArchivedStatusChanged(addedSelfUser: addedSelfUser) self.checkIfVerificationLevelChanged(addedUsers: Set(addedRoles.compactMap { $0.user }), addedSelfUser: addedSelfUser) } } private enum FetchOrCreation { case fetched case created } // Fetch an existing role or create a new one if needed // Returns whether it was created or found private func updateExistingOrCreateParticipantRole(for user: ZMUser, with role: Role?) -> (FetchOrCreation, ParticipantRole)? { guard let moc = self.managedObjectContext else { return nil } // If the user is already there, just change the role if let current = self.participantRoles.first(where: {$0.user == user}) { if let role = role { current.role = role } return (.fetched, current) } else { // A new participant role let participantRole = ParticipantRole.insertNewObject(in: moc) participantRole.conversation = self participantRole.user = user participantRole.role = role return (.created, participantRole) } } private func checkIfArchivedStatusChanged(addedSelfUser: Bool) { if addedSelfUser && self.mutedStatus == MutedMessageOptionValue.none.rawValue && self.isArchived { self.isArchived = false } } private func checkIfVerificationLevelChanged(addedUsers: Set<ZMUser>, addedSelfUser: Bool) { let clients = Set(addedUsers.flatMap { $0.clients }) self.decreaseSecurityLevelIfNeededAfterDiscovering(clients: clients, causedBy: addedUsers) if addedSelfUser { self.increaseSecurityLevelIfNeededAfterTrusting(clients: clients) } } /// Remove participants to the conversation. The method will decide on its own whether /// this operation need to be synchronized to the backend or not based on the current context. /// If the operation is executed from the UI context, then the operation will be synchronized. /// If the operation is executed from the sync context, then the operation will not be synchronized. /// /// The method will handle the case when the participant is not there, so it's safe to call /// it even if the user is not there. /// /// The method will also check if the addition of the users will change the verification status, the archive /// status, etc. @objc public func removeParticipantsAndUpdateConversationState(users: Set<ZMUser>, initiatingUser: ZMUser? = nil) { guard let moc = self.managedObjectContext else { return } let existingUsers = Set(self.participantRoles.map { $0.user }) let removedUsers = Set(users.compactMap { user -> ZMUser? in guard existingUsers.contains(user), let existingRole = participantRoles.first(where: { $0.user == user }) else { return nil } participantRoles.remove(existingRole) moc.delete(existingRole) return user }) if !removedUsers.isEmpty { let removedSelf = removedUsers.contains(where: { $0.isSelfUser }) self.checkIfArchivedStatusChanged(removedSelfUser: removedSelf, initiatingUser: initiatingUser) self.checkIfVerificationLevelChanged(removedUsers: removedUsers) } } /// Remove participants to the conversation. The method will decide on its own whether /// this operation need to be synchronized to the backend or not based on the current context. /// If the operation is executed from the UI context, then the operation will be synchronized. /// If the operation is executed from the sync context, then the operation will not be synchronized. /// /// The method will handle the case when the participant is not there, so it's safe to call /// it even if the user is not there. /// /// The method will also check if the addition of the users will change the verification status, the archive /// status, etc. @objc public func removeParticipantAndUpdateConversationState(user: ZMUser, initiatingUser: ZMUser? = nil) { self.removeParticipantsAndUpdateConversationState(users: Set(arrayLiteral: user), initiatingUser: initiatingUser) } private func checkIfArchivedStatusChanged(removedSelfUser: Bool, initiatingUser: ZMUser?) { if removedSelfUser, let initiatingUser = initiatingUser { self.isArchived = initiatingUser.isSelfUser } } private func checkIfVerificationLevelChanged(removedUsers: Set<ZMUser>) { self.increaseSecurityLevelIfNeededAfterRemoving(users: removedUsers) } // MARK: - Conversation roles /// List of roles for the conversation whether it's linked with a team or not @objc public func getRoles() -> Set<Role> { if let team = team { return team.roles } return nonTeamRoles } /// Check if roles are missing, and mark them to download if needed @objc public func markToDownloadRolesIfNeeded() { guard conversationType == .group, !isTeamConversation else { return } // if there are no roles with actions if nonTeamRoles.isEmpty || !nonTeamRoles.contains(where: { !$0.actions.isEmpty }) { needsToDownloadRoles = true } } // MARK: - Utils func has(participantWithId userId: Proteus_UserId?) -> Bool { return localParticipants.contains { $0.userId == userId } } }
cf2e806948daa2f206d657d90190499e
38.467822
131
0.677516
false
false
false
false
alltheflow/iCopyPasta
refs/heads/master
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/Driver+Extensions.swift
mit
2
// // Driver+Extensions.swift // Tests // // Created by Krunoslav Zaher on 12/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation extension Driver : Equatable { } public func == <T>(lhs: Driver<T>, rhs: Driver<T>) -> Bool { return lhs.asObservable() === rhs.asObservable() }
41b126af7cf7c45c737b9e673ddd7530
17.882353
60
0.6625
false
true
false
false
siemensikkema/Fairness
refs/heads/master
FairnessTests/Participant.swift
mit
1
import UIKit typealias NameChangeCallback = () -> () class Participant { var balance = 0.0 var nameOrNil: String? { didSet { nameChangeCallback?() } } var nameChangeCallback: NameChangeCallback? init(name: String? = nil, nameChangeCallback: NameChangeCallback? = nil, balance: Double = 0.0) { self.balance = balance self.nameOrNil = name self.nameChangeCallback = nameChangeCallback } } extension Participant: DebugPrintable { var debugDescription: String { return "name: \(nameOrNil), balance: \(balance) hash: \(hashValue)" } } extension Participant: Hashable, Equatable { var hashValue: Int { return ObjectIdentifier(self).hashValue } } func ==(lhs: Participant, rhs: Participant) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) }
027c3ccc1c7bcba85c8110287b895217
24.205882
104
0.660047
false
false
false
false
cotkjaer/SilverbackFramework
refs/heads/master
SilverbackFramework/NSError.swift
mit
1
// // NSError.swift // SilverbackFramework // // Created by Christian Otkjær on 21/04/15. // Copyright (c) 2015 Christian Otkjær. All rights reserved. // import Foundation import UIKit extension NSError { public class var defaultAsyncErrorHandler : ((NSError) -> Void) { return { (error: NSError) -> Void in error.presentAsAlert() } } public convenience init( domain: String, code: Int, description: String? = nil, reason: String? = nil, underlyingError: NSError? = nil) { var errorUserInfo: [String : AnyObject] = [:] if description != nil { errorUserInfo[NSLocalizedDescriptionKey] = description ?? "" } if reason != nil { errorUserInfo[NSLocalizedFailureReasonErrorKey] = reason ?? "" } if underlyingError != nil { errorUserInfo[NSUnderlyingErrorKey] = underlyingError } self.init(domain: domain, code: code, userInfo: errorUserInfo) } public func presentAsAlert(handler:(() -> Void)? = nil) { presentInViewController(nil, withHandler: handler) } // public func presentInViewController(controller: UIViewController?) // { // let alertController = UIAlertController(title: self.localizedDescription, message: self.localizedFailureReason, preferredStyle: .Alert) // // //TODO: localizedRecoveryOptions and localizedRecoverySuggestion // // // let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in // // // ... // // } // // alertController.addAction(cancelAction) // // let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in // // println("Ignored Error: \(self)") // } // alertController.addAction(OKAction) // // controller?.presentViewController(alertController, animated: true) { NSLog("Showing error: \(self)") } // } public func presentInViewController(controller: UIViewController?, withHandler handler:(() -> Void)? = nil) { let alertController = UIAlertController(title: self.localizedDescription, message: self.localizedFailureReason, preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in if let realHandler = handler { realHandler() } else { debugPrint("Ignored Error: \(self)") } } alertController.addAction(OKAction) if let realController = controller ?? UIApplication.topViewController() { realController.presentViewController(alertController, animated: true) { debugPrint("Showing error: \(self)") } } else { debugPrint("ERROR could not be presented: \(self)") } } }
ececd9ee28f8fe837fe721e9f35b2d21
31.138298
145
0.579139
false
false
false
false
FreddyZeng/Charts
refs/heads/master
Source/Charts/Renderers/YAxisRenderer.swift
apache-2.0
1
// // YAxisRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif @objc(ChartYAxisRenderer) open class YAxisRenderer: AxisRendererBase { @objc public init(viewPortHandler: ViewPortHandler, yAxis: YAxis?, transformer: Transformer?) { super.init(viewPortHandler: viewPortHandler, transformer: transformer, axis: yAxis) } /// draws the y-axis labels to the screen open override func renderAxisLabels(context: CGContext) { guard let yAxis = self.axis as? YAxis else { return } if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled { return } let xoffset = yAxis.xOffset let yoffset = yAxis.labelFont.lineHeight / 2.5 + yAxis.yOffset let dependency = yAxis.axisDependency let labelPosition = yAxis.labelPosition var xPos = CGFloat(0.0) var textAlign: NSTextAlignment if dependency == .left { if labelPosition == .outsideChart { textAlign = .right xPos = viewPortHandler.offsetLeft - xoffset } else { textAlign = .left xPos = viewPortHandler.offsetLeft + xoffset } } else { if labelPosition == .outsideChart { textAlign = .left xPos = viewPortHandler.contentRight + xoffset } else { textAlign = .right xPos = viewPortHandler.contentRight - xoffset } } drawYLabels( context: context, fixedPosition: xPos, positions: transformedPositions(), offset: yoffset - yAxis.labelFont.lineHeight, textAlign: textAlign) } open override func renderAxisLine(context: CGContext) { guard let yAxis = self.axis as? YAxis else { return } if !yAxis.isEnabled || !yAxis.drawAxisLineEnabled { return } context.saveGState() context.setStrokeColor(yAxis.axisLineColor.cgColor) context.setLineWidth(yAxis.axisLineWidth) if yAxis.axisLineDashLengths != nil { context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if yAxis.axisDependency == .left { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) context.strokePath() } else { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } /// draws the y-labels on the specified x-position internal func drawYLabels( context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat, textAlign: NSTextAlignment) { guard let yAxis = self.axis as? YAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor let from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1 let to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1) for i in stride(from: from, to: to, by: 1) { let text = yAxis.getFormattedLabel(i) ChartUtils.drawText( context: context, text: text, point: CGPoint(x: fixedPosition, y: positions[i].y + offset), align: textAlign, attributes: [NSAttributedStringKey.font: labelFont, NSAttributedStringKey.foregroundColor: labelTextColor]) } } open override func renderGridLines(context: CGContext) { guard let yAxis = self.axis as? YAxis else { return } let leftSpace: CGFloat = yAxis.lineFirstSpace let rightSpace: CGFloat = yAxis.lineLastSpace if !yAxis.isEnabled { return } if yAxis.drawGridLinesEnabled { let positions = transformedPositions() context.saveGState() defer { context.restoreGState() } context.clip(to: self.gridClippingRect) context.setShouldAntialias(yAxis.gridAntialiasEnabled) context.setStrokeColor(yAxis.gridColor.cgColor) context.setLineWidth(yAxis.gridLineWidth) context.setLineCap(yAxis.gridLineCap) if yAxis.gridLineDashLengths != nil { context.setLineDash(phase: yAxis.gridLineDashPhase, lengths: yAxis.gridLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } // draw the grid for i in 0 ..< positions.count { drawGridLine(context: context, position: positions[i]) } } if yAxis.drawZeroLineEnabled { // draw zero line drawZeroLine(context: context) } } @objc open var lineFirstSpace : CGFloat { guard let yAxis = self.axis as? YAxis else { return 0.0 } return yAxis.lineFirstSpace } @objc open var lineLastSpace : CGFloat { guard let yAxis = self.axis as? YAxis else { return 0.0 } return yAxis.lineLastSpace } @objc open var gridClippingRect: CGRect { var contentRect = viewPortHandler.contentRect let dy = self.axis?.gridLineWidth ?? 0.0 let leftSpace: CGFloat = lineFirstSpace let rightSpace: CGFloat = lineLastSpace contentRect.origin.y -= dy / 2.0 contentRect.size.height += dy contentRect.origin.x -= leftSpace contentRect.size.width += (leftSpace + rightSpace) return contentRect } @objc open func drawGridLine( context: CGContext, position: CGPoint) { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft - lineFirstSpace, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight + lineFirstSpace + lineLastSpace, y: position.y)) context.strokePath() } @objc open func transformedPositions() -> [CGPoint] { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer else { return [CGPoint]() } var positions = [CGPoint]() positions.reserveCapacity(yAxis.entryCount) let entries = yAxis.entries for i in stride(from: 0, to: yAxis.entryCount, by: 1) { positions.append(CGPoint(x: 0.0, y: entries[i])) } transformer.pointValuesToPixel(&positions) return positions } /// Draws the zero line at the specified position. @objc open func drawZeroLine(context: CGContext) { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer, let zeroLineColor = yAxis.zeroLineColor else { return } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.y -= yAxis.zeroLineWidth / 2.0 clippingRect.size.height += yAxis.zeroLineWidth context.clip(to: clippingRect) context.setStrokeColor(zeroLineColor.cgColor) context.setLineWidth(yAxis.zeroLineWidth) let pos = transformer.pixelForValues(x: 0.0, y: 0.0) if yAxis.zeroLineDashLengths != nil { context.setLineDash(phase: yAxis.zeroLineDashPhase, lengths: yAxis.zeroLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.move(to: CGPoint(x: viewPortHandler.contentLeft - lineFirstSpace, y: pos.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight + lineFirstSpace + lineLastSpace, y: pos.y)) context.drawPath(using: CGPathDrawingMode.stroke) } open override func renderLimitLines(context: CGContext) { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer else { return } var limitLines = yAxis.limitLines // 从小到大排序lines limitLines = limitLines.sorted(by: { (left, right) -> Bool in return left.limit < right.limit }) if limitLines.count == 0 { return } context.saveGState() let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) var bottomSpacePosition = CGPoint(x: viewPortHandler.contentLeft - lineFirstSpace, y: viewPortHandler.contentHeight)// 上次渲染的line位置 for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.y -= l.lineWidth / 2.0 clippingRect.size.height += l.lineWidth context.clip(to: clippingRect) position.x = 0.0 position.y = CGFloat(l.limit) position = position.applying(trans) context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft - lineFirstSpace, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight + lineFirstSpace + lineLastSpace, y: position.y)) context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokePath() context.beginPath() // 绘制线下面的区域颜色,从小到大进行渲染颜色 context.setFillColor(l.lineBottomSpaceColor.cgColor) context.setStrokeColor(NSUIColor.clear.cgColor) context.move(to: CGPoint(x: viewPortHandler.contentLeft - lineFirstSpace, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight + lineLastSpace + lineFirstSpace, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight + lineLastSpace + lineFirstSpace, y: bottomSpacePosition.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentLeft - lineFirstSpace, y: bottomSpacePosition.y)) bottomSpacePosition = CGPoint(x: position.x, y: position.y - l.lineWidth/2.0) context.fillPath() let label = l.label // if drawing the limit-value label is enabled if l.drawLabelEnabled && label.count > 0 { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = 4.0 + l.xOffset let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset if l.labelPosition == .rightTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .right, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .rightBottom { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .right, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .leftTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .left, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .left, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } } } context.restoreGState() } }
98493651cf8aff80bf7fac4899299428
33.062645
138
0.545331
false
false
false
false
petester42/RxMoya
refs/heads/master
RxMoya/Moya+RxSwift.swift
mit
1
import Foundation import RxSwift /// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures. public class RxMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> { /// Current requests that have not completed or errored yet. /// Note: Do not access this directly. It is public only for unit-testing purposes (sigh). public var inflightRequests = Dictionary<Endpoint<T>, Observable<MoyaResponse>>() /// Initializes a reactive provider. override public init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) { super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure) } /// Designated request-making method. public func request(token: T) -> Observable<MoyaResponse> { let endpoint = self.endpoint(token) return `defer` { [weak self] () -> Observable<MoyaResponse> in if let existingObservable = self?.inflightRequests[endpoint] { return existingObservable } let observable: Observable<MoyaResponse> = AnonymousObservable { observer in let cancellableToken = self?.request(token) { (data, statusCode, response, error) -> () in if let error = error { if let statusCode = statusCode { sendError(observer, NSError(domain: error.domain, code: statusCode, userInfo: error.userInfo)) } else { sendError(observer, error) } } else { if let data = data { sendNext(observer, MoyaResponse(statusCode: statusCode!, data: data, response: response)) } sendCompleted(observer) } } return AnonymousDisposable { if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = nil cancellableToken?.cancel() objc_sync_exit(weakSelf) } } } if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = observable objc_sync_exit(weakSelf) } return observable } } }
61899cb3afd9cc5465faa3eaf85498bd
46.711864
314
0.59254
false
false
false
false
adamkornafeld/CocoaSkeleton
refs/heads/develop
CocoaTouchSkeleton/AppDelegate.swift
mit
1
// // AppDelegate.swift // CocoaTouch // // Created by Adam Kornafeld on 6/12/16. // Copyright © 2016 Adam Kornafeld. All rights reserved. // import UIKit import CocoaSkeletonCore import CoreData import CocoaLumberjackSwift @UIApplicationMain public class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { public var window: UIWindow? public static let instance = UIApplication.sharedApplication().delegate as! AppDelegate public let app = App.instance public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self let app = App.instance if let context = app.contextCoordinator.mainQueueContext { context.performBlock { let predicate = NSPredicate(format: "attribute = %@", "Adam") let ent = context.managedObjectOfClass(Entity.self, predicate: predicate) if let unwrappedEnt = ent as? Entity { DDLogVerbose("\(unwrappedEnt.attribute)") } else { let ent = NSEntityDescription.insertNewObjectForEntityForName(NSStringFromClass(Entity), inManagedObjectContext: context) as! Entity ent.attribute = "Adam" try! context.save() } } } return true } public 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. } public 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. } public 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. } public 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. } public func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view public func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
91c1f843884ea47a4d66b028183df52a
49.976744
285
0.722172
false
false
false
false
muyang00/YEDouYuTV
refs/heads/master
YEDouYuZB/YEDouYuZB/Home/Views/RecommendGameView.swift
apache-2.0
1
// // RecommendGameView.swift // YEDouYuZB // // Created by yongen on 17/3/31. // Copyright © 2017年 yongen. All rights reserved. // import UIKit protocol RecommendGameViewDelegate : class { func recommendGameView(_ recommendView : RecommendGameView, index: Int) } private let kGameCellID = "kGameCellID" private let kEdgeInsetMargin : CGFloat = 10 class RecommendGameView: UIView { var groups : [BaseGameModel]? { didSet{ self.collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() //设置该控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() collectionView.backgroundColor = UIColor.white collectionView.register( UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } } //MARK: - 快速从xib创建类方法 extension RecommendGameView{ class func recommedGameView () -> RecommendGameView{ return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView } } extension RecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseGame = self.groups![(indexPath as IndexPath).item] return cell } } extension RecommendGameView : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("RecommendGameView ----", indexPath) } }
8b5693e31331cad13e231ef5e0632286
28.956522
126
0.704886
false
false
false
false
kevinup7/S4HeaderExtensions
refs/heads/master
Sources/S4HeaderExtensions/MessageHeaders/Pragma.swift
mit
1
import S4 extension Headers { /** The `Pragma` header field allows backwards compatibility with HTTP/1.0 caches, so that clients can specify a `no-cache` request that they will understand (as `Cache-Control` was not defined until HTTP/1.1). When the `Cache-Control` header field is also present and understood in a request, `Pragma` is ignored. ## Example Headers `Pragma: no-cache` ## Examples var request = Request() request.headers.pragma = .NoCache - seealso: [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.4) */ public var pragma: Pragma? { get { return headers["Pragma"].flatMap({ Pragma(headerValue: $0) }) } set { headers["Pragma"] = newValue?.headerValue } } } public enum Pragma: Equatable { case noCache case custom(String) } extension Pragma: HeaderValueInitializable { public init?(headerValue: String) { guard headerValue != "" else { return nil } let lower = CaseInsensitiveString(headerValue) if lower == "no-cache" { self = .noCache } else { self = .custom(headerValue) } } } extension Pragma: HeaderValueRepresentable { public var headerValue: String { switch self { case .noCache: return "no-cache" case .custom(let string): return string } } } public func ==(lhs: Pragma, rhs: Pragma) -> Bool { return lhs.headerValue == rhs.headerValue }
32f75a8f5797f38fa8c21735c5651e01
23.876923
77
0.576994
false
false
false
false
tuanan94/FRadio-ios
refs/heads/xcode8
Pods/NotificationBannerSwift/NotificationBanner/Classes/StatusBarNotificationBanner.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2017 Dalton Hinterscher 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 #if CARTHAGE_CONFIG import MarqueeLabelSwift #else import MarqueeLabel #endif public class StatusBarNotificationBanner: BaseNotificationBanner { public override var bannerHeight: CGFloat { get { if let customBannerHeight = customBannerHeight { return customBannerHeight } else if shouldAdjustForIphoneX() { return super.bannerHeight } else { return 20.0 } } set { customBannerHeight = newValue } } override init(style: BannerStyle, colors: BannerColorsProtocol? = nil) { super.init(style: style, colors: colors) titleLabel = MarqueeLabel() titleLabel?.animationDelay = 2 titleLabel?.type = .leftRight titleLabel!.font = UIFont.systemFont(ofSize: 12.5, weight: UIFont.Weight.bold) titleLabel!.textAlignment = .center titleLabel!.textColor = .white contentView.addSubview(titleLabel!) titleLabel!.snp.makeConstraints { (make) in make.top.equalToSuperview() make.left.equalToSuperview().offset(5) make.right.equalToSuperview().offset(-5) make.bottom.equalToSuperview() } updateMarqueeLabelsDurations() } public convenience init(title: String, style: BannerStyle = .info, colors: BannerColorsProtocol? = nil) { self.init(style: style, colors: colors) titleLabel!.text = title } public convenience init(attributedTitle: NSAttributedString, style: BannerStyle = .info, colors: BannerColorsProtocol? = nil) { self.init(style: style, colors: colors) titleLabel!.attributedText = attributedTitle } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
9bce21fec14dfb095515176a4bb268a6
36.792683
147
0.660213
false
false
false
false
fleurdeswift/digital-asset-database
refs/heads/master
DigitalAssetManager/TitleInstanceVideoClipDelegate.swift
gpl-3.0
1
// // TitleInstanceVideoClipDelegate.swift // DigitalAssetDatabase // // Copyright © 2015 Fleur de Swift. All rights reserved. // import DigitalAssetDatabase; import VLCKit import VideoClipAnnotationEditor public class TitleInstanceVideoClipDelegate : NSObject, VideoClipDelegate { private var mediaPlayer: VLCMediaPlayer; private var lastPoint: VideoClipPoint?; public init(mediaPlayer: VLCMediaPlayer) { self.mediaPlayer = mediaPlayer; } public func currentTimeChanged(videoClipView: VideoClipView, point: VideoClipPoint?, event: NSEvent?) { if let time = point?.time { self.lastPoint = point; if mediaPlayer.playing { if let event = event { if event.type != NSEventType.LeftMouseDown || event.clickCount == 1 { return; } } } self.mediaPlayer.time = time; } } public func selectionChanged(videoClipView: VideoClipView, range: VideoClipRange?) { } public func selectionChanged(videoClipView: VideoClipView, annotations: Set<HashAnnotation>?) { } }
9e71018f1341fbc24b160623718f5c24
27.536585
107
0.639316
false
false
false
false
PureSwift/Cacao
refs/heads/develop
Sources/Cacao/UIKeyCommand.swift
mit
1
// // UIKeyCommand.swift // Cacao // // Created by Alsey Coleman Miller on 11/26/17. // import Foundation public final class UIKeyCommand { } // These are pre-defined constants for use with the input property of UIKeyCommand objects. public let UIKeyInputUpArrow = "UIKeyInputUpArrow" public let UIKeyInputDownArrow = "UIKeyInputDownArrow" public let UIKeyInputLeftArrow = "UIKeyInputLeftArrow" public let UIKeyInputRightArrow = "UIKeyInputRightArrow" public let UIKeyInputEscape = "UIKeyInputEscape"
3215f5e7e95839bbbb5f4712acaf697f
23.666667
91
0.776062
false
false
false
false
wenghengcong/Coderpursue
refs/heads/master
BeeFun/Pods/SkeletonView/Sources/SkeletonLayer.swift
mit
1
// // SkeletonLayer.swift // SkeletonView-iOS // // Created by Juanpe Catalán on 02/11/2017. // Copyright © 2017 SkeletonView. All rights reserved. // import UIKit public typealias SkeletonLayerAnimation = (CALayer) -> CAAnimation public enum SkeletonType { case solid case gradient var layer: CALayer { switch self { case .solid: return CALayer() case .gradient: return CAGradientLayer() } } var layerAnimation: SkeletonLayerAnimation { switch self { case .solid: return { $0.pulse } case .gradient: return { $0.sliding } } } } struct SkeletonLayer { private var maskLayer: CALayer private weak var holder: UIView? var type: SkeletonType { return maskLayer is CAGradientLayer ? .gradient : .solid } var contentLayer: CALayer { return maskLayer } init(withType type: SkeletonType, usingColors colors: [UIColor], andSkeletonHolder holder: UIView) { self.holder = holder self.maskLayer = type.layer self.maskLayer.anchorPoint = .zero self.maskLayer.bounds = holder.maxBoundsEstimated addMultilinesIfNeeded() self.maskLayer.tint(withColors: colors) } func removeLayer() { maskLayer.removeFromSuperlayer() } func addMultilinesIfNeeded() { guard let multiLineView = holder as? ContainsMultilineText else { return } maskLayer.addMultilinesLayers(lines: multiLineView.numLines, type: type, lastLineFillPercent: multiLineView.lastLineFillingPercent, multilineCornerRadius: multiLineView.multilineCornerRadius) } } extension SkeletonLayer { func start(_ anim: SkeletonLayerAnimation? = nil) { let animation = anim ?? type.layerAnimation contentLayer.playAnimation(animation, key: "skeletonAnimation") } func stopAnimation() { contentLayer.stopAnimation(forKey: "skeletonAnimation") } }
98e9c2258ec776c713e08667459b6173
25.205128
199
0.646282
false
false
false
false
esttorhe/MammutAPI
refs/heads/master
Sources/MammutAPI/Models/Instance.swift
mit
1
// // Created by Esteban Torres on 24.04.17. // Copyright (c) 2017 Esteban Torres. All rights reserved. // import Foundation public struct Instance { let uri: String let title: String let description: String let email: String let version: String } // MARK: - Equatable extension Instance: Equatable { public static func ==(lhs: Instance, rhs: Instance) -> Bool { return ( lhs.uri == rhs.uri && lhs.title == rhs.title && lhs.email == rhs.email && lhs.version == rhs.version ) } }
3c9c71f35160682cbafcece715d5fe34
20.888889
65
0.57022
false
false
false
false
AbeHaruhiko/Welco-iOS
refs/heads/master
Welco-iOS/AppDelegate.swift
mit
1
/** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import UIKit import Parse // If you want to use any of the UI components, uncomment this line // import ParseUI // If you want to use Crash Reporting - uncomment this line // import ParseCrashReporting @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //-------------------------------------- // MARK: - UIApplicationDelegate //-------------------------------------- func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Enable storing and querying data from Local Datastore. // Remove this line if you don't want to use Local Datastore features or want to use cachePolicy. Parse.enableLocalDatastore() // **************************************************************************** // Uncomment this line if you want to enable Crash Reporting // ParseCrashReporting.enable() // // Uncomment and fill in with your Parse credentials: // Parse.setApplicationId("your_application_id", clientKey: "your_client_key") Parse.setApplicationId("Ikzt3vnq6LwIKSb4WDP8RkOcUW3wRlsQuLUlrrFN", clientKey: "2mBGwz3A3YD8SMo1UuKXD6M9wEl9QOCUkBV1KDf6") // // If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as // described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/ // Uncomment the line inside ParseStartProject-Bridging-Header and the following line here: // PFFacebookUtils.initializeFacebook() // **************************************************************************** PFUser.enableAutomaticUser() let defaultACL = PFACL(); // If you would like all objects to be private by default, remove this line. defaultACL.publicReadAccess = true PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true) if application.applicationState != UIApplicationState.Background { // Track an app open here if we launch with a push, unless // "content_available" was used to trigger a background push (introduced in iOS 7). // In that case, we skip tracking here to avoid double counting the app-open. let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus") let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:") var noPushPayload = false; if let options = launchOptions { noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil; } if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) { PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions) } } // // Swift 1.2 // // if application.respondsToSelector("registerUserNotificationSettings:") { // let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound // let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil) // application.registerUserNotificationSettings(settings) // application.registerForRemoteNotifications() // } else { // let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound // application.registerForRemoteNotificationTypes(types) // } // // Swift 2.0 // // if #available(iOS 8.0, *) { // let types: UIUserNotificationType = [.Alert, .Badge, .Sound] // let settings = UIUserNotificationSettings(forTypes: types, categories: nil) // application.registerUserNotificationSettings(settings) // application.registerForRemoteNotifications() // } else { // let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound] // application.registerForRemoteNotificationTypes(types) // } return true } //-------------------------------------- // MARK: Push Notifications //-------------------------------------- func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let installation = PFInstallation.currentInstallation() installation.setDeviceTokenFromData(deviceToken) installation.saveInBackground() PFPush.subscribeToChannelInBackground("") { (succeeded: Bool, error: NSError?) in if succeeded { print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n"); } else { print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.\n", error) } } } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { if error.code == 3010 { print("Push notifications are not supported in the iOS Simulator.\n") } else { print("application:didFailToRegisterForRemoteNotificationsWithError: %@\n", error) } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { PFPush.handlePush(userInfo) if application.applicationState == UIApplicationState.Inactive { PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo) } } /////////////////////////////////////////////////////////// // Uncomment this method if you want to use Push Notifications with Background App Refresh /////////////////////////////////////////////////////////// // func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { // if application.applicationState == UIApplicationState.Inactive { // PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo) // } // } //-------------------------------------- // MARK: Facebook SDK Integration //-------------------------------------- /////////////////////////////////////////////////////////// // Uncomment this method if you are using Facebook /////////////////////////////////////////////////////////// // func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { // return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication, session:PFFacebookUtils.session()) // } }
1677f5245136410cd4163adfc807c6cf
46.425806
193
0.61257
false
false
false
false
fancyydk/Sino-Korean-IME
refs/heads/master
SinoKoreanLetter.swift
apache-2.0
1
// // SinoKoreanLetter.swift // SinoKoreanKeyboardApp // // Created by Dongyon Kang on 6/8/15. // Copyright (c) 2015 Dongyon Kang. All rights reserved. // import Foundation enum Jaum: String { case Giyeok = "\u{3131}" // ㄱ case Ssanggiyeok = "\u{3132}" // ㄲ case Nieun = "\u{3134}" // ㄴ case Digeut = "\u{3137}" // ㄷ case Ssangdigeut = "\u{3138}" // ㄸ case Rieul = "\u{3139}" // ㄹ case Mieum = "\u{3141}" // ㅁ case Bieup = "\u{3142}" // ㅂ case Ssangbieup = "\u{3143}" // ㅃ case Siot = "\u{3145}" // ㅅ case Ssangsiot = "\u{3146}" // ㅆ case Ieung = "\u{3147}" // ㅇ case Jieut = "\u{3148}" // ㅈ case Ssangjieut = "\u{3149}" // ㅉ case Chieut = "\u{314A}" // ㅊ case Kieuk = "\u{314B}" // ㅋ case Tieut = "\u{314C}" // ㅌ case Pieup = "\u{314D}" // ㅍ case Hieut = "\u{314E}" // ㅎ static let allValues = [Giyeok, Ssanggiyeok, Nieun, Digeut, Ssangdigeut, Rieul, Mieum, Bieup, Ssangbieup, Siot, Ssangsiot, Ieung, Jieut, Ssangjieut, Chieut, Kieuk, Tieut, Pieup, Hieut] } enum Moum: String { case A = "\u{314F}" // ㅏ case Ae = "\u{3150}" // ㅐ case Ya = "\u{3151}" // ㅑ case Yae = "\u{3152}" // ㅒ case Eo = "\u{3153}" // ㅓ case E = "\u{3154}" // ㅔ case Yeo = "\u{3155}" // ㅕ case Ye = "\u{3156}" // ㅖ case O = "\u{3157}" // ㅗ case Wa = "\u{3158}" // ㅘ case Wae = "\u{3159}" // ㅙ case Oe = "\u{315A}" // ㅚ case Yo = "\u{315B}" // ㅛ case U = "\u{315C}" // ㅜ case Wo = "\u{315D}" // ㅝ case We = "\u{315E}" // ㅞ case Wi = "\u{315F}" // ㅟ case Yu = "\u{3160}" // ㅠ case Eu = "\u{3161}" // ㅡ case Ui = "\u{3162}" // ㅢ case I = "\u{3163}" // ㅣ static let allValues = [A, Ae, Ya, Yae, Eo, E, Yeo, Ye, O, Wa, Wae, Oe, Yo, U, Wo, We, Wi, Yu, Eu, Ui, I] } public class SinoKoreanLetter { var skChar: [String] var letters: [String] var partnerList: Dictionary<String, [String]> var maxPartnerNumber: Int var base: Int var count: Int { get { return skChar.count } } var isEmpty: Bool { get { return skChar.isEmpty } } var complexifiable: Bool { get { return canAdd("") } } var rawString: String { get { var morpheme = "" for char in skChar { morpheme += char } return morpheme } } var letter: String { get { if isEmpty { return "" } var i = 0 var s = skChar[0].unicodeScalars var scalar = Int(s[s.startIndex].value) var retStr = letters[scalar - base] if skChar.count >= 2 { i = find(partnerList[skChar[0]]!, skChar[1])! + 1 if skChar.count == 3 { i++ } retStr = letters[scalar+i - base] } return retStr } } init() { skChar = [] letters = [] partnerList = [String: [String]]() maxPartnerNumber = 0 base = 0 } init(skChar: [String], letters: [String], partnerList: [String: [String]], maxPartnerNumber: Int, base: Int) { self.skChar = skChar self.letters = letters self.partnerList = [String: [String]]() self.maxPartnerNumber = maxPartnerNumber self.base = 0 } class func isJaum(skChar: SinoKoreanLetter) -> Bool { if skChar is Chosung || skChar is Jongsung { return true } return false } class func isJaum(letter: String) -> Bool { for jaum in Jaum.allValues { if (jaum.rawValue == letter) { return true } } return false } class func isMoum(skChar: SinoKoreanLetter) -> Bool { if skChar is Jungsung { return true } return false } class func isMoum(letter: String) -> Bool { for moum in Moum.allValues { if (moum.rawValue == letter) { return true } } return false } func add(letter: String) -> Bool { // if there's a previously entered character, // make sure the new character is compatible with the previous one // and can form a single character if !canAdd(letter) { return false } skChar.append(letter) return true } func canAdd(letter: String) -> Bool { if !isEmpty { if skChar.count >= maxPartnerNumber { // if already full return false } else if partnerList[skChar.last!] == nil { // if the last letter doesn't allow complex letters return false } else if letter != "" && !contains(partnerList[skChar.last!]!, letter) { // if letter is not in the partner list return false } } return true } func remove() -> String { return skChar.removeLast() } func removeAll() { skChar.removeAll(keepCapacity: false) } func get(i: Int) -> String { if i >= 0 && i < count { return skChar[i] } return "" } func getFirst() -> String { return get(0) } func getLast() -> String { return get(count-1) } }
500963b45421846e8b7ed6f1bd0f25a7
28.813131
188
0.455023
false
false
false
false
Roommate-App/roomy
refs/heads/master
InkChat/Pods/IBAnimatable/IBAnimatable/BlurEffectStyle.swift
apache-2.0
3
// // Created by Jake Lin on 12/5/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit extension UIBlurEffectStyle : IBEnum { /** initialize a UIBlurEffectStyle from string. `extraLight`, `light`, `dark`, `prominent` (iOS 10+), `extraLight` (iOS 10+) */ public init?(string: String?) { guard let string = string?.lowercased() else { return nil } switch string { case "extralight": self = .extraLight return case "light": self = .light return case "dark": self = .dark return case "prominent": if #available(iOS 10.0, *) { self = .prominent return } case "regular": if #available(iOS 10.0, *) { self = .regular return } default: break } return nil } }
9c59f6a1d13c70ead37e22f7320ff75a
19.7
126
0.562802
false
false
false
false
icylydia/PlayWithLeetCode
refs/heads/master
412. Fizz Buzz/Solution.swift
mit
1
class Solution { func fizzBuzz(_ n: Int) -> [String] { var ans = [String]() for i in 1...n { var s = "" if i % 3 == 0 { s += "Fizz" } if i % 5 == 0 { s += "Buzz" } if i % 3 != 0 && i % 5 != 0 { s += "\(i)" } ans.append(s) } return ans } }
736045c11f4ebd17bba15544ff6cc1d1
14.631579
41
0.364865
false
false
false
false
noppoMan/SwiftKnex
refs/heads/master
Sources/SwiftKnex/Clauses/Table.swift
mit
1
// // Table.swift // SwiftKnex // // Created by Yuki Takei on 2017/01/18. // // //var alias: String? { get set } //func `as`(_ alias: String) -> Self enum TableType: QueryBuildable { case string(String) case queryBuilder(QueryBuilder) func build() throws -> (String, [Any]) { switch self { case .string(let table): return (pack(key: table), []) case .queryBuilder(let qb): let (sql, params) = try qb.build(.select).build() return ("(\(sql))", params) } } } public struct Table: QueryBuildable, AliasAttacheble { let type: TableType public var alias: String? public init(_ qb: QueryBuilder) { self.type = .queryBuilder(qb) } public init(_ name: String) { self.type = .string(name) } public func build() throws -> (String, [Any]) { let (sql, params) = try type.build() if let alias = self.alias { return ("(\(sql)) AS \(alias)", params) } return (sql, params) } }
d7ac8b7681ac7f685eec9fc06eac317c
20.705882
61
0.518519
false
false
false
false
lionhylra/UIView-InterruptibleTap
refs/heads/master
UIView+InterruptibleTapGestureRecognizer.swift
mit
1
// // UIView+InterruptibleTapGestureRecognizer.swift // GestureTest // // Created by HeYilei on 3/12/2015. // Copyright © 2015 jEyLaBs. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Yilei He, lionhylra.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 var touchResponsibleRange:CGFloat = 80.0 @objc public protocol InterruptibleTapDelegate:class{ optional func viewPressed(view:UIView!) optional func viewNotPressed(view:UIView!) optional func action(view:UIView!) } public extension UIView { private struct AssociatedKeys { static var delegateKey = "delegate" } private var interruptibleTapdelegate:InterruptibleTapDelegate! { get{ return objc_getAssociatedObject(self, &AssociatedKeys.delegateKey) as? InterruptibleTapDelegate } set{ objc_setAssociatedObject(self, &AssociatedKeys.delegateKey, newValue as AnyObject, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) } } func addInterruptibleTapGestureRecognizerWithDelegate(delegate:InterruptibleTapDelegate){ self.interruptibleTapdelegate = delegate self.userInteractionEnabled = true let longPress = UILongPressGestureRecognizer(target: self, action: "viewTapped:") longPress.minimumPressDuration = 0.01 self.addGestureRecognizer(longPress) } @objc private func viewTapped(gestureRecognizer:UILongPressGestureRecognizer){ struct staticVariables{ static var startLocation:CGPoint = CGPointZero static var distance:CGFloat = 0.0 } switch gestureRecognizer.state { case .Began: self.interruptibleTapdelegate.viewPressed?(gestureRecognizer.view) staticVariables.startLocation = gestureRecognizer.locationInView(nil) staticVariables.distance = 0.0 case.Changed: if CGPointEqualToPoint(staticVariables.startLocation, CGPointZero) { return } let currentLocation = gestureRecognizer.locationInView(nil) staticVariables.distance = hypot(staticVariables.startLocation.x - currentLocation.x, staticVariables.startLocation.y - currentLocation.y) if staticVariables.distance > touchResponsibleRange { self.interruptibleTapdelegate.viewNotPressed?(gestureRecognizer.view) }else{ self.interruptibleTapdelegate.viewPressed?(gestureRecognizer.view) } case.Ended: self.interruptibleTapdelegate.viewNotPressed?(gestureRecognizer.view) if staticVariables.distance < touchResponsibleRange { self.interruptibleTapdelegate.action?(gestureRecognizer.view) } default: self.interruptibleTapdelegate.viewNotPressed?(gestureRecognizer.view) } } }
af7a5630b7f29cc7bf5e6cd466d8ac43
42.26087
150
0.704271
false
false
false
false
jpavley/Emoji-Tac-Toe2
refs/heads/master
BattleMode.swift
mit
1
// // BattleMode.swift // Emoji Tac Toe // // Created by John Pavley on 1/24/18. // Copyright © 2018 Epic Loot. All rights reserved. // import Foundation enum BattleModeAttack: Int { case meWin = 0 case youWin = 1 case takeAllCorners = 2 case takeAllMiddles = 3 case switchLocations = 4 case jumpToCenter = 5 case mixUp = 6 case wipeOut = 7 } class BattleMode { enum AttackRank: Int { case instantWin = 1 case nearlyInstantWin = 2 case mixerUpper = 3 } struct attackNames { static let meWin = "Untouched Is Mine" static let youWin = "Untouched Is Yours" static let takeAllCorners = "Take All Corners" static let takeAllMiddles = "Take All Middles" static let switchLocations = "Swap Places" static let jumpToCenter = "Take Center" static let mixUp = "Mix It Up" static let wipeOut = "Wipe Out" } var activePlayer: PlayerRole var currentGameboard: Gameboard var attackList: [[BattleModeAttack]] init(activePlayer: PlayerRole, currentGameboard: Gameboard) { self.activePlayer = activePlayer self.currentGameboard = currentGameboard self.attackList = [[BattleModeAttack]]() createAttackList() } fileprivate func createAttackList(){ let rank1Attacks:[BattleModeAttack] = [.meWin, .youWin] let rank2Attacks:[BattleModeAttack] = [.takeAllCorners, .takeAllMiddles] let rank3Attacks:[BattleModeAttack] = [.switchLocations, .jumpToCenter, .mixUp, .wipeOut] attackList.append(contentsOf: [rank1Attacks, rank2Attacks, rank3Attacks]) } /// Chooses a battlemode attack move based on the following probability table. /// Rank 1: Instant Win (10% probability). /// Rank 2: Nearly Instant Win (20% probability). /// Rank 3: Mixer upper (70% probability). /// Within each rank an attack move is chosen at random. func chooseAttackID() -> BattleModeAttack { // assemble the list of ranks with frequency based on probability var rankList = [AttackRank]() for _ in 0..<10 { rankList.append(.instantWin) } for _ in 0..<20 { rankList.append(.nearlyInstantWin) } for _ in 0..<70 { rankList.append(.mixerUpper) } // find the rank of the attack based on the probability let randomRank = rankList[diceRoll(100)] // some ranks have more attacks then other var rankCount: Int switch randomRank { case .instantWin: rankCount = 2 case .nearlyInstantWin: rankCount = 2 case .mixerUpper: rankCount = 4 } // return a random attack based on the random rank let attackRankID = randomRank.rawValue - 1 let battleModeAttack = attackList[attackRankID][diceRoll(rankCount)] return battleModeAttack } /// Returns an updated gameboard with the effects of an attack /// randomly chosen. func attack() -> (Gameboard, String) { let randomMove = chooseAttackID() switch randomMove { case .meWin: // rank 1 (10%) return (meWin(), attackNames.meWin) case .youWin: // rank 1 (10%) return (youWin(), attackNames.youWin) case .takeAllCorners: // rank 2 (20%) return (takeAllCorners(), attackNames.takeAllCorners) case .takeAllMiddles: // rank 2 (20%) return (takeAllMiddles(), attackNames.takeAllMiddles) case .switchLocations: // rank 3 (70%) return (switchLocations(), attackNames.switchLocations) case .jumpToCenter: // rank 3 (70%) return (jumpToCenter(), attackNames.jumpToCenter) case .mixUp: // rank 3 (70%) return (mixUp(), attackNames.mixUp) case .wipeOut: // rank 3 (70%) return (wipeOut(), attackNames.wipeOut) } } /// All untouched cells become player cells func meWin() -> Gameboard { let gameString = TicTacToeGame(gameboard: currentGameboard) .text .replacingOccurrences(of: "_", with: activePlayer.rawValue) return transformTextIntoGameboard(textRepresentation: gameString)! } /// All untouched cells become opponet's cells func youWin() -> Gameboard { let opponent = (activePlayer == PlayerRole.cross) ? PlayerRole.nought : PlayerRole.cross let gameString = TicTacToeGame(gameboard: currentGameboard) .text .replacingOccurrences(of: "_", with: opponent.rawValue) return transformTextIntoGameboard(textRepresentation: gameString)! } /// All cells cells become untouched func wipeOut() -> Gameboard { return transformTextIntoGameboard(textRepresentation: "_________")! } /// Player cells switch places with opponet cells func switchLocations() -> Gameboard { let opponent = (activePlayer == PlayerRole.cross) ? PlayerRole.nought : PlayerRole.cross let gameString = TicTacToeGame(gameboard: currentGameboard) .text .replacingOccurrences(of: opponent.rawValue, with: "@") .replacingOccurrences(of: activePlayer.rawValue, with: opponent.rawValue) .replacingOccurrences(of: "@", with: activePlayer.rawValue) return transformTextIntoGameboard(textRepresentation: gameString)! } /// Player steals the corners of the gameboard func takeAllCorners() -> Gameboard { var updatedGameboard = currentGameboard for cell in cellCorners { updatedGameboard[cell] = activePlayer } return updatedGameboard } /// Player steals the middle cells of the gameboard func takeAllMiddles() -> Gameboard { var updatedGameboard = currentGameboard for cell in cellMiddles { updatedGameboard[cell] = activePlayer } return updatedGameboard } /// Take the center func jumpToCenter() -> Gameboard { var updatedGameboard = currentGameboard updatedGameboard[cellCenter] = activePlayer return updatedGameboard } /// Scramble the board func mixUp() -> Gameboard { var updatedGameboard = currentGameboard let states: [PlayerRole] = [.untouched, .nought, .cross] for i in 0..<updatedGameboard.count { updatedGameboard[i] = states[diceRoll(3)] } return updatedGameboard } }
2e44f75443e4f0ab6004f747218f10f6
30.87156
97
0.593696
false
false
false
false
jacobwhite/firefox-ios
refs/heads/master
Client/Frontend/AuthenticationManager/AuthenticationSettingsViewController.swift
mpl-2.0
1
/* 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 Shared import SwiftKeychainWrapper import LocalAuthentication private let logger = Logger.browserLogger private func presentNavAsFormSheet(_ presented: UINavigationController, presenter: UINavigationController?, settings: AuthenticationSettingsViewController?) { presented.modalPresentationStyle = .formSheet presenter?.present(presented, animated: true) { if let selectedRow = settings?.tableView.indexPathForSelectedRow { settings?.tableView.deselectRow(at: selectedRow, animated: false) } } } class TurnPasscodeOnSetting: Setting { weak var settings: AuthenticationSettingsViewController? override var accessibilityIdentifier: String? { return "TurnOnPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.settings = settings as? AuthenticationSettingsViewController super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOnPasscode, enabled: true), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: SetupPasscodeViewController()), presenter: navigationController, settings: settings) } } class TurnPasscodeOffSetting: Setting { weak var settings: AuthenticationSettingsViewController? override var accessibilityIdentifier: String? { return "TurnOffPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.settings = settings as? AuthenticationSettingsViewController super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOffPasscode, enabled: true), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: RemovePasscodeViewController()), presenter: navigationController, settings: settings) } } class ChangePasscodeSetting: Setting { weak var settings: AuthenticationSettingsViewController? override var accessibilityIdentifier: String? { return "ChangePasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool) { self.settings = settings as? AuthenticationSettingsViewController let attributedTitle: NSAttributedString = NSAttributedString.tableRowTitle(AuthenticationStrings.changePasscode, enabled: enabled) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: ChangePasscodeViewController()), presenter: navigationController, settings: settings) } } class RequirePasscodeSetting: Setting { weak var settings: AuthenticationSettingsViewController? fileprivate weak var navigationController: UINavigationController? override var accessibilityIdentifier: String? { return "PasscodeInterval" } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { // Only show the interval if we are enabled and have an interval set. let authenticationInterval = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() if let interval = authenticationInterval?.requiredPasscodeInterval, enabled { return NSAttributedString.tableRowTitle(interval.settingTitle, enabled: false) } return NSAttributedString(string: "") } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) { self.navigationController = settings.navigationController self.settings = settings as? AuthenticationSettingsViewController let title = AuthenticationStrings.requirePasscode let attributedTitle = NSAttributedString.tableRowTitle(title, enabled: enabled ?? true) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else { navigateToRequireInterval() return } if authInfo.requiresValidation() { AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.requirePasscodeTouchReason, success: { self.navigateToRequireInterval() }, cancel: nil, fallback: { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self) self.deselectRow() }) } else { self.navigateToRequireInterval() } } fileprivate func navigateToRequireInterval() { navigationController?.pushViewController(RequirePasscodeIntervalViewController(), animated: true) } } extension RequirePasscodeSetting: PasscodeEntryDelegate { @objc func passcodeValidationDidSucceed() { navigationController?.dismiss(animated: true) { self.navigateToRequireInterval() } } } class TouchIDSetting: Setting { fileprivate let authInfo: AuthenticationKeychainInfo? fileprivate weak var navigationController: UINavigationController? fileprivate weak var switchControl: UISwitch? fileprivate var touchIDSuccess: (() -> Void)? fileprivate var touchIDFallback: (() -> Void)? init( title: NSAttributedString?, navigationController: UINavigationController? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil, touchIDSuccess: (() -> Void)? = nil, touchIDFallback: (() -> Void)? = nil) { self.touchIDSuccess = touchIDSuccess self.touchIDFallback = touchIDFallback self.navigationController = navigationController self.authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() super.init(title: title, delegate: delegate, enabled: enabled) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .none // In order for us to recognize a tap gesture without toggling the switch, // the switch is wrapped in a UIView which has a tap gesture recognizer. This way // we can disable interaction of the switch and still handle tap events. let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.isOn = authInfo?.useTouchID ?? false control.isUserInteractionEnabled = false switchControl = control let accessoryContainer = UIView(frame: control.frame) accessoryContainer.addSubview(control) let gesture = UITapGestureRecognizer(target: self, action: #selector(switchTapped)) accessoryContainer.addGestureRecognizer(gesture) cell.accessoryView = accessoryContainer } @objc fileprivate func switchTapped() { guard let authInfo = authInfo else { logger.error("Authentication info should always be present when modifying Touch ID preference.") return } if authInfo.useTouchID { AppAuthenticator.presentAuthenticationUsingInfo( authInfo, touchIDReason: AuthenticationStrings.disableTouchReason, success: self.touchIDSuccess, cancel: nil, fallback: self.touchIDFallback ) } else { toggleTouchID(true) } } func toggleTouchID(_ enabled: Bool) { authInfo?.useTouchID = enabled KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authInfo) switchControl?.setOn(enabled, animated: true) } } class AuthenticationSettingsViewController: SettingsTableViewController { override func viewDidLoad() { super.viewDidLoad() updateTitleForTouchIDState() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .PasscodeDidRemove, object: nil) notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .PasscodeDidCreate, object: nil) notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .UIApplicationDidBecomeActive, object: nil) tableView.accessibilityIdentifier = "AuthenticationManager.settingsTableView" } override func generateSettings() -> [SettingSection] { if let _ = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() { return passcodeEnabledSettings() } else { return passcodeDisabledSettings() } } fileprivate func updateTitleForTouchIDState() { let localAuthContext = LAContext() if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { let title: String if #available(iOS 11.0, *), localAuthContext.biometryType == .faceID { title = AuthenticationStrings.faceIDPasscodeSetting } else { title = AuthenticationStrings.touchIDPasscodeSetting } navigationItem.title = title } else { navigationItem.title = AuthenticationStrings.passcode } } fileprivate func passcodeEnabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOffSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: true) ]) var requirePasscodeSectionChildren: [Setting] = [RequirePasscodeSetting(settings: self)] let localAuthContext = LAContext() if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { let title: String if #available(iOS 11.0, *), localAuthContext.biometryType == .faceID { title = Strings.UseFaceID } else { title = Strings.UseTouchID } requirePasscodeSectionChildren.append( TouchIDSetting( title: NSAttributedString.tableRowTitle(title, enabled: true), navigationController: self.navigationController, delegate: nil, enabled: true, touchIDSuccess: { [unowned self] in self.touchIDAuthenticationSucceeded() }, touchIDFallback: { [unowned self] in self.fallbackOnTouchIDFailure() } ) ) } let requirePasscodeSection = SettingSection(title: nil, children: requirePasscodeSectionChildren) settings += [ passcodeSection, requirePasscodeSection, ] return settings } fileprivate func passcodeDisabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOnSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: false) ]) let requirePasscodeSection = SettingSection(title: nil, children: [ RequirePasscodeSetting(settings: self, delegate: nil, enabled: false), ]) settings += [ passcodeSection, requirePasscodeSection, ] return settings } } extension AuthenticationSettingsViewController { @objc func refreshSettings(_ notification: Notification) { updateTitleForTouchIDState() settings = generateSettings() tableView.reloadData() } } extension AuthenticationSettingsViewController: PasscodeEntryDelegate { fileprivate func getTouchIDSetting() -> TouchIDSetting? { guard settings.count >= 2 && settings[1].count >= 2 else { return nil } return settings[1][1] as? TouchIDSetting } func touchIDAuthenticationSucceeded() { getTouchIDSetting()?.toggleTouchID(false) } func fallbackOnTouchIDFailure() { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self) } @objc func passcodeValidationDidSucceed() { getTouchIDSetting()?.toggleTouchID(false) navigationController?.dismiss(animated: true, completion: nil) } }
5acf512c6b34cd0ef47170b6a59a6a29
37.632312
158
0.673949
false
false
false
false
Karumi/Alamofire-Result
refs/heads/antitypical-Result
Tests/ManagerTests.swift
mit
1
// ManagerTests.swift // // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. @testable import Alamofire import Foundation import XCTest import Result class ManagerTestCase: BaseTestCase { // MARK: Initialization Tests func testInitializerWithDefaultArguments() { // Given, When let manager = Manager() // Then XCTAssertNotNil(manager.session.delegate, "session delegate should not be nil") XCTAssertTrue(manager.delegate === manager.session.delegate, "manager delegate should equal session delegate") XCTAssertNil(manager.session.serverTrustPolicyManager, "session server trust policy manager should be nil") } func testInitializerWithSpecifiedArguments() { // Given let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() let delegate = Manager.SessionDelegate() let serverTrustPolicyManager = ServerTrustPolicyManager(policies: [:]) // When let manager = Manager( configuration: configuration, delegate: delegate, serverTrustPolicyManager: serverTrustPolicyManager ) // Then XCTAssertNotNil(manager.session.delegate, "session delegate should not be nil") XCTAssertTrue(manager.delegate === manager.session.delegate, "manager delegate should equal session delegate") XCTAssertNotNil(manager.session.serverTrustPolicyManager, "session server trust policy manager should not be nil") } func testThatFailableInitializerSucceedsWithDefaultArguments() { // Given let delegate = Manager.SessionDelegate() let session: NSURLSession = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() return NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) }() // When let manager = Manager(session: session, delegate: delegate) // Then if let manager = manager { XCTAssertTrue(manager.delegate === manager.session.delegate, "manager delegate should equal session delegate") XCTAssertNil(manager.session.serverTrustPolicyManager, "session server trust policy manager should be nil") } else { XCTFail("manager should not be nil") } } func testThatFailableInitializerSucceedsWithSpecifiedArguments() { // Given let delegate = Manager.SessionDelegate() let session: NSURLSession = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() return NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) }() let serverTrustPolicyManager = ServerTrustPolicyManager(policies: [:]) // When let manager = Manager(session: session, delegate: delegate, serverTrustPolicyManager: serverTrustPolicyManager) // Then if let manager = manager { XCTAssertTrue(manager.delegate === manager.session.delegate, "manager delegate should equal session delegate") XCTAssertNotNil(manager.session.serverTrustPolicyManager, "session server trust policy manager should not be nil") } else { XCTFail("manager should not be nil") } } func testThatFailableInitializerFailsWithWhenDelegateDoesNotEqualSessionDelegate() { // Given let delegate = Manager.SessionDelegate() let session: NSURLSession = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() return NSURLSession(configuration: configuration, delegate: Manager.SessionDelegate(), delegateQueue: nil) }() // When let manager = Manager(session: session, delegate: delegate) // Then XCTAssertNil(manager, "manager should be nil") } func testThatFailableInitializerFailsWhenSessionDelegateIsNil() { // Given let delegate = Manager.SessionDelegate() let session: NSURLSession = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() return NSURLSession(configuration: configuration, delegate: nil, delegateQueue: nil) }() // When let manager = Manager(session: session, delegate: delegate) // Then XCTAssertNil(manager, "manager should be nil") } // MARK: Start Requests Immediately Tests func testSetStartRequestsImmediatelyToFalseAndResumeRequest() { // Given let manager = Alamofire.Manager() manager.startRequestsImmediately = false let URL = NSURL(string: "https://httpbin.org/get")! let URLRequest = NSURLRequest(URL: URL) let expectation = expectationWithDescription("\(URL)") var response: NSHTTPURLResponse? // When manager.request(URLRequest) .response { _, responseResponse, _, _ in response = responseResponse expectation.fulfill() } .resume() waitForExpectationsWithTimeout(timeout, handler: nil) // Then XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(response?.statusCode == 200, "response status code should be 200") } // MARK: Deinitialization Tests func testReleasingManagerWithPendingRequestDeinitializesSuccessfully() { // Given var manager: Manager? = Alamofire.Manager() manager?.startRequestsImmediately = false let URL = NSURL(string: "https://httpbin.org/get")! let URLRequest = NSURLRequest(URL: URL) // When let request = manager?.request(URLRequest) manager = nil // Then XCTAssertTrue(request?.task.state == .Suspended, "request task state should be '.Suspended'") XCTAssertNil(manager, "manager should be nil") } func testReleasingManagerWithPendingCanceledRequestDeinitializesSuccessfully() { // Given var manager: Manager? = Alamofire.Manager() manager!.startRequestsImmediately = false let URL = NSURL(string: "https://httpbin.org/get")! let URLRequest = NSURLRequest(URL: URL) // When let request = manager!.request(URLRequest) request.cancel() manager = nil // Then let state = request.task.state XCTAssertTrue(state == .Canceling || state == .Completed, "state should be .Canceling or .Completed") XCTAssertNil(manager, "manager should be nil") } } // MARK: - class ManagerConfigurationHeadersTestCase: BaseTestCase { enum ConfigurationType { case Default, Ephemeral, Background } func testThatDefaultConfigurationHeadersAreSentWithRequest() { // Given, When, Then executeAuthorizationHeaderTestForConfigurationType(.Default) } func testThatEphemeralConfigurationHeadersAreSentWithRequest() { // Given, When, Then executeAuthorizationHeaderTestForConfigurationType(.Ephemeral) } func testThatBackgroundConfigurationHeadersAreSentWithRequest() { // Given, When, Then executeAuthorizationHeaderTestForConfigurationType(.Background) } private func executeAuthorizationHeaderTestForConfigurationType(type: ConfigurationType) { // Given let manager: Manager = { let configuration: NSURLSessionConfiguration = { let configuration: NSURLSessionConfiguration switch type { case .Default: configuration = NSURLSessionConfiguration.defaultSessionConfiguration() case .Ephemeral: configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() case .Background: let identifier = "com.alamofire.test.manager-configuration-tests" configuration = NSURLSessionConfiguration.backgroundSessionConfigurationForAllPlatformsWithIdentifier(identifier) } var headers = Alamofire.Manager.defaultHTTPHeaders headers["Authorization"] = "Bearer 123456" configuration.HTTPAdditionalHeaders = headers return configuration }() return Manager(configuration: configuration) }() let expectation = expectationWithDescription("request should complete successfully") var response: Response<AnyObject, NSError>? // When manager.request(.GET, "https://httpbin.org/headers") .responseJSON { closureResponse in response = closureResponse expectation.fulfill() } waitForExpectationsWithTimeout(timeout, handler: nil) // Then if let response = response { XCTAssertNotNil(response.request, "request should not be nil") XCTAssertNotNil(response.response, "response should not be nil") XCTAssertNotNil(response.data, "data should not be nil") XCTAssertTrue(response.result.isSuccess, "result should be a success") if let headers = response.result.value?["headers" as NSString] as? [String: String], authorization = headers["Authorization"] { XCTAssertEqual(authorization, "Bearer 123456", "authorization header value does not match") } else { XCTFail("failed to extract authorization header value") } } else { XCTFail("response should not be nil") } } }
149fe8bab3478e037327cb1a25476825
37.409253
133
0.666265
false
true
false
false
PlutoMa/SwiftProjects
refs/heads/master
022.Basic Animations/BasicAnimations/BasicAnimations/ViewController.swift
mit
1
// // ViewController.swift // BasicAnimations // // Created by Dareway on 2017/11/3. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit class ViewController: UIViewController { let tableView = UITableView(frame: CGRect.zero, style: .plain) private let dataSource = ["Position","Opacity","Scale","Color","Rotation"] private let cellHeight: CGFloat = 66 override func viewDidLoad() { super.viewDidLoad() title = "Animations" view.backgroundColor = UIColor.white tableView.frame = view.bounds tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "reuseCell") view.addSubview(tableView) } } // MARK: - UITableViewDelegate & UITableViewDataSource extension ViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeight } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell", for: indexPath) cell.textLabel?.text = dataSource[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.row { case 0: self.navigationController?.pushViewController(PositionAnimationViewController(), animated: true) case 1: self.navigationController?.pushViewController(OpacityAnimationViewController(), animated: true) case 2: self.navigationController?.pushViewController(ScaleAnimationViewController(), animated: true) case 3: self.navigationController?.pushViewController(ColorAnimationViewController(), animated: true) case 4: self.navigationController?.pushViewController(RotationAnimationViewController(), animated: true) default: return } } }
75128792264ea63d94071a02e000767a
34.132353
108
0.685224
false
false
false
false
Takanu/Pelican
refs/heads/master
Sources/Pelican/Session/Modules/Monitor/FloodMonitor.swift
mit
1
// // Flood.swift // Pelican // // Created by Takanu Kyriako on 20/08/2017. // import Foundation /** Used for monitoring and controlling updates sent to a session by a user. */ public class FloodMonitor { /// The currently active set of limits. var limits: [FloodLimit] = [] init() { } /** Adds a new flood monitor to the class. If the criteria for the flood monitor you're attempting to add match a monitor thats already being used, a new monitor will not be created. */ public func add(type: [UpdateType], hits: Int, duration: Duration, action: @escaping () -> ()) { let limit = FloodLimit(type: type, hits: hits, duration: duration, action: action) if limits.contains(limit) { return } limits.append(limit) } /** Passes the update to all available monitors. */ public func handle(_ update: Update) { limits.forEach( { $0.bump(update) } ) } /** Clears all flood monitors currently being stored. */ public func clearAll() { limits.removeAll() } } /** Defines a set of rules that a FloodLimit class can check for. */ public class FloodLimit: Equatable { // CRITERIA /// The type of update to look for when incrementing the hit counter. var type: [UpdateType] = [] /// The number of hits currently received within the flood monitor's `duration`. var hits: Int /// The length of time the flood monitor range lasts for. var duration: Duration /// The action to be triggered should the monitor var action: () -> () // CURRENT STATE var currentTime: Date = Date() var currentHits: Int = 0 var actionExecuted: Bool = false /** Creates a new FloodMonitor type. */ init(type: [UpdateType], hits: Int, duration: Duration, action: @escaping () -> ()) { self.type = type self.hits = hits self.duration = duration self.action = action } /** Uses an update to attempt bumping the hits that have occurred on the monitor, in an attempt to trigger the action belonging to it. */ public func bump(_ update: Update) { // Check that we can actually bump the monitor if self.type.contains(update.type) == false { return } // If so, check the times and hits if Date().timeIntervalSince1970 > (currentTime.timeIntervalSince1970 + duration.rawValue) { resetTime() return } // Otherwise bump the hits and check if we've hit the requirement for the action to be triggered. currentHits += 1 if currentHits >= hits && actionExecuted == false { action() actionExecuted = true } } /** Resets all properties related to measuring hits and action triggering. */ public func resetTime() { currentTime = Date() currentHits = 0 actionExecuted = false } public static func ==(lhs: FloodLimit, rhs: FloodLimit) -> Bool { if lhs.type == rhs.type && lhs.hits == rhs.hits && lhs.duration == rhs.duration { return true } return false } }
6c3d03f090fc5016568fed200c2d13e9
21.261538
111
0.67208
false
false
false
false
abelondev/JSchemaForm
refs/heads/master
Example/Pods/Eureka/Source/Rows/PopoverSelectorRow.swift
apache-2.0
7
// // PopoverSelectorRow.swift // Eureka // // Created by Martin Barreto on 2/24/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation public class _PopoverSelectorRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell: TypedCellType, Cell.Value == T> : SelectorRow<T, Cell, SelectorViewController<T>> { public required init(tag: String?) { super.init(tag: tag) onPresentCallback = { [weak self] (_, viewController) -> Void in guard let porpoverController = viewController.popoverPresentationController, tableView = self?.baseCell.formViewController()?.tableView, cell = self?.cell else { fatalError() } porpoverController.sourceView = tableView porpoverController.sourceRect = tableView.convertRect(cell.detailTextLabel?.frame ?? cell.textLabel?.frame ?? cell.contentView.frame, fromView: cell) } presentationMode = .Popover(controllerProvider: ControllerProvider.Callback { return SelectorViewController<T>(){ _ in } }, completionCallback: { [weak self] in $0.dismissViewControllerAnimated(true, completion: nil) self?.reload() }) } public override func didSelect() { deselect() super.didSelect() } } public final class PopoverSelectorRow<T: Equatable> : _PopoverSelectorRow<T, PushSelectorCell<T>>, RowType { public required init(tag: String?) { super.init(tag: tag) } }
335404bb71173ad139a68ced89de8da6
38.447368
173
0.66511
false
false
false
false
hiragram/YHImageViewer
refs/heads/master
Pod/Classes/YHImageViewer.swift
mit
1
// // YHImageViewer.swift // YHImageViewer // // Created by yuyahirayama on 2015/07/19. // Copyright (c) 2015年 Yuya Hirayama. All rights reserved. // import UIKit public class YHImageViewer: NSObject { private var window:UIWindow! private var backgroundView:UIView! private var imageView:UIImageView! private var startFrame:CGRect! private var completion:(()->Void)! public var backgroundColor:UIColor? public var fadeAnimationDuration:NSTimeInterval = 0.15 public func show(targetImageView:UIImageView) { // Create UIWindow let window = UIWindow() window.frame = UIScreen.mainScreen().bounds window.backgroundColor = UIColor.clearColor() window.windowLevel = UIWindowLevelAlert let windowTapRecognizer = UITapGestureRecognizer(target: self, action: Selector("windowTapped:")) window.addGestureRecognizer(windowTapRecognizer) self.window = window window.makeKeyAndVisible() // Initialize background view let backgroundView = UIView() if let color = self.backgroundColor { backgroundView.backgroundColor = color } else { backgroundView.backgroundColor = UIColor.blackColor() } backgroundView.frame = self.window.bounds backgroundView.alpha = 0 self.window.addSubview(backgroundView) self.backgroundView = backgroundView // Initialize UIImageView let image = targetImageView.image if image == nil { fatalError("UIImageView is not initialized correctly.") } let imageView = UIImageView(image: image) self.imageView = imageView let startFrame = targetImageView.convertRect(targetImageView.bounds, toView: self.backgroundView) self.startFrame = startFrame imageView.frame = startFrame self.backgroundView.addSubview(imageView) // Initialize drag gesture recognizer let imageDragRecognizer = UIPanGestureRecognizer(target: self, action: Selector("imageDragged:")) self.imageView.userInteractionEnabled = true self.imageView.addGestureRecognizer(imageDragRecognizer) // Initialize pinch gesture recognizer let imagePinchRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("imagePinched:")) self.imageView.userInteractionEnabled = true self.imageView.addGestureRecognizer(imagePinchRecognizer) // Start animation UIView.animateWithDuration(self.fadeAnimationDuration, delay: 0, options: nil, animations: { () -> Void in backgroundView.alpha = 1 }) { (_) -> Void in self.moveImageToCenter() } } public func show(targetImageView:UIImageView, completion: () -> Void) { self.completion = completion self.show(targetImageView) } func moveImageToCenter() { if let imageView = self.imageView { UIView.animateWithDuration(0.2, delay: 0, options: nil, animations: { () -> Void in let width = self.window.bounds.size.width let height = width / imageView.image!.size.width * imageView.image!.size.height self.imageView.frame.size = CGSizeMake(width, height) self.imageView.center = self.window.center }) { (_) -> Void in self.adjustBoundsAndTransform(self.imageView) } } } func windowTapped(recognizer:UIGestureRecognizer) { self.moveToFirstFrame { () -> Void in self.close() } // self.debug() } func imageDragged(recognizer:UIPanGestureRecognizer) { switch (recognizer.state) { case .Changed: // Move target view if let targetView = recognizer.view { let variation = recognizer.translationInView(targetView) targetView.center = CGPointMake(targetView.center.x + variation.x * targetView.transform.a, targetView.center.y + variation.y * targetView.transform.a) let velocity = recognizer.velocityInView(targetView) } recognizer.setTranslation(CGPointZero, inView: recognizer.view) case .Ended: // Check velocity if let targetView = recognizer.view { let variation = recognizer.translationInView(targetView) let velocity = recognizer.velocityInView(targetView) let straightVelocity = sqrt(velocity.x * velocity.x + velocity.y * velocity.y) let velocityThreshold = 1000 let goalPointRate = 5000.0 if straightVelocity > 1000 { let radian = atan2(velocity.y, velocity.x) let goalPoint = CGPointMake(cos(radian) * CGFloat(goalPointRate), sin(radian) * CGFloat(goalPointRate)) UIView.animateWithDuration(0.4, delay: 0, options: nil, animations: { () -> Void in targetView.center = goalPoint }, completion: { (_) -> Void in self.close() }) } else { self.adjustImageViewFrame() } } default: _ = 0 } self.debug() } func imagePinched(recognizer:UIPinchGestureRecognizer) { let targetView = recognizer.view! let scale = recognizer.scale let velocity = recognizer.velocity let point = recognizer.locationInView(targetView) switch (recognizer.state) { case .Changed: let transform = targetView.transform.a targetView.transform = CGAffineTransformMakeScale(scale, scale) case .Ended , .Cancelled: let center = targetView.center self.adjustBoundsAndTransform(targetView) self.adjustImageViewFrame() default: _ = 0 } self.debug() } func close() { UIView.animateWithDuration(self.fadeAnimationDuration, delay: 0, options: nil, animations: { () -> Void in self.backgroundView.alpha = 0 }) { (_) -> Void in self.window = nil } if var completionFunction = self.completion { completion() } } func moveToFirstFrame(completion: () -> Void) { UIView.animateWithDuration(0.2, delay: 0, options: nil, animations: { () -> Void in self.imageView.frame = self.startFrame }) { (_) -> Void in completion() } } func debug() { // println("frame: \(self.imageView.frame) bounds: \(self.imageView.bounds) center: \(self.imageView.center) transform: \(self.imageView.transform.a)") } func adjustBoundsAndTransform(view: UIView) { let center = view.center let scale = view.transform.a view.bounds.size = CGSizeMake(view.bounds.size.width * scale, view.bounds.size.height * scale) view.transform = CGAffineTransformMakeScale(1.0, 1.0) view.center = center } func isImageSmallerThanScreen() -> Bool { let imageWidth = self.imageView.frame.size.width let imageHeight = self.imageView.frame.size.height let screenWidth = self.window.bounds.size.width let screenHeight = self.window.bounds.size.height return imageWidth <= screenWidth && imageHeight <= screenHeight } func adjustImageViewFrame() { if self.isImageSmallerThanScreen() { self.moveImageToCenter() return } let targetView = self.imageView var originX:CGFloat = targetView.frame.origin.x var originY:CGFloat = targetView.frame.origin.y var animateX = true var animateY = true if (targetView.frame.origin.x > 0) { originX = 0 } else if (targetView.frame.origin.x < self.window.bounds.width - targetView.bounds.size.width) { originX = self.window.bounds.width - targetView.bounds.size.width }else { animateX = false } if (targetView.bounds.size.height < self.window.bounds.size.height) { originY = (self.window.bounds.size.height - targetView.bounds.size.height)/2 } else if targetView.frame.origin.y > 0{ originY = 0 } else if targetView.frame.origin.y + targetView.bounds.size.height < self.window.bounds.height { originY = self.window.bounds.size.height - targetView.bounds.size.height } else { animateY = false } if animateX || animateY { UIView.animateWithDuration(0.2, animations: { () -> Void in targetView.frame = CGRectMake(originX, originY, targetView.bounds.size.width, targetView.bounds.size.height) }, completion: { (_) -> Void in }) } } }
15ad86a220c471236fdf67fa17f0a8e0
37.291667
167
0.596844
false
false
false
false
demmys/treeswift
refs/heads/master
src/Parser/OperatorComposer.swift
bsd-2-clause
1
class OperatorComposer : TokenComposer { private enum State { case Head case ReservedOperator(CharacterClass) case DotOperatorHead case OperatorCharacter, DotOperatorCharacter } private var state = State.Head private var prev: CharacterClass private var value: String? init(prev: CharacterClass){ self.prev = prev } func put(cc: CharacterClass, _ c: Character) -> Bool { switch state { case .Head: switch cc { case .OperatorHead: value = String(c) state = .OperatorCharacter return true case .DotOperatorHead: value = String(c) state = .DotOperatorHead return true case .LessThan, .GraterThan, .Ampersand, .Question, .Exclamation: value = String(c) state = .ReservedOperator(cc) return true default: value = nil return false } case .DotOperatorHead: switch cc { case .DotOperatorHead, .Dot: value!.append(c) state = .DotOperatorCharacter return true default: value = nil return false } case .OperatorCharacter: switch cc { case .OperatorHead, .OperatorFollow, .LessThan, .GraterThan, .Ampersand, .Question, .Exclamation, .Equal, .Arrow, .Minus, .LineCommentHead, .BlockCommentHead, .BlockCommentTail: value!.append(c) return true default: value = nil return false } case .DotOperatorCharacter: switch cc { case .OperatorHead, .OperatorFollow, .LessThan, .GraterThan, .Ampersand, .Question, .Exclamation, .Equal, .Arrow, .Minus, .LineCommentHead, .BlockCommentHead, .BlockCommentTail, .DotOperatorHead, .Dot: value!.append(c) return true default: value = nil return false } case .ReservedOperator: value = nil return false } } func compose(follow: CharacterClass) -> TokenKind? { if let v = value { let kind = createKind(prev: self.prev, value: v, follow: follow) switch state { case .OperatorCharacter, .DotOperatorCharacter: return kind case let .ReservedOperator(cc): switch cc { case .LessThan: switch kind { case .PrefixOperator: return .PrefixLessThan default: return kind } case .GraterThan: switch kind { case .PostfixOperator: return .PostfixGraterThan default: return kind } case .Ampersand: switch kind { case .PrefixOperator: return .PrefixAmpersand default: return kind } case .Question: switch kind { case .PrefixOperator: return .PrefixQuestion case .BinaryOperator: return .BinaryQuestion case .PostfixOperator: return .PostfixQuestion default: assert(false, "[System Error] Unimplemented operator type found.") } case .Exclamation: switch kind { case .PostfixOperator: return .PostfixExclamation default: return kind } default: assert(false, "[System Error] Unimplemented reserved operator found.") } default: break } } return nil } private func createKind(prev prev: CharacterClass, value: String, follow: CharacterClass) -> TokenKind { let headSeparated = isSeparator(prev, isPrev: true) let tailSeparated = isSeparator(follow, isPrev: false) if headSeparated { if tailSeparated { return .BinaryOperator(value) } return .PrefixOperator(value) } else { if tailSeparated { return .PostfixOperator(value) } return .BinaryOperator(value) } } private func isSeparator(cc: CharacterClass, isPrev: Bool) -> Bool { switch cc { case .EndOfFile, .LineFeed, .Semicolon, .Space: return true case .BlockCommentTail, .LeftParenthesis, .LeftBrace, .LeftBracket: return isPrev case .BlockCommentHead, .RightParenthesis, .RightBrace, .RightBracket: return !isPrev default: return false } } func isEndOfToken(follow: CharacterClass) -> Bool { switch state { case .OperatorCharacter: switch follow { case .OperatorHead, .OperatorFollow, .LessThan, .GraterThan, .Ampersand, .Question, .Exclamation, .Equal, .Arrow, .Minus, .LineCommentHead, .BlockCommentHead, .BlockCommentTail: return false default: return true } case .DotOperatorCharacter: switch follow { case .OperatorHead, .OperatorFollow, .LessThan, .GraterThan, .Ampersand, .Question, .Exclamation, .Equal, .Arrow, .Minus, .DotOperatorHead, .Dot, .LineCommentHead, .BlockCommentHead, .BlockCommentTail: return false default: return true } case .ReservedOperator: return true default: return false } } }
246f5d8a54e17da1bff20a8d9563f3fa
32.78125
83
0.473481
false
false
false
false
lucaslouca/swift-concurrency
refs/heads/master
app-ios/Fluxcapacitor/FXCRadioButtonGroup.swift
mit
1
// // FXCRadioButtonGroup.swift // Fluxcapacitor // // Created by Lucas Louca on 05/06/15. // Copyright (c) 2015 Lucas Louca. All rights reserved. // import UIKit class FXCRadioButtonGroup: NSObject { var buttonsArray = [UIButton]() private weak var currentSelectedButton:UIButton? = nil init(buttons: UIButton...) { super.init() for aButton in buttons { aButton.addTarget(self, action: "selected:", forControlEvents: UIControlEvents.TouchUpInside) } self.buttonsArray = buttons } func addButton(aButton: UIButton) { buttonsArray.append(aButton) aButton.addTarget(self, action: "selected:", forControlEvents: UIControlEvents.TouchUpInside) } func removeButton(aButton: UIButton) { for (index, iteratingButton) in buttonsArray.enumerate() { if(iteratingButton == aButton) { iteratingButton.removeTarget(self, action: "selected:", forControlEvents: UIControlEvents.TouchUpInside) if currentSelectedButton == iteratingButton { currentSelectedButton = nil } buttonsArray.removeAtIndex(index) } } } func selected(sender: UIButton) { if(sender.selected) { sender.selected = false } else { for aButton in buttonsArray { aButton.selected = false } sender.selected = true } } func selectedButton() -> UIButton? { return currentSelectedButton } }
c60a5e05d640d293ede2f92079297e37
28.555556
120
0.600251
false
false
false
false
magnetsystems/message-samples-ios
refs/heads/master
QuickStart/QuickStart/SubscribersViewController.swift
apache-2.0
1
/* * Copyright (c) 2015 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import MagnetMax class SubscribersViewController: UITableViewController { // MARK: Public properties var channel : MMXChannel! var subscribers : [MMUser] = [] // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() let limit: Int32 = 10 let offset: Int32 = 0 channel.subscribersWithLimit(limit, offset: offset, success: { [weak self] (count, users) in self?.subscribers = users self?.tableView.reloadData() }, failure: { (error) -> Void in print("[ERROR]: \(error)") }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let tabBarVC = self.tabBarController { tabBarVC.navigationItem.title = "Subscribers" tabBarVC.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Invite", style: .Plain, target: self, action: Selector("inviteUserAction")) } //for receiving incoming invites NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveChannelInvite:", name: MMXDidReceiveChannelInviteNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveChannelInviteResponse:", name: MMXDidReceiveChannelInviteResponseNotification, object: nil) // Indicate that you are ready to receive messages now! MMX.start() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Public implementation func inviteUserAction() { //Show popup let invitePopup = UIAlertController(title: "Invite user", message: "", preferredStyle: .Alert) invitePopup.addTextFieldWithConfigurationHandler { txtfUserName in txtfUserName.placeholder = "User name" txtfUserName.text = MMUser.currentUser()?.userName } let close = UIAlertAction(title: "Cancel", style: .Destructive, handler: nil) let invite = UIAlertAction(title: "Send", style: .Default) { [weak self] _ in if let userName = invitePopup.textFields?.first?.text where (userName.isEmpty == false) { //Find user with name MMUser.usersWithUserNames([userName], success: { users in // Invite founded user if let user = users.first { self?.channel.inviteUser(user, comments: "Subscribe to the \(self?.channel.name)", success: { invite in print("Invited") }, failure: { error in print("[ERROR]: \(error)") }) } }, failure: { error in print("[ERROR]: \(error)") }) } } invitePopup.addAction(close) invitePopup.addAction(invite) self.presentViewController(invitePopup, animated: true, completion: nil) } // MARK: - Notification handlers func didReceiveChannelInvite(notification: NSNotification) { let userInfo : [NSObject : AnyObject] = notification.userInfo! let invite = userInfo[MMXInviteKey] as! MMXInvite //Show popup let inviteResponse = UIAlertController(title: "Invite", message: "You were invited to \(invite.channel.name)", preferredStyle: .Alert) let decline = UIAlertAction(title: "Decline", style: .Default) { _ in invite.declineWithComments("No, thanks", success: nil, failure: { error in print("[ERROR]: \(error)") }) } let accept = UIAlertAction(title: "Accept", style: .Default) { _ in invite.acceptWithComments("Hello!", success: nil, failure: { (error) -> Void in print("[ERROR]: \(error)") }) } inviteResponse.addAction(decline) inviteResponse.addAction(accept) self.presentViewController(inviteResponse, animated: true, completion: nil) } func didReceiveChannelInviteResponse(notification: NSNotification) { let userInfo : [NSObject : AnyObject] = notification.userInfo! let inviteResponse = userInfo[MMXInviteResponseKey] as! MMXInviteResponse let message: String? if inviteResponse.accepted { message = "accepted" } else { message = "declined" } print("\(inviteResponse.sender.userName) \(message) invite to join \(inviteResponse.channel.name)") } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return subscribers.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SubscriberCellIdentifier", forIndexPath: indexPath) let user = subscribers[indexPath.row] cell.textLabel?.text = user.userName return cell } }
17ad755618887aab93bea2596f403288
37.219355
175
0.623903
false
false
false
false
JaSpa/swift
refs/heads/master
stdlib/public/SDK/Dispatch/Private.swift
apache-2.0
18
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Redeclarations of all SwiftPrivate functions with appropriate markup. @available(*, unavailable, renamed:"DispatchQueue.init(label:qos:attributes:autoreleaseFrequency:target:)") public func dispatch_queue_create(_ label: UnsafePointer<Int8>?, _ attr: __OS_dispatch_queue_attr?) -> DispatchQueue { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.init(label:qos:attributes:autoreleaseFrequency:target:)") public func dispatch_queue_create_with_target(_ label: UnsafePointer<Int8>?, _ attr: __OS_dispatch_queue_attr?, _ queue: DispatchQueue?) -> DispatchQueue { fatalError() } @available(*, unavailable, renamed:"DispatchIO.init(type:fileDescriptor:queue:cleanupHandler:)") public func dispatch_io_create(_ type: UInt, _ fd: Int32, _ queue: DispatchQueue, _ cleanup_handler: (Int32) -> Void) -> DispatchIO { fatalError() } @available(*, unavailable, renamed:"DispatchIO.init(type:path:oflag:mode:queue:cleanupHandler:)") public func dispatch_io_create_with_path(_ type: UInt, _ path: UnsafePointer<Int8>, _ oflag: Int32, _ mode: mode_t, _ queue: DispatchQueue, _ cleanup_handler: (Int32) -> Void) -> DispatchIO { fatalError() } @available(*, unavailable, renamed:"DispatchIO.init(type:io:queue:cleanupHandler:)") public func dispatch_io_create_with_io(_ type: UInt, _ io: DispatchIO, _ queue: DispatchQueue, _ cleanup_handler: (Int32) -> Void) -> DispatchIO { fatalError() } @available(*, unavailable, renamed:"DispatchIO.read(fileDescriptor:length:queue:handler:)") public func dispatch_read(_ fd: Int32, _ length: Int, _ queue: DispatchQueue, _ handler: (__DispatchData, Int32) -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchIO.read(self:offset:length:queue:ioHandler:)") func dispatch_io_read(_ channel: DispatchIO, _ offset: off_t, _ length: Int, _ queue: DispatchQueue, _ io_handler: (Bool, __DispatchData?, Int32) -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchIO.write(self:offset:data:queue:ioHandler:)") func dispatch_io_write(_ channel: DispatchIO, _ offset: off_t, _ data: __DispatchData, _ queue: DispatchQueue, _ io_handler: (Bool, __DispatchData?, Int32) -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchIO.write(fileDescriptor:data:queue:handler:)") func dispatch_write(_ fd: Int32, _ data: __DispatchData, _ queue: DispatchQueue, _ handler: (__DispatchData?, Int32) -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchData.init(bytes:)") public func dispatch_data_create(_ buffer: UnsafeRawPointer, _ size: Int, _ queue: DispatchQueue?, _ destructor: (() -> Void)?) -> __DispatchData { fatalError() } @available(*, unavailable, renamed:"getter:DispatchData.count(self:)") public func dispatch_data_get_size(_ data: __DispatchData) -> Int { fatalError() } @available(*, unavailable, renamed:"DispatchData.withUnsafeBytes(self:body:)") public func dispatch_data_create_map(_ data: __DispatchData, _ buffer_ptr: UnsafeMutablePointer<UnsafeRawPointer?>?, _ size_ptr: UnsafeMutablePointer<Int>?) -> __DispatchData { fatalError() } @available(*, unavailable, renamed:"DispatchData.append(self:_:)") public func dispatch_data_create_concat(_ data1: __DispatchData, _ data2: __DispatchData) -> __DispatchData { fatalError() } @available(*, unavailable, renamed:"DispatchData.subdata(self:in:)") public func dispatch_data_create_subrange(_ data: __DispatchData, _ offset: Int, _ length: Int) -> __DispatchData { fatalError() } @available(*, unavailable, renamed:"DispatchData.enumerateBytes(self:block:)") public func dispatch_data_apply(_ data: __DispatchData, _ applier: (__DispatchData, Int, UnsafeRawPointer, Int) -> Bool) -> Bool { fatalError() } @available(*, unavailable, renamed:"DispatchData.region(self:location:)") public func dispatch_data_copy_region(_ data: __DispatchData, _ location: Int, _ offset_ptr: UnsafeMutablePointer<Int>) -> __DispatchData { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.async(self:group:qos:flags:execute:)") public func dispatch_group_async(_ group: DispatchGroup, _ queue: DispatchQueue, _ block: () -> Void) { fatalError() } @available(*, unavailable, renamed: "DispatchGroup.notify(self:qos:flags:queue:execute:)") public func dispatch_group_notify(_ group: DispatchGroup, _ queue: DispatchQueue, _ block: () -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchGroup.wait(self:timeout:)") public func dispatch_group_wait(_ group: DispatchGroup, _ timeout: dispatch_time_t) -> Int { fatalError() } @available(*, unavailable, renamed:"DispatchIO.close(self:flags:)") public func dispatch_io_close(_ channel: DispatchIO, _ flags: UInt) { fatalError() } @available(*, unavailable, renamed:"DispatchIO.setInterval(self:interval:flags:)") public func dispatch_io_set_interval(_ channel: DispatchIO, _ interval: UInt64, _ flags: UInt) { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.apply(attributes:iterations:execute:)") public func dispatch_apply(_ iterations: Int, _ queue: DispatchQueue, _ block: (Int) -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.async(self:execute:)") public func dispatch_async(_ queue: DispatchQueue, _ block: () -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.global(attributes:)") public func dispatch_get_global_queue(_ identifier: Int, _ flags: UInt) -> DispatchQueue { fatalError() } @available(*, unavailable, renamed: "getter:DispatchQueue.main()") public func dispatch_get_main_queue() -> DispatchQueue { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.Attributes.initiallyInactive") public func dispatch_queue_attr_make_initially_inactive(_ attr: __OS_dispatch_queue_attr?) -> __OS_dispatch_queue_attr { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.AutoreleaseFrequency.workItem") public func dispatch_queue_attr_make_with_autorelease_frequency(_ attr: __OS_dispatch_queue_attr?, _ frequency: __dispatch_autorelease_frequency_t) -> __OS_dispatch_queue_attr { fatalError() } @available(*, unavailable, renamed:"DispatchQoS") public func dispatch_queue_attr_make_with_qos_class(_ attr: __OS_dispatch_queue_attr?, _ qos_class: qos_class_t, _ relative_priority: Int32) -> __OS_dispatch_queue_attr { fatalError() } @available(*, unavailable, renamed:"getter:DispatchQueue.label(self:)") public func dispatch_queue_get_label(_ queue: DispatchQueue?) -> UnsafePointer<Int8> { fatalError() } @available(*, unavailable, renamed:"getter:DispatchQueue.qos(self:)") public func dispatch_queue_get_qos_class(_ queue: DispatchQueue, _ relative_priority_ptr: UnsafeMutablePointer<Int32>?) -> qos_class_t { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.asyncAfter(self:deadline:qos:flags:execute:)") public func dispatch_after(_ when: dispatch_time_t, _ queue: DispatchQueue, _ block: () -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.async(self:group:qos:flags:execute:)") public func dispatch_barrier_async(_ queue: DispatchQueue, _ block: () -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.sync(self:flags:execute:)") public func dispatch_barrier_sync(_ queue: DispatchQueue, _ block: () -> Void) { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.setSpecific(self:key:value:)") public func dispatch_queue_set_specific(_ queue: DispatchQueue, _ key: UnsafeRawPointer, _ context: UnsafeMutableRawPointer?, _ destructor: (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.getSpecific(self:key:)") public func dispatch_queue_get_specific(_ queue: DispatchQueue, _ key: UnsafeRawPointer) -> UnsafeMutableRawPointer? { fatalError() } @available(*, unavailable, renamed:"DispatchQueue.getSpecific(key:)") public func dispatch_get_specific(_ key: UnsafeRawPointer) -> UnsafeMutableRawPointer? { fatalError() } @available(*, unavailable, renamed:"dispatchPrecondition(_:)") public func dispatch_assert_queue(_ queue: DispatchQueue) { fatalError() } @available(*, unavailable, renamed:"dispatchPrecondition(_:)") public func dispatch_assert_queue_barrier(_ queue: DispatchQueue) { fatalError() } @available(*, unavailable, renamed:"dispatchPrecondition(_:)") public func dispatch_assert_queue_not(_ queue: DispatchQueue) { fatalError() } @available(*, unavailable, renamed:"DispatchSemaphore.wait(self:timeout:)") public func dispatch_semaphore_wait(_ dsema: DispatchSemaphore, _ timeout: dispatch_time_t) -> Int { fatalError() } @available(*, unavailable, renamed: "DispatchSemaphore.signal(self:)") public func dispatch_semaphore_signal(_ dsema: DispatchSemaphore) -> Int { fatalError() } @available(*, unavailable, message:"Use DispatchSource class methods") public func dispatch_source_create(_ type: __dispatch_source_type_t, _ handle: UInt, _ mask: UInt, _ queue: DispatchQueue?) -> DispatchSource { fatalError() } @available(*, unavailable, renamed:"DispatchSource.setEventHandler(self:handler:)") public func dispatch_source_set_event_handler(_ source: DispatchSource, _ handler: (() -> Void)?) { fatalError() } @available(*, unavailable, renamed:"DispatchSource.setCancelHandler(self:handler:)") public func dispatch_source_set_cancel_handler(_ source: DispatchSource, _ handler: (() -> Void)?) { fatalError() } @available(*, unavailable, renamed:"DispatchSource.cancel(self:)") public func dispatch_source_cancel(_ source: DispatchSource) { fatalError() } @available(*, unavailable, renamed:"getter:DispatchSource.isCancelled(self:)") public func dispatch_source_testcancel(_ source: DispatchSource) -> Int { fatalError() } @available(*, unavailable, renamed:"getter:DispatchSource.handle(self:)") public func dispatch_source_get_handle(_ source: DispatchSource) -> UInt { fatalError() } @available(*, unavailable, renamed:"getter:DispatchSource.mask(self:)") public func dispatch_source_get_mask(_ source: DispatchSource) -> UInt { fatalError() } @available(*, unavailable, renamed:"getter:DispatchSource.data(self:)") public func dispatch_source_get_data(_ source: DispatchSource) -> UInt { fatalError() } @available(*, unavailable, renamed:"DispatchUserDataAdd.mergeData(self:value:)") public func dispatch_source_merge_data(_ source: DispatchSource, _ value: UInt) { fatalError() } @available(*, unavailable, renamed:"DispatchTimerSource.setTimer(self:start:interval:leeway:)") public func dispatch_source_set_timer(_ source: DispatchSource, _ start: dispatch_time_t, _ interval: UInt64, _ leeway: UInt64) { fatalError() } @available(*, unavailable, renamed:"DispatchSource.setRegistrationHandler(self:handler:)") public func dispatch_source_set_registration_handler(_ source: DispatchSource, _ handler: (() -> Void)?) { fatalError() } @available(*, unavailable, renamed:"DispatchTime.now()") public func dispatch_time(_ when: dispatch_time_t, _ delta: Int64) -> dispatch_time_t { fatalError() } @available(*, unavailable, renamed:"DispatchWalltime.init(time:)") public func dispatch_walltime(_ when: UnsafePointer<timespec>?, _ delta: Int64) -> dispatch_time_t { fatalError() } @available(*, unavailable, renamed: "DispatchQueue.GlobalQueuePriority.high") public var DISPATCH_QUEUE_PRIORITY_HIGH: Int { fatalError() } @available(*, unavailable, renamed: "DispatchQueue.GlobalQueuePriority.default") public var DISPATCH_QUEUE_PRIORITY_DEFAULT: Int { fatalError() } @available(*, unavailable, renamed: "DispatchQueue.GlobalQueuePriority.low") public var DISPATCH_QUEUE_PRIORITY_LOW: Int { fatalError() } @available(*, unavailable, renamed: "DispatchQueue.GlobalQueuePriority.background") public var DISPATCH_QUEUE_PRIORITY_BACKGROUND: Int { fatalError() } @available(*, unavailable, renamed: "DispatchIO.StreamType.stream") public var DISPATCH_IO_STREAM: Int { fatalError() } @available(*, unavailable, renamed: "DispatchIO.StreamType.random") public var DISPATCH_IO_RANDOM: Int { fatalError() } @available(*, unavailable, renamed: "DispatchIO.CloseFlags.stop") public var DISPATCH_IO_STOP: Int { fatalError() } @available(*, unavailable, renamed: "DispatchIO.IntervalFlags.strictInterval") public var DISPATCH_IO_STRICT_INTERVAL: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.MachSendEvent.dead") public var DISPATCH_MACH_SEND_DEAD: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.MemoryPressureEvent.normal") public var DISPATCH_MEMORYPRESSURE_NORMAL: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.MemoryPressureEvent.warning") public var DISPATCH_MEMORYPRESSURE_WARN: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.MemoryPressureEvent.critical") public var DISPATCH_MEMORYPRESSURE_CRITICAL: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.ProcessEvent.exit") public var DISPATCH_PROC_EXIT: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.ProcessEvent.fork") public var DISPATCH_PROC_FORK: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.ProcessEvent.exec") public var DISPATCH_PROC_EXEC: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.ProcessEvent.signal") public var DISPATCH_PROC_SIGNAL: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.TimerFlags.strict") public var DISPATCH_TIMER_STRICT: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.delete") public var DISPATCH_VNODE_DELETE: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.write") public var DISPATCH_VNODE_WRITE: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.extend") public var DISPATCH_VNODE_EXTEND: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.attrib") public var DISPATCH_VNODE_ATTRIB: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.link") public var DISPATCH_VNODE_LINK: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.rename") public var DISPATCH_VNODE_RENAME: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.revoke") public var DISPATCH_VNODE_REVOKE: Int { fatalError() } @available(*, unavailable, renamed: "DispatchSource.FileSystemEvent.funlock") public var DISPATCH_VNODE_FUNLOCK: Int { fatalError() } @available(*, unavailable, renamed: "DispatchTime.now()") public var DISPATCH_TIME_NOW: Int { fatalError() } @available(*, unavailable, renamed: "DispatchTime.distantFuture") public var DISPATCH_TIME_FOREVER: Int { fatalError() }
c4aa62bbbc49d6a54ddbbb0ef0daab97
31.480932
193
0.733351
false
false
false
false
DanielAsher/SwiftReferenceApp
refs/heads/master
SwiftReferenceApp/Playgrounds/Scratch.playground/Pages/UITextChecker.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation import UIKit var str : NSString = "Hello, playgund" let strRange = str.rangeOfString(str as String) let checker = UITextChecker() //str. let misspelledRange = checker.rangeOfMisspelledWordInString(str as String, range: strRange, startingAt: 0, wrap: false, language: "en") let guessWords = checker.guessesForWordRange(misspelledRange, inString: str as String, language: "en") let str2 = "What's nex" let nsstr2 = NSString(string: str2) let partialWordRange = nsstr2.rangeOfString("nex") let completions = checker.completionsForPartialWordRange(partialWordRange, inString: str2, language: "en") //extension String { // func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? { // let from16 = advance(utf16.startIndex, nsRange.location, utf16.endIndex) // let to16 = advance(from16, nsRange.length, utf16.endIndex) // if let from = String.Index(from16, within: self), // let to = String.Index(to16, within: self) { // return from ..< to // } // return nil // } //} //: [Next](@next)
327b18b941916d0938cfdcb4782dea5f
30.914286
135
0.682184
false
false
false
false
ivanchoo/MonthCalendarView
refs/heads/master
MonthCalendarView/MonthCalendarView.swift
mit
1
// // MonthCalendarView.swift // MonthCalendar // // Created by Ivan Choo on 15/1/15. // Copyright (c) 2015 Ivan Choo. All rights reserved. // import UIKit public let MonthCalendarViewBackgroundKind = "MonthCalendarViewBackgroundKind" private let MonthCalendarViewCurrentMonthSection = 2 private let MonthCalendarFlagYYYYMM: NSCalendarUnit = .EraCalendarUnit | .YearCalendarUnit | .MonthCalendarUnit private let MonthCalendarFlagYYYYMMDD: NSCalendarUnit = MonthCalendarFlagYYYYMM | .DayCalendarUnit // MARK: - MonthCalendarViewDelegate @objc public protocol MonthCalendarViewDelegate { optional func calendarViewWillChangeCurrentMonth(calendarView: MonthCalendarView) optional func calendarViewDidChangeCurrentMonth(calendarView: MonthCalendarView) optional func calendarViewDidChangeIntrinsicContentSize(calendarView: MonthCalendarView) optional func calendarView(calendarView: MonthCalendarView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool optional func calendarView(calendarView: MonthCalendarView, didSelectItemAtIndexPath indexPath: NSIndexPath) optional func calendarView(calendarView: MonthCalendarView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool optional func calendarView(calendarView: MonthCalendarView, didDeselectItemAtIndexPath indexPath: NSIndexPath) optional func calendarView(calendarView: MonthCalendarView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool optional func calendarView(calendarView: MonthCalendarView, didHighlightItemAtIndexPath indexPath: NSIndexPath) optional func calendarView(calendarView: MonthCalendarView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) optional func calendarView(calendarView: MonthCalendarView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) optional func calendarView(calendarView: MonthCalendarView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, forItemAtIndexPath indexPath: NSIndexPath) optional func calendarView(calendarView: MonthCalendarView, didEndDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) optional func calendarView(calendarView: MonthCalendarView, didEndDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, forItemAtIndexPath indexPath: NSIndexPath) optional func calendarView(calendarView: MonthCalendarView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell? optional func calendarView(calendarView: MonthCalendarView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView? } // MARK: - MonthCalendarView @IBDesignable public class MonthCalendarView: UIView, UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { public var calendar: NSCalendar = NSCalendar.currentCalendar() { didSet { setCalendarNeedsUpdate() } } public var currentMonth: NSDate = NSDate() { didSet { currentMonth = normalizeDate(currentMonth, withFlags: MonthCalendarFlagYYYYMM) setCalendarNeedsUpdate() } } public var previousMonth: NSDate { return dateFromCurrentMonthWithOffset(-1) } public var nextMonth: NSDate { return dateFromCurrentMonthWithOffset(1) } public var today: NSDate = NSDate() { didSet { today = normalizeDate(today, withFlags: MonthCalendarFlagYYYYMMDD) setCalendarNeedsUpdate() } } @IBInspectable public var calendarRowHeight: CGFloat = 60 { didSet { setCalendarNeedsUpdate() } } @IBInspectable public var showHorizontalGridlines: Bool = true { didSet { setCalendarNeedsUpdate() } } @IBInspectable public var showVerticalGridlines: Bool = true { didSet { setCalendarNeedsUpdate() } } @IBInspectable public var showWeekendBackground: Bool = true { didSet { setCalendarNeedsUpdate() } } @IBInspectable public var gridlineColor: UIColor = UIColor(white: 0.9, alpha: 1) { didSet { setCalendarNeedsUpdate() } } @IBInspectable public var weekendBackgroundColor: UIColor = UIColor(white: 0.95, alpha: 1) { didSet { setCalendarNeedsUpdate() } } @IBInspectable public var allowsSelection: Bool { get { return collectionView.allowsSelection } set { collectionView.allowsSelection = newValue } } @IBInspectable public var allowsMultipleSelection: Bool { get { return collectionView.allowsMultipleSelection } set { collectionView.allowsMultipleSelection = newValue } } public weak var delegate: MonthCalendarViewDelegate? public var collectionView: UICollectionView! public var panGesture: UIPanGestureRecognizer! public private(set) var calendarCellSize = CGSizeZero public var selectedDates: [NSDate] { get { return selectedDatesSet.allObjects as [NSDate] } set { selectedDatesSet.removeAllObjects() selectedDatesSet.addObjectsFromArray(newValue) setCalendarNeedsUpdate() } } private var calendarNeedsUpdate: Bool = true private var sections: [MonthCalendarSection] = [] private var lastPanOrigin = CGPointZero private var lastIntrisicContentSize = CGSizeZero private var selectedDatesSet = NSMutableSet() public func dateAtIndexPath(indexPath: NSIndexPath) -> NSDate? { if indexPath.section < 0 && indexPath.section >= sections.count { return nil } let section = sections[indexPath.section] if indexPath.item == 0 { return section.startDate } let comps = calendar.components(MonthCalendarFlagYYYYMMDD, fromDate: section.startDate) comps.day += indexPath.item return calendar.dateFromComponents(comps)! } public func indexPathForDate(date: NSDate) -> NSIndexPath? { let month = normalizeDate(date, withFlags: MonthCalendarFlagYYYYMM) for (index, section) in enumerate(sections) { if month == section.month { let comps = calendar.components(.DayCalendarUnit, fromDate: section.startDate, toDate: date, options: nil) return NSIndexPath(forItem: comps.day, inSection: index) } } return nil } public func dateFromCurrentMonthWithOffset(offset: Int) -> NSDate { let comps = calendar.components(MonthCalendarFlagYYYYMM, fromDate: currentMonth) comps.month += offset return calendar.dateFromComponents(comps)! } public func isWeekendForDate(date: NSDate) -> Bool { let comps = calendar.components(.WeekdayCalendarUnit, fromDate: date) return comps.weekday == 1 || comps.weekday == 7 } public func isCurrentMonthForDate(date: NSDate) -> Bool { let normalized = normalizeDate(date, withFlags: MonthCalendarFlagYYYYMM) return normalized == currentMonth } public func isTodayEqualToDate(date: NSDate) -> Bool { let normalized = normalizeDate(date, withFlags: MonthCalendarFlagYYYYMMDD) return today == normalized } public func isSelectedDate(date: NSDate) -> Bool { let normalized = normalizeDate(date, withFlags: MonthCalendarFlagYYYYMMDD) return selectedDatesSet.containsObject(normalized) } public func setCurrentMonth(month: NSDate, animated: Bool) { if !animated { self.currentMonth = month return } let currentMonth = normalizeDate(month, withFlags: MonthCalendarFlagYYYYMM) var existingSection = -1 for (index, section) in enumerate(sections) { if section.month == currentMonth { existingSection = index break } } if existingSection >= 0 { scrollCalendarToSection(existingSection, animated: true) return } // Rebuild datasource var months: [NSDate] = sections.map { return $0.month } let nextSection = currentMonth.earlierDate(currentMonth) == currentMonth ? 0 : months.count - 1 months[nextSection] = currentMonth updateSectionsWithDates(months) collectionView.reloadData() updateCalendarSelection() collectionView.layoutIfNeeded() scrollCalendarToSection(nextSection, animated: true) } public func reloadItemsAtDates(dates: [NSDate]) { var indexPaths: [NSIndexPath] = [] for date in dates { if let indexPath = indexPathForDate(date) { indexPaths.append(indexPath) } } if indexPaths.count > 0 { collectionView.reloadItemsAtIndexPaths(indexPaths) } } public func handlePan(gesture: UIPanGestureRecognizer) { let offset = gesture.translationInView(self) switch gesture.state { case .Began: lastPanOrigin = originForSection(MonthCalendarViewCurrentMonthSection) delegate?.calendarViewWillChangeCurrentMonth?(self) fallthrough case .Changed: collectionView.contentOffset = CGPoint(x: 0, y: lastPanOrigin.y - offset.y) case .Ended, .Cancelled: let velocity = gesture.velocityInView(self) let pushFactor = calendarRowHeight * 4 * 0.3 var section = MonthCalendarViewCurrentMonthSection let diff = collectionView.contentOffset.y - lastPanOrigin.y if abs(velocity.y) > pushFactor || abs(diff) > pushFactor { section += (diff > 0 ? 1 : -1) } scrollCalendarToSection(section, animated: true) default: break } } public func updateCalendarIfNeeded() { if calendarNeedsUpdate { calendarNeedsUpdate = false updateCalendarCellSize() updateCalendarDataSource() collectionView.reloadData() scrollCalendarToSection(MonthCalendarViewCurrentMonthSection, animated: false) updateCalendarSelection() collectionView.layoutIfNeeded() invalidateIntrinsicContentSize() } } public func setCalendarNeedsUpdate() { calendarNeedsUpdate = true setNeedsLayout() } private func setup() { clipsToBounds = true let now = NSDate() currentMonth = now today = now collectionView = UICollectionView(frame: bounds, collectionViewLayout: MonthCalendarViewLayout()) collectionView.backgroundColor = nil collectionView.dataSource = self collectionView.delegate = self collectionView.setTranslatesAutoresizingMaskIntoConstraints(false) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.scrollEnabled = false collectionView.registerClass(MonthCalendarViewCell.self, forCellWithReuseIdentifier: MonthCalendarViewCell.identifier()) collectionView.registerClass(MonthCalendarViewBackground.self, forSupplementaryViewOfKind: MonthCalendarViewBackgroundKind, withReuseIdentifier: MonthCalendarViewBackground.identifier()) addSubview(collectionView) panGesture = UIPanGestureRecognizer(target: self, action: "handlePan:") addGestureRecognizer(panGesture) } private func originForSection(section: Int) -> CGPoint { return collectionView.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: section))!.frame.origin } private func scrollCalendarToSection(section: Int, animated: Bool) { collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: section), atScrollPosition: .Top, animated: animated) } private func normalizeDate(date: NSDate, withFlags unitFlags: NSCalendarUnit) -> NSDate { let comps = calendar.components(unitFlags, fromDate: date) return calendar.dateFromComponents(comps)! } private func updateCalendarSelection() { for date in selectedDatesSet { if let indexPath = indexPathForDate(date as NSDate) { collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None) } } } private func updateCalendarDataSource() { let calendar = self.calendar let comps = calendar.components(MonthCalendarFlagYYYYMM, fromDate: currentMonth) let month = comps.month let dates = Array(-2...2).map { (offset) -> NSDate in comps.month = month + offset return self.calendar.dateFromComponents(comps)! } updateSectionsWithDates(dates) } private func updateSectionsWithDates(dates: [NSDate]) { // TODO: update with [date, date, date ... ] let currentSections = sections.reduce([:], combine: { (var dict, section) -> [NSDate: MonthCalendarSection] in dict[section.month] = section return dict }) let calendar = self.calendar let lastIndex = dates.count - 1 sections = [] for (index, month) in enumerate(dates) { if let exist = currentSections[month] { if index != lastIndex { sections.append(exist) continue } } // calculate the startDate of section, which is the first day of the first week of the current month var fdom: NSDate? // First day of month calendar.rangeOfUnit(.DayCalendarUnit, startDate: &fdom, interval: nil, forDate: month) var comps = calendar.components(MonthCalendarFlagYYYYMMDD | .WeekdayCalendarUnit, fromDate: fdom!) comps.day -= comps.weekday - 1 let startDate = calendar.dateFromComponents(comps)! // determine the number of rows (weeks) // note that the last week of the month contains dates from next month, so we will exclude it (only if it's not the last section) comps.day = calendar.rangeOfUnit(.DayCalendarUnit, inUnit: .MonthCalendarUnit, forDate: month).length let ldom = calendar.dateFromComponents(comps)! // Last day of month let lwdom = calendar.components(.WeekdayCalendarUnit, fromDate: ldom).weekday // Last weekday of the month, 1 ~ 7 let numberOfWeeks = calendar.rangeOfUnit(.WeekCalendarUnit, inUnit: .MonthCalendarUnit, forDate: month).length // Number of weeks in the month let numberOfRows = numberOfWeeks - (lwdom < 7 && index != lastIndex ? 1 : 0) let numberOfItems = numberOfRows * 7 let section = MonthCalendarSection(month: month, startDate: startDate, numberOfRows: numberOfRows, numberOfWeeks: numberOfWeeks, numberOfItems: numberOfItems) sections.append(section) } } private func updateCalendarCellSize() { calendarCellSize = CGSize(width: CGRectGetWidth(bounds) / 7, height: calendarRowHeight) } private func updateCalendarScrollPosition() { let origin = collectionView.contentOffset var index = -1 Array(0..<sections.count).reduce(CGFloat.max, combine: { (prev, section) -> CGFloat in let diff = abs(self.originForSection(section).y - origin.y) if diff < prev { index = section return diff } return prev }) if index == MonthCalendarViewCurrentMonthSection { return } let section = sections[index] currentMonth = section.month delegate?.calendarViewDidChangeCurrentMonth?(self) } // MARK: UIView public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } public override func layoutSubviews() { collectionView.frame = CGRect(x: 0, y: 0, width: CGRectGetWidth(bounds), height: calendarRowHeight * 6) updateCalendarIfNeeded() super.layoutSubviews() scrollCalendarToSection(MonthCalendarViewCurrentMonthSection, animated: false) } public override func intrinsicContentSize() -> CGSize { var height: CGFloat = UIViewNoIntrinsicMetric if !sections.isEmpty { height = calendarRowHeight * CGFloat(sections[MonthCalendarViewCurrentMonthSection].numberOfWeeks) } return CGSize(width: UIViewNoIntrinsicMetric, height: height) } public override func invalidateIntrinsicContentSize() { super.invalidateIntrinsicContentSize() let next = intrinsicContentSize() if !CGSizeEqualToSize(next, lastIntrisicContentSize) { lastIntrisicContentSize = next delegate?.calendarViewDidChangeIntrinsicContentSize?(self) } } // MARK: UICollectionViewDelegate public func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return delegate?.calendarView?(self, shouldSelectItemAtIndexPath: indexPath) ?? allowsSelection } public func collectionView(collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return delegate?.calendarView?(self, shouldDeselectItemAtIndexPath: indexPath) ?? allowsSelection } public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { delegate?.calendarView?(self, didSelectItemAtIndexPath: indexPath) if !allowsMultipleSelection { selectedDatesSet.removeAllObjects() } let date = dateAtIndexPath(indexPath) assert(date != nil, "Inconsistent internal state, cannot resolve selection to date") selectedDatesSet.addObject(date!) if let cell = collectionView.cellForItemAtIndexPath(indexPath) { cell.setNeedsLayout() } } public func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { delegate?.calendarView?(self, didDeselectItemAtIndexPath: indexPath) let date = dateAtIndexPath(indexPath) assert(date != nil, "Inconsistent internal state, cannot resolve deselection to date") selectedDatesSet.removeObject(date!) if let cell = collectionView.cellForItemAtIndexPath(indexPath) { cell.setNeedsLayout() } } public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { delegate?.calendarView?(self, willDisplayCell: cell, forItemAtIndexPath: indexPath) } public func collectionView(collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, atIndexPath indexPath: NSIndexPath) { delegate?.calendarView?(self, willDisplaySupplementaryView: view, forElementKind: elementKind, forItemAtIndexPath: indexPath) } public func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { delegate?.calendarView?(self, didEndDisplayCell: cell, forItemAtIndexPath: indexPath) } public func collectionView(collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, atIndexPath indexPath: NSIndexPath) { delegate?.calendarView?(self, didEndDisplaySupplementaryView: view, forElementKind: elementKind, forItemAtIndexPath: indexPath) } public func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return delegate?.calendarView?(self, shouldHighlightItemAtIndexPath: indexPath) ?? true } public func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) { delegate?.calendarView?(self, didHighlightItemAtIndexPath: indexPath) } public func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) { delegate?.calendarView?(self, didUnhighlightItemAtIndexPath: indexPath) } // MARK: UICollectionViewDataSource public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return sections.count } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return sections[section].numberOfItems } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if let cell = delegate?.calendarView?(self, cellForItemAtIndexPath: indexPath) { return cell } let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MonthCalendarViewCell.identifier(), forIndexPath: indexPath) as MonthCalendarViewCell cell.calendarView = self cell.selected = contains(collectionView.indexPathsForSelectedItems() as [NSIndexPath], indexPath) return cell } public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if let view = delegate?.calendarView?(self, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) { return view } if kind == MonthCalendarViewBackgroundKind { let view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: MonthCalendarViewBackground.identifier(), forIndexPath: indexPath) as MonthCalendarViewBackground view.calendarView = self return view } assertionFailure("Unknown supplementary element kind \(kind)") } // MARK: UICollectionViewDelegateFlowLayout public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return calendarCellSize } // MARK: UIScrollViewDelegate public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { updateCalendarScrollPosition() } } // MARK: - MonthCalendarViewLayout public class MonthCalendarViewLayout: UICollectionViewFlowLayout { public override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { if var attrs = super.layoutAttributesForElementsInRect(rect) { attrs.append(layoutAttributesForSupplementaryViewOfKind(MonthCalendarViewBackgroundKind, atIndexPath: NSIndexPath(forItem: 0, inSection: 0))) return attrs } return nil } public override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { var attr = super.layoutAttributesForSupplementaryViewOfKind(elementKind, atIndexPath: indexPath) switch elementKind { case MonthCalendarViewBackgroundKind: if attr == nil { attr = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, withIndexPath: indexPath) } attr.zIndex = -1 attr.frame = CGRect(origin: CGPointZero, size: collectionViewContentSize()) default: break } return attr } } // MARK: - MonthCalendarViewCell /// Default implementation of day cell public class MonthCalendarViewCell: UICollectionViewCell { weak public var calendarView: MonthCalendarView? { didSet { setNeedsLayout() } } public let label = UILabel() public var indexPath: NSIndexPath? private var circleView: UIView? public class func identifier() -> String { return "MonthCalendarViewCell" } public override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!) { super.applyLayoutAttributes(layoutAttributes) indexPath = layoutAttributes.indexPath setNeedsLayout() } public override func layoutSubviews() { // TODO: Fix selection flickering if label.superview == nil { label.textAlignment = .Center label.frame = bounds label.autoresizingMask = .FlexibleWidth | .FlexibleHeight contentView.addSubview(label) } let date: NSDate! = indexPath != nil ? calendarView?.dateAtIndexPath(indexPath!) : nil if date != nil { let cv = calendarView! let comps = cv.calendar.components(.DayCalendarUnit, fromDate: date) let isToday = cv.isTodayEqualToDate(date) let isCurrentMonth = cv.isCurrentMonthForDate(date) let fontSize: CGFloat = 17 let isBold = isCurrentMonth && isToday let isSelected = cv.isSelectedDate(date) label.text = "\(comps.day)" label.font = isBold ? UIFont.boldSystemFontOfSize(fontSize) : UIFont.systemFontOfSize(fontSize) if isSelected { label.textColor = UIColor.whiteColor() if circleView == nil { circleView = UIView() contentView.insertSubview(circleView!, atIndex: 0) } let width = CGRectGetWidth(bounds) let height = CGRectGetHeight(bounds) let circleDiameter = min(fontSize + 12, min(width, height)) let circleSize = CGSize(width: circleDiameter, height: circleDiameter) if isCurrentMonth { circleView!.backgroundColor = isToday ? tintColor : UIColor.darkTextColor() } else { circleView!.backgroundColor = UIColor.lightGrayColor() } circleView!.layer.cornerRadius = circleDiameter / 2 circleView!.frame = CGRect(origin: CGPoint(x: (width - circleDiameter) / 2, y: (height - circleDiameter) / 2), size: circleSize) } else { label.textColor = isToday ? tintColor : (isCurrentMonth ? UIColor.darkTextColor() : UIColor.lightGrayColor()) circleView?.removeFromSuperview() circleView = nil } } else { label.text = "" backgroundColor = nil } super.layoutSubviews() } } // MARK: - MonthCalendarViewBackground public class MonthCalendarViewBackground: UICollectionReusableView { public weak var calendarView: MonthCalendarView? { didSet { setNeedsDisplay() } } public class func identifier() -> String { return "MonthCalendarViewBackground" } public override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!) { super.applyLayoutAttributes(layoutAttributes) opaque = false setNeedsDisplay() } public override func drawRect(rect: CGRect) { super.drawRect(rect) let ctx = UIGraphicsGetCurrentContext() CGContextClearRect(ctx, bounds) if let cv = self.calendarView { let width = CGRectGetWidth(bounds) let height = CGRectGetHeight(bounds) let cellSize = cv.calendarCellSize // Draw weekends, first and last column if cv.showWeekendBackground { let weekends = [ CGRect(x: 0, y: 0, width: cellSize.width, height: height), CGRect(x: width - cellSize.width, y: 0, width: cellSize.width, height: height) ] CGContextSetFillColorWithColor(ctx, cv.weekendBackgroundColor.CGColor) for rect in weekends { CGContextFillRect(ctx, rect) } } if cv.showHorizontalGridlines { var y = cellSize.height while y < height { CGContextMoveToPoint(ctx, 0, y) CGContextAddLineToPoint(ctx, width, y) y += cellSize.height } } if cv.showVerticalGridlines { var x = cellSize.width var i = 0 while x < width { CGContextMoveToPoint(ctx, x, 0) CGContextAddLineToPoint(ctx, x, height) x += cellSize.width i++ } } CGContextSetLineWidth(ctx, 1.0 / UIScreen.mainScreen().scale) CGContextSetStrokeColorWithColor(ctx, cv.gridlineColor.CGColor) CGContextStrokePath(ctx) } } } // MARK: - MonthCalendarSection /// Internal structure containing month section information private struct MonthCalendarSection { let month: NSDate let startDate: NSDate let numberOfRows: Int let numberOfWeeks: Int let numberOfItems: Int }
6719368ffde0a28b2b400703a3d5053b
41.216667
206
0.669617
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureKYC/Sources/FeatureKYCUI/MobileNumber/KYCConfirmPhoneNumberController.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import FeatureKYCDomain import PlatformKit import PlatformUIKit import ToolKit final class KYCConfirmPhoneNumberController: KYCBaseViewController, BottomButtonContainerView, ProgressableView { // MARK: ProgressableView var barColor: UIColor = .green var startingValue: Float = 0.75 @IBOutlet var progressView: UIProgressView! // MARK: Public Properties var phoneNumber: String = "" { didSet { guard isViewLoaded else { return } labelPhoneNumber.text = phoneNumber } } // MARK: BottomButtonContainerView var optionalOffset: CGFloat = 0 var originalBottomButtonConstraint: CGFloat! @IBOutlet var layoutConstraintBottomButton: NSLayoutConstraint! // MARK: IBOutlets @IBOutlet private var labelPhoneNumber: UILabel! @IBOutlet private var validationTextFieldConfirmationCode: ValidationTextField! @IBOutlet private var primaryButton: PrimaryButtonContainer! private lazy var presenter: KYCVerifyPhoneNumberPresenter = KYCVerifyPhoneNumberPresenter(view: self) deinit { cleanUp() } // MARK: Factory override class func make(with coordinator: KYCRouter) -> KYCConfirmPhoneNumberController { let controller = makeFromStoryboard(in: .module) controller.router = coordinator controller.pageType = .confirmPhone return controller } // MARK: View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() validationTextFieldConfirmationCode.autocapitalizationType = .allCharacters validationTextFieldConfirmationCode.contentType = .oneTimeCode labelPhoneNumber.text = phoneNumber originalBottomButtonConstraint = layoutConstraintBottomButton.constant validationTextFieldConfirmationCode.becomeFocused() primaryButton.actionBlock = { [unowned self] in self.onNextTapped() } setupProgressView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setUpBottomButtonContainerView() validationTextFieldConfirmationCode.becomeFocused() } // MARK: - KYCRouterDelegate override func apply(model: KYCPageModel) { guard case .phone(let user) = model else { return } guard let mobile = user.mobile, phoneNumber.count == 0 else { return } phoneNumber = mobile.phone } // MARK: Actions @IBAction func onResendCodeTapped(_ sender: Any) { presenter.startVerification(number: phoneNumber) } private func onNextTapped() { guard case .valid = validationTextFieldConfirmationCode.validate() else { validationTextFieldConfirmationCode.becomeFocused() Logger.shared.warning("text field is invalid.") return } guard let code = validationTextFieldConfirmationCode.text else { Logger.shared.warning("code is nil.") return } presenter.verifyNumber(with: code) } } extension KYCConfirmPhoneNumberController: KYCConfirmPhoneNumberView { func confirmCodeSuccess() { router.handle(event: .nextPageFromPageType(pageType, nil)) } func startVerificationSuccess() { Logger.shared.info("Verification code sent.") } func hideLoadingView() { primaryButton.isLoading = false } func showError(message: String) { AlertViewPresenter.shared.standardError(message: message, in: self) } func showLoadingView(with text: String) { primaryButton.isLoading = true } }
7c15df108d11e09af574956e4926c1cb
28.902439
113
0.692496
false
false
false
false
jonnguy/HSTracker
refs/heads/master
HSTracker/Logging/Enums/PlayState.swift
mit
1
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 19/02/16. */ import Foundation enum PlayState: Int, CaseIterable { case invalid = 0, playing = 1, winning = 2, losing = 3, won = 4, lost = 5, tied = 6, disconnected = 7, conceded = 8 init?(rawString: String) { let string = rawString.lowercased() for _enum in PlayState.allCases where "\(_enum)" == string { self = _enum return } if let value = Int(rawString), let _enum = PlayState(rawValue: value) { self = _enum return } self = .invalid } }
220fd7a79923cc350b61531cc1214adc
22.083333
79
0.574007
false
false
false
false
grigaci/WallpapersCollectionView
refs/heads/master
WallpapersCollectionView/WallpapersCollectionView/Classes/GUI/TransylvaniaPhotos/BITransylvaniaPhotosViewController.swift
mit
1
// // BITransylvaniaPhotosViewController.swift // WallpapersCollectionView // // Created by Bogdan Iusco on 8/9/14. // Copyright (c) 2014 Grigaci. All rights reserved. // import UIKit class BITransylvaniaPhotosViewController: UICollectionViewController { let kCollectionViewCellID = NSStringFromClass(BITransylvaniaPhotosViewController.self) override init() { var layout = UICollectionViewFlowLayout() layout.estimatedItemSize = CGSizeMake(100, 100) layout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20) super.init(collectionViewLayout: layout) self.collectionView.dataSource = self self.collectionView.delegate = self self.title = BILocalizedString("Transylvania Photos") } convenience required init(coder: NSCoder) { self.init() } override func viewDidLoad() { super.viewDidLoad() self.collectionView.registerClass(BIPhotoCollectionViewCell.self, forCellWithReuseIdentifier: kCollectionViewCellID) } override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return BIModelManager.sharedInstance.locationsCount } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var location = BIModelManager.sharedInstance.locationAtIndex(section) var countPhotos = (location != nil) ? location?.photos.count : 0 return countPhotos! } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell:BIPhotoCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(kCollectionViewCellID, forIndexPath: indexPath) as BIPhotoCollectionViewCell var location = BIModelManager.sharedInstance.locationAtIndex(indexPath.section) var photo = location?.photos.objectAtIndex(indexPath.row) as BIPhoto cell.photo = photo return cell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { var cell:BIPhotoCollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath) as BIPhotoCollectionViewCell var photoViewController: BIPhotoViewController = BIPhotoViewController(nibName: nil, bundle: nil) // Set photo photoViewController.photo = cell.photo // Set title var location = BIModelManager.sharedInstance.locationAtIndex(indexPath.section) photoViewController.title = location?.name // Push it on nav stack self.navigationController?.pushViewController(photoViewController, animated: true) } }
83ae24f3f88dc6ba86010e0fb8b4f43e
40.424242
175
0.742868
false
false
false
false
apple/swift-docc-symbolkit
refs/heads/main
Sources/SymbolKit/UnifiedSymbolGraph/UnifiedSymbolGraph.swift
apache-2.0
1
/* This source file is part of the Swift.org open source project Copyright (c) 2021-2022 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 Swift project authors */ import Foundation /// A combined ``SymbolGraph`` from multiple languages' views of the same module. public class UnifiedSymbolGraph { /// The module that these combined symbol graphs represent. public var moduleName: String /// The decoded metadata about the module being represented, indexed by the file path of the symbol graph it was decoded from. /// /// Some module symbol graphs contain different metadata (e.g. platform it was rendered for, "bystander" modules, etc), and this allows users of unified graph data to load individual graphs' module data. public var moduleData: [URL: SymbolGraph.Module] /// Metadata about the individual symbol graphs that were combined together, indexed by the file path of each input symbol graph. public var metadata: [URL: SymbolGraph.Metadata] /// The symbols in the module, indexed by precise identifier. public var symbols: [String: UnifiedSymbolGraph.Symbol] /// The relationships between symbols. @available(*, deprecated, message: "Use unifiedRelationships and orphanRelationships instead") public var relationships: [SymbolGraph.Relationship] { var allRelations = mergeRelationships(Array(relationshipsByLanguage.values.joined())) allRelations.append(contentsOf: self.orphanRelationships) return allRelations } /// The relationships between symbols, separated by the language's view those relationships are /// relevant in. public var relationshipsByLanguage: [Selector: [SymbolGraph.Relationship]] /// A list of relationships between symbols, for which neither the source nor target were able /// to be matched with an appropriate symbol in the collected graphs. public var orphanRelationships: [SymbolGraph.Relationship] public init?(fromSingleGraph graph: SymbolGraph, at url: URL) { let (_, isMainGraph) = GraphCollector.moduleNameFor(graph, at: url) self.moduleName = graph.module.name self.moduleData = [url: graph.module] self.metadata = [url: graph.metadata] self.symbols = graph.symbols.mapValues { UnifiedSymbolGraph.Symbol(fromSingleSymbol: $0, module: graph.module, isMainGraph: isMainGraph) } self.relationshipsByLanguage = [:] self.orphanRelationships = [] loadRelationships(fromGraph: graph) } } extension UnifiedSymbolGraph { func loadRelationships(fromGraph graph: SymbolGraph) { var newRelations: [Selector: [SymbolGraph.Relationship]] = [:] for rel in graph.relationships { // associate each relationship with a selector based on the symbol(s) it references let selectors: [Selector] if let sourceSym = graph.symbols[rel.source] { selectors = [Selector(interfaceLanguage: sourceSym.identifier.interfaceLanguage, platform: graph.module.platform.name)] } else if let targetSym = graph.symbols[rel.target] { selectors = [Selector(interfaceLanguage: targetSym.identifier.interfaceLanguage, platform: graph.module.platform.name)] } else if let unifiedSourceSym = self.symbols[rel.source] { selectors = unifiedSourceSym.mainGraphSelectors } else if let unifiedTargetSym = self.symbols[rel.target] { selectors = unifiedTargetSym.mainGraphSelectors } else { // If we can't find the appropriate selector(s) to use, consider the relationship an // orphan and save it for later. self.orphanRelationships.append(rel) continue } for selector in selectors { if !newRelations.keys.contains(selector) { newRelations[selector] = [] } newRelations[selector]!.append(rel) } } for (key: selector, value: relations) in newRelations { self.relationshipsByLanguage[selector] = mergeRelationships(self.relationshipsByLanguage[selector, default: []], relations) } } /// Merge the given lists of ``SymbolGraph/Relationship``s. /// /// This function will deduplicate relationships based on their source, target, and kind. If it sees a duplicate, it will keep the first one it sees. func mergeRelationships(_ relationsList: [SymbolGraph.Relationship]...) -> [SymbolGraph.Relationship] { struct RelationKey: Hashable { let source: String let target: String let kind: SymbolGraph.Relationship.Kind init(fromRelation relationship: SymbolGraph.Relationship) { self.source = relationship.source self.target = relationship.target self.kind = relationship.kind } static func makePair(fromRelation relationship: SymbolGraph.Relationship) -> (RelationKey, SymbolGraph.Relationship) { return (RelationKey(fromRelation: relationship), relationship) } } let allRelations = relationsList.joined() // deduplicate the combined relationships array by source/target/kind // FIXME: Actually merge relationships if they have different mixins (rdar://84267943) let map = [:].merging(allRelations.map({ RelationKey.makePair(fromRelation: $0) }), uniquingKeysWith: { r1, r2 in r1 }) return Array(map.values) } /// Scans over ``orphanRelationships`` and sorts any whose source/target symbols were loaded /// after the relationship was. /// /// Since relationships are added to ``relationshipsByLanguage`` based on what symbols are /// available when the relationship is being loaded, a relationship can be considered an /// "orphan" even when it's not, if the symbol graphs are loaded in a certain order. This /// method was added to ensure that these relationships can be properly assigned a language /// even if the symbol information isn't in the same symbol graph. internal func collectOrphans() { var newRelations: [Selector: [SymbolGraph.Relationship]] = [:] var remainingOrphans: [SymbolGraph.Relationship] = [] for rel in self.orphanRelationships { let selectors: [Selector] if let unifiedSourceSym = self.symbols[rel.source] { selectors = unifiedSourceSym.mainGraphSelectors } else if let unifiedSourceSym = self.symbols[rel.target] { selectors = unifiedSourceSym.mainGraphSelectors } else { remainingOrphans.append(rel) continue } for selector in selectors { if !newRelations.keys.contains(selector) { newRelations[selector] = [] } newRelations[selector]!.append(rel) } } for (key: selector, value: relations) in newRelations { self.relationshipsByLanguage[selector] = mergeRelationships(self.relationshipsByLanguage[selector, default: []], relations) } self.orphanRelationships = remainingOrphans } /// Merge the given symbol graph with this one. public func mergeGraph(graph: SymbolGraph, at url: URL) { let (_, isMainGraph) = GraphCollector.moduleNameFor(graph, at: url) self.metadata[url] = graph.metadata self.moduleData[url] = graph.module for (key: precise, value: sym) in graph.symbols { if let existingSymbol = self.symbols[precise] { existingSymbol.mergeSymbol(symbol: sym, module: graph.module, isMainGraph: isMainGraph) } else { self.symbols[precise] = Symbol(fromSingleSymbol: sym, module: graph.module, isMainGraph: isMainGraph) } } loadRelationships(fromGraph: graph) } } extension UnifiedSymbolGraph { /// A combination of interface language and list of platforms that allows a symbol to be distinguished from another when unifying symbol graphs. public struct Selector: Equatable, Hashable, Encodable { /// The interface language used for the symbol. public let interfaceLanguage: String /// The platform that the symbol was built for. /// /// If the symbol graph that the symbol was sourced from does not contain a `module.platform.operatingSystem`, this will be `nil`. public let platform: String? public init(interfaceLanguage: String, platform: String?) { self.interfaceLanguage = interfaceLanguage self.platform = platform } /// Creates a ``UnifiedSymbolGraph/Selector`` for the given symbol graph's language and platform. /// /// If `graph` has no symbols, this will return `nil`. public init?(forSymbolGraph graph: SymbolGraph) { guard let lang = graph.symbols.first?.value.identifier.interfaceLanguage else { return nil } self.interfaceLanguage = lang self.platform = graph.module.platform.name } } }
57f5af23e5d4aeb0332adac5d71f4943
44.317308
207
0.664651
false
false
false
false
LYM-mg/GoodBookDemo
refs/heads/master
GoodBookDemo/GoodBookDemo/Login/MGLoginViewController.swift
mit
1
// // MGLoginViewController.swift // GoodBookDemo // // Created by ming on 16/5/7. // Copyright © 2016年 ming. All rights reserved. // import UIKit class MGLoginViewController: UIViewController{ // MARK:- 属性 /** 账号 */ @IBOutlet weak var accountField: UITextField! /** 密码 */ @IBOutlet weak var passwordField: UITextField! /** 登录按钮 */ @IBOutlet weak var loginBtn: UIButton! @IBOutlet weak var topLayout: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() MGNotificationCenter.addObserver(self, selector: Selector("keyboardDidHide"), name: UIKeyboardDidHideNotification, object: nil) MGNotificationCenter.addObserver(self, selector: Selector("keyboardDidShow"), name: UIKeyboardDidShowNotification, object: nil) } // MARK:- 操作 // 登录 @IBAction func loginBtnClick(sender: UIButton) { AVUser.logInWithUsernameInBackground(self.accountField.text, password: self.passwordField.text) { (user, error) -> Void in if error == nil { self.dismissViewControllerAnimated(true, completion: { () -> Void in }) }else{ if error.code == 210{ ProgressHUD.showError("用户名或密码错误") }else if error.code == 211 { ProgressHUD.showError("不存在该用户") }else if error.code == 216 { ProgressHUD.showError("未验证邮箱") }else if error.code == 1{ ProgressHUD.showError("操作频繁") }else{ ProgressHUD.showError("登录失败") } } } } // MARK:- 注册键盘出现和消失 func keyboardDidShow() { UIView.animateWithDuration(0.3) { () -> Void in self.topLayout.constant = -200 self.view.layoutIfNeeded() } } func keyboardDidHide() { UIView.animateWithDuration(0.3) { () -> Void in self.topLayout.constant = 15 self.view.layoutIfNeeded() } } }
889ca3dc6c486dd29065732c06c17d27
29.492754
135
0.561787
false
false
false
false
vuinguyen/SubstringHashSwift
refs/heads/master
TrelloPlayground.playground/Contents.swift
apache-2.0
1
//: Playground - noun: a place where people can play // Author: Vui Nguyen // What: Test code to prepare software program that will be submitted // as part of my Trello application for the iOS Developer Position // Date: February 28, 2016 import UIKit func hash (eightLetterString: String) ->Int64 { var h:Int64 = 7 let letters:String = "acdegilmnoprstuw" for i in 0..<eightLetterString.characters.count { let eightLetterStringIndex = eightLetterString.startIndex.advancedBy(i); print(eightLetterStringIndex) let eightLetterStringChar = eightLetterString[eightLetterStringIndex] print(eightLetterStringChar) let lettersIndex = letters.characters.indexOf(eightLetterStringChar) let position = letters.startIndex.distanceTo(lettersIndex!) h = (h * 37 + position); print(h); print("\n") } return h } hash("leepadg") func reverseHash(hashie:Int64, wordLength:Int) -> String { let letters:String = "acdegilmnoprstuw" let thirtySeven:Int64 = 37 var remainders = [Int64]() remainders.insert(hashie, atIndex: 0) print(remainders[0]) var remainder = hashie for i in 1..<wordLength+1 { remainders.insert(remainder / thirtySeven, atIndex: i) remainder = remainders[i] print (remainder) } var reversedString:String = "" var resultString:String = "" var letterIndex = 0 for i in 0..<wordLength { letterIndex = remainders[i] - (remainders[i+1] * 37) print("\n") print(letterIndex) let lettersStringIndex = letters.startIndex.advancedBy(letterIndex); print (letters[lettersStringIndex]) resultString.append(letters[lettersStringIndex]) } reversedString = String(resultString.characters.reverse()) print(reversedString) return reversedString } reverseHash(680131659347, wordLength:7) reverseHash(25377615533200, wordLength:8)
1689363b9452ae5908f37a0fd04a450c
27.681159
80
0.676099
false
false
false
false
KrishMunot/swift
refs/heads/master
stdlib/public/core/Collection.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A type that provides subscript access to its elements. /// /// - Important: In most cases, it's best to ignore this protocol and use /// `CollectionType` instead, as it has a more complete interface. public protocol Indexable { // This protocol is almost an implementation detail of the standard // library; it is used to deduce things like the `SubSequence` and // `Iterator` type from a minimal collection, but it is also used in // exposed places like as a constraint on `IndexingIterator`. /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. associatedtype Index : ForwardIndex /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. /// /// - Complexity: O(1) var startIndex: Index { get } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. /// /// - Complexity: O(1) var endIndex: Index { get } // The declaration of _Element and subscript here is a trick used to // break a cyclic conformance/deduction that Swift can't handle. We // need something other than a Collection.Iterator.Element that can // be used as IndexingIterator<T>'s Element. Here we arrange for // the Collection itself to have an Element type that's deducible from // its subscript. Ideally we'd like to constrain this Element to be the same // as Collection.Iterator.Element (see below), but we have no way of // expressing it today. associatedtype _Element /// Returns the element at the given `position`. /// /// - Complexity: O(1) subscript(position: Index) -> _Element { get } } /// A type that supports subscript assignment to a mutable collection. public protocol MutableIndexable { associatedtype Index : ForwardIndex var startIndex: Index { get } var endIndex: Index { get } associatedtype _Element subscript(position: Index) -> _Element { get set } } /// The iterator used for collections that don't specify one. public struct IndexingIterator<Elements : Indexable> : IteratorProtocol, Sequence { /// Create an *iterator* over the given collection. public /// @testable init(_elements: Elements) { self._elements = _elements self._position = _elements.startIndex } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Precondition: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> Elements._Element? { if _position == _elements.endIndex { return nil } let element = _elements[_position] _position._successorInPlace() return element } internal let _elements: Elements internal var _position: Elements.Index } /// A multi-pass sequence with addressable positions. /// /// Positions are represented by an associated `Index` type. Whereas /// an arbitrary sequence may be consumed as it is traversed, a /// collection is multi-pass: any element may be revisited merely by /// saving its index. /// /// The sequence view of the elements is identical to the collection /// view. In other words, the following code binds the same series of /// values to `x` as does `for x in self {}`: /// /// for i in startIndex..<endIndex { /// let x = self[i] /// } public protocol Collection : Indexable, Sequence { /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. /// /// By default, a `Collection` satisfies `Sequence` by /// supplying a `IndexingIterator` as its associated `Iterator` /// type. associatedtype Iterator : IteratorProtocol = IndexingIterator<Self> // FIXME: Needed here so that the `Iterator` is properly deduced from // a custom `makeIterator()` function. Otherwise we get an // `IndexingIterator`. <rdar://problem/21539115> func makeIterator() -> Iterator // FIXME: should be constrained to Collection // (<rdar://problem/20715009> Implement recursive protocol // constraints) /// A `Sequence` that can represent a contiguous subrange of `self`'s /// elements. /// /// - Note: This associated type appears as a requirement in /// `Sequence`, but is restated here with stricter /// constraints: in a `Collection`, the `SubSequence` should /// also be a `Collection`. associatedtype SubSequence : Indexable, Sequence = Slice<Self> /// Returns the element at the given `position`. subscript(position: Index) -> Iterator.Element { get } /// Returns a collection representing a contiguous sub-range of /// `self`'s elements. /// /// - Complexity: O(1) subscript(bounds: Range<Index>) -> SubSequence { get } /// Returns `self[startIndex..<end]` /// /// - Complexity: O(1) @warn_unused_result func prefix(upTo end: Index) -> SubSequence /// Returns `self[start..<endIndex]` /// /// - Complexity: O(1) @warn_unused_result func suffix(from start: Index) -> SubSequence /// Returns `prefix(upTo: position.successor())` /// /// - Complexity: O(1) @warn_unused_result func prefix(through position: Index) -> SubSequence /// Returns `true` iff `self` is empty. var isEmpty: Bool { get } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`; /// O(N) otherwise. var count: Index.Distance { get } // The following requirement enables dispatching for indexOf when // the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found; /// `nil` otherwise. /// /// - Complexity: O(N). @warn_unused_result func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? /// Returns the first element of `self`, or `nil` if `self` is empty. var first: Iterator.Element? { get } } /// Supply the default `makeIterator()` method for `Collection` models /// that accept the default associated `Iterator`, /// `IndexingIterator<Self>`. extension Collection where Iterator == IndexingIterator<Self> { public func makeIterator() -> IndexingIterator<Self> { return IndexingIterator(_elements: self) } } /// Supply the default "slicing" `subscript` for `Collection` models /// that accept the default associated `SubSequence`, `Slice<Self>`. extension Collection where SubSequence == Slice<Self> { public subscript(bounds: Range<Index>) -> Slice<Self> { Index._failEarlyRangeCheck2( rangeStart: bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return Slice(_base: self, bounds: bounds) } } extension Collection where SubSequence == Self { /// If `!self.isEmpty`, remove the first element and return it, otherwise /// return `nil`. /// /// - Complexity: O(1) @warn_unused_result public mutating func popFirst() -> Iterator.Element? { guard !isEmpty else { return nil } let element = first! self = self[startIndex.successor()..<endIndex] return element } } extension Collection where SubSequence == Self, Index : BidirectionalIndex { /// If `!self.isEmpty`, remove the last element and return it, otherwise /// return `nil`. /// /// - Complexity: O(1) @warn_unused_result public mutating func popLast() -> Iterator.Element? { guard !isEmpty else { return nil } let element = last! self = self[startIndex..<endIndex.predecessor()] return element } } /// Default implementations of core requirements extension Collection { /// Returns `true` iff `self` is empty. /// /// - Complexity: O(1) public var isEmpty: Bool { return startIndex == endIndex } /// Returns the first element of `self`, or `nil` if `self` is empty. /// /// - Complexity: O(1) public var first: Iterator.Element? { // NB: Accessing `startIndex` may not be O(1) for some lazy collections, // so instead of testing `isEmpty` and then returning the first element, // we'll just rely on the fact that the iterator always yields the // first element first. var i = makeIterator() return i.next() } /// Returns a value less than or equal to the number of elements in /// `self`, *nondestructively*. /// /// - Complexity: O(`count`). public var underestimatedCount: Int { return numericCast(count) } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`; /// O(N) otherwise. public var count: Index.Distance { return startIndex.distance(to: endIndex) } /// Customization point for `Sequence.index(of:)`. /// /// Define this method if the collection can find an element in less than /// O(N) by exploiting collection-specific knowledge. /// /// - Returns: `nil` if a linear search should be attempted instead, /// `Optional(nil)` if the element was not found, or /// `Optional(Optional(index))` if an element was found. /// /// - Complexity: O(`count`). @warn_unused_result public // dispatching func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? { return nil } } //===----------------------------------------------------------------------===// // Default implementations for Collection //===----------------------------------------------------------------------===// extension Collection { /// Returns an `Array` containing the results of mapping `transform` /// over `self`. /// /// - Complexity: O(N). @warn_unused_result public func map<T>( @noescape _ transform: (Iterator.Element) throws -> T ) rethrows -> [T] { let count: Int = numericCast(self.count) if count == 0 { return [] } var result = ContiguousArray<T>() result.reserveCapacity(count) var i = self.startIndex for _ in 0..<count { result.append(try transform(self[i])) i = i.successor() } _expectEnd(i, self) return Array(result) } /// Returns a subsequence containing all but the first `n` elements. /// /// - Precondition: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropFirst(_ n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let start = startIndex.advanced(by: numericCast(n), limit: endIndex) return self[start..<endIndex] } /// Returns a subsequence containing all but the last `n` elements. /// /// - Precondition: `n >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func dropLast(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let amount = Swift.max(0, numericCast(count) - n) let end = startIndex.advanced(by: numericCast(amount), limit: endIndex) return self[startIndex..<end] } /// Returns a subsequence, up to `maxLength` in length, containing the /// initial elements. /// /// If `maxLength` exceeds `self.count`, the result contains all /// the elements of `self`. /// /// - Precondition: `maxLength >= 0` /// - Complexity: O(`maxLength`) @warn_unused_result public func prefix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a prefix of negative length from a collection") let end = startIndex.advanced(by: numericCast(maxLength), limit: endIndex) return self[startIndex..<end] } /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `self`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `self`. /// /// - Precondition: `maxLength >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let amount = Swift.max(0, numericCast(count) - maxLength) let start = startIndex.advanced(by: numericCast(amount), limit: endIndex) return self[start..<endIndex] } /// Returns `self[startIndex..<end]` /// /// - Complexity: O(1) @warn_unused_result public func prefix(upTo end: Index) -> SubSequence { return self[startIndex..<end] } /// Returns `self[start..<endIndex]` /// /// - Complexity: O(1) @warn_unused_result public func suffix(from start: Index) -> SubSequence { return self[start..<endIndex] } /// Returns `prefix(upTo: position.successor())` /// /// - Complexity: O(1) @warn_unused_result public func prefix(through position: Index) -> SubSequence { return prefix(upTo: position.successor()) } /// Returns the maximal `SubSequence`s of `self`, in order, that /// don't contain elements satisfying the predicate `isSeparator`. /// /// - Parameter maxSplits: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplits + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing *all* the elements of `self` following the /// last split point. /// The default value is `Int.max`. /// /// - Parameter omittingEmptySubsequences: If `false`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `true`. /// /// - Precondition: `maxSplits >= 0` @warn_unused_result public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, @noescape isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [SubSequence] = [] var subSequenceStart: Index = startIndex func appendSubsequence(end: Index) -> Bool { if subSequenceStart == end && omittingEmptySubsequences { return false } result.append(self[subSequenceStart..<end]) return true } if maxSplits == 0 || isEmpty { appendSubsequence(end: endIndex) return result } var subSequenceEnd = subSequenceStart let cachedEndIndex = endIndex while subSequenceEnd != cachedEndIndex { if try isSeparator(self[subSequenceEnd]) { let didAppend = appendSubsequence(end: subSequenceEnd) subSequenceEnd._successorInPlace() subSequenceStart = subSequenceEnd if didAppend && result.count == maxSplits { break } continue } subSequenceEnd._successorInPlace() } if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences { result.append(self[subSequenceStart..<cachedEndIndex]) } return result } } extension Collection where Iterator.Element : Equatable { /// Returns the maximal `SubSequence`s of `self`, in order, around a /// `separator` element. /// /// - Parameter maxSplits: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplits + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing *all* the elements of `self` following the /// last split point. /// The default value is `Int.max`. /// /// - Parameter omittingEmptySubsequences: If `false`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// equal to `separator`. /// The default value is `true`. /// /// - Precondition: `maxSplits >= 0` @warn_unused_result public func split( separator: Iterator.Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [SubSequence] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, isSeparator: { $0 == separator }) } } extension Collection where Index : BidirectionalIndex { /// Returns a subsequence containing all but the last `n` elements. /// /// - Precondition: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropLast(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let end = endIndex.advanced(by: numericCast(-n), limit: startIndex) return self[startIndex..<end] } /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `self`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `self`. /// /// - Precondition: `maxLength >= 0` /// - Complexity: O(`maxLength`) @warn_unused_result public func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let start = endIndex.advanced(by: numericCast(-maxLength), limit: startIndex) return self[start..<endIndex] } } extension Collection where SubSequence == Self { /// Remove the element at `startIndex` and return it. /// /// - Complexity: O(1) /// - Precondition: `!self.isEmpty`. @discardableResult public mutating func removeFirst() -> Iterator.Element { _precondition(!isEmpty, "can't remove items from an empty collection") let element = first! self = self[startIndex.successor()..<endIndex] return element } /// Remove the first `n` elements. /// /// - Complexity: /// - O(1) if `Index` conforms to `RandomAccessIndex` /// - O(n) otherwise /// - Precondition: `n >= 0 && self.count >= n`. public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[startIndex.advanced(by: numericCast(n))..<endIndex] } } extension Collection where SubSequence == Self, Index : BidirectionalIndex { /// Remove an element from the end. /// /// - Complexity: O(1) /// - Precondition: `!self.isEmpty` @discardableResult public mutating func removeLast() -> Iterator.Element { let element = last! self = self[startIndex..<endIndex.predecessor()] return element } /// Remove the last `n` elements. /// /// - Complexity: /// - O(1) if `Index` conforms to `RandomAccessIndex` /// - O(n) otherwise /// - Precondition: `n >= 0 && self.count >= n`. public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[startIndex..<endIndex.advanced(by: numericCast(-n))] } } extension Sequence where Self : _ArrayProtocol, Self.Element == Self.Iterator.Element { // A fast implementation for when you are backed by a contiguous array. public func _copyContents( initializing ptr: UnsafeMutablePointer<Iterator.Element> ) -> UnsafeMutablePointer<Iterator.Element> { let s = self._baseAddressIfContiguous if s != nil { let count = self.count ptr.initializeFrom(s, count: count) _fixLifetime(self._owner) return ptr + count } else { var p = ptr for x in self { p.initialize(with: x) p += 1 } return p } } } extension Collection { public func _preprocessingPass<R>(@noescape _ preprocess: () -> R) -> R? { return preprocess() } } /// A *collection* that supports subscript assignment. /// /// For any instance `a` of a type conforming to /// `MutableCollection`, : /// /// a[i] = x /// let y = a[i] /// /// is equivalent to: /// /// a[i] = x /// let y = x /// public protocol MutableCollection : MutableIndexable, Collection { // FIXME: should be constrained to MutableCollection // (<rdar://problem/20715009> Implement recursive protocol // constraints) associatedtype SubSequence : Collection /*: MutableCollection*/ = MutableSlice<Self> /// Access the element at `position`. /// /// - Precondition: `position` indicates a valid position in `self` and /// `position != endIndex`. /// /// - Complexity: O(1) subscript(position: Index) -> Iterator.Element {get set} /// Returns a collection representing a contiguous sub-range of /// `self`'s elements. /// /// - Complexity: O(1) for the getter, O(`bounds.count`) for the setter. subscript(bounds: Range<Index>) -> SubSequence {get set} /// Call `body(p)`, where `p` is a pointer to the collection's /// mutable contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of mutable contiguous storage, `body` is not /// called and `nil` is returned. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func _withUnsafeMutableBufferPointerIfSupported<R>( @noescape _ body: (UnsafeMutablePointer<Iterator.Element>, Int) throws -> R ) rethrows -> R? // FIXME: the signature should use UnsafeMutableBufferPointer, but the // compiler can't handle that. // // <rdar://problem/21933004> Restore the signature of // _withUnsafeMutableBufferPointerIfSupported() that mentions // UnsafeMutableBufferPointer } extension MutableCollection { public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( @noescape _ body: (UnsafeMutablePointer<Iterator.Element>, Int) throws -> R ) rethrows -> R? { return nil } public subscript(bounds: Range<Index>) -> MutableSlice<Self> { get { Index._failEarlyRangeCheck2( rangeStart: bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return MutableSlice(_base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } } internal func _writeBackMutableSlice< C : MutableCollection, Slice_ : Collection where C._Element == Slice_.Iterator.Element, C.Index == Slice_.Index >(_ self_: inout C, bounds: Range<C.Index>, slice: Slice_) { C.Index._failEarlyRangeCheck2( rangeStart: bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: self_.startIndex, boundsEnd: self_.endIndex) // FIXME(performance): can we use // _withUnsafeMutableBufferPointerIfSupported? Would that create inout // aliasing violations if the newValue points to the same buffer? var selfElementIndex = bounds.startIndex let selfElementsEndIndex = bounds.endIndex var newElementIndex = slice.startIndex let newElementsEndIndex = slice.endIndex while selfElementIndex != selfElementsEndIndex && newElementIndex != newElementsEndIndex { self_[selfElementIndex] = slice[newElementIndex] selfElementIndex._successorInPlace() newElementIndex._successorInPlace() } _precondition( selfElementIndex == selfElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a smaller size") _precondition( newElementIndex == newElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a larger size") } @available(*, unavailable, message: "Bit enum has been deprecated. Please use Int instead.") public enum Bit {} @available(*, unavailable, renamed: "IndexingIterator") public struct IndexingGenerator<Elements : Indexable> {} @available(*, unavailable, renamed: "Collection") public typealias CollectionType = Collection extension Collection { @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator @available(*, unavailable, renamed: "makeIterator") public func generate() -> Iterator { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Removed in Swift 3. Please use underestimatedCount property.") public func underestimateCount() -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Please use split(maxSplits:omittingEmptySubsequences:isSeparator:) instead") public func split( _ maxSplit: Int = Int.max, allowEmptySlices: Bool = false, @noescape isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { fatalError("unavailable function can't be called") } } extension Collection where Iterator.Element : Equatable { @available(*, unavailable, message: "Please use split(separator:maxSplits:omittingEmptySubsequences:) instead") public func split( _ separator: Iterator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [SubSequence] { fatalError("unavailable function can't be called") } } @available(*, unavailable, renamed: "MutableCollection") public typealias MutableCollectionType = MutableCollection @available(*, unavailable, message: "PermutationGenerator has been removed in Swift 3") public struct PermutationGenerator<C : Collection, Indices : Sequence> {} @available(*, unavailable, message: "Please use 'Collection where SubSequence : MutableCollection'") public typealias MutableSliceable = Collection
7bd1e1e9be754581ae0da866c6c04dd8
32.07888
115
0.665308
false
false
false
false
zxpLearnios/MyProject
refs/heads/master
test_projectDemo1/TVC && NAV/TabBar/MyTabBar.swift
mit
1
// // MyTabBar.swift // test_projectDemo1 // // Created by Jingnan Zhang on 16/5/30. // Copyright © 2016年 Jingnan Zhang. All rights reserved. // 虽然替换了tabbar,但设置tabbar自身的属性时,还需在TVC里进行 import UIKit class MyTabBar: UITabBar { fileprivate let totalCount:CGFloat = 4 // 必须自己来修改,这样其实会更方便 var buttonW:CGFloat = 0.0 // 方便外界的加号按钮来设置 var onceToken:Int = 0 // MARK: 初始化 override init(frame: CGRect) { super.init(frame: frame) self.doInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } fileprivate func doInit() { } // 有几个子控件就会调用几次 override func layoutSubviews() { super.layoutSubviews() let buttonY:CGFloat = 0 buttonW = self.frame.width / totalCount let buttonH = self.frame.height var index:CGFloat = 0 debugPrint("layoutSubviews-------tabbar") // dispatch_once(&onceToken) { for item in self.subviews { var buttonX = index * self.buttonW // 只找出 所有的UITabBarItem, if item.isKind(of: UIControl.classForCoder()) { if index > 0 { buttonX = (index + 1) * self.buttonW } item.frame = CGRect(x: buttonX, y: buttonY, width: self.buttonW, height: buttonH) index += 1 // 最后一个加的控制器多对应的item, 此时将此item放在第二个的位置处; if index == self.totalCount { let rVC = kwindow!.rootViewController as! MyCustomTVC if rVC.isCompleteAnimate { // 在按钮动画结束后, 移除并加新的按钮 rVC.plusBtn.removeFromSuperview() buttonX = self.buttonW item.frame = CGRect(x: buttonX, y: buttonY, width: self.buttonW, height: buttonH) } } } // } } } }
1e14da73182dfd96de4b07818dea8b51
26.5375
109
0.470268
false
false
false
false
ivanbruel/SwipeIt
refs/heads/master
Pods/Localizable/Pod/LocalizableLanguage.swift
mit
1
// // Language.swift // Localizable // // Created by Ivan Bruel on 23/02/16. // Copyright © 2016 Localizable. All rights reserved. // import Foundation // MARK: Properties and Initializer final class LocalizableLanguage: Language { private struct JSONKeys { static let code = "code" static let modifiedAt = "modified_at" static let strings = "keywords" } private static let directory = "LocalizableLanguage" let code: String var modifiedAt: Int var strings: [String: String] init(code: String, modifiedAt: Int, strings: [String: String]) { self.code = code self.modifiedAt = modifiedAt self.strings = strings } convenience init(code: String) { guard let json: [String: AnyObject] = StorageHelper.loadObject(LocalizableLanguage.directory, filename: code) else { self.init(code: code, modifiedAt: 0, strings: [:]) return } let code = json[JSONKeys.code] as? String ?? code let version = json[JSONKeys.modifiedAt] as? Int ?? 0 let strings = json[JSONKeys.strings] as? [String: String] ?? [:] self.init(code: code, modifiedAt: version, strings: strings) } } // MARK: JSONRepresentable extension LocalizableLanguage: JSONRepresentable { convenience init?(json: [String: AnyObject]) { guard let code = json[JSONKeys.code] as? String, modifiedAt = json[JSONKeys.modifiedAt] as? Int, strings = json[JSONKeys.strings] as? [String: String] else { return nil } self.init(code: code, modifiedAt: modifiedAt, strings: strings) } var json: [String: AnyObject] { return [ JSONKeys.code: code, JSONKeys.modifiedAt: modifiedAt, JSONKeys.strings: strings ] } } // MARK: Storage extension LocalizableLanguage { private func save() { StorageHelper.saveObject(json, directory: LocalizableLanguage.directory, filename: code) } } // MARK: Networking extension LocalizableLanguage { func update(token: String, completion: ((NSError?) -> Void)?) { Network.sharedInstance .performRequest(.UpdateLanguage(language: self), token: token) { [weak self] (json, error) in guard let `self` = self, code = json?[JSONKeys.code] as? String, modifiedAt = json?[JSONKeys.modifiedAt] as? String, strings = json?[JSONKeys.strings] as? [String: String] where code == self.code else { completion?(error) return } self.modifiedAt = Int(modifiedAt) ?? 0 self.strings += strings self.save() completion?(error) } } }
5e372cda0bb01644738be9963104769d
24.405941
99
0.658223
false
false
false
false
AdilSoomro/ASBottomSheet
refs/heads/master
ASBottomSheet/Classes/ASBottomSheetItem.swift
mit
1
// // ASBottomSheetItem.swift // Imagitor // // Created by Adil Soomro on 3/13/17. // Copyright © 2017 BooleanBites Ltd. All rights reserved. // import UIKit public typealias ActionSuccess = () -> (); @objc open class ASBottomSheetItem: NSObject { var title:String? = nil var icon:UIImage? = nil private var tintedIcon:UIImage? = nil @objc open var action: ActionSuccess? = nil @objc public init(withTitle title:String, withIcon icon:UIImage) { super.init() self.title = title self.icon = icon } /** * Makes a tinted image * - parameter color: the tint color * - returns: a tinted image */ func tintedImage(withColor color:UIColor?) -> UIImage? { //cache the previous icon, and don't make new one if self.tintedIcon != nil { return tintedIcon } guard icon != nil else { return nil } UIGraphicsBeginImageContextWithOptions (icon!.size, false, UIScreen.main.scale); let context:CGContext = UIGraphicsGetCurrentContext()!; let rect:CGRect = CGRect(x:0,y: 0, width:icon!.size.width, height:icon!.size.height); //resolve CG/iOS coordinate mismatch context.scaleBy(x: 1, y: -1); context.translateBy(x: 0, y: -rect.size.height); //set the clipping area to the image context.clip(to: rect, mask: icon!.cgImage!); //set the fill color context.setFillColor((color?.cgColor.components!)!); context.fill(rect); //blend mode overlay context.setBlendMode(.overlay); //draw the image context.draw(icon!.cgImage!, in: rect) self.tintedIcon = UIGraphicsGetImageFromCurrentImageContext()!; UIGraphicsEndImageContext(); return tintedIcon } }
20c09229bf68bcf6bc54aa9f59a40d4d
26.971429
93
0.578141
false
false
false
false
GreenCom-Networks/ios-charts
refs/heads/master
Advanced/Pods/Charts/Charts/Classes/Data/Implementations/Standard/ScatterChartDataSet.swift
apache-2.0
8
// // ScatterChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics public class ScatterChartDataSet: LineScatterCandleRadarChartDataSet, IScatterChartDataSet { @objc public enum ScatterShape: Int { case Square case Circle case Triangle case Cross case X case Custom } // The size the scatter shape will have public var scatterShapeSize = CGFloat(10.0) // The type of shape that is set to be drawn where the values are at // **default**: .Square public var scatterShape = ScatterChartDataSet.ScatterShape.Square // The radius of the hole in the shape (applies to Square, Circle and Triangle) // **default**: 0.0 public var scatterShapeHoleRadius: CGFloat = 0.0 // Color for the hole in the shape. Setting to `nil` will behave as transparent. // **default**: nil public var scatterShapeHoleColor: NSUIColor? = nil // Custom path object to draw where the values are at. // This is used when shape is set to Custom. public var customScatterShape: CGPath? // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! ScatterChartDataSet copy.scatterShapeSize = scatterShapeSize copy.scatterShape = scatterShape copy.customScatterShape = customScatterShape return copy } }
1a2d3163b4504a8b90ada3e82efdafeb
27.644068
90
0.671598
false
false
false
false
IntrepidPursuits/swift-wisdom
refs/heads/master
SwiftWisdom/Core/Colors/ColorDescriptor.swift
mit
1
// // ColorDescriptor.swift // ChristmasCheer // // Created by Logan Wright on 10/25/15. // Copyright © 2015 lowriDevs. All rights reserved. // import UIKit public protocol ColorPalette { var rawValue: ColorDescriptor { get } } extension ColorPalette { public var color: UIColor { return rawValue.color } } public enum ColorDescriptor { case patternImage(imageName: String) case rgb255(r: Int, g: Int, b: Int, a: Int) case rgbFloat(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) case hex(hex: String) } extension ColorDescriptor: ExpressibleByStringLiteral, RawRepresentable, Equatable { public typealias RawValue = StringLiteralType public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = StringLiteralType public var color: UIColor { switch self { case let .patternImage(imageName: imageName): let image = UIImage(named: imageName)! return UIColor(patternImage: image) case let .rgb255(r: ri, g: gi, b: bi, a: ai): let r = CGFloat(ri) let g = CGFloat(gi) let b = CGFloat(bi) let a = CGFloat(ai) return UIColor(red: r / 255, green: g / 255, blue: b / 255, alpha: a / 255) case let .rgbFloat(r: r, g: g, b: b, a: a): return UIColor(red: r, green: g, blue: b, alpha: a) case let .hex(hex: hex): return UIColor(ip_hex: hex)! } } public var rawValue: RawValue { switch self { case let .patternImage(imageName: imageName): return imageName case let .rgb255(r: r, g: g, b: b, a: a): return "\(r),\(g),\(b),\(a)" case let .rgbFloat(r: r, g: g, b: b, a: a): return "\(r),\(g),\(b),\(a)" case let .hex(hex: hex): return hex } } // MARK: Initializers public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { guard let colorDescriptor = ColorDescriptor(value) else { fatalError( "Unrecognized color literal! Use format `r,g,b,a` on 255 or 0-1.0 scale, a valid UIImage name, or a 6 character hex string w/ `#` prefix") } self = colorDescriptor } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { guard let colorDescriptor = ColorDescriptor(value) else { fatalError( "Unrecognized color literal! Use format `r,g,b,a` on 255 or 0-1.0 scale, a valid UIImage name, or a 6 character hex string w/ `#` prefix") } self = colorDescriptor } public init(stringLiteral value: StringLiteralType) { guard let colorDescriptor = ColorDescriptor(value) else { fatalError( "Unrecognized color literal! Use format `r,g,b,a` on 255 or 0-1.0 scale, a valid UIImage name, or a 6 character hex string w/ `#` prefix") } self = colorDescriptor } public init?(rawValue: RawValue) { self.init(rawValue) } public init?(_ string: String) { let rgbComponents = string.components(separatedBy: ",") if rgbComponents.count == 4 { // If any portion of the string has a `.`, we are in 0-1.0 scale if string.contains(".") { let floats = rgbComponents .compactMap { Double($0) } .map { CGFloat($0) } self = .rgbFloat(r: floats[0], g: floats[1], b: floats[2], a: floats[3]) } else { let ints = rgbComponents.compactMap { Int($0) } self = .rgb255(r: ints[0], g: ints[1], b: ints[2], a: ints[3]) } } else if string.hasPrefix("#") { guard string.dropFirst().allSatisfy({ $0.isHexDigit }) else { return nil } self = .hex(hex: string) } else if UIImage(named: string) != nil { self = .patternImage(imageName: string) } else { return nil } } } // MARK: Operator Overloads extension ColorDescriptor { public static func == (lhs: ColorDescriptor, rhs: ColorDescriptor) -> Bool { return lhs.rawValue == rhs.rawValue } }
e1385c21763440e45d3df0aa0063e786
32.317829
150
0.579572
false
false
false
false
MrLSPBoy/LSPDouYu
refs/heads/master
LSPDouYuTV/LSPDouYuTV/Classes/Main/Controller/LSBaseViewController.swift
mit
1
// // LSBaseViewController.swift // LSPDouYuTV // // Created by lishaopeng on 17/3/6. // Copyright © 2017年 lishaopeng. All rights reserved. // import UIKit class LSBaseViewController: UIViewController { var contentView : UIView? //MARK:-懒加载属性 fileprivate lazy var animImageView : UIImageView = { [unowned self] in let imageView = UIImageView(image: UIImage(named: "img_loading_1")) imageView.center = self.view.center imageView.animationImages = [UIImage(named: "img_loading_1")!,UIImage(named: "img_loading_2")!] imageView.animationDuration = 0.5 imageView.animationRepeatCount = LONG_MAX imageView.autoresizingMask = [.flexibleTopMargin, . flexibleBottomMargin] return imageView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } extension LSBaseViewController { func setupUI(){ //1.隐藏内容的View contentView?.isHidden = true //2.添加执行动画的UIImageView view.addSubview(animImageView) //3.执行动画 animImageView.startAnimating() //4.设置view的背景颜色 view.backgroundColor = UIColor(r: 250, g: 250, b: 250) } func loadDataFinished() { //1.停止动画 animImageView.stopAnimating() //2.隐藏animImageView animImageView.isHidden = true //3.显示内容的View contentView?.isHidden = false } }
3dca5671f34fa7a078cf55dfc5384373
23.596774
103
0.611803
false
false
false
false
ahoppen/swift
refs/heads/main
test/Constraints/opened_existentials.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -enable-experimental-opened-existential-types protocol Q { } protocol P { associatedtype A: Q } extension Int: P { typealias A = Double } extension Array: P where Element: P { typealias A = String } extension Double: Q { } extension String: Q { } func acceptGeneric<T: P>(_: T) -> T.A? { nil } func acceptCollection<C: Collection>(_ c: C) -> C.Element { c.first! } // --- Simple opening of existential values func testSimpleExistentialOpening(p: any P, pq: any P & Q, c: any Collection) { let pa = acceptGeneric(p) let _: Int = pa // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}} let pqa = acceptGeneric(pq) let _: Int = pqa // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}} let element = acceptCollection(c) let _: Int = element // expected-error{{cannot convert value of type 'Any' to specified type 'Int'}} } // --- Requirements on nested types protocol CollectionOfPs: Collection where Self.Element: P { } func takeCollectionOfPs<C: Collection>(_: C) -> C.Element.A? where C.Element: P { nil } func testCollectionOfPs(cp: any CollectionOfPs) { let e = takeCollectionOfPs(cp) let _: Int = e // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}} } // --- Multiple opened existentials in the same expression func takeTwoGenerics<T1: P, T2: P>(_ a: T1, _ b: T2) -> (T1, T2) { (a, b) } extension P { func combineThePs<T: P & Q>(_ other: T) -> (A, T.A)? { nil } } func testMultipleOpened(a: any P, b: any P & Q) { let r1 = takeTwoGenerics(a, b) let _: Int = r1 // expected-error{{cannot convert value of type '(any P, any P & Q)' to specified type 'Int'}} let r2 = a.combineThePs(b) let _: Int = r2 // expected-error{{cannot convert value of type '(any Q, any Q)?' to specified type 'Int'}} } // --- Opening existential metatypes func conjureValue<T: P>(of type: T.Type) -> T? { nil } func testMagic(pt: any P.Type) { let pOpt = conjureValue(of: pt) let _: Int = pOpt // expected-error{{cannot convert value of type '(any P)?' to specified type 'Int'}} } // --- With primary associated types and opaque parameter types protocol CollectionOf<Element>: Collection { } extension Array: CollectionOf { } extension Set: CollectionOf { } // expected-note@+2{{required by global function 'reverseIt' where 'some CollectionOf<T>' = 'any CollectionOf'}} @available(SwiftStdlib 5.1, *) func reverseIt<T>(_ c: some CollectionOf<T>) -> some CollectionOf<T> { return c.reversed() } @available(SwiftStdlib 5.1, *) func useReverseIt(_ c: any CollectionOf) { // Can't type-erase the `T` from the result. _ = reverseIt(c) // expected-error{{type 'any CollectionOf' cannot conform to 'CollectionOf'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} } /// --- Opening existentials when returning opaque types. @available(SwiftStdlib 5.1, *) extension P { func getQ() -> some Q { let a: A? = nil return a! } func getCollectionOf() -> some CollectionOf<A> { return [] as [A] } } @available(SwiftStdlib 5.1, *) func getPQ<T: P>(_: T) -> some Q { let a: T.A? = nil return a! } // expected-note@+2{{required by global function 'getCollectionOfP' where 'T' = 'any P'}} @available(SwiftStdlib 5.1, *) func getCollectionOfP<T: P>(_: T) -> some CollectionOf<T.A> { return [] as [T.A] } func funnyIdentity<T: P>(_ value: T) -> T? { value } func arrayOfOne<T: P>(_ value: T) -> [T] { [value] } struct X<T: P> { // expected-note@-1{{required by generic struct 'X' where 'T' = 'any P'}} func f(_: T) { } } // expected-note@+1{{required by global function 'createX' where 'T' = 'any P'}} func createX<T: P>(_ value: T) -> X<T> { X<T>() } func doNotOpenOuter(p: any P) { _ = X().f(p) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} } func takesVariadic<T: P>(_ args: T...) { } // expected-note@-1 2{{required by global function 'takesVariadic' where 'T' = 'any P'}} // expected-note@-2{{in call to function 'takesVariadic'}} func callVariadic(p1: any P, p2: any P) { takesVariadic() // expected-error{{generic parameter 'T' could not be inferred}} takesVariadic(p1) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} takesVariadic(p1, p2) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} } func takesInOut<T: P>(_ value: inout T) { } func passesInOut(i: Int) { var p: any P = i takesInOut(&p) } @available(SwiftStdlib 5.1, *) func testReturningOpaqueTypes(p: any P) { let q = p.getQ() let _: Int = q // expected-error{{cannot convert value of type 'any Q' to specified type 'Int'}} p.getCollectionOf() // expected-error{{member 'getCollectionOf' cannot be used on value of type 'any P'; consider using a generic constraint instead}} let q2 = getPQ(p) let _: Int = q2 // expected-error{{cannot convert value of type 'any Q' to specified type 'Int'}} getCollectionOfP(p) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} let fi = funnyIdentity(p) let _: Int = fi // expected-error{{cannot convert value of type '(any P)?' to specified type 'Int'}} _ = arrayOfOne(p) // okay, arrays are covariant in their argument _ = createX(p) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} } // Type-erasing vs. opening for parameters after the opened one. func takeValueAndClosure<T: P>(_ value: T, body: (T) -> Void) { } func takeValueAndClosureBackwards<T: P>(body: (T) -> Void, _ value: T) { } // expected-note@-1{{required by global function 'takeValueAndClosureBackwards(body:_:)' where 'T' = 'any P'}} func genericFunctionTakingP<T: P>(_: T) { } func genericFunctionTakingPQ<T: P & Q>(_: T) { } func overloadedGenericFunctionTakingP<T: P>(_: T) -> Int { 0 } func overloadedGenericFunctionTakingP<T: P>(_: T) { } func testTakeValueAndClosure(p: any P) { // Type-erase when not provided with a generic function. takeValueAndClosure(p) { x in print(x) let _: Int = x // expected-error{{cannot convert value of type 'any P' to specified type 'Int'}} } // Do not erase when referring to a generic function. takeValueAndClosure(p, body: genericFunctionTakingP) takeValueAndClosure(p, body: overloadedGenericFunctionTakingP) takeValueAndClosure(p, body: genericFunctionTakingPQ) // expected-error{{global function 'genericFunctionTakingPQ' requires that 'T' conform to 'Q'}} // Do not allow opening if there are any uses of the type parameter before // the opened parameter. This maintains left-to-right evaluation order. takeValueAndClosureBackwards( // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} body: { x in x as Int }, // expected-error{{'any P' is not convertible to 'Int'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} p) }
fdfc685101a882255b13afe028c785e6
34.330189
152
0.674366
false
false
false
false
kouky/MavlinkPrimaryFlightDisplay
refs/heads/master
Sources/Mac/MavlinkController.swift
mit
1
// // MavlinkController.swift // MavlinkPrimaryFlightDisplay // // Created by Michael Koukoullis on 22/11/2015. // Copyright © 2015 Michael Koukoullis. All rights reserved. // import Cocoa import ORSSerial import ReactiveMavlink import ReactiveCocoa import Result class MavlinkController: NSObject { // MARK: Properties let reactiveMavlink = ReactiveMavlink() var serialPort: ORSSerialPort? { didSet { oldValue?.close() oldValue?.delegate = nil if let port = serialPort { port.delegate = self port.baudRate = 57600 port.numberOfStopBits = 1 port.parity = .None port.open() startUsbMavlinkSession() } } } var availableSerialPorts: SignalProducer<[ORSSerialPort], NoError>{ return availablePorts.producer } private let availablePorts = MutableProperty<[ORSSerialPort]>([]) private let serialPortManager = ORSSerialPortManager.sharedSerialPortManager() // MARK: Initializers override init() { super.init() let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: #selector(MavlinkController.serialPortsWereConnected(_:)), name: ORSSerialPortsWereConnectedNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(MavlinkController.serialPortsWereDisconnected(_:)), name: ORSSerialPortsWereDisconnectedNotification, object: nil) NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self availablePorts.value = serialPortManager.availablePorts } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - Actions private func startUsbMavlinkSession() { guard let port = serialPort where port.open else { print("Serial port is not open") return } guard let data = "mavlink start -d /dev/ttyACM0\n".dataUsingEncoding(NSUTF32LittleEndianStringEncoding) else { print("Cannot create mavlink USB start command") return } port.sendData(data) } // MARK: - Notifications func serialPortsWereConnected(notification: NSNotification) { if let userInfo = notification.userInfo { let connectedPorts = userInfo[ORSConnectedSerialPortsKey] as! [ORSSerialPort] print("Ports were connected: \(connectedPorts)") self.postUserNotificationForConnectedPorts(connectedPorts) } availablePorts.value = serialPortManager.availablePorts } func serialPortsWereDisconnected(notification: NSNotification) { if let userInfo = notification.userInfo { let disconnectedPorts: [ORSSerialPort] = userInfo[ORSDisconnectedSerialPortsKey] as! [ORSSerialPort] print("Ports were disconnected: \(disconnectedPorts)") self.postUserNotificationForDisconnectedPorts(disconnectedPorts) } availablePorts.value = serialPortManager.availablePorts } private func postUserNotificationForConnectedPorts(connectedPorts: [ORSSerialPort]) { let unc = NSUserNotificationCenter.defaultUserNotificationCenter() for port in connectedPorts { let userNote = NSUserNotification() userNote.title = NSLocalizedString("Serial Port Connected", comment: "Serial Port Connected") userNote.informativeText = "Serial Port \(port.name) was connected to your Mac." userNote.soundName = nil; unc.deliverNotification(userNote) } } private func postUserNotificationForDisconnectedPorts(disconnectedPorts: [ORSSerialPort]) { let unc = NSUserNotificationCenter.defaultUserNotificationCenter() for port in disconnectedPorts { let userNote = NSUserNotification() userNote.title = NSLocalizedString("Serial Port Disconnected", comment: "Serial Port Disconnected") userNote.informativeText = "Serial Port \(port.name) was disconnected from your Mac." userNote.soundName = nil; unc.deliverNotification(userNote) } } } extension MavlinkController: ORSSerialPortDelegate { func serialPortWasOpened(serialPort: ORSSerialPort) { } func serialPortWasClosed(serialPort: ORSSerialPort) { } func serialPortWasRemovedFromSystem(serialPort: ORSSerialPort) { self.serialPort = nil } func serialPort(serialPort: ORSSerialPort, didReceiveData data: NSData) { reactiveMavlink.receiveData(data) } func serialPort(serialPort: ORSSerialPort, didEncounterError error: NSError) { print("SerialPort \(serialPort.name) encountered an error: \(error)") } } extension MavlinkController: NSUserNotificationCenterDelegate { func userNotificationCenter(center: NSUserNotificationCenter, didDeliverNotification notification: NSUserNotification) { let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3.0 * Double(NSEC_PER_SEC))) dispatch_after(popTime, dispatch_get_main_queue()) { center.removeDeliveredNotification(notification) } } func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true } }
c9bb9df2c73aaa72d616fab1e4c952db
35.097403
179
0.675841
false
false
false
false
LoganWright/Genome
refs/heads/master
Packages/Node-1.0.1/Sources/Node/Convertible/Convertible+Init.swift
mit
2
extension NodeRepresentable { /** Map the node back to a convertible type - parameter type: the type to map to -- can be inferred - throws: if mapping fails - returns: convertible representation of object */ public func converted<T: NodeInitializable>( to type: T.Type = T.self, in context: Context = EmptyNode) throws -> T { let node = try makeNode() return try type.init(node: node, in: context) } } extension NodeInitializable { public init(node representable: NodeRepresentable, in context: Context = EmptyNode) throws { let node = try representable.makeNode() try self.init(node: node, in: context) } public init(node representable: NodeRepresentable?, in context: Context = EmptyNode) throws { let node = try representable?.makeNode() ?? .null try self.init(node: node, in: context) } } // MARK: Non-Homogenous extension NodeInitializable { public init(node representable: [String: NodeRepresentable], in context: Context = EmptyNode) throws { var converted: [String: Node] = [:] for (key, val) in representable { converted[key] = try Node(node: val) } let node = Node.object(converted) try self.init(node: node, in: context) } public init(node representable: [String: NodeRepresentable?], in context: Context = EmptyNode) throws { var converted: [String: Node] = [:] for (key, val) in representable { converted[key] = try Node(node: val) } let node = Node.object(converted) try self.init(node: node, in: context) } public init(node representable: [NodeRepresentable], in context: Context = EmptyNode) throws { var converted: [Node] = [] for val in representable { converted.append(try Node(node: val)) } let node = Node.array(converted) try self.init(node: node, in: context) } public init(node representable: [NodeRepresentable?], in context: Context = EmptyNode) throws { var converted: [Node] = [] for val in representable { converted.append(try Node(node: val)) } let node = Node.array(converted) try self.init(node: node, in: context) } }
158d65350fa7018d7f93ac5a3b6b8f63
29.986667
107
0.618761
false
false
false
false
NocturneZX/TTT-Pre-Internship-Exercises
refs/heads/master
Swift/Class5HWFlickrInSwift/FlickrInSwift/FlickrDataDownloader.swift
gpl-2.0
1
// // FlickrDataDownloader.swift // FlickrInSwift // // Created by Julio Reyes on 4/14/15. // Copyright (c) 2015 Julio Reyes. All rights reserved. // import UIKit class FlickrDataDownloader: NSObject{ let PHOTO_COUNT:Int = 20 let FLICKR_API_KEY:String = "cb9ddc90f13df3d47819c30111c851be" let FLICKR_SECRET_KEY:String = "d198467a13b07d76" let searchTerm = "Gundam" let currentpage:Int = 0 func getArrayOfPhotoObjectsforTheSearchTerm(searchStr:String, completion:(searchString:String!, flickrPhotos:NSMutableArray!, error:NSError!)->()) { currentpage + 1 let concatURL = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(FLICKR_API_KEY)&text=\(self.searchTerm)&sort=interestingness-desc&page=\(currentpage)&per_page=\(PHOTO_COUNT)&format=json&nojsoncallback=1" var error:NSError? var data:NSData? var response: NSURLResponse? let searchURL: NSURL = NSURL(string: concatURL)! if error != nil{ completion(searchString: searchStr, flickrPhotos: nil, error: error) }else{ let request: NSURLRequest = NSURLRequest(URL: searchURL) let operationQueue: NSOperationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 1 let flickrTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {(data: NSData!,response: NSURLResponse!,error: NSError!) -> Void in //closure starts here if(error != nil){ completion(searchString: searchStr, flickrPhotos: nil, error: error) }else{ let results = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as! NSDictionary let resultArray:NSArray = results.valueForKeyPath("photos.photo") as! NSArray let flickrPhotos:NSMutableArray = NSMutableArray() for photoObject in resultArray{ let photoDict:NSDictionary = photoObject as! NSDictionary //println(photoDict) var flickrPhoto:FlickrPhoto = FlickrPhoto(photoID: nil,photoTitle: nil,photoURL: nil,photoThumbURL: nil,photoAuthor: nil) var farm = photoDict.objectForKey("farm") as! Int var server = photoDict.objectForKey("server")as! String var secret = photoDict.objectForKey("secret") as! String var photoID = photoDict.objectForKey("id")as! String var owner = photoDict["owner"] as! String var title = photoDict["title"] as! String var httpThumbString = "http://farm\(farm).staticflickr.com/\(server)/\(photoID)_\(secret)_t.jpg" as String var photoThumbURL = NSURL(string: httpThumbString) var httpImageString = "http://farm\(farm).staticflickr.com/\(server)/\(photoID)_\(secret)_m.jpg" as String var photoURL = NSURL(string: httpThumbString) //Setup the Flickr class flickrPhoto.filckrphotoID = photoID; flickrPhoto.filckrphotoTitle = title; flickrPhoto.filckrphotoImageURL = photoURL; flickrPhoto.filckrphotoThumbnailImageURL = photoThumbURL; flickrPhoto.filckrphotoAuthor = owner; flickrPhotos.addObject(flickrPhoto) } completion(searchString: searchStr, flickrPhotos: flickrPhotos, error: nil) // Return the data to the main thread } });// Closure ends here flickrTask.resume() } } }
2eebe8d16970c45c60eac88e8af575d9
47.333333
240
0.5647
false
false
false
false
carabina/Carlos
refs/heads/master
Tests/CompositionTests.swift
mit
2
import Foundation import Quick import Nimble import Carlos private struct ComposedCacheSharedExamplesContext { static let CacheToTest = "composedCache" static let FirstComposedCache = "cache1" static let SecondComposedCache = "cache2" } class CompositionSharedExamplesConfiguration: QuickConfiguration { override class func configure(configuration: Configuration) { sharedExamples("get without considering set calls") { (sharedExampleContext: SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } context("when calling get") { let key = "test key" var cache1Request: CacheRequest<Int>! var cache2Request: CacheRequest<Int>! var successSentinel: Bool? var failureSentinel: Bool? var successValue: Int? var resultRequest: CacheRequest<Int>! beforeEach { cache1Request = CacheRequest<Int>() cache1.cacheRequestToReturn = cache1Request cache2Request = CacheRequest<Int>() cache2.cacheRequestToReturn = cache2Request for cache in [cache1, cache2] { cache.numberOfTimesCalledGet = 0 cache.numberOfTimesCalledSet = 0 } resultRequest = composedCache.get(key).onSuccess({ result in successSentinel = true successValue = result }).onFailure({ _ in failureSentinel = true }) } it("should not call any success closure") { expect(successSentinel).to(beNil()) } it("should not call any failure closure") { expect(failureSentinel).to(beNil()) } it("should call get on the first cache") { expect(cache1.numberOfTimesCalledGet).to(equal(1)) } it("should not call get on the second cache") { expect(cache2.numberOfTimesCalledGet).to(equal(0)) } context("when the first request succeeds") { let value = 1022 beforeEach { cache1Request.succeed(value) } it("should call the success closure") { expect(successSentinel).notTo(beNil()) } it("should pass the right value") { expect(successValue).to(equal(value)) } it("should not call the failure closure") { expect(failureSentinel).to(beNil()) } it("should not call get on the second cache") { expect(cache2.numberOfTimesCalledGet).to(equal(0)) } } context("when the first request fails") { beforeEach { successSentinel = nil failureSentinel = nil cache1Request.fail(nil) } it("should not call the success closure") { expect(successSentinel).to(beNil()) } it("should not call the failure closure") { expect(failureSentinel).to(beNil()) } it("should call get on the second cache") { expect(cache2.numberOfTimesCalledGet).to(equal(1)) } it("should not do other get calls on the first cache") { expect(cache1.numberOfTimesCalledGet).to(equal(1)) } context("when the second request succeeds") { let value = -122 beforeEach { cache2Request.succeed(value) } it("should call the success closure") { expect(successSentinel).notTo(beNil()) } it("should pass the right value") { expect(successValue).to(equal(value)) } it("should not call the failure closure") { expect(failureSentinel).to(beNil()) } } context("when the second request fails") { beforeEach { cache2Request.fail(nil) } it("should not call the success closure") { expect(successSentinel).to(beNil()) } it("should call the failure closure") { expect(failureSentinel).notTo(beNil()) } it("should not do other get calls on the first cache") { expect(cache1.numberOfTimesCalledGet).to(equal(1)) } it("should not do other get calls on the second cache") { expect(cache2.numberOfTimesCalledGet).to(equal(1)) } } } } } sharedExamples("get on caches") { (sharedExampleContext: SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } context("when calling get") { let key = "test key" var cache1Request: CacheRequest<Int>! var cache2Request: CacheRequest<Int>! var successSentinel: Bool? var failureSentinel: Bool? var successValue: Int? var resultRequest: CacheRequest<Int>! beforeEach { cache1Request = CacheRequest<Int>() cache1.cacheRequestToReturn = cache1Request cache2Request = CacheRequest<Int>() cache2.cacheRequestToReturn = cache2Request for cache in [cache1, cache2] { cache.numberOfTimesCalledGet = 0 cache.numberOfTimesCalledSet = 0 } resultRequest = composedCache.get(key).onSuccess({ result in successSentinel = true successValue = result }).onFailure({ _ in failureSentinel = true }) } itBehavesLike("get without considering set calls") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } context("when the first request fails") { beforeEach { successSentinel = nil failureSentinel = nil cache1Request.fail(nil) } context("when the second request succeeds") { let value = -122 beforeEach { cache2Request.succeed(value) } it("should set the value on the first cache") { expect(cache1.numberOfTimesCalledSet).to(equal(1)) } it("should set the value on the first cache with the right key") { expect(cache1.didSetKey).to(equal(key)) } it("should set the right value on the first cache") { expect(cache1.didSetValue).to(equal(value)) } it("should not set the same value again on the second cache") { expect(cache2.numberOfTimesCalledSet).to(equal(0)) } } } } } sharedExamples("first cache is a cache") { (sharedExampleContext: SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } context("when calling set") { let key = "this key" let value = 102 beforeEach { composedCache.set(value, forKey: key) } it("should call set on the first cache") { expect(cache1.numberOfTimesCalledSet).to(equal(1)) } it("should pass the right key on the first cache") { expect(cache1.didSetKey).to(equal(key)) } it("should pass the right value on the first cache") { expect(cache1.didSetValue).to(equal(value)) } } context("when calling clear") { beforeEach { composedCache.clear() } it("should call clear on the first cache") { expect(cache1.numberOfTimesCalledClear).to(equal(1)) } } context("when calling onMemoryWarning") { beforeEach { composedCache.onMemoryWarning() } it("should call onMemoryWarning on the first cache") { expect(cache1.numberOfTimesCalledOnMemoryWarning).to(equal(1)) } } } sharedExamples("second cache is a cache") { (sharedExampleContext: SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } context("when calling set") { let key = "this key" let value = 102 beforeEach { composedCache.set(value, forKey: key) } it("should call set on the second cache") { expect(cache2.numberOfTimesCalledSet).to(equal(1)) } it("should pass the right key on the second cache") { expect(cache2.didSetKey).to(equal(key)) } it("should pass the right value on the second cache") { expect(cache2.didSetValue).to(equal(value)) } } context("when calling clear") { beforeEach { composedCache.clear() } it("should call clear on the second cache") { expect(cache2.numberOfTimesCalledClear).to(equal(1)) } } context("when calling onMemoryWarning") { beforeEach { composedCache.onMemoryWarning() } it("should call onMemoryWarning on the second cache") { expect(cache2.numberOfTimesCalledOnMemoryWarning).to(equal(1)) } } } sharedExamples("a composition of two fetch closures") { (sharedExampleContext: SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } itBehavesLike("get without considering set calls") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } sharedExamples("a composition of a fetch closure and a cache") { (sharedExampleContext: SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } itBehavesLike("get without considering set calls") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } itBehavesLike("second cache is a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } sharedExamples("a composition of a cache and a fetch closure") { (sharedExampleContext: SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } itBehavesLike("get on caches") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } itBehavesLike("first cache is a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } sharedExamples("a composed cache") { (sharedExampleContext: SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } itBehavesLike("get on caches") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } itBehavesLike("first cache is a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } itBehavesLike("second cache is a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } } } class CompositionTests: QuickSpec { override func spec() { var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! describe("Cache composition using two cache levels with the global function") { beforeEach { cache1 = CacheLevelFake<String, Int>() cache2 = CacheLevelFake<String, Int>() composedCache = compose(cache1, cache2) } itBehavesLike("a composed cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } describe("Cache composition using two cache levels with the operator") { beforeEach { cache1 = CacheLevelFake<String, Int>() cache2 = CacheLevelFake<String, Int>() composedCache = cache1 >>> cache2 } itBehavesLike("a composed cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } describe("Cache composition using a cache level and a fetch closure, with the global function") { beforeEach { cache1 = CacheLevelFake<String, Int>() cache2 = CacheLevelFake<String, Int>() composedCache = compose(cache1, cache2.get) } itBehavesLike("a composition of a cache and a fetch closure") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } describe("Cache composition using a cache level and a fetch closure, with the operator") { beforeEach { cache1 = CacheLevelFake<String, Int>() cache2 = CacheLevelFake<String, Int>() composedCache = cache1 >>> cache2.get } itBehavesLike("a composition of a cache and a fetch closure") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } describe("Cache composition using a fetch closure and a cache level, with the global function") { beforeEach { cache1 = CacheLevelFake<String, Int>() cache2 = CacheLevelFake<String, Int>() composedCache = compose(cache1.get, cache2) } itBehavesLike("a composition of a fetch closure and a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } describe("Cache composition using a fetch closure and a cache level, with the operator") { beforeEach { cache1 = CacheLevelFake<String, Int>() cache2 = CacheLevelFake<String, Int>() composedCache = cache1.get >>> cache2 } itBehavesLike("a composition of a fetch closure and a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } describe("Cache composition using two fetch closures, with the global function") { beforeEach { cache1 = CacheLevelFake<String, Int>() cache2 = CacheLevelFake<String, Int>() composedCache = compose(cache1.get, cache2.get) } itBehavesLike("a composition of two fetch closures") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } describe("Cache composition using two fetch closures, with the operator") { beforeEach { cache1 = CacheLevelFake<String, Int>() cache2 = CacheLevelFake<String, Int>() composedCache = cache1.get >>> cache2.get } itBehavesLike("a composition of two fetch closures") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2, ComposedCacheSharedExamplesContext.CacheToTest: composedCache ] } } } }
29ecedd44e777a9539bc27dafac9e08c
35.120066
127
0.623497
false
false
false
false
malcommac/Hydra
refs/heads/master
Sources/Hydra/Promise+Cancel.swift
mit
1
/* * Hydra * Fullfeatured lightweight Promise & Await Library for Swift * * Created by: Daniele Margutti * Email: [email protected] * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * 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 public extension Promise { /// Catch a cancelled promise. /// /// - Parameters: /// - context: context in which the body will be executed. If not specified `.main` is used. /// - body: body to execute /// - Returns: a new void promise @discardableResult func cancelled(in context: Context? = nil, _ body: @escaping (() -> (Void))) -> Promise<Void> { let ctx = context ?? .main let nextPromise = Promise<Void>(in: ctx, token: self.invalidationToken) { resolve, reject, operation in let onResolve = Observer.onResolve(ctx, { _ in resolve(()) }) let onReject = Observer.onReject(ctx, reject) let onCancel = Observer.onCancel(ctx, { body() operation.cancel() }) self.add(observers: onResolve, onReject, onCancel) } nextPromise.runBody() self.runBody() return nextPromise } }
e4b1ef65a93a53961ff9422b9ce9ed7e
33.870968
105
0.727105
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/Systems/GithubUserSession.swift
mit
1
// // GithubUserSession.swift // Freetime // // Created by Ryan Nystrom on 5/17/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation final class GithubUserSession: NSObject, NSCoding { enum Keys { static let token = "token" static let authMethod = "authMethod" static let username = "username" } enum AuthMethod: String { case oauth, pat } let token: String let authMethod: AuthMethod // mutable to handle migration from time when username wasn't captured // can freely mutate and manually update. caller must then save updated session. var username: String? init( token: String, authMethod: AuthMethod, username: String? ) { self.token = token self.authMethod = authMethod self.username = username } // MARK: NSCoding convenience init?(coder aDecoder: NSCoder) { guard let token = aDecoder.decodeObject(forKey: Keys.token) as? String else { return nil } let storedAuthMethod = aDecoder.decodeObject(forKey: Keys.authMethod) as? String let authMethod = storedAuthMethod.flatMap(AuthMethod.init) ?? .oauth let username = aDecoder.decodeObject(forKey: Keys.username) as? String self.init( token: token, authMethod: authMethod, username: username ) } func encode(with aCoder: NSCoder) { aCoder.encode(token, forKey: Keys.token) aCoder.encode(authMethod.rawValue, forKey: Keys.authMethod) aCoder.encode(username, forKey: Keys.username) } }
8dd9c482232b359448813b1945713db0
24.828125
88
0.633999
false
false
false
false
everald/JetPack
refs/heads/master
Sources/Extensions/UIKit/UITableView.swift
mit
1
import UIKit public extension UITableView { fileprivate struct AssociatedKeys { fileprivate static var indexPathForCurrentHeightComputation = UInt8() } @nonobjc public func deselectAllRowsAnimated(_ animated: Bool) { for indexPath in indexPathsForSelectedRows ?? [] { deselectRow(at: indexPath, animated: animated) } } @nonobjc public var firstIndexPath: IndexPath? { let sectionCount = numberOfSections guard sectionCount > 0 else { return nil } for section in 0 ..< sectionCount { let rowCount = numberOfRows(inSection: section) guard rowCount > 0 else { continue } return IndexPath(row: 0, section: section) } return nil } @nonobjc public var floatsHeaderAndFooterViews: Bool { get { return redirected_headerAndFooterViewsFloat() } set { redirected_setHeaderAndFooterViewsFloat(newValue) } } @nonobjc internal fileprivate(set) var indexPathForCurrentHeightComputation: IndexPath? { get { return objc_getAssociatedObject(self, &AssociatedKeys.indexPathForCurrentHeightComputation) as? IndexPath } set { objc_setAssociatedObject(self, &AssociatedKeys.indexPathForCurrentHeightComputation, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @nonobjc public var lastIndexPath: IndexPath? { let sectionCount = numberOfSections guard sectionCount > 0 else { return nil } for section in (0 ..< sectionCount).reversed() { let rowCount = numberOfRows(inSection: section) guard rowCount > 0 else { continue } return IndexPath(row: rowCount - 1, section: section) } return nil } public override var maximumContentOffset: CGPoint { let numberOfSections = self.numberOfSections guard numberOfSections > 0 else { return super.maximumContentOffset } // we cannot rely on contentSize while update animations are in-flight, so we use ret(forSection:) instead let lastSectionRect = rect(forSection: numberOfSections - 1) let size = self.bounds.size let contentInset = self.contentInset return CGPoint( left: 0, top: max(lastSectionRect.bottom + contentInset.bottom - size.height, -contentInset.top) ) } @objc(JetPack_floatsHeaderAndFooterViews) fileprivate dynamic func redirected_headerAndFooterViewsFloat() -> Bool { // called when private function is no longer available return true } @objc(JetPack_setFloatsHeaderAndFooterViews:) fileprivate dynamic func redirected_setHeaderAndFooterViewsFloat(_ headerAndFooterViewsFloat: Bool) { // called when private function is no longer available } @nonobjc public func scrollRowAtIndexPathToVisible(_ indexPath: IndexPath, insets: UIEdgeInsets = .zero, animated: Bool = false) -> Bool { let contentSize = self.contentSize var rect = rectForRow(at: indexPath).insetBy(insets.inverse) rect.left = rect.left.coerced(in: 0 ... max(contentSize.width - rect.width, 0)) rect.top = rect.top.coerced(in: 0 ... max(contentSize.height - rect.height, 0)) guard !bounds.insetBy(contentInset).contains(rect) else { return false } scrollRectToVisible(rect, animated: animated) return true } @objc(JetPack_computeHeightForCell:atIndexPath:) fileprivate dynamic func swizzled_computeHeightForCell(_ cell: UITableViewCell, atIndexPath indexPath: IndexPath) -> CGFloat { indexPathForCurrentHeightComputation = indexPath let height = swizzled_computeHeightForCell(cell, atIndexPath: indexPath) indexPathForCurrentHeightComputation = nil return height } } @objc(_JetPack_Extensions_UIKit_UITableView_Initialization) private class StaticInitialization: NSObject, StaticInitializable { static func staticInitialize() { // yep, private API necessary :( redirectMethod(in: UITableView.self, from: #selector(UITableView.redirected_headerAndFooterViewsFloat), to: obfuscatedSelector("_header", "And", "Footer", "Views", "Float")) redirectMethod(in: UITableView.self, from: #selector(UITableView.redirected_setHeaderAndFooterViewsFloat), to: obfuscatedSelector("_set", "Header", "And", "Footer", "Views" ,"Float:")) // UIKit doesn't let us properly implement our own sizeThatFits() in UITableViewCell subclasses because we're unable to determine the correct size of .contentView swizzleMethod(in: UITableView.self, from: obfuscatedSelector("_", "height", "For", "Cell:", "at", "Index", "Path:"), to: #selector(UITableView.swizzled_computeHeightForCell(_:atIndexPath:))) } }
bba53c42ec9899e4970d928533997d85
29.136986
192
0.752955
false
false
false
false
gtranchedone/AlgorithmsSwift
refs/heads/master
Algorithms.playground/Pages/Problem - Test for Cyclicity.xcplaygroundpage/Contents.swift
mit
1
/*: [Previous](@previous) # Test for cyclicity ### Although a linked list is supposed to be a sequence of nodes ending in null, it is possible to create a cycle in a linked list by assigning to the next field of a node a reference to an earlier one. Given a reference to the head of a list, how would you determine if the list contains a cycle? Write a program that returns null if a list doesn’t contain a cycle or the node starting the cycle otherwise. */ // O(n) time and space func testForCyclicity<T>(head: ListNode<T>) -> ListNode<T>? { var currentNode: ListNode<T>? = head var bag = Bag<ListNode<T>>() while true { bag.insert(currentNode!) let nextNode = currentNode?.next if nextNode == nil || bag.contains(nextNode!) { return nextNode // cycle start or nil to indicate no cycle } currentNode = nextNode } } // O(n) time and O(1) space func testForCyclicityEfficiently<T>(head: ListNode<T>) -> ListNode<T>? { var i: ListNode<T>? = head, j: ListNode<T>? = head while j?.next?.next != nil { i = i?.next j = j?.next?.next if i === j { // cycle detected // calculate cycle length var cycleLength = 0 repeat { cycleLength++ j = j?.next } while (i !== j) // find cycle start var cycleIterator: ListNode<T>? = head while cycleLength-- > 0 { cycleIterator = cycleIterator?.next } var otherIterator: ListNode<T>? = head while cycleIterator !== otherIterator { cycleIterator = cycleIterator?.next otherIterator = otherIterator?.next } return otherIterator } } return nil } let list = List<Int>(values: [1, 2, 3, 4]) list.head?.next?.next?.next?.next = list.head?.next testForCyclicity(list.head!)?.value testForCyclicityEfficiently(list.head!)?.value let list2 = List<Int>(values: [1, 2, 3, 4]) testForCyclicity(list2.head!) testForCyclicityEfficiently(list2.head!) //: [Next](@next)
687251125b9d99ceb81ff86d712dfcfa
34.295082
407
0.594984
false
true
false
false
MaWenxing/FFLabel
refs/heads/master
CSYMicroBlockSina/Pods/FFLabel/FFLabel/Source/FFLabel.swift
mit
8
// // FFLabel.swift // FFLabel // // Created by 刘凡 on 15/7/18. // Copyright © 2015年 joyios. All rights reserved. // import UIKit @objc public protocol FFLabelDelegate: NSObjectProtocol { optional func labelDidSelectedLinkText(label: FFLabel, text: String) } public class FFLabel: UILabel { public var linkTextColor = UIColor.blueColor() public var selectedBackgroudColor = UIColor.lightGrayColor() public weak var labelDelegate: FFLabelDelegate? // MARK: - override properties override public var text: String? { didSet { updateTextStorage() } } override public var attributedText: NSAttributedString? { didSet { updateTextStorage() } } override public var font: UIFont! { didSet { updateTextStorage() } } override public var textColor: UIColor! { didSet { updateTextStorage() } } // MARK: - upadte text storage and redraw text private func updateTextStorage() { if attributedText == nil { return } let attrStringM = addLineBreak(attributedText!) regexLinkRanges(attrStringM) addLinkAttribute(attrStringM) textStorage.setAttributedString(attrStringM) setNeedsDisplay() } /// add link attribute private func addLinkAttribute(attrStringM: NSMutableAttributedString) { var range = NSRange(location: 0, length: 0) var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range) attributes[NSFontAttributeName] = font! attributes[NSForegroundColorAttributeName] = textColor attrStringM.addAttributes(attributes, range: range) attributes[NSForegroundColorAttributeName] = linkTextColor for r in linkRanges { attrStringM.setAttributes(attributes, range: r) } } /// use regex check all link ranges private let patterns = ["[a-zA-Z]*://[a-zA-Z0-9/\\.]*", "#.*?#", "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*"] private func regexLinkRanges(attrString: NSAttributedString) { linkRanges.removeAll() let regexRange = NSRange(location: 0, length: attrString.string.characters.count) for pattern in patterns { let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators) let results = regex.matchesInString(attrString.string, options: NSMatchingOptions(rawValue: 0), range: regexRange) for r in results { linkRanges.append(r.rangeAtIndex(0)) } } } /// add line break mode private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString { let attrStringM = NSMutableAttributedString(attributedString: attrString) var range = NSRange(location: 0, length: 0) var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range) var paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle if paragraphStyle != nil { paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping } else { // iOS 8.0 can not get the paragraphStyle directly paragraphStyle = NSMutableParagraphStyle() paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping attributes[NSParagraphStyleAttributeName] = paragraphStyle attrStringM.setAttributes(attributes, range: range) } return attrStringM } public override func drawTextInRect(rect: CGRect) { let range = glyphsRange() let offset = glyphsOffset(range) layoutManager.drawBackgroundForGlyphRange(range, atPoint: offset) layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero) } private func glyphsRange() -> NSRange { return NSRange(location: 0, length: textStorage.length) } private func glyphsOffset(range: NSRange) -> CGPoint { let rect = layoutManager.boundingRectForGlyphRange(range, inTextContainer: textContainer) let height = (bounds.height - rect.height) * 0.5 return CGPoint(x: 0, y: height) } // MARK: - touch events public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let location = touches.first!.locationInView(self) selectedRange = linkRangeAtLocation(location) modifySelectedAttribute(true) } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let location = touches.first!.locationInView(self) if let range = linkRangeAtLocation(location) { if !(range.location == selectedRange?.location && range.length == selectedRange?.length) { modifySelectedAttribute(false) selectedRange = range modifySelectedAttribute(true) } } else { modifySelectedAttribute(false) } } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if selectedRange != nil { let text = (textStorage.string as NSString).substringWithRange(selectedRange!) labelDelegate?.labelDidSelectedLinkText!(self, text: text) let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()) { self.modifySelectedAttribute(false) } } } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { modifySelectedAttribute(false) } private func modifySelectedAttribute(isSet: Bool) { if selectedRange == nil { return } var attributes = textStorage.attributesAtIndex(0, effectiveRange: nil) attributes[NSForegroundColorAttributeName] = linkTextColor let range = selectedRange! if isSet { attributes[NSBackgroundColorAttributeName] = selectedBackgroudColor } else { attributes[NSBackgroundColorAttributeName] = UIColor.clearColor() selectedRange = nil } textStorage.addAttributes(attributes, range: range) setNeedsDisplay() } private func linkRangeAtLocation(location: CGPoint) -> NSRange? { if textStorage.length == 0 { return nil } let offset = glyphsOffset(glyphsRange()) let point = CGPoint(x: offset.x + location.x, y: offset.y + location.y) let index = layoutManager.glyphIndexForPoint(point, inTextContainer: textContainer) for r in linkRanges { if index >= r.location && index <= r.location + r.length { return r } } return nil } // MARK: - init functions override public init(frame: CGRect) { super.init(frame: frame) prepareLabel() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareLabel() } public override func layoutSubviews() { super.layoutSubviews() textContainer.size = bounds.size } private func prepareLabel() { textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) textContainer.lineFragmentPadding = 0 userInteractionEnabled = true } // MARK: lazy properties private lazy var linkRanges = [NSRange]() private var selectedRange: NSRange? private lazy var textStorage = NSTextStorage() private lazy var layoutManager = NSLayoutManager() private lazy var textContainer = NSTextContainer() }
948ffd6ae8f3bdf43ad6715d66d6bd50
31.955285
128
0.622918
false
false
false
false
yangyueguang/MyCocoaPods
refs/heads/master
tools/Stars/XPlayer.swift
mit
1
// // XPlayer.swift import UIKit import SnapKit import CoreMedia import CoreGraphics import QuartzCore import MediaPlayer import AVFoundation let kOffset = "contentOffset" let SliderFillColorAnim = "fillColor" // playerLayer的填充模式 enum XPlayerFillMode : Int { case resize case aspect case aspectFill } enum PanDirection: Int { case horizontal = 0 case vertical = 1 } // 播放器的几种状态 enum XPlayerState: Int { case failed = 0 // 播放失败 case buffering // 缓冲中 case playing // 播放中 case stopped // 停止播放 case pause // 暂停播放 } enum XPImage: String { case play = "play" case pause = "pause" case back = "back_full" case close = "close" case lock = "lock-nor" case unlock = "unlock-nor" case full = "fullscreen" case slider = "slider" case download = "download" case play_btn = "play_btn" case loading = "loading_bgView" case brightness = "brightness" case management = "management_mask" case not_download = "not_download" case repeat_video = "repeat_video" case shrinkscreen = "shrinkscreen" case top_shadow = "top_shadow" case bottom_shadow = "bottom_shadow" var img: UIImage? { return UIImage(named: rawValue) } } extension CALayer { func animateKey(_ animationName: String, fromValue: Any?, toValue: Any?, customize block: ((_ animation: CABasicAnimation?) -> Void)?) { setValue(toValue, forKey: animationName) let anim = CABasicAnimation(keyPath: animationName) anim.fromValue = fromValue ?? presentation()?.value(forKey: animationName) anim.toValue = toValue block?(anim) add(anim, forKey: animationName) } } // 私有类 class ASValuePopUpView: UIView, CAAnimationDelegate { var currentValueOffset: (() -> CGFloat)? var colorDidUpdate:((UIColor) -> Void)? var arrowLength: CGFloat = 8 var widthPaddingFactor: CGFloat = 1.15 var heightPaddingFactor: CGFloat = 1.1 private var shouldAnimate = false private var animDuration: TimeInterval = 0 private var arrowCenterOffset: CGFloat = 0 var imageView = UIImageView() var timeLabel = UILabel() private var colorAnimLayer = CAShapeLayer() private lazy var pathLayer = CAShapeLayer(layer: layer) var cornerRadius: CGFloat = 0 { didSet { if oldValue != self.cornerRadius { pathLayer.path = path(for: bounds, withArrowOffset: arrowCenterOffset)?.cgPath } } } var color: UIColor? { get { if let fill = pathLayer.presentation()?.fillColor { return UIColor(cgColor: fill) } return nil } set(newValue) { pathLayer.fillColor = newValue?.cgColor colorAnimLayer.removeAnimation(forKey: SliderFillColorAnim) } } var opaqueColor: UIColor? { let a = colorAnimLayer.presentation() let co = a?.fillColor ?? pathLayer.fillColor if let components = co?.components { if (components.count == 2) { return UIColor(white: components[0], alpha: 1) } else { return UIColor(red: components[0], green: components[1], blue: components[2], alpha: 1) } } else { return nil } } override init(frame: CGRect) { super.init(frame: frame) cornerRadius = 4.0 shouldAnimate = false self.layer.anchorPoint = CGPoint(x:0.5, y: 1) self.isUserInteractionEnabled = false layer.addSublayer(colorAnimLayer) timeLabel.text = "10:00" timeLabel.textAlignment = .center timeLabel.textColor = UIColor.white addSubview(timeLabel) addSubview(imageView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func action(for layer: CALayer, forKey event: String) -> CAAction? { if shouldAnimate { let anim = CABasicAnimation(keyPath: event) anim.beginTime = CACurrentMediaTime() anim.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) anim.fromValue = layer.presentation()?.value(forKey: event) anim.duration = animDuration return anim } else { return nil } } func setAnimatedColors(animatedColors: [UIColor], withKeyTimes keyTimes:[NSNumber]) { var cgColors:[CGColor] = [] for col in animatedColors { cgColors.append(col.cgColor) } let colorAnim = CAKeyframeAnimation(keyPath:SliderFillColorAnim) colorAnim.keyTimes = keyTimes colorAnim.values = cgColors colorAnim.fillMode = .both colorAnim.duration = 1.0 colorAnim.delegate = self colorAnimLayer.speed = Float.leastNormalMagnitude colorAnimLayer.timeOffset = 0.0 colorAnimLayer.add(colorAnim, forKey: SliderFillColorAnim) } func setAnimationOffset(animOffset: CGFloat, returnColor:((UIColor?) -> Void)) { if (colorAnimLayer.animation(forKey: SliderFillColorAnim) != nil) { colorAnimLayer.timeOffset = CFTimeInterval(animOffset) pathLayer.fillColor = colorAnimLayer.presentation()?.fillColor returnColor(opaqueColor) } } func setFrame(frame:CGRect, arrowOffset:CGFloat) { if arrowOffset != arrowCenterOffset || !frame.size.equalTo(self.frame.size) { let a = path(for: frame, withArrowOffset: arrowOffset) pathLayer.path = a?.cgPath } arrowCenterOffset = arrowOffset let anchorX = 0.5+(arrowOffset/frame.size.width) self.layer.anchorPoint = CGPoint(x:anchorX, y:1) self.layer.position = CGPoint(x:frame.origin.x + frame.size.width*anchorX,y: 0) self.layer.bounds = CGRect(origin: CGPoint.zero, size: frame.size) } func animateBlock(block:((TimeInterval) -> Void)) { shouldAnimate = true animDuration = 0.5 let anim = layer.animation(forKey: "position") if let anim = anim { let elapsedTime = min(CACurrentMediaTime() - anim.beginTime, anim.duration) animDuration = animDuration * elapsedTime / anim.duration } block(animDuration) shouldAnimate = false } func showAnimated(animated: Bool){ if (!animated) { self.layer.opacity = 1.0 return } CATransaction.begin() let anim = self.layer.animation(forKey: "transform") let a = layer.presentation()?.value(forKey: "transform") let b = NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1)) let fromValue = (anim == nil ? b : a) layer.animateKey("transform", fromValue: fromValue, toValue: NSValue(caTransform3D: CATransform3DIdentity)) { (animation) in animation?.duration = 0.4 animation?.timingFunction = CAMediaTimingFunction(controlPoints:0.8 ,2.5 ,0.35 ,0.5) } layer.animateKey("opacity", fromValue: nil, toValue: 1.0) { (animation) in animation?.duration = 0.1 } CATransaction.commit() } func hideAnimated(animated: Bool, completionBlock block:@escaping(() -> Void)) { CATransaction.begin() CATransaction.setCompletionBlock {[weak self] in block() self?.layer.transform = CATransform3DIdentity } if (animated) { layer.animateKey("transform", fromValue: nil, toValue: NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1)), customize: { (animation) in animation?.duration = 0.55 animation?.timingFunction = CAMediaTimingFunction(controlPoints: 0.1 ,-2 ,0.3 ,3) }) layer.animateKey("opacity", fromValue: nil, toValue: 0, customize: { (animation) in animation?.duration = 0.75 }) } else { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: { self.layer.opacity = 0.0 }) } CATransaction.commit() } func animationDidStart(_ anim: CAAnimation) { colorAnimLayer.speed = 0.0 colorAnimLayer.timeOffset = CFTimeInterval(currentValueOffset?() ?? 0) pathLayer.fillColor = colorAnimLayer.presentation()?.fillColor colorDidUpdate?(opaqueColor ?? .red) } func path(for rect: CGRect, withArrowOffset arrowOffset: CGFloat) -> UIBezierPath? { var rect = rect if rect.equalTo(CGRect.zero) { return nil } rect = CGRect(origin: CGPoint.zero, size: rect.size) var roundedRect = rect roundedRect.size.height -= arrowLength let popUpPath = UIBezierPath(roundedRect: roundedRect, cornerRadius: cornerRadius) let maxX = roundedRect.maxX let arrowTipX = rect.midX + arrowOffset let tip = CGPoint(x: arrowTipX, y: rect.maxY) let arrowLength = roundedRect.height / 2.0 let x = arrowLength * tan(45.0 * .pi / 180) let arrowPath = UIBezierPath() arrowPath.move(to: tip) arrowPath.addLine(to: CGPoint(x: max(arrowTipX - x, 0), y: roundedRect.maxY - arrowLength)) arrowPath.addLine(to: CGPoint(x: min(arrowTipX + x, maxX), y: roundedRect.maxY - arrowLength)) arrowPath.close() popUpPath.append(arrowPath) return popUpPath } override func layoutSubviews() { super.layoutSubviews() let textRect = CGRect(x:self.bounds.origin.x, y:0, width:self.bounds.size.width,height: 13) timeLabel.frame = textRect let imageReact = CGRect(x:self.bounds.origin.x+5, y:textRect.size.height+textRect.origin.y, width:self.bounds.size.width-10, height:56) imageView.frame = imageReact } } /// 亮度类 私有类 class XBrightnessView: UIView { static let shared = XBrightnessView() // 调用单例记录播放状态是否锁定屏幕方向 var isLockScreen = false // cell上添加player时候,不允许横屏,只运行竖屏状态状态 var isAllowLandscape = false var backImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 79, height: 76)) lazy var title = UILabel(frame: CGRect(x: 0, y: 5, width: bounds.size.width, height: 30)) lazy var longView = UIView(frame: CGRect(x: 13, y: 132, width: bounds.size.width - 26, height: 7)) var tipArray: [UIImageView] = [] var orientationDidChange = false var timer: Timer? override init(frame: CGRect) { super.init(frame: frame) backImage.image = XPImage.brightness.img self.frame = CGRect(x: APPW * 0.5, y: APPH * 0.5, width: 155, height: 155) layer.cornerRadius = 10 layer.masksToBounds = true let toolbar = UIToolbar(frame: bounds) toolbar.alpha = 0.97 addSubview(toolbar) addSubview(backImage) title.font = UIFont.boldSystemFont(ofSize: 16) title.textColor = UIColor(red: 0.25, green: 0.22, blue: 0.21, alpha: 1.00) title.textAlignment = .center title.text = "亮度" addSubview(title) longView.backgroundColor = UIColor(red: 0.25, green: 0.22, blue: 0.21, alpha: 1.00) addSubview(longView) let tipW: CGFloat = (longView.bounds.size.width - 17) / 16 for i in 0..<16 { let tipX = CGFloat(i) * (tipW + 1) + 1 let image = UIImageView() image.backgroundColor = UIColor.white image.frame = CGRect(x: tipX, y: 1, width: tipW, height: 5) longView.addSubview(image) tipArray.append(image) } updateLongView(sound: UIScreen.main.brightness) NotificationCenter.default.addObserver(self, selector: #selector(updateLayer(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) UIScreen.main.addObserver(self, forKeyPath: "brightness", options: .new, context: nil) alpha = 0.0 } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let ab = change?[NSKeyValueChangeKey(rawValue: "new")] as? NSNumber let sound = CGFloat(ab?.floatValue ?? 0) if self.alpha == 0 { self.alpha = 1.0 timer?.invalidate() timer = Timer(timeInterval: 3, target: self, selector: #selector(disAppearSoundView), userInfo: nil, repeats: false) RunLoop.main.add(timer!, forMode: .default) } updateLongView(sound: sound) } @objc func updateLayer(_ notify: Notification?) { orientationDidChange = true setNeedsLayout() } @objc func disAppearSoundView() { if (self.alpha == 1.0) { UIView.animate(withDuration: 0.8) { self.alpha = 0 } } } func updateLongView(sound: CGFloat) { let stage = CGFloat( 1 / 15.0) let level = Int(sound / stage) for i in 0..<self.tipArray.count { let img = tipArray[i] img.isHidden = i > level } } override func willMove(toSuperview newSuperview: UIView?) { setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews() let orien = UIDevice.current.orientation if orientationDidChange { UIView.animate(withDuration: 0.25, animations: { if orien == .portrait || orien == .faceUp { self.center = CGPoint(x: APPW * 0.5, y: (APPH - 10) * 0.5) } else { self.center = CGPoint(x: APPW * 0.5, y: APPH * 0.5) } }) { (finished) in self.orientationDidChange = false } } else { if orien == .portrait { self.center = CGPoint(x: APPW * 0.5, y: (APPH - 10) * 0.5) } else { self.center = CGPoint(x: APPW * 0.5, y: APPH * 0.5) } } backImage.center = CGPoint(x: 155 * 0.5, y: 155 * 0.5) } deinit { UIScreen.main.removeObserver(self, forKeyPath: "brightness") NotificationCenter.default.removeObserver(self) } } /// 滑块 私有类 class ASValueTrackingSlider: UISlider { var popUpView = ASValuePopUpView() var popUpViewAlwaysOn = false var keyTimes: [NSNumber] = [] var valueRange: Float {return maximumValue - minimumValue} var popUpViewAnimatedColors: [UIColor] = [] var sliderWillDisplayPopUpView: (() -> Void)? var sliderDidHidePopUpView: (() -> Void)? var tempOffset: CGFloat {return CGFloat((self.value - self.minimumValue) / self.valueRange)} override var value: Float { didSet { popUpView.setAnimationOffset(animOffset: tempOffset) { (color) in super.minimumTrackTintColor = color } } } var autoAdjustTrackColor = true { didSet { if (autoAdjustTrackColor != oldValue) { super.minimumTrackTintColor = oldValue ? popUpView.opaqueColor: nil } } } var popUpViewColor: UIColor? { didSet { popUpViewAnimatedColors = [] popUpView.color = self.popUpViewColor if (autoAdjustTrackColor) { super.minimumTrackTintColor = popUpView.opaqueColor } } } override func awakeFromNib() { super.awakeFromNib() autoAdjustTrackColor = true popUpViewAlwaysOn = false self.popUpViewColor = UIColor(hue: 0.6, saturation: 0.6, brightness: 0.5, alpha: 0.8) self.popUpView.alpha = 0.0 popUpView.colorDidUpdate = {[weak self] color in guard let `self` = self else { return } let temp = self.autoAdjustTrackColor self.minimumTrackTintColor = color self.autoAdjustTrackColor = temp } popUpView.currentValueOffset = { [weak self] in return self?.tempOffset ?? 0 } addSubview(self.popUpView) } required init?(coder: NSCoder) { super.init(coder: coder) } func setPopUpViewAnimatedColors(colors: [UIColor], withPositions positions: [NSNumber] = []) { if (positions.count <= 0) { return } popUpViewAnimatedColors = colors keyTimes = [] for num in positions.sorted(by: { (a, b) -> Bool in return a.floatValue < b.floatValue }) { keyTimes.append(NSNumber(value: (num.floatValue - minimumValue) / valueRange)) } if (colors.count >= 2) { self.popUpView.setAnimatedColors(animatedColors: colors, withKeyTimes: keyTimes) } else { self.popUpViewColor = colors.last != nil ? nil : popUpView.color } } @objc func didBecomeActiveNotification(note: NSNotification) { if !self.popUpViewAnimatedColors.isEmpty { self.popUpView.setAnimatedColors(animatedColors: popUpViewAnimatedColors, withKeyTimes: keyTimes) } } func showPopUpViewAnimated(_ animated: Bool) { sliderWillDisplayPopUpView?() popUpView.showAnimated(animated: animated) } func hidePopUpViewAnimated(_ animated: Bool) { sliderWillDisplayPopUpView?() popUpView.hideAnimated(animated: animated) { self.sliderDidHidePopUpView?() } } override func layoutSubviews() { super.layoutSubviews() let popUpViewSize = CGSize(width: 100, height: 56 + self.popUpView.arrowLength + 18) let thumbRect = self.thumbRect(forBounds: bounds, trackRect: trackRect(forBounds: bounds), value: value) let thumbW = thumbRect.size.width let thumbH = thumbRect.size.height var popUpRect = CGRect(x: 0, y: thumbRect.origin.y - popUpViewSize.height, width: (thumbW - popUpViewSize.width)/2, height: (thumbH - popUpViewSize.height)/2) let minOffsetX = popUpRect.minX let maxOffsetX = popUpRect.maxX - self.bounds.width let offset = minOffsetX < 0.0 ? minOffsetX : (maxOffsetX > 0.0 ? maxOffsetX : 0.0) popUpRect.origin.x -= offset popUpView.setFrame(frame: popUpRect, arrowOffset: offset) } override func didMoveToWindow() { if self.window == nil { NotificationCenter.default.removeObserver(self) } else { if !popUpViewAnimatedColors.isEmpty { popUpView.setAnimatedColors(animatedColors: popUpViewAnimatedColors, withKeyTimes: keyTimes) } NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActiveNotification(note:)), name: UIApplication.didBecomeActiveNotification, object: nil) } } override func setValue(_ value: Float, animated: Bool) { if animated { func anim() { super.setValue(value, animated: animated) self.popUpView.setAnimationOffset(animOffset: tempOffset) { (color) in self.minimumTrackTintColor = color } self.layoutIfNeeded() } popUpView.animateBlock {(duration) in UIView.animate(withDuration: duration) { anim() } } } else { super.setValue(value, animated: animated) } } override var minimumTrackTintColor: UIColor? { willSet { autoAdjustTrackColor = false } } override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let begin = super.beginTracking(touch, with: event) if begin && !self.popUpViewAlwaysOn { self.popUpViewAlwaysOn = true self.showPopUpViewAnimated(false) } return begin } override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let conti = super.continueTracking(touch, with: event) if conti { popUpView.setAnimationOffset(animOffset: tempOffset) { (color) in super.minimumTrackTintColor = color } } return conti } override func cancelTracking(with event: UIEvent?) { super.cancelTracking(with: event) if !popUpViewAlwaysOn { hidePopUpViewAnimated(false) } } override func endTracking(_ touch: UITouch?, with event: UIEvent?) { super.endTracking(touch, with: event) if !popUpViewAlwaysOn { hidePopUpViewAnimated(false) } } } /// 播放控制类 私有类 class XPlayerControlView: UIView { @IBOutlet weak var videoSlider: ASValueTrackingSlider! // 滑杆 @IBOutlet weak var titleLabel: UILabel! // 标题 @IBOutlet weak var startBtn: UIButton! // 开始播放按钮 @IBOutlet weak var currentTimeLabel: UILabel! // 当前播放时长label @IBOutlet weak var totalTimeLabel: UILabel! // 视频总时长label @IBOutlet weak var progressView: UIProgressView! // 缓冲进度条 @IBOutlet weak var fullScreenBtn: UIButton! // 全屏按钮 @IBOutlet weak var lockBtn: UIButton! // 锁定屏幕方向按钮 @IBOutlet weak var horizontalLabel: UILabel! // 快进快退label @IBOutlet weak var activity: UIActivityIndicatorView! // 系统菊花 @IBOutlet weak var backBtn: UIButton! // 返回按钮 @IBOutlet weak var repeatBtn: UIButton! // 重播按钮 @IBOutlet weak var topView: UIView! @IBOutlet weak var topImageView: UIImageView! // 顶部渐变 @IBOutlet weak var bottomView: UIView! @IBOutlet weak var bottomImageView: UIImageView! // 底部渐变 @IBOutlet weak var downLoadBtn: UIButton! // 缓存按钮 @IBOutlet weak var resolutionBtn: UIButton! // 切换分辨率按钮 @IBOutlet weak var playeBtn: UIButton! // 播放按钮 // 切换分辨率的block var resolutionBlock: ((UIButton?) -> Void)? // slidertap事件Block var tapBlock: ((CGFloat) -> Void)? // 分辨率的View var resolutionView = UIView() // 分辨率的名称 var resolutionArray: [String] = [] { didSet { resolutionBtn.setTitle(resolutionArray.first, for: .normal) resolutionView.isHidden = true resolutionView.backgroundColor = UIColor(white: 0.7, alpha: 1) addSubview(resolutionView) resolutionView.snp.makeConstraints { (make) in make.width.equalTo(40) make.height.equalTo(CGFloat(resolutionArray.count * 30)) make.leading.equalTo(resolutionBtn.snp.leading) make.top.equalTo(resolutionBtn.snp.bottom) } for i in 0..<resolutionArray.count { let btn = UIButton(type: .custom) btn.tag = 200 + i resolutionView.addSubview(btn) btn.titleLabel?.font = UIFont.systemFont(ofSize: 14) btn.frame = CGRect(x: 0, y: CGFloat(30 * i), width: 40, height: 30) btn.setTitle(resolutionArray[i], for: .normal) btn.addTarget(self, action: #selector(changeResolution(_:)), for: .touchUpInside) } } } class func xibView() -> XPlayerControlView { let xib = UINib(nibName: "XPlayerControlView", bundle: nil) let controlView = xib.instantiate(withOwner: nil, options: nil).first as! XPlayerControlView return controlView } override func awakeFromNib() { super.awakeFromNib() initial() } override init(frame: CGRect) { super.init(frame: frame) initial() } required init?(coder: NSCoder) { super.init(coder: coder) } private func initial() { videoSlider.popUpViewColor = .red videoSlider.setThumbImage(XPImage.slider.img, for: .normal) resolutionBtn.addTarget(self, action: #selector(resolutionAction(_:)), for: .touchUpInside) let sliderTap = UITapGestureRecognizer(target: self, action: #selector(tapSliderAction(_:))) videoSlider.addGestureRecognizer(sliderTap) activity.stopAnimating() resetControlView() } // 点击topView上的按钮 @objc func resolutionAction(_ sender: UIButton?) { sender?.isSelected = !(sender?.isSelected ?? false) resolutionView.isHidden = !(sender?.isSelected)! } // 点击切换分别率按钮 @objc func changeResolution(_ sender: UIButton?) { resolutionView.isHidden = true resolutionBtn.isSelected = false resolutionBtn.setTitle(sender?.titleLabel?.text, for: .normal) resolutionBlock?(sender) } // UISlider TapAction @objc func tapSliderAction(_ tap: UITapGestureRecognizer?) { if (tap?.view is UISlider) { let slider = tap?.view as? UISlider let point = tap?.location(in: slider) let length = slider?.frame.size.width // 视频跳转的value let tapValue = (point?.x ?? 0.0) / (length ?? 0.0) tapBlock?(tapValue) } } // MARK: - Public Method func resetControlView() { videoSlider.value = 0 progressView.progress = 0 currentTimeLabel.text = "00:00" totalTimeLabel.text = "00:00" horizontalLabel.isHidden = true repeatBtn.isHidden = true playeBtn.isHidden = true resolutionView.isHidden = true backgroundColor = UIColor.clear downLoadBtn.isEnabled = true } func resetControlViewForResolution() { horizontalLabel.isHidden = true repeatBtn.isHidden = true resolutionView.isHidden = true playeBtn.isHidden = true downLoadBtn.isEnabled = true backgroundColor = UIColor.clear } func showControlView() { topView.alpha = 1 bottomView.alpha = 1 lockBtn.alpha = 1 } func hideControlView() { topView.alpha = 0 bottomView.alpha = 0 lockBtn.alpha = 0 resolutionBtn.isSelected = true resolutionAction(resolutionBtn) } } class XPlayer: UIView { static let shared = XPlayer() let nessView = XBrightnessView.shared // 视频URL var videoURL: URL? { didSet { if (self.placeholderImageName.isEmpty) { let image = XPImage.loading.img self.layer.contents = image?.cgImage } self.repeatToPlay = false self.playDidEnd = false self.addNotifications() self.onDeviceOrientationChange() self.isPauseByUser = true self.controlView.playeBtn.isHidden = false self.controlView.hideControlView() } } // 视频标题 var title = "" {didSet {self.controlView.titleLabel.text = title}} // 视频URL的数组 var videoURLArray: [String] = [] // 返回按钮Block var goBackBlock: (() -> Void)? var downloadBlock: ((String?) -> Void)? // 从xx秒开始播放视频跳转 var seekTime = 0 // 是否自动播放 var isAutoPlay = false { didSet {if isAutoPlay {self.configZFPlayer()}}} // 是否有下载功能(默认是关闭) var hasDownload = false {didSet {self.controlView.downLoadBtn.isHidden = !hasDownload}} // 是否被用户暂停 private(set) var isPauseByUser = false // 播放属性 private var player: AVPlayer? private lazy var urlAsset = AVURLAsset(url: videoURL!) private lazy var imageGenerator = AVAssetImageGenerator(asset: self.urlAsset) // playerLayer private var playerLayer: AVPlayerLayer? private var timeObserve: Any? // 用来保存快进的总时长 private var sumTime: CGFloat = 0.0 // 定义一个实例变量,保存枚举值 private var panDirection: PanDirection = .horizontal // 是否为全屏 private var isFullScreen = false // 是否锁定屏幕方向 private var isLocked = false // 是否在调节音量 private var isVolume = false // 是否显示controlView private var isMaskShowing = false // 是否播放本地文件 private var isLocalVideo = false // slider上次的值 private var sliderLastValue: Float = 0.0 // 是否再次设置URL播放视频 private var repeatToPlay = false // 播放完了 private var playDidEnd = false // 进入后台 private var didEnterBackground = false private var tap: UITapGestureRecognizer? private var doubleTap: UITapGestureRecognizer? // player所在cell的indexPath private var indexPath = IndexPath(row: 0, section: 0) // cell上imageView的tag private var cellImageViewTag = 0 // ViewController中页面是否消失 private var viewDisappear = false // 是否在cell上播放video private var isCellVideo = false // 是否缩小视频在底部 private var isBottomVideo = false // 是否切换分辨率 private var isChangeResolution = false // 播发器的几种状态 private var state: XPlayerState = .failed { didSet { if (state == .playing) { self.layer.contents = XPImage.management.img?.cgImage } else if (state == .failed) { self.controlView.downLoadBtn.isEnabled = false } // 控制菊花显示、隐藏 if state == .buffering { controlView.activity.startAnimating() } else { controlView.activity.stopAnimating() } } } // 播放前占位图片的名称,不设置就显示默认占位图(需要在设置视频URL之前设置) var placeholderImageName = "" { didSet { let image = UIImage(named:placeholderImageName) ?? XPImage.loading.img self.layer.contents = image?.cgImage } } // 设置playerLayer的填充模式 var playerLayerGravity: XPlayerFillMode = .aspectFill { didSet { switch (playerLayerGravity) { case .resize: self.playerLayer?.videoGravity = .resizeAspect case .aspect: self.playerLayer?.videoGravity = .resizeAspect case .aspectFill: self.playerLayer?.videoGravity = .resizeAspectFill } } } // 切换分辨率传的字典(key:分辨率名称,value:分辨率url) var resolutionDic: [String : String] = [:] { didSet { self.controlView.resolutionBtn.isHidden = false self.videoURLArray = [] self.controlView.resolutionArray = [] resolutionDic.forEach {[weak self] (key,value) in self?.videoURLArray.append(value) self?.controlView.resolutionArray.append(key) } } } private var playerItem: AVPlayerItem? { didSet { if (oldValue == playerItem) {return} NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: oldValue) oldValue?.removeObserver(self, forKeyPath: "status") oldValue?.removeObserver(self, forKeyPath: "loadedTimeRanges") oldValue?.removeObserver(self, forKeyPath: "playbackBufferEmpty") oldValue?.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp") NotificationCenter.default.addObserver(self, selector: #selector(moviePlayDidEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem) playerItem?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil) playerItem?.addObserver(self, forKeyPath: "loadedTimeRanges", options: NSKeyValueObservingOptions.new, context: nil) // 缓冲区空了,需要等待数据 playerItem?.addObserver(self, forKeyPath: "playbackBufferEmpty", options: NSKeyValueObservingOptions.new, context: nil) // 缓冲区有足够数据可以播放了 playerItem?.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: NSKeyValueObservingOptions.new, context: nil) } } // 滑杆 private var volumeViewSlider: UISlider? // 控制层View private var controlView = XPlayerControlView.xibView() // palyer加到tableView private var tableView: UITableView? { didSet { if oldValue == self.tableView { return } oldValue?.removeObserver(self, forKeyPath: kOffset) self.tableView?.addObserver(self, forKeyPath: kOffset, options: NSKeyValueObservingOptions.new, context: nil) } } override init(frame: CGRect) { super.init(frame: frame) initializeThePlayer() } required init?(coder: NSCoder) { super.init(coder: coder) } override func awakeFromNib() { super.awakeFromNib() initializeThePlayer() } func initializeThePlayer() { unLockTheScreen() self.addSubview(controlView) controlView.snp.makeConstraints { (make) in make.edges.equalTo(UIEdgeInsets.zero) } controlView.layoutSubviews() } deinit { self.playerItem = nil self.tableView = nil NotificationCenter.default.removeObserver(self) if let time = self.timeObserve { player?.removeTimeObserver(time) self.timeObserve = nil } } // 重置player public func resetPlayer() { self.playDidEnd = false self.playerItem = nil self.didEnterBackground = false self.seekTime = 0 self.isAutoPlay = false player?.removeTimeObserver(timeObserve!) self.timeObserve = nil NotificationCenter.default.removeObserver(self) pause() playerLayer?.removeFromSuperlayer() // self.imageGenerator = nil self.player?.replaceCurrentItem(with: nil) self.player = nil if (self.isChangeResolution) { self.controlView.resetControlViewForResolution() self.isChangeResolution = false }else { self.controlView.resetControlView() } if (!self.repeatToPlay) { removeFromSuperview() } self.isBottomVideo = false if (self.isCellVideo && !self.repeatToPlay) { self.viewDisappear = true self.isCellVideo = false self.tableView = nil self.indexPath = IndexPath(row: 0, section: 0) } } // 在当前页面,设置新的Player的URL调用此方法 public func resetToPlayNewURL() { self.repeatToPlay = true self.resetPlayer() } // 添加观察者、通知 func addNotifications() { let not = NotificationCenter.default // app退到后台 not.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.willResignActiveNotification, object: nil) // app进入前台 not.addObserver(self, selector: #selector(appDidEnterPlayGround), name: UIApplication.didBecomeActiveNotification, object: nil) // slider开始滑动事件 controlView.videoSlider.addTarget(self, action: #selector(progressSliderTouchBegan), for: .touchDown) // slider滑动中事件 controlView.videoSlider.addTarget(self, action: #selector(progressSliderValueChanged), for: .valueChanged) // slider结束滑动事件 controlView.videoSlider.addTarget(self, action: #selector(progressSliderTouchEnded), for: .touchUpInside) controlView.videoSlider.addTarget(self, action: #selector(progressSliderTouchEnded), for: .touchCancel) controlView.videoSlider.addTarget(self, action: #selector(progressSliderTouchEnded), for: .touchUpOutside) // 播放按钮点击事件 controlView.startBtn.addTarget(self, action: #selector(startAction), for: .touchUpInside) // cell上播放视频的话,该返回按钮为× if (self.isCellVideo) { controlView.backBtn.setImage(XPImage.close.img, for: .normal) }else { controlView.backBtn.setImage(XPImage.back.img, for: .normal) } // 返回按钮点击事件 controlView.backBtn.addTarget(self, action: #selector(backButtonAction), for: .touchUpInside) // 全屏按钮点击事件 controlView.fullScreenBtn.addTarget(self, action: #selector(fullScreenAction), for: .touchUpInside) // 锁定屏幕方向点击事件 controlView.lockBtn.addTarget(self, action: #selector(lockScreenAction), for: .touchUpInside) // 重播 controlView.repeatBtn.addTarget(self, action: #selector(repeatPlay), for: .touchUpInside) // 中间按钮播放 controlView.playeBtn.addTarget(self, action: #selector(configZFPlayer), for: .touchUpInside) controlView.downLoadBtn.addTarget(self, action: #selector(downloadVideo), for: .touchUpInside) controlView.resolutionBlock = {btn in let currentTime = CMTimeGetSeconds(self.player!.currentTime()) let videoStr = self.videoURLArray[(btn?.tag ?? 0)-200] let videoURL = URL(string: videoStr) if videoStr == self.videoURL?.absoluteString { return } self.isChangeResolution = true self.resetToPlayNewURL() self.videoURL = videoURL self.seekTime = Int(currentTime) self.isAutoPlay = true } controlView.tapBlock = { value in self.pause() let duration = self.playerItem!.duration let total = Int32(duration.value) / duration.timescale let dragedSeconds = floorf(Float(CGFloat(total) * value)) self.controlView.startBtn.isSelected = true self.seekToTime(Int(dragedSeconds)) } // 监测设备方向 UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(onDeviceOrientationChange), name: UIDevice.orientationDidChangeNotification, object: nil) } //pragma mark - layoutSubviews override func layoutSubviews() { super.layoutSubviews() self.playerLayer?.frame = self.bounds UIApplication.shared.isStatusBarHidden = false self.isMaskShowing = false self.animateShow() self.layoutIfNeeded() } //pragma mark - 设置视频URL // 用于cell上播放player public func setVideoURL(videoURL: URL, tableView: UITableView, indexPath: IndexPath, tag: Int) { if (!self.viewDisappear && (self.playerItem != nil)) { self.resetPlayer() } self.isCellVideo = true self.viewDisappear = false self.cellImageViewTag = tag self.tableView = tableView self.indexPath = indexPath self.videoURL = videoURL } // 设置Player相关参数 @objc func configZFPlayer() { self.playerItem = AVPlayerItem(asset: urlAsset) self.player = AVPlayer(playerItem: playerItem) self.playerLayer = AVPlayerLayer(player: player) self.playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspect self.layer.insertSublayer(playerLayer!, at: 0) self.isMaskShowing = true self.autoFadeOutControlBar() self.createGesture() self.createTimer() self.configureVolume() if self.videoURL?.scheme == "file" { self.state = .playing self.isLocalVideo = true self.controlView.downLoadBtn.isEnabled = false } else { self.state = .buffering self.isLocalVideo = false } self.play() self.controlView.startBtn.isSelected = true self.isPauseByUser = false self.controlView.playeBtn.isHidden = true self.setNeedsLayout() self.layoutIfNeeded() } // 创建手势 func createGesture() { self.tap = UITapGestureRecognizer(target: self, action: #selector(tapAction)) self.tap?.delegate = self self.addGestureRecognizer(self.tap!) self.doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapAction)) self.doubleTap?.numberOfTapsRequired = 2 self.addGestureRecognizer(self.doubleTap!) self.tap?.delaysTouchesBegan = true self.tap?.require(toFail: self.doubleTap!) } func createTimer() { self.timeObserve = self.player?.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 1), queue: nil, using: { (time) in let currentItem = self.playerItem if let item = currentItem, item.seekableTimeRanges.count > 0, item.duration.timescale != 0 { let currentTime = Int(CMTimeGetSeconds(item.currentTime())) let proMin = currentTime / 60 let proSec = currentTime % 60 let totalTime = Int(item.duration.value) / Int(item.duration.timescale) let durMin = totalTime / 60 let durSec = totalTime % 60 self.controlView.videoSlider.value = Float(currentTime) / Float(totalTime) self.controlView.currentTimeLabel.text = String(format: "%02zd:%02zd", proMin, proSec) self.controlView.totalTimeLabel.text = String(format:"%02zd:%02zd", durMin, durSec) } }) } // 获取系统音量 func configureVolume() { let volumeView = MPVolumeView() volumeViewSlider = nil for view in volumeView.subviews { if view.description == "MPVolumeSlider"{ volumeViewSlider = view as? UISlider break } } // 使用这个category的应用不会随着手机静音键打开而静音,可在手机静音下播放声音 let se = AVAudioSession.sharedInstance() try? se.setCategory(.playback) // 监听耳机插入和拔掉通知 NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListenerCallback(notification:)), name: NSNotification.Name(rawValue: AVAudioSessionRouteChangeReasonKey), object: nil) } // 耳机插入、拔出事件 @objc func audioRouteChangeListenerCallback(notification: NSNotification) { let interuptionDict = notification.userInfo let routeChangeReason = interuptionDict?[AVAudioSessionRouteChangeReasonKey] as! AVAudioSession.RouteChangeReason switch (routeChangeReason) { case .newDeviceAvailable: break case .oldDeviceUnavailable: self.play() case .categoryChange: print("AVAudioSessionRouteChangeReasonCategoryChange") default: break } } //pragma mark - ShowOrHideControlView func autoFadeOutControlBar() { if (!self.isMaskShowing) { return } NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hideControlView), object: nil) self.perform(#selector(hideControlView), with: nil, afterDelay: TimeInterval(7)) } // 取消延时隐藏controlView的方法 public func cancelAutoFadeOutControlBar() { NSObject.cancelPreviousPerformRequests(withTarget: self) } // 隐藏控制层 @objc func hideControlView() { if (!self.isMaskShowing) { return } UIView.animate(withDuration: TimeInterval(0.35), animations: { self.controlView.hideControlView() if (self.isFullScreen) { self.controlView.backBtn.alpha = 0 UIApplication.shared.setStatusBarHidden(true, with: UIStatusBarAnimation.fade) }else if (self.isBottomVideo && !self.isFullScreen) { self.controlView.backBtn.alpha = 1 }else { self.controlView.backBtn.alpha = 0 } }) { finished in self.isMaskShowing = false } } // 显示控制层 func animateShow() { if (self.isMaskShowing) { return } UIView.animate(withDuration: TimeInterval(0.35), animations: { self.controlView.backBtn.alpha = 1 if (self.isBottomVideo && !self.isFullScreen) { self.controlView.hideControlView() }else if (self.playDidEnd) { self.controlView.hideControlView() }else { self.controlView.showControlView() } UIApplication.shared.setStatusBarHidden(false, with: UIStatusBarAnimation.fade) }) { (finished) in self.isMaskShowing = true self.autoFadeOutControlBar() } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if object as? AVPlayerItem == player?.currentItem { if keyPath == "status" { if player?.currentItem?.status == AVPlayerItem.Status.readyToPlay { self.state = .playing let pan = UIPanGestureRecognizer(target: self, action: #selector(panDirection(_:))) pan.delegate = self self.addGestureRecognizer(pan) self.seekToTime(seekTime) } else if player?.currentItem?.status == AVPlayerItem.Status.failed { self.state = .failed self.controlView.horizontalLabel.isHidden = false self.controlView.horizontalLabel.text = "视频加载失败" } } else if keyPath == "loadedTimeRanges" { let totalDuration = CMTimeGetSeconds(self.playerItem!.duration) let progres = self.availableDuration() / totalDuration let progressView = controlView.progressView progressView?.setProgress(Float(progres), animated: false) let tiaojian = ((progressView?.progress ?? 0) - controlView.videoSlider.value > 0.05) if !self.isPauseByUser && !self.didEnterBackground && tiaojian { self.play() } } else if keyPath == "playbackBufferEmpty" { if (self.playerItem?.isPlaybackBufferEmpty ?? false) { self.state = .buffering self.bufferingSomeSecond() } } else if keyPath == "playbackLikelyToKeepUp" { if (self.playerItem?.isPlaybackLikelyToKeepUp ?? false) && self.state == .buffering { self.state = .playing } } }else if (object as? UITableView == self.tableView) { if keyPath == kOffset { let orien = UIDevice.current.orientation if orien == .landscapeLeft || orien == .landscapeRight { return } // 当tableview滚动时处理playerView的位置 self.handleScrollOffsetWithDict(change ?? [:]) } } } // KVO TableViewContentOffset func handleScrollOffsetWithDict(_ dict: [NSKeyValueChangeKey : Any]) { let cell = self.tableView?.cellForRow(at: indexPath) let visableCells = self.tableView?.visibleCells if visableCells?.contains(cell!) ?? false { self.updatePlayerViewToCell() }else { self.updatePlayerViewToBottom() } } // 缩小到底部,显示小视频 func updatePlayerViewToBottom() { if (self.isBottomVideo) { return } self.isBottomVideo = true if (self.playDidEnd) { //如果播放完了,滑动到小屏bottom位置时,直接resetPlayer self.repeatToPlay = false self.playDidEnd = false self.resetPlayer() return } UIApplication.shared.keyWindow?.addSubview(self) self.snp.makeConstraints { (make) in make.width.equalTo(APPW * 0.5 - 20) make.rightMargin.equalTo(10) make.bottom.equalTo(tableView?.snp.bottom ?? self.snp.bottom).offset(-10) make.height.equalTo(self.snp.width).multipliedBy(9.0 / 16) } // 不显示控制层 controlView.hideControlView() } // 回到cell显示 func updatePlayerViewToCell() { if (!self.isBottomVideo) { return } self.isBottomVideo = false self.controlView.alpha = 1 self.setOrientationPortrait() controlView.showControlView() } // 设置横屏的约束 func setOrientationLandscape() { if (self.isCellVideo) { tableView?.removeObserver(self, forKeyPath: kOffset) UIApplication.shared.setStatusBarStyle(.lightContent, animated: true) UIApplication.shared.keyWindow?.insertSubview(self, belowSubview: XBrightnessView.shared) self.snp.remakeConstraints { (make) in make.edges.equalTo(UIEdgeInsets.zero) } } } // 设置竖屏的约束 func setOrientationPortrait() { if (self.isCellVideo) { UIApplication.shared.setStatusBarStyle(.default, animated: true) self.removeFromSuperview() let cell = self.tableView?.cellForRow(at: indexPath) let visableCells = self.tableView?.visibleCells self.isBottomVideo = false if !(visableCells?.contains(cell!) ?? false) { self.updatePlayerViewToBottom() }else { let cellImageView = cell?.viewWithTag(self.cellImageViewTag) self.addPlayerToCellImageView(cellImageView as! UIImageView) } } } // pragma mark 屏幕转屏相关 // 强制屏幕转屏 func interfaceOrientation(_ orientation: UIInterfaceOrientation) { if orientation == UIInterfaceOrientation.landscapeLeft || orientation == UIInterfaceOrientation.landscapeRight { self.setOrientationLandscape() }else if (orientation == UIInterfaceOrientation.portrait) { self.setOrientationPortrait() } // 直接调用这个方法通不过apple上架审核 // UIDevice.current.orientation = UIDeviceOrientation.landscapeRight } // 全屏按钮事件 @objc func fullScreenAction(_ sender: UIButton?) { if (self.isLocked) { self.unLockTheScreen() return } if (self.isCellVideo && sender?.isSelected == true) { self.interfaceOrientation(.portrait) return } let orientation = UIDevice.current.orientation let interfaceOrientation = UIInterfaceOrientation(rawValue: orientation.rawValue) ?? .portrait switch (interfaceOrientation) { case .portraitUpsideDown: nessView.isAllowLandscape = false self.interfaceOrientation(.portrait) case .portrait: nessView.isAllowLandscape = true self.interfaceOrientation(.landscapeRight) case .landscapeLeft: if (self.isBottomVideo || !self.isFullScreen) { nessView.isAllowLandscape = true self.interfaceOrientation(.landscapeRight) } else { nessView.isAllowLandscape = false self.interfaceOrientation(.portrait) } case .landscapeRight: if (self.isBottomVideo || !self.isFullScreen) { nessView.isAllowLandscape = true self.interfaceOrientation(.landscapeRight) } else { nessView.isAllowLandscape = false self.interfaceOrientation(.portrait) } default: if (self.isBottomVideo || !self.isFullScreen) { nessView.isAllowLandscape = true self.interfaceOrientation(.landscapeRight) } else { nessView.isAllowLandscape = false self.interfaceOrientation(.portrait) } } } // 屏幕方向发生变化会调用这里 @objc func onDeviceOrientationChange() { if (self.isLocked) { self.isFullScreen = true return } let orientation = UIDevice.current.orientation let interfaceOrientation = UIInterfaceOrientation(rawValue:orientation.rawValue) ?? .portrait switch (interfaceOrientation) { case .portraitUpsideDown: self.controlView.fullScreenBtn.isSelected = true if (self.isCellVideo) { controlView.backBtn.setImage(XPImage.back.img, for: .normal) } self.isFullScreen = true case .portrait: self.isFullScreen = !self.isFullScreen self.controlView.fullScreenBtn.isSelected = false if (self.isCellVideo) { // 改为只允许竖屏播放 nessView.isAllowLandscape = false controlView.backBtn.setImage(XPImage.close.img, for: .normal) // 点击播放URL时候不会调用次方法 if (!self.isFullScreen) { // 竖屏时候table滑动到可视范围 tableView?.scrollToRow(at: indexPath, at: .middle, animated: false) // 重新监听tableview偏移量 tableView?.addObserver(self, forKeyPath: kOffset, options: .new, context: nil) } // 当设备转到竖屏时候,设置为竖屏约束 self.setOrientationPortrait() }else { } self.isFullScreen = false case .landscapeLeft: self.controlView.fullScreenBtn.isSelected = true if (self.isCellVideo) { controlView.backBtn.setImage(XPImage.back.img, for: .normal) } self.isFullScreen = true case .landscapeRight: self.controlView.fullScreenBtn.isSelected = true if (self.isCellVideo) { controlView.backBtn.setImage(XPImage.back.img, for: .normal) } self.isFullScreen = true default:break } // 设置显示or不显示锁定屏幕方向按钮 self.controlView.lockBtn.isHidden = !self.isFullScreen // 在cell上播放视频 && 不允许横屏(此时为竖屏状态,解决自动转屏到横屏,状态栏消失bug) if (self.isCellVideo && !nessView.isAllowLandscape) { controlView.backBtn.setImage(XPImage.close.img, for: .normal) self.controlView.fullScreenBtn.isSelected = false self.controlView.lockBtn.isHidden = true self.isFullScreen = false } } // 锁定屏幕方向按钮 @objc func lockScreenAction(_ sender: UIButton) { sender.isSelected = !sender.isSelected self.isLocked = sender.isSelected nessView.isLockScreen = sender.isSelected } // 解锁屏幕方向锁定 func unLockTheScreen() { // 调用AppDelegate单例记录播放状态是否锁屏 nessView.isLockScreen = false self.controlView.lockBtn.isSelected = false self.isLocked = false self.interfaceOrientation(.portrait) } // player添加到cellImageView上 public func addPlayerToCellImageView(_ imageView: UIImageView) { imageView.addSubview(self) self.snp.remakeConstraints { (make) in make.edges.equalTo(UIEdgeInsets.zero) } } // pragma mark - 缓冲较差时候 // 缓冲较差时候回调这里 func bufferingSomeSecond() { self.state = .buffering var isBuffering = false if (isBuffering) { return } isBuffering = true self.player?.pause() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) { if (self.isPauseByUser) { isBuffering = false return } self.play() isBuffering = false if !(self.playerItem?.isPlaybackLikelyToKeepUp ?? false) { self.bufferingSomeSecond() } } } // 计算缓冲进度 func availableDuration() -> TimeInterval { let loadedTimeRanges = player?.currentItem?.loadedTimeRanges let timeRange = loadedTimeRanges?.first?.timeRangeValue let startSeconds = CMTimeGetSeconds(timeRange!.start) let durationSeconds = CMTimeGetSeconds(timeRange!.duration) let result = startSeconds + durationSeconds// 计算缓冲总进度 return result } // 轻拍方法 @objc func tapAction(_ gesture: UITapGestureRecognizer) { if (gesture.state == .recognized) { if (self.isBottomVideo && !self.isFullScreen) { self.fullScreenAction(self.controlView.fullScreenBtn) return } if isMaskShowing { self.hideControlView() } else { self.animateShow() } } } // 双击播放/暂停 @objc func doubleTapAction(_ gesture: UITapGestureRecognizer) { self.animateShow() self.startAction(self.controlView.startBtn) } // 播放、暂停按钮事件 @objc func startAction(_ button: UIButton?) { button?.isSelected = !(button?.isSelected ?? false) self.isPauseByUser = !self.isPauseByUser if button?.isSelected ?? false { self.play() if (self.state == .pause) { self.state = .playing } } else { self.pause() if (self.state == .playing) { self.state = .pause } } } // 播放 public func play() { self.controlView.startBtn.isSelected = true self.isPauseByUser = false player?.play() } // 暂停 public func pause() { self.controlView.startBtn.isSelected = false self.isPauseByUser = true player?.pause() } // 返回按钮事件 @objc func backButtonAction() { if (self.isLocked) { self.unLockTheScreen() return }else { if (!self.isFullScreen) { if (self.isCellVideo) { self.resetPlayer() self.removeFromSuperview() return } self.pause() self.goBackBlock?() }else { self.interfaceOrientation(.portrait) } } } // 重播点击事件 @objc func repeatPlay(_ sender: UIButton) { self.playDidEnd = false self.repeatToPlay = false self.isMaskShowing = false self.animateShow() self.controlView.resetControlView() self.seekToTime(0) } @objc func downloadVideo(_ sender: UIButton) { let urlStr = self.videoURL?.absoluteString self.downloadBlock?(urlStr) } // pragma mark - NSNotification Action // 播放完了 @objc func moviePlayDidEnd(notification: NSNotification) { self.state = .stopped if (self.isBottomVideo && !self.isFullScreen) { self.repeatToPlay = false self.playDidEnd = false self.resetPlayer() } else { self.controlView.backgroundColor = UIColor(white: 0.6, alpha: 1) self.playDidEnd = true self.controlView.repeatBtn.isHidden = false self.isMaskShowing = false self.animateShow() } } // 应用退到后台 @objc func appDidEnterBackground() { self.didEnterBackground = true player?.pause() self.state = .pause self.cancelAutoFadeOutControlBar() self.controlView.startBtn.isSelected = false } // 应用进入前台 @objc func appDidEnterPlayGround() { self.didEnterBackground = false self.isMaskShowing = false self.animateShow() if (!self.isPauseByUser) { self.state = .playing self.controlView.startBtn.isSelected = true self.isPauseByUser = false self.play() } } // pragma mark - slider事件 // slider开始滑动事件 @objc func progressSliderTouchBegan(slider: ASValueTrackingSlider) { NSObject.cancelPreviousPerformRequests(withTarget: self) } // slider滑动中事件 @objc func progressSliderValueChanged(_ slider: ASValueTrackingSlider) { if (self.player?.currentItem?.status == .readyToPlay) { let value = slider.value - self.sliderLastValue if (value == 0) { return } self.sliderLastValue = slider.value self.pause() let total = Float(Int32(playerItem!.duration.value) / (playerItem!.duration.timescale)) let dragedSeconds = floorf(total * slider.value) let dragedCMTime = CMTimeMake(value: Int64(dragedSeconds), timescale: 1) let proMin = Int(CMTimeGetSeconds(dragedCMTime)) / 60 let proSec = Int(CMTimeGetSeconds(dragedCMTime)) % 60 let durMin = Int(total) / 60//总秒 let durSec = Int(total) % 60//总分钟 let currentTime = String(format:"%02zd:%02zd", proMin, proSec) let totalTime = String(format:"%02zd:%02zd", durMin, durSec) if (total > 0) { self.controlView.videoSlider.popUpView.isHidden = !self.isFullScreen self.controlView.currentTimeLabel.text = currentTime if (self.isFullScreen) { self.controlView.videoSlider.popUpView.timeLabel.text = currentTime let queue = DispatchQueue(label: "com.playerPic.queue") queue.async { let cgImage = try? self.imageGenerator.copyCGImage(at: dragedCMTime, actualTime: nil) var image = XPImage.loading.img if let cg = cgImage { image = UIImage(cgImage: cg) } DispatchQueue.main.async { self.controlView.videoSlider.setThumbImage(image, for: .normal) } } } else { self.controlView.horizontalLabel.isHidden = false self.controlView.horizontalLabel.text = "\(currentTime) / \(totalTime)" } }else { slider.value = 0 } }else { slider.value = 0 } } // slider结束滑动事件 @objc func progressSliderTouchEnded(_ slider: ASValueTrackingSlider) { if (self.player?.currentItem?.status == .readyToPlay) { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.controlView.horizontalLabel.isHidden = true } self.controlView.startBtn.isSelected = true self.isPauseByUser = false self.autoFadeOutControlBar() let total = CGFloat(Int32(playerItem!.duration.value) / playerItem!.duration.timescale) let dragedSeconds = floorf(Float(total) * slider.value) self.seekToTime(Int(dragedSeconds)) } } // 从xx秒开始播放视频跳转 func seekToTime(_ dragedSeconds: NSInteger, completionHandler:((Bool) -> Void)? = nil) { if (self.player?.currentItem?.status == .readyToPlay) { // seekTime:completionHandler:不能精确定位 // 可以使用seekToTime:toleranceBefore:toleranceAfter:completionHandler: // 转换成CMTime才能给player来控制播放进度 let dragedCMTime = CMTimeMake(value: Int64(dragedSeconds), timescale: 1) player?.seek(to: dragedCMTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero, completionHandler: { (finished) in // 视频跳转回调 completionHandler?(finished) self.play() self.seekTime = 0 if (!(self.playerItem?.isPlaybackLikelyToKeepUp ?? false) && !self.isLocalVideo) { self.state = .buffering } }) } } // pragma mark - UIPanGestureRecognizer手势方法 // pan手势事件 @objc func panDirection(_ pan: UIPanGestureRecognizer) { let locationPoint = pan.location(in: self) let veloctyPoint = pan.velocity(in: self) switch (pan.state) { case .began: let x = abs(veloctyPoint.x) let y = abs(veloctyPoint.y) if (x > y) { self.controlView.horizontalLabel.isHidden = false self.panDirection = .horizontal let time = self.player!.currentTime() self.sumTime = CGFloat(time.value)/CGFloat(time.timescale) self.pause() } else if (x < y){ self.panDirection = .vertical if (locationPoint.x > self.bounds.size.width / 2) { self.isVolume = true }else { self.isVolume = false } } case .changed: switch (self.panDirection) { case .horizontal: self.controlView.horizontalLabel.isHidden = false self.horizontalMoved(veloctyPoint.x) case .vertical: self.verticalMoved(veloctyPoint.y) } case .ended: switch (self.panDirection) { case .horizontal: self.play() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { self.controlView.horizontalLabel.isHidden = true } self.controlView.startBtn.isSelected = true self.isPauseByUser = false self.seekToTime(NSInteger(self.sumTime)) self.sumTime = 0 case .vertical: self.isVolume = false DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.controlView.horizontalLabel.isHidden = true } } default: break } } // pan垂直移动的方法 func verticalMoved(_ value: CGFloat) { if self.isVolume { let v = volumeViewSlider?.value ?? 0 self.volumeViewSlider?.value = v - Float(value) / 10000 } else { UIScreen.main.brightness -= value / 10000 } } // pan水平移动的方法 func horizontalMoved(_ value: CGFloat) { if (value == 0) { return } self.sumTime += value / 200 let totalTime = self.playerItem!.duration let totalMovieDuration = CGFloat(Int32(totalTime.value)/totalTime.timescale) if (self.sumTime > totalMovieDuration) { self.sumTime = totalMovieDuration} if (self.sumTime < 0) { self.sumTime = 0 } let nowTime = self.durationStringWithTime(Int(self.sumTime)) let durationTime = self.durationStringWithTime(Int(totalMovieDuration)) self.controlView.horizontalLabel.text = "\(nowTime) / \(durationTime)" self.controlView.videoSlider.value = Float(self.sumTime/totalMovieDuration) self.controlView.currentTimeLabel.text = nowTime } // 根据时长求出字符串 func durationStringWithTime(_ time: Int) -> String { // 获取分钟 let min = String(format: "%02d",time / 60) // 获取秒数 let sec = String(format: "%02d",time % 60) return "\(min):\(sec)" } } extension XPlayer: UIGestureRecognizerDelegate, UIAlertViewDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) { let point = touch.location(in: self.controlView) // (屏幕下方slider区域) || (在cell上播放视频 && 不是全屏状态) || (播放完了) =====> 不响应pan手势 if ((point.y > self.bounds.size.height-40) || (self.isCellVideo && !self.isFullScreen) || self.playDidEnd) { return false } return true } // 在cell上播放视频 && 不是全屏状态 && 点在控制层上 if (self.isBottomVideo && !self.isFullScreen && touch.view == self.controlView) { self.fullScreenAction(self.controlView.fullScreenBtn) return false } if (self.isBottomVideo && !self.isFullScreen && touch.view == self.controlView.backBtn) { // 关闭player self.resetPlayer() self.removeFromSuperview() return false } return true } func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex:NSInteger) { if (alertView.tag == 1000 ) { if (buttonIndex == 0) { self.backButtonAction()} // 点击取消,直接调用返回函数 if (buttonIndex == 1) { self.configZFPlayer()} // 点击确定,设置player相关参数 } } }
a81c4ad5bb36993fac4c6728b372a596
38.610229
208
0.602119
false
false
false
false
ALiOSDev/ALTableView
refs/heads/master
ALTableViewSwift/ALTableView/ALTableView/ALTableViewClasses/ALTableView/ALTableViewPullToRefresh.swift
mit
1
// // ALTableViewPullToRefresh.swift // ALTableView // // Created by lorenzo villarroel perez on 24/4/18. // Copyright © 2018 ALTableView. All rights reserved. // import UIKit extension ALTableView { private static let refreshControlTag = 1000 public func addPullToRefresh(title: NSAttributedString = NSAttributedString(string: ""), backgroundColor: UIColor = .clear, tintColor: UIColor = .black) { if let tableView = self.tableView { let refreshControl: UIRefreshControl = UIRefreshControl() refreshControl.backgroundColor = backgroundColor refreshControl.tintColor = tintColor refreshControl.addTarget(self, action: #selector(refreshTriggered(_:)), for: .valueChanged) refreshControl.attributedTitle = title if #available(iOS 10.0, *) { tableView.refreshControl = refreshControl } else { refreshControl.tag = ALTableView.refreshControlTag tableView.addSubview(refreshControl) } } } @objc private func refreshTriggered(_ sender: Any) { self.delegate?.tableViewPullToRefresh?() if let tableView = self.tableView { if #available(iOS 10.0, *) { tableView.refreshControl?.endRefreshing() } else { if let refreshControl = tableView.viewWithTag(ALTableView.refreshControlTag) as? UIRefreshControl { refreshControl.endRefreshing() } } } } }
8d333940ce421adae19a201b2d75d160
33.673913
158
0.609404
false
false
false
false
michalciurus/KatanaRouter
refs/heads/master
Pods/Katana/Katana/Plastic/Anchor.swift
mit
1
// // Anchor.swift // Katana // // Copyright © 2016 Bending Spoons. // Distributed under the MIT License. // See the LICENSE file for more information. import CoreGraphics /** An abstract representation of a `PlasticView` layout property. */ public struct Anchor: Equatable { /// This enum represents the possible kinds of anchor public enum Kind { /// the left edge of the view the anchor pertains to case left /// the right edge of the view the anchor pertains to case right /// the horizontal center of the view the anchor pertains to case centerX /// the top edge of the view the anchor pertains to case top /// the bottom edge of the view the anchor pertains to case bottom /// the vertical center of the view the anchor pertains to case centerY } /// the kind of the anchor let kind: Kind /// the `PlasticView` to which the anchor is associated to let view: PlasticView /// the offset at which this anchor will be set, with respect to the anchor it will be assigned to let offset: Value /** Creates an anchor with a given type, related to a specific `PlasticView` - parameter kind: the kind of the anchor - parameter view: the view the anchor pertains to - parameter offset: the offset at which this anchor will be set, with respect to the anchor it will be assigned to */ init(kind: Kind, view: PlasticView, offset: Value = .zero) { self.kind = kind self.view = view self.offset = offset } /** As the `Anchor` instance symbolizes a line in a given view, this method will return that line's horizontal or vertical coordinate in the node description native view's coordinate system */ var coordinate: CGFloat { let absoluteOrigin = self.view.absoluteOrigin let size = self.view.frame let coord: CGFloat switch self.kind { case .left: coord = absoluteOrigin.x case .right: coord = absoluteOrigin.x + size.width case .centerX: coord = absoluteOrigin.x + size.width / 2.0 case .top: coord = absoluteOrigin.y case .bottom: coord = absoluteOrigin.y + size.height case .centerY: coord = absoluteOrigin.y + size.height / 2.0 } return coord + view.scaleValue(offset) } /** Implementation of the Equatable protocol - parameter lhs: the first anchor - parameter rhs: the second anchor - returns: true if the two anchors are equals, false otherwise. Two anchors are considered equal if the are related to the same view and to they also have the same kind */ public static func == (lhs: Anchor, rhs: Anchor) -> Bool { return lhs.kind == rhs.kind && lhs.view === rhs.view } /** Create an anchor equal to `lhs`, but with an offset equal to `lhs.offset + rhs` */ public static func + (lhs: Anchor, rhs: Value) -> Anchor { return Anchor(kind: lhs.kind, view: lhs.view, offset: lhs.offset + rhs) } /** Create an anchor equal to `lhs`, but with an offset equal to `lhs.offset - rhs` */ public static func - (lhs: Anchor, rhs: Value) -> Anchor { return Anchor(kind: lhs.kind, view: lhs.view, offset: lhs.offset + -rhs) } /** Create an anchor equal to `lhs`, but with an offset equal to `lhs.offset + Value.scalable(rhs)` */ public static func + (lhs: Anchor, rhs: CGFloat) -> Anchor { return lhs + .scalable(rhs) } /** Create an anchor equal to `lhs`, but with an offset equal to `lhs.offset - Value.scalable(rhs)` */ public static func - (lhs: Anchor, rhs: CGFloat) -> Anchor { return lhs - .scalable(rhs) } }
7f36a47b7fb7d5e3dac3b8ba719b3269
28.04
121
0.664187
false
false
false
false
ibari/StationToStation
refs/heads/master
StationToStation/StationCell.swift
gpl-2.0
1
// // StationCell.swift // StationToStation // // Created by Ian on 6/8/15. // Copyright (c) 2015 Ian Bari. All rights reserved. // import UIKit class StationCell: UICollectionViewCell { @IBOutlet weak var banerImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var trackCountLabel: UILabel! var station: Station! { didSet { banerImageView.setImageWithURL(NSURL(string: station.imageUrl)) nameLabel.text = station!.name let tracks = station.playlist!.tracks.count trackCountLabel.text = (tracks == 1) ? "\(station.playlist!.tracks.count) Track" : "\(station.playlist!.tracks.count) Tracks" } } override func awakeFromNib() { super.awakeFromNib() } override func layoutSubviews() { super.layoutSubviews() } }
e0e279ff657a33c8fd8484c045aea7a8
25.058824
137
0.626411
false
false
false
false
markedwardmurray/Precipitate
refs/heads/master
Precipitate/DataEntryCollator.swift
mit
1
// // HourlyDataEntryCollator.swift // Precipitate // // Created by Mark Murray on 12/7/15. // Copyright © 2015 markedwardmurray. All rights reserved. // import Foundation import SwiftyJSON import Charts class DataEntryCollator { let currentlyIcon: String let summary: String let hours: [NSTimeInterval] let sunriseTime: NSTimeInterval // from daily data let sunsetTime: NSTimeInterval // from daily data let hourlyDataEntrys: [String: [ChartDataEntry] ] let days: [NSTimeInterval] let dailyDataEntrys: [String: [ChartDataEntry] ] init(json: JSON) { let hourlyData = json["hourly"]["data"] let dailyData = json["daily"]["data"] currentlyIcon = json["currently"]["icon"].string! summary = json["currently"]["summary"].string! sunriseTime = NSTimeInterval(dailyData[0]["sunriseTime"].double!) sunsetTime = NSTimeInterval(dailyData[0]["sunsetTime"].double!) hours = DataEntryCollator.allHoursFromHourlyData(hourlyData) hourlyDataEntrys = DataEntryCollator.dataEntrysFromHourlyData(hourlyData) days = DataEntryCollator.allDaysFromDailyData(dailyData) dailyDataEntrys = DataEntryCollator.dataEntrysFromDailyData(dailyData) } class private func allHoursFromHourlyData(hourlyData: JSON) -> [NSTimeInterval] { var allHours = [NSTimeInterval]() for var i = 0; i < hourlyData.count; i++ { if let time = hourlyData[i]["time"].double { let hour = NSTimeInterval(time) allHours.append(hour) } else { print("error: no time at index in hourly data") } } return allHours } class private func allDaysFromDailyData(dailyData: JSON) -> [NSTimeInterval] { var allDays = [NSTimeInterval]() for var i = 0; i < dailyData.count; i++ { if let time = dailyData[i]["time"].double { let day = NSTimeInterval(time) allDays.append(day) } else { print("error: no time at index in daily data") } } return allDays } class private func dataEntrysFromHourlyData(hourlyData: JSON) -> [String:[ChartDataEntry]] { var dataDictionary = [ String: [ChartDataEntry] ]() for hourlyKey in DataEntryCollator.hourlyKeys { var dataEntrys = [ChartDataEntry]() for var i = 0; i < hourlyData.count; i++ { if let yVal = hourlyData[i][hourlyKey].double { let dataEntry = ChartDataEntry(value: yVal, xIndex: i) dataEntrys.append(dataEntry) } else { let nilEntry = ChartDataEntry(value: 0.0, xIndex: i) dataEntrys.append(nilEntry) } } dataDictionary[hourlyKey] = dataEntrys } return dataDictionary } class private func dataEntrysFromDailyData(dailyData: JSON) -> [String:[ChartDataEntry]] { var dataDictionary = [ String: [ChartDataEntry] ]() for dailyKey in DataEntryCollator.dailyKeys { var dataEntrys = [ChartDataEntry]() for var i = 0; i < dailyData.count; i++ { if let yVal = dailyData[i][dailyKey].double { let dataEntry = ChartDataEntry(value: yVal, xIndex: i) dataEntrys.append(dataEntry) } else { let nilEntry = ChartDataEntry(value: 0.0, xIndex: i) dataEntrys.append(nilEntry) } } dataDictionary[dailyKey] = dataEntrys } return dataDictionary } static let hourlyKeys: [String] = [ "temperature", "apparentTemperature", "precipProbability", "precipIntensity", "precipAccumulation", "windSpeed", "cloudCover", "visibility", "ozone", "humidity", "dewPoint", "pressure" ] static let dailyKeys: [String] = [ "temperatureMin", "temperatureMax", "apparentTemperatureMin", "apparentTemperatureMax", "precipProbability", "precipIntensity", "precipIntensityMax", "windSpeed", "cloudCover", "visibility", "ozone", "humidity", "dewPoint", "pressure" ] }
3eff3443616472aa685dca511e8e99c7
29.292208
96
0.550911
false
false
false
false
manGoweb/SpecTools
refs/heads/master
SpecTools/Classes/Checks/Checks+UICollectionView.swift
mit
1
// // Checks+UICollectionView.swift // SpecTools // // Created by Ondrej Rafaj on 15/09/2017. // import Foundation import UIKit extension Check where T: UICollectionView { // MARK: UICollectionView /// Check if there are any cells that don't fit criteria specified in a closure /// - Parameter fit: Closure that needs to evaluate the cell which is passed onto it /// - Returns: Bool (true if no issue is found) public func allCells(fit evaluateClosure: (UICollectionViewCell)->Bool) -> Bool { return allCells(thatDontFit: evaluateClosure).count == 0 } /// Check if there are any cells that don't fit criteria specified in a closure /// - Parameter fit: Closure that needs to evaluate the cell which is passed onto it /// - Returns: [IndexPath] Index path of all cells that do not match the given criteria public func allCells(thatDontFit evaluateClosure: (UICollectionViewCell)->Bool) -> [IndexPath] { var indexPaths: [IndexPath] = [] for sectionIndex in 0...element.spec.find.numberOfSections() { row: for rowIndex in 0...element.spec.find.number(ofRowsIn: sectionIndex) { let indexPath = IndexPath(item: rowIndex, section: sectionIndex) guard let cell = element.dataSource?.collectionView(element, cellForItemAt: indexPath) else { fatalError("Data source is not set") } let ok = evaluateClosure(cell) if !ok { indexPaths.append(indexPath) } } } return indexPaths } }
7725bed8af625162777747a1334518ec
35.822222
109
0.625226
false
false
false
false
Zhendeshede/weiboBySwift
refs/heads/master
新浪微博/新浪微博/UserAccess.swift
mit
1
// // UserAccess.swift // 新浪微博 // // Created by 李旭飞 on 15/10/11. // Copyright © 2015年 lee. All rights reserved. // import UIKit class UserAccess: NSObject,NSCoding { //用户是否登录标记 class var userLogin : Bool{ return loadUserAccount != nil } // 接口获取授权后的token var access_token:String? // 当前授权用户的UID var uid:String? // token的生命周期,单位是秒数 private var expires_in:NSTimeInterval=0{ didSet{ expiresDate=NSDate(timeIntervalSinceNow: expires_in) } } private var expiresDate:NSDate? //用户昵称 var name:String? // 用户头像 var avatar_large:String? //MARK:- 用字典加载模型 init(dictionary:[String:AnyObject]){ super.init() setValuesForKeysWithDictionary(dictionary) //MARK:- 为全局账户赋值,重点(不赋值会从本地去加载,会卡顿) UserAccess.useraccount=self } //防止字典的键与模型属性不对应时奔溃 override func setValue(value: AnyObject?, forUndefinedKey key: String) {} override var description: String { //对对象对描述 let properties=["access_token","expires_in","uid","expiresDate"] return "\(dictionaryWithValuesForKeys(properties))" } ///账户信息本地保存路径 private static let accountPath=NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("token.plist") //MARK :- 加载用户信息 func loadUserInfo(finished:(error:NSError?)->()){ self.saveAccount() NetworkTool.shareNetworkTool.loadUserInfo(uid!) { (result, error) -> () in if error != nil{ finished(error: error) return } self.name=result!["name"] as? String self.avatar_large=result!["avatar_large"] as? String self.saveAccount() finished(error: nil) } } //MARK:- 保存用户账号授权 func saveAccount(){ NSKeyedArchiver.archiveRootObject(self, toFile: UserAccess.accountPath) } /// 定义全局的用户信息变量 private static var useraccount:UserAccess? //MARK:- 获取用户账号授权 class var loadUserAccount:UserAccess?{ print(UserAccess.accountPath) //判断账户是否存在 if useraccount==nil{ useraccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccess } // 判断日期是否过期 if let date = useraccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending{ useraccount = nil } return useraccount } //MARK:- 归档,解档 required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObjectForKey("access_token") as? String expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate uid = aDecoder.decodeObjectForKey("uid") as? String expires_in = aDecoder.decodeDoubleForKey("expires_in") name = aDecoder.decodeObjectForKey("name") as? String avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String } //归档 func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeObject(expiresDate, forKey: "expiresDate") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeDouble(expires_in, forKey: "expires_in") aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(avatar_large, forKey: "avatar_large") } }
ed9fd08e60937a0e27a4dca536b56ec3
26.64
202
0.639074
false
false
false
false
0xTim/gitignore.io
refs/heads/master
Tests/GitignoreIOServerTests/Extensions/String+ExtensionsTests.swift
mit
1
// // String+ExtensionsTests.swift // GitignoreIO // // Created by Joe Blau on 12/21/16. // // import XCTest import Foundation @testable import GitignoreIOServer class String_ExtensionsTests: XCTestCase { static let allTests = [ ("testStringName_valid", testStringName_valid), ("testStringName_empty", testStringName_empty), ("testStringFileName_valid", testStringFileName_valid), ("testStringFileName_empty", testStringFileName_empty), ("testRemoveDuplicateLines", testRemoveDuplicateLines), ] func testStringName_valid() { let path = URL(fileURLWithPath: "/User/ElonMusk/Developer/GitIgnoreIO/data/custom/tesla.gitignore") XCTAssertEqual(path.name, "tesla") } func testStringName_empty() { let path = URL(fileURLWithPath: "") XCTAssertFalse(path.name.isNull) } func testStringFileName_valid() { let path = URL(fileURLWithPath: "/User/ElonMusk/Developer/GitIgnoreIO/data/custom/tesla.gitignore") XCTAssertEqual(path.fileName, "tesla.gitignore") } func testStringFileName_empty() { let path = URL(fileURLWithPath: "") XCTAssertFalse(path.fileName.isEmpty) } func testRemoveDuplicateLines() { let string = "abc\n" .appending("#comment\n") .appending("\n") .appending("dup\n") .appending("\n") .appending("dup\n") .appending("xyz\n") let answer = "abc\n" .appending("#comment\n") .appending("\n") .appending("dup\n") .appending("\n") .appending("xyz\n") XCTAssertEqual(string.removeDuplicateLines(), answer) } }
4b8db007df07133ea8d8eda8d38c06c5
27.901639
107
0.605786
false
true
false
false
PD-Jell/Swift_study
refs/heads/master
SwiftStudy/RxSwift/RxSwift-city/RxCityViewController.swift
mit
1
// // RxCityViewController.swift // SwiftStudy // // Created by YooHG on 7/7/20. // Copyright © 2020 Jell PD. All rights reserved. // import UIKit import RxSwift import RxCocoa class RxCityViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! let searchController: UISearchController = UISearchController(searchResultsController: nil) var searchBar: UISearchBar { return searchController.searchBar } var shownCities = [String]() let allCities = ["New York", "London", "Oslo", "Warsaw", "Berlin", "Praga"] let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() searchController.obscuresBackgroundDuringPresentation = false // UISearchController가 뷰를 흐리게 하는 걸 막는다. searchBar.showsCancelButton = true definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar tableView.dataSource = self searchBar .rx.text // RxCocoa의 Observable 속성 .orEmpty // 옵셔널 해제 .debounce(DispatchTimeInterval.milliseconds(500), scheduler: MainScheduler.instance) .distinctUntilChanged() // 새로운 값이 이전과 같으면 무시. .filter{$0.isEmpty} // 새로운 값이 빈 값인지 확인. .subscribe(onNext: { [unowned self] query in // 새로운 값에 대한 알림을 받음. unowned는...? print("query: \(query)") self.shownCities = self.allCities.filter { $0.hasPrefix(query) } // 일치하는 친구만 찾아서 shownCities에 쑉 self.tableView.reloadData() }) .disposed(by: disposeBag) // 기본적으로 observable은 사라지지 않지만 여기에 담으면 뷰가 해제될 때 같이 해제할 수 있다. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shownCities.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cityPrototypeCell", for: indexPath) cell.textLabel?.text = shownCities[indexPath.row] return cell } }
cb8f64497c5bb7b587e416e2f220403f
34.721311
111
0.652134
false
false
false
false
OctoberHammer/CoreDataCollViewFRC
refs/heads/master
CoreDataCallViewFRC/WithInternalStorageVC.swift
mit
1
// // WithInternalStorageVC.swift // CoreDataCallViewFRC // // Created by October Hammer on 10/20/17. // Copyright © 2017 Ocotober Hammer. All rights reserved. //https://www.youtube.com/watch?v=0JJJ2WGpw_I import Foundation import UIKit import CoreData private let reuseIdentifier = "ItemCell" class WithInternalStorageVC: UICollectionViewController, NSFetchedResultsControllerDelegate { var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer lazy var fetchedResultController: NSFetchedResultsController<InternalData>? = { if let context = self.container?.viewContext { let fetchRequest = NSFetchRequest<InternalData>(entityName: "InternalData") fetchRequest.sortDescriptors = []//NSSortDescriptor(key: "title", ascending: true) let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) frc.delegate = self return frc } else { return nil } }() override func viewDidLoad() { super.viewDidLoad() let nibCategory = UINib(nibName: reuseIdentifier, bundle: nil) self.collectionView!.register(nibCategory, forCellWithReuseIdentifier: reuseIdentifier) print(container?.persistentStoreDescriptions.first?.url) container?.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyStoreTrump do { try self.fetchedResultController?.performFetch() print(self.fetchedResultController?.fetchedObjects?.count ?? 0) } catch let err { print(err.localizedDescription) } } 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. } */ // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items if let count = self.fetchedResultController?.fetchedObjects?.count { return count } return 0 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ItemCell let item = self.fetchedResultController?.object(at: indexPath) as! InternalData //print(item.title) // Configure the cell DispatchQueue.main.async{ cell.configure(with: item) } return cell } @IBAction func populateCoreData(_ sender: UIBarButtonItem) { if let container = self.container { container.viewContext.automaticallyMergesChangesFromParent = true let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) backgroundContext.parent = container.viewContext generateRandomObjects(backgroundContext: backgroundContext) } } var blockOperations: [BlockOperation] = [] func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { if type == .insert { blockOperations.append(BlockOperation(block: { if let newIndexPath = newIndexPath { self.collectionView?.insertItems(at: [newIndexPath]) } }) ) } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { collectionView?.performBatchUpdates({ for everyOperation in self.blockOperations { everyOperation.start() } }, completion: {(completed) in let lastIndex = (self.fetchedResultController?.sections![0].numberOfObjects ?? 1) - 1 print("Total: \(lastIndex)") let indexPath = IndexPath(item: lastIndex, section: 0) self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true) do { try self.container?.viewContext.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror.localizedDescription), \(nserror.userInfo)") } }) } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { } */ }
55b6bcf9f759520895d3527ed5533d37
37.280702
200
0.660709
false
false
false
false
CodaFi/Basis
refs/heads/master
BasisTests/CompareSpec.swift
mit
2
// // CompareSpec.swift // Basis // // Created by Robert Widmann on 9/26/14. // Copyright (c) 2014 TypeLift. All rights reserved. // Released under the MIT license. // import Basis import XCTest class CompareSpec : XCTestCase { func testGroupBy() { let x = [1, 1, 2, 3, 3, 4, 4, 4, 5, 6, 6] let y = [[1, 1], [2], [3, 3], [4, 4, 4], [5], [6, 6]] XCTAssertTrue(and(zip(groupBy(==)(x).map({ $0.count }))(y.map({ $0.count })).map(==)), "") XCTAssertTrue(and(zip(groupBy(==)(x).map(head))(y.map(head)).map(==)), "") XCTAssertTrue(and(groupBy(==)(x).map({ l in all({ head(l) == $0 })(l) })), "") } func testNubBy() { let x = [1, 1, 2, 3, 3, 4, 4, 4, 5, 6, 6] let y = [1, 2, 3, 4, 5, 6] XCTAssertTrue(and(zip(nubBy(==)(x))(y).map(==)), "") } func testComparing() { let x = [(2, 3), (1, 4), (4, 2), (5, 1), (3, 5)] let y = [(1, 4), (2, 3), (3, 5), (4, 2), (5, 1)] let z = [(5, 1), (4, 2), (2, 3), (1, 4), (3, 5)] let s = sortBy(comparing(fst))(x) XCTAssertTrue(s.map(fst) == y.map(fst), "") XCTAssertTrue(s.map(snd) == y.map(snd), "") let t = sortBy(comparing(snd))(x) XCTAssertTrue(t.map(fst) == z.map(fst), "") XCTAssertTrue(t.map(snd) == z.map(snd), "") } func testArrayComparisons() { let xs = [1, 2, 3, 4] let ys = [1, 2, 3] let zs = [3, 4, 5] XCTAssertTrue(xs >= xs, "") XCTAssertTrue(ys >= ys, "") XCTAssertTrue(zs >= zs, "") XCTAssertTrue(xs <= xs, "") XCTAssertTrue(ys <= ys, "") XCTAssertTrue(zs <= zs, "") XCTAssertTrue(xs >= ys, "") XCTAssertTrue(zs >= ys, "") XCTAssertTrue(xs <= zs, "") XCTAssertTrue(ys <= xs, "") XCTAssertTrue(ys <= zs, "") XCTAssertTrue(zs >= xs, "") XCTAssertTrue(xs > ys, "") XCTAssertTrue(zs > ys, "") XCTAssertTrue(xs < zs, "") XCTAssertTrue(ys < xs, "") XCTAssertTrue(ys < zs, "") XCTAssertTrue(zs > xs, "") let l : [Int] = [] let r : [Int] = [] XCTAssertTrue(l >= r, "") XCTAssertTrue(l <= r, "") XCTAssertFalse(l < r, "") XCTAssertFalse(l > r, "") } }
9b1142f8bc8661fb4df2e7c3dfac7e8f
24.1375
92
0.524117
false
true
false
false