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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CesarValiente/CursoSwiftUniMonterrey2-UI | refs/heads/master | week4/PizzasForWatch/PizzasForWatch WatchKit Extension/IngredientsVC.swift | mit | 1 | //
// IngredientsVC.swift
// PizzasForWatch
//
// Created by Cesar Valiente on 24/01/16.
// Copyright © 2016 Cesar Valiente. All rights reserved.
//
import WatchKit
import Foundation
class IngredientsVC: WKInterfaceController {
@IBOutlet var pizzaIngredientsPicker: WKInterfacePicker!
var pizza : Pizza?
var pizzaIngredientsArray : [WKPickerItem] = []
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
pizza = (context as! Pizza)
setup()
}
private func setup () {
pizza?.ingredients = Ingredients.One
pizzaIngredientsArray = createPickerItems()
pizzaIngredientsPicker.setItems(pizzaIngredientsArray)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func onPizzaIngredientsPickerClick(value: Int) {
let item = pizzaIngredientsArray[value]
let ingredients : Ingredients = fromStringToIngredients(item.title)
pizza?.ingredients = ingredients
}
private func createPickerItems () -> [WKPickerItem] {
var pickerItems : [WKPickerItem] = []
pickerItems.append(createPizzaIngredientsPickerItem(0, ingredients: Ingredients.One))
pickerItems.append(createPizzaIngredientsPickerItem(1, ingredients: Ingredients.Two))
pickerItems.append(createPizzaIngredientsPickerItem(2, ingredients: Ingredients.Three))
pickerItems.append(createPizzaIngredientsPickerItem(3, ingredients: Ingredients.Four))
pickerItems.append(createPizzaIngredientsPickerItem(4, ingredients: Ingredients.Five))
return pickerItems
}
private func createPizzaIngredientsPickerItem (index : Int, ingredients : Ingredients) -> WKPickerItem {
let item = WKPickerItem()
item.title = ingredients.rawValue
return item
}
@IBAction func onAcceptBtnClick() {
pushControllerWithName("review", context: pizza)
}
}
| b89d5312f16d5951a9331ab95e8082b9 | 30.318182 | 108 | 0.689889 | false | false | false | false |
CreazyShadow/SimpleDemo | refs/heads/master | DemoClass/RxSwiftProject/Pods/RxCocoa/RxCocoa/RxCocoa.swift | apache-2.0 | 12 | //
// RxCocoa.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import class Foundation.NSNull
import RxSwift
#if os(iOS)
import UIKit
#endif
/// RxCocoa errors.
public enum RxCocoaError
: Swift.Error
, CustomDebugStringConvertible {
/// Unknown error has occurred.
case unknown
/// Invalid operation was attempted.
case invalidOperation(object: Any)
/// Items are not yet bound to user interface but have been requested.
case itemsNotYetBound(object: Any)
/// Invalid KVO Path.
case invalidPropertyName(object: Any, propertyName: String)
/// Invalid object on key path.
case invalidObjectOnKeyPath(object: Any, sourceObject: AnyObject, propertyName: String)
/// Error during swizzling.
case errorDuringSwizzling
/// Casting error.
case castingError(object: Any, targetType: Any.Type)
}
// MARK: Debug descriptions
extension RxCocoaError {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error occurred."
case let .invalidOperation(object):
return "Invalid operation was attempted on `\(object)`."
case let .itemsNotYetBound(object):
return "Data source is set, but items are not yet bound to user interface for `\(object)`."
case let .invalidPropertyName(object, propertyName):
return "Object `\(object)` doesn't have a property named `\(propertyName)`."
case let .invalidObjectOnKeyPath(object, sourceObject, propertyName):
return "Unobservable object `\(object)` was observed as `\(propertyName)` of `\(sourceObject)`."
case .errorDuringSwizzling:
return "Error during swizzling."
case .castingError(let object, let targetType):
return "Error casting `\(object)` to `\(targetType)`"
}
}
}
// MARK: Error binding policies
func bindingError(_ error: Swift.Error) {
let error = "Binding error: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
}
/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass.
func rxAbstractMethod(message: String = "Abstract method", file: StaticString = #file, line: UInt = #line) -> Swift.Never {
rxFatalError(message, file: file, line: line)
}
func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage(), file: file, line: line)
}
func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) {
#if DEBUG
fatalError(lastMessage(), file: file, line: line)
#else
print("\(file):\(line): \(lastMessage())")
#endif
}
// MARK: casts or fatal error
// workaround for Swift compiler bug, cheers compiler team :)
func castOptionalOrFatalError<T>(_ value: Any?) -> T? {
if value == nil {
return nil
}
let v: T = castOrFatalError(value)
return v
}
func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: AnyObject) throws -> T? {
if NSNull().isEqual(object) {
return nil
}
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOrFatalError<T>(_ value: AnyObject!, message: String) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError(message)
}
return result
}
func castOrFatalError<T>(_ value: Any!) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError("Failure converting from \(value) to \(T.self)")
}
return result
}
// MARK: Error messages
let dataSourceNotSet = "DataSource not set"
let delegateNotSet = "Delegate not set"
// MARK: Shared with RxSwift
func rxFatalError(_ lastMessage: String) -> Never {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
| 482780f7b2ffa8f945ed353edef6ddfd | 30.177632 | 230 | 0.669973 | false | false | false | false |
DanilaVladi/Microsoft-Cognitive-Services-Swift-SDK | refs/heads/master | SDK/CognitiveServices/ComputerVision/AnalyzeImage.swift | apache-2.0 | 2 | // AnalyzeImageComputerVision.swift
//
// Copyright (c) 2016 Vladimir Danila
//
// 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 UIKit
import CoreGraphics
protocol AnalyzeImageDelegate {
/// Images that contain faces will be analyzed further for the emotions contained in the image. Since that might take longer than the initially returned object this delegate is recommended.
func finnishedGeneratingObject(_ analyzeImageObject: AnalyzeImage.AnalyzeImageObject)
}
/**
RequestObject is the required parameter for the AnalyzeImage API containing all required information to perform a request
- parameter resource: The path or data of the image or
- parameter visualFeatures, details: Read more about those [here](https://dev.projectoxford.ai/docs/services/56f91f2d778daf23d8ec6739/operations/56f91f2e778daf14a499e1fa)
*/
typealias AnalyzeImageRequestObject = (resource: Any, visualFeatures: [AnalyzeImage.AnalyzeImageVisualFeatures])
/**
Analyze Image
This operation extracts a rich set of visual features based on the image content.
- You can try Image Analysation here: https://www.microsoft.com/cognitive-services/en-us/computer-vision-api
*/
class AnalyzeImage: NSObject {
var delegate: AnalyzeImageDelegate?
final class AnalyzeImageObject {
// Categories
var categories: [[String : AnyObject]]?
// Faces
var faces: [FaceObject]? = []
// Metadata
var rawMetaData: [String : AnyObject]?
var imageSize: CGSize?
var imageFormat: String?
// ImageType
var imageType: (clipArtType: Int?, lineDrawingType: Int?)?
// Description
var rawDescription: [String : AnyObject]?
var rawDescriptionCaptions: [String : AnyObject]?
var descriptionText: String?
var descriptionTextConfidence: Float?
var tags: [String]?
// Color
var blackAndWhite: Bool?
var dominantColors: [String]?
var accentColorHex: String?
var dominantForegroundColor: String?
var dominantBackgroundColor: String?
var isAdultContent: Bool?
var adultScore: Float?
var isRacyContent: Bool?
var racyContentScore: Float?
var imageData: Data!
var rawDict: [String : AnyObject]?
var requestID: String?
// Intern Object classes
typealias FaceObject = FaceStruct
struct FaceStruct {
let age: Int?
let gender: String?
let faceRectangle: CGRect?
let emotion: String?
}
}
/// The url to perform the requests on
final let url = "https://api.projectoxford.ai/vision/v1.0/analyze"
/// Your private API key. If you havn't changed it yet, go ahead!
let key = CognitiveServicesApiKeys.ComputerVision.rawValue
enum AnalyzeImageErros: Error {
case error(code: String, message: String)
case invalidImageFormat(message: String)
// Unknown Error
case unknown(message: String)
}
/**
Used as a parameter for `recognizeCharactersOnImageUrl`
Read more about it [here](https://dev.projectoxford.ai/docs/services/56f91f2d778daf23d8ec6739/operations/56f91f2e778daf14a499e1fa)
*/
enum AnalyzeImageVisualFeatures: String {
case None = ""
case Categories = "Categories"
case Tags = "Tags"
case Description = "Description"
case Faces = "Faces"
case ImageType = "ImageType"
case Color = "Color"
case Adult = "Adult"
}
/**
Used as a parameter for `recognizeCharactersOnImageUrl`
Read more about it [here](https://dev.projectoxford.ai/docs/services/56f91f2d778daf23d8ec6739/operations/56f91f2e778daf14a499e1fa)
*/
enum AnalyzeImageDetails: String {
case None = ""
case Description = "Description"
}
final func analyzeImageWithRequestObject(_ requestObject: AnalyzeImageRequestObject, completion: @escaping (_ response: AnalyzeImageObject?) -> Void) throws {
if key == "ComputerVision Key" {
assertionFailure("Enter your ComputerVision API key first")
}
// Query parameters
let visualFeatures = requestObject.visualFeatures
.map {$0.rawValue}
.joined(separator: ",")
let parameters = ["visualFeatures=\(visualFeatures)"].joined(separator: "&")
let requestURL = URL(string: url + "?" + parameters)!
var request = URLRequest(url: requestURL)
request.httpMethod = "POST"
// Request Parameter
if let path = requestObject.resource as? String {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = "{\"url\":\"\(path)\"}".data(using: String.Encoding.utf8)
}
else if let imageData = requestObject.resource as? Data {
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.httpBody = imageData
}
else if let image = requestObject.resource as? UIImage {
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image, 0.7)
request.httpBody = imageData
}
else {
throw AnalyzeImageErros.invalidImageFormat(message: "[Swift SDK] Input data is not a valid image.")
}
let imageData = request.httpBody!
request.setValue(key, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
let started = Date()
let task = URLSession.shared.dataTask(with: request){ data, response, error in
if error != nil{
print("Error -> \(error)")
completion(nil)
return
} else {
let results = try! JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
let analyzeObject = self.objectFromDict(results, data: imageData)
let interval = Date().timeIntervalSince(started)
print(interval)
// Hand dict over
DispatchQueue.main.async {
completion(analyzeObject)
}
}
}
task.resume()
}
private func objectFromDict(_ dict: [String : AnyObject]?, data: Data) -> AnalyzeImageObject {
let analyzeObject = AnalyzeImageObject()
analyzeObject.rawDict = dict
analyzeObject.imageData = data
if let categories = dict?["categories"] as? [[String : AnyObject]] {
analyzeObject.categories = categories
}
var containsFaces = false
if let faces = dict?["faces"] as? [[String : AnyObject]] {
containsFaces = faces.count != 0
if faces.count >= 1 {
analyzeObject.getEmotions({ emotionFaces in
faces.enumerated().forEach({ faceDict in
let emotionFace = emotionFaces![faceDict.offset]
// Analyze Image face
let age = faceDict.element["age"] as? Int
let gender = faceDict.element["gender"] as? String
let emotionFaceRectangle = emotionFace["faceRectangle"] as? [String : CGFloat]
var rect: CGRect? {
if let left = emotionFaceRectangle?["left"],
let top = emotionFaceRectangle?["top"],
let width = emotionFaceRectangle?["width"],
let height = emotionFaceRectangle?["height"] {
return CGRect(x: left, y: top, width: width, height: height)
}
return nil
}
let emotions = emotionFace["scores"] as? [String : AnyObject]
let sortedEmotions = emotions?.sorted { (val1, val2) -> Bool in
return val1.1 as! Float > val2.1 as! Float
}.map {
$0.0
}
print("Sorted emotions: " + sortedEmotions!.description)
let primaryEmotion = sortedEmotions?.first
print("Primary Emotion :" + primaryEmotion!)
let face = AnalyzeImageObject.FaceObject (
age: age,
gender: gender,
faceRectangle: rect,
emotion: primaryEmotion
)
analyzeObject.faces?.append(face)
})
self.delegate?.finnishedGeneratingObject(analyzeObject)
})
}
}
analyzeObject.requestID = dict?["requestId"] as? String
// Medadata values
if let metaData = dict?["metadata"] as? [String : AnyObject] {
analyzeObject.rawMetaData = metaData
if let width = metaData["width"] as? CGFloat,
let height = metaData["height"] as? CGFloat {
analyzeObject.imageSize = CGSize(width: width, height: height)
}
analyzeObject.imageFormat = metaData["format"] as? String
}
if let imageType = dict?["imageType"] as? [String : Int] {
analyzeObject.imageType = (imageType["clipArtType"], imageType["lineDrawingType"])
}
// Description values
if let description = dict?["description"] as? [String : AnyObject] {
analyzeObject.rawDescription = description
analyzeObject.tags = description["tags"] as? [String]
// Captions values
if let captionsRaw = description["captions"] as? NSArray {
let captions = captionsRaw.firstObject as? [String : AnyObject]
analyzeObject.rawDescriptionCaptions = captions
analyzeObject.descriptionText = captions?["text"] as? String
}
}
if let color = dict?["color"] as? [String : AnyObject] {
analyzeObject.blackAndWhite = color["isBWImg"] as? Bool
analyzeObject.dominantForegroundColor = color["dominantColorForeground"] as? String
analyzeObject.dominantBackgroundColor = color["dominantColorBackground"] as? String
analyzeObject.dominantColors = color["dominantColors"] as? [String]
analyzeObject.accentColorHex = color["accentColor"] as? String
}
if containsFaces == false {
delegate?.finnishedGeneratingObject(analyzeObject)
}
return analyzeObject
}
}
extension AnalyzeImage.AnalyzeImageObject {
func getEmotions(_ completion: @escaping (_ response: [[String : AnyObject]]?) -> Void) {
let path = "https://api.projectoxford.ai/emotion/v1.0/recognize"
let requestURL = URL(string: path)!
var request = URLRequest(url: requestURL)
request.httpMethod = "POST"
// Request Parameter
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.httpBody = self.imageData
let key = CognitiveServicesApiKeys.Emotion.rawValue
if key == "Emotion Key" {
assertionFailure("Enter your Emotion API key")
}
request.setValue(key, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
let task = URLSession.shared.dataTask(with: request){ data, response, error in
if error != nil{
print("Error -> \(error)")
completion(nil)
return
} else {
if let results = try! JSONSerialization.jsonObject(with: data!, options: []) as? [[String : AnyObject]] {
// Hand dict over
DispatchQueue.main.async {
completion(results)
}
}
else {
print((try! JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]) ?? "Something went wrong with the Emotion API")
}
}
}
task.resume()
}
}
extension AnalyzeImage.AnalyzeImageObject {
class func createTestFace() -> FaceObject {
let emotions = ["Neutral", "Happy", "Bored", "Excited"]
let face = FaceObject(
age: Int(arc4random_uniform(60)),
gender: "Male",
faceRectangle: CGRect(x: 0, y: 0, width: 400, height: 400),
emotion: emotions[Int(arc4random_uniform(UInt32(emotions.count - 1)))]
)
return face
}
}
| 5096b64ecb77466c41f3f5b1d1e87e03 | 34.546135 | 191 | 0.554511 | false | false | false | false |
mohitathwani/swift-corelibs-foundation | refs/heads/master | Foundation/Locale.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
//
//===----------------------------------------------------------------------===//
import CoreFoundation
internal func __NSLocaleIsAutoupdating(_ locale: NSLocale) -> Bool {
return false // Auto-updating is only on Darwin
}
internal func __NSLocaleCurrent() -> NSLocale {
return CFLocaleCopyCurrent()._nsObject
}
/**
`Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted.
Locales are typically used to provide, format, and interpret information about and according to the user’s customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user.
*/
public struct Locale : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable, ReferenceConvertible {
public typealias ReferenceType = NSLocale
public typealias LanguageDirection = NSLocale.LanguageDirection
internal var _wrapped : NSLocale
internal var _autoupdating : Bool
/// Returns the user's current locale.
public static var current : Locale {
return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: false)
}
/// Returns a locale which tracks the user's current preferences.
///
/// If mutated, this Locale will no longer track the user's preferences.
///
/// - note: The autoupdating Locale will only compare equal to another autoupdating Locale.
public static var autoupdatingCurrent : Locale {
// swift-corelibs-foundation does not yet support autoupdating, but we can return the current locale (which will not change).
return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: true)
}
@available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case")
public static var system : Locale { fatalError() }
// MARK: -
//
/// Return a locale with the specified identifier.
public init(identifier: String) {
_wrapped = NSLocale(localeIdentifier: identifier)
_autoupdating = false
}
internal init(reference: NSLocale) {
_wrapped = reference.copy() as! NSLocale
if __NSLocaleIsAutoupdating(reference) {
_autoupdating = true
} else {
_autoupdating = false
}
}
private init(adoptingReference reference: NSLocale, autoupdating: Bool) {
_wrapped = reference
_autoupdating = autoupdating
}
// MARK: -
//
/// Returns a localized string for a specified identifier.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forIdentifier identifier: String) -> String? {
return _wrapped.displayName(forKey: .identifier, value: identifier)
}
/// Returns a localized string for a specified language code.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forLanguageCode languageCode: String) -> String? {
return _wrapped.displayName(forKey: .languageCode, value: languageCode)
}
/// Returns a localized string for a specified region code.
///
/// For example, in the "en" locale, the result for `"fr"` is `"France"`.
public func localizedString(forRegionCode regionCode: String) -> String? {
return _wrapped.displayName(forKey: .countryCode, value: regionCode)
}
/// Returns a localized string for a specified script code.
///
/// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`.
public func localizedString(forScriptCode scriptCode: String) -> String? {
return _wrapped.displayName(forKey: .scriptCode, value: scriptCode)
}
/// Returns a localized string for a specified variant code.
///
/// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`.
public func localizedString(forVariantCode variantCode: String) -> String? {
return _wrapped.displayName(forKey: .variantCode, value: variantCode)
}
/// Returns a localized string for a specified `Calendar.Identifier`.
///
/// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`.
public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? {
// NSLocale doesn't export a constant for this
let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), kCFLocaleCalendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue._cfObject)._swiftObject
return result
}
/// Returns a localized string for a specified ISO 4217 currency code.
///
/// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`.
/// - seealso: `Locale.isoCurrencyCodes`
public func localizedString(forCurrencyCode currencyCode: String) -> String? {
return _wrapped.displayName(forKey: .currencyCode, value: currencyCode)
}
/// Returns a localized string for a specified ICU collation identifier.
///
/// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`.
public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier)
}
/// Returns a localized string for a specified ICU collator identifier.
public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier)
}
// MARK: -
//
/// Returns the identifier of the locale.
public var identifier: String {
return _wrapped.localeIdentifier
}
/// Returns the language code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "zh".
public var languageCode: String? {
return _wrapped.object(forKey: .languageCode) as? String
}
/// Returns the region code of the locale, or nil if it has none.
///
/// For example, for the locale "zh-Hant-HK", returns "HK".
public var regionCode: String? {
// n.b. this is called countryCode in ObjC
if let result = _wrapped.object(forKey: .countryCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the script code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "Hant".
public var scriptCode: String? {
return _wrapped.object(forKey: .scriptCode) as? String
}
/// Returns the variant code for the locale, or nil if it has none.
///
/// For example, for the locale "en_POSIX", returns "POSIX".
public var variantCode: String? {
if let result = _wrapped.object(forKey: .variantCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the exemplar character set for the locale, or nil if has none.
public var exemplarCharacterSet: CharacterSet? {
return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet
}
/// Returns the calendar for the locale, or the Gregorian calendar as a fallback.
public var calendar: Calendar {
// NSLocale should not return nil here
if let result = _wrapped.object(forKey: .calendar) as? Calendar {
return result
} else {
return Calendar(identifier: .gregorian)
}
}
/// Returns the collation identifier for the locale, or nil if it has none.
///
/// For example, for the locale "en_US@collation=phonebook", returns "phonebook".
public var collationIdentifier: String? {
return _wrapped.object(forKey: .collationIdentifier) as? String
}
/// Returns true if the locale uses the metric system.
///
/// -seealso: MeasurementFormatter
public var usesMetricSystem: Bool {
// NSLocale should not return nil here, but just in case
if let result = (_wrapped.object(forKey: .usesMetricSystem) as? NSNumber)?.boolValue {
return result
} else {
return false
}
}
/// Returns the decimal separator of the locale.
///
/// For example, for "en_US", returns ".".
public var decimalSeparator: String? {
return _wrapped.object(forKey: .decimalSeparator) as? String
}
/// Returns the grouping separator of the locale.
///
/// For example, for "en_US", returns ",".
public var groupingSeparator: String? {
return _wrapped.object(forKey: .groupingSeparator) as? String
}
/// Returns the currency symbol of the locale.
///
/// For example, for "zh-Hant-HK", returns "HK$".
public var currencySymbol: String? {
return _wrapped.object(forKey: .currencySymbol) as? String
}
/// Returns the currency code of the locale.
///
/// For example, for "zh-Hant-HK", returns "HKD".
public var currencyCode: String? {
return _wrapped.object(forKey: .currencyCode) as? String
}
/// Returns the collator identifier of the locale.
public var collatorIdentifier: String? {
return _wrapped.object(forKey: .collatorIdentifier) as? String
}
/// Returns the quotation begin delimiter of the locale.
///
/// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK".
public var quotationBeginDelimiter: String? {
return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String
}
/// Returns the quotation end delimiter of the locale.
///
/// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK".
public var quotationEndDelimiter: String? {
return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String
}
/// Returns the alternate quotation begin delimiter of the locale.
///
/// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK".
public var alternateQuotationBeginDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String
}
/// Returns the alternate quotation end delimiter of the locale.
///
/// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK".
public var alternateQuotationEndDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String
}
// MARK: -
//
/// Returns a list of available `Locale` identifiers.
public static var availableIdentifiers: [String] {
return NSLocale.availableLocaleIdentifiers
}
/// Returns a list of available `Locale` language codes.
public static var isoLanguageCodes: [String] {
return NSLocale.isoLanguageCodes
}
/// Returns a list of available `Locale` region codes.
public static var isoRegionCodes: [String] {
// This was renamed from Obj-C
return NSLocale.isoCountryCodes
}
/// Returns a list of available `Locale` currency codes.
public static var isoCurrencyCodes: [String] {
return NSLocale.isoCurrencyCodes
}
/// Returns a list of common `Locale` currency codes.
public static var commonISOCurrencyCodes: [String] {
return NSLocale.commonISOCurrencyCodes
}
/// Returns a list of the user's preferred languages.
///
/// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports.
/// - seealso: `Bundle.preferredLocalizations(from:)`
/// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)`
public static var preferredLanguages: [String] {
return NSLocale.preferredLanguages
}
/// Returns a dictionary that splits an identifier into its component pieces.
public static func components(fromIdentifier string: String) -> [String : String] {
return NSLocale.components(fromLocaleIdentifier: string)
}
/// Constructs an identifier from a dictionary of components.
public static func identifier(fromComponents components: [String : String]) -> String {
return NSLocale.localeIdentifier(fromComponents: components)
}
/// Returns a canonical identifier from the given string.
public static func canonicalIdentifier(from string: String) -> String {
return NSLocale.canonicalLocaleIdentifier(from: string)
}
/// Returns a canonical language identifier from the given string.
public static func canonicalLanguageIdentifier(from string: String) -> String {
return NSLocale.canonicalLanguageIdentifier(from: string)
}
/// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted.
public static func identifier(fromWindowsLocaleCode code: Int) -> String? {
return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code))
}
/// Returns the Windows locale code from a given identifier, or nil if it could not be converted.
public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? {
let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier)
if result == 0 {
return nil
} else {
return Int(result)
}
}
/// Returns the character direction for a specified language code.
public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.characterDirection(forLanguage: isoLangCode)
}
/// Returns the line direction for a specified language code.
public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.lineDirection(forLanguage: isoLangCode)
}
// MARK: -
@available(*, unavailable, renamed: "init(identifier:)")
public init(localeIdentifier: String) { fatalError() }
@available(*, unavailable, renamed: "identifier")
public var localeIdentifier: String { fatalError() }
@available(*, unavailable, renamed: "localizedString(forIdentifier:)")
public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() }
@available(*, unavailable, renamed: "availableIdentifiers")
public static var availableLocaleIdentifiers: [String] { fatalError() }
@available(*, unavailable, renamed: "components(fromIdentifier:)")
public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() }
@available(*, unavailable, renamed: "identifier(fromComponents:)")
public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() }
@available(*, unavailable, renamed: "canonicalIdentifier(from:)")
public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() }
@available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)")
public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() }
@available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)")
public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() }
@available(*, unavailable, message: "use regionCode instead")
public var countryCode: String { fatalError() }
@available(*, unavailable, message: "use localizedString(forRegionCode:) instead")
public func localizedString(forCountryCode countryCode: String) -> String { fatalError() }
@available(*, unavailable, renamed: "isoRegionCodes")
public static var isoCountryCodes: [String] { fatalError() }
// MARK: -
//
public var description: String {
return _wrapped.description
}
public var debugDescription : String {
return _wrapped.debugDescription
}
public var hashValue : Int {
if _autoupdating {
return 1
} else {
return _wrapped.hash
}
}
public static func ==(lhs: Locale, rhs: Locale) -> Bool {
if lhs._autoupdating || rhs._autoupdating {
return lhs._autoupdating == rhs._autoupdating
} else {
return lhs._wrapped.isEqual(rhs._wrapped)
}
}
}
extension Locale : _ObjectTypeBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSLocale {
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) {
if !_conditionallyBridgeFromObjectiveC(input, result: &result) {
fatalError("Unable to bridge \(NSLocale.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool {
result = Locale(reference: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale {
var result: Locale? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
| 50e5208404609b324a1c93d20aa838dd | 38.598291 | 282 | 0.655569 | false | false | false | false |
pabloepi/MZDiagnoser | refs/heads/master | MZDiagnoser/MZDiagnoserController.swift | mit | 1 | //
// MZDiagnoser.swift
// ToddDiagnoser
//
// Created by Pablo on 9/18/16.
// Copyright © 2016 Mozio. All rights reserved.
//
class MZDiagnoserController: NSObject {
class func generateDiagnosis(fromQuestions questions: Array<MZQuestion>,
positiveAnswers positives: Array<MZQuestion>,
negativeAnswers negative: Array<MZQuestion>) throws -> MZResult {
if questions.count != positives.count + negative.count {
throw NSError.generateError("All questions must be answered")
}
var percentage = 0
for question_MZ in positives { percentage += Int(question_MZ.weight) }
return MZResult(percentage: percentage)
}
}
extension NSError {
private static let domain = "com.mozio.todd"
class func generateError(message: String) -> NSError {
let userInfo = [NSLocalizedDescriptionKey: message]
return NSError(domain: domain,
code: 9999,
userInfo: userInfo)
}
}
| 56b1367a88248561539a0dfe40596a8d | 28 | 128 | 0.54836 | false | false | false | false |
Arcovv/CleanArchitectureRxSwift | refs/heads/master | Domain/Entries/Album.swift | mit | 1 | //
// Album.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 10.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import Foundation
public struct Album {
public let title: String
public let uid: String
public let userId: String
public init(title: String,
uid: String,
userId: String) {
self.title = title
self.uid = uid
self.userId = userId
}
}
extension Album: Equatable {
public static func == (lhs: Album, rhs: Album) -> Bool {
return lhs.uid == rhs.uid &&
lhs.title == rhs.title &&
lhs.userId == rhs.userId
}
}
| fb8c541eb32a802b911b2973ff4cb0ff | 20.677419 | 60 | 0.578869 | false | false | false | false |
Kuruchy/ios_mememe | refs/heads/master | MemeMe/MemeMeTableViewController.swift | apache-2.0 | 1 | //
// MemeMeTableViewController.swift
// MemeMe
//
// Created by Bruno Retolaza on 12.10.17.
// Copyright © 2017 Bruno Retolaza. All rights reserved.
//
import UIKit
// MARK: Table View Controller
class MemeMeTableViewController: UIViewController, UITableViewDataSource {
var memes: [Meme]!
@IBOutlet var memeTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
memeTableView.dataSource = self
memeTableView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
memes = appDelegate.memes
memeTableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return memes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MemeMeTableViewCell") as! MemeMeTableViewCell
let meme = memes[indexPath.row]
// Set the name and image of the cell with the meme atributes
cell.setupCellWith(meme)
return cell
}
}
// MARK: Table View Delegate
extension MemeMeTableViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailController = self.storyboard!.instantiateViewController(withIdentifier: "MemeMeDetailViewController") as! MemeMeDetailViewController
detailController.meme = memes[(indexPath as NSIndexPath).row]
self.navigationController!.pushViewController(detailController, animated: true)
}
}
| c3c7b04974b55573060f542f4085c237 | 31 | 150 | 0.691598 | false | false | false | false |
swifteiro/NeonTransfer | refs/heads/master | Pods/JSONHelper/JSONHelper/Extensions/NSDecimalNumber.swift | mit | 1 | //
// Copyright © 2016 Baris Sencan. All rights reserved.
//
import Foundation
extension NSDecimalNumber: Convertible {
public static func convertFromValue<T>(value: T?) throws -> Self? {
guard let value = value else { return nil }
if let doubleValue = value as? Double {
return self.init(double: doubleValue)
} else if let stringValue = value as? String {
return self.init(string: stringValue)
} else if let floatValue = value as? Float {
return self.init(float: floatValue)
} else if let intValue = value as? Int {
return self.init(integer: intValue)
}
throw ConversionError.UnsupportedType
}
}
| 33bee3b0d48293bcd366d06813c15b55 | 26.458333 | 69 | 0.6783 | false | false | false | false |
gmilos/swift | refs/heads/master | stdlib/private/StdlibUnittest/StdlibCoreExtras.swift | apache-2.0 | 2 | //===--- StdlibCoreExtras.swift -------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftPrivate
import SwiftPrivateLibcExtras
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
#if _runtime(_ObjC)
import Foundation
#endif
//
// These APIs don't really belong in a unit testing library, but they are
// useful in tests, and stdlib does not have such facilities yet.
//
func findSubstring(_ string: String, _ substring: String) -> String.Index? {
if substring.isEmpty {
return string.startIndex
}
#if _runtime(_ObjC)
return string.range(of: substring)?.lowerBound
#else
// FIXME(performance): This is a very non-optimal algorithm, with a worst
// case of O((n-m)*m). When non-objc String has a match function that's better,
// this should be removed in favor of using that.
// Operate on unicode scalars rather than codeunits.
let haystack = string.unicodeScalars
let needle = substring.unicodeScalars
for matchStartIndex in haystack.indices {
var matchIndex = matchStartIndex
var needleIndex = needle.startIndex
while true {
if needleIndex == needle.endIndex {
// if we hit the end of the search string, we found the needle
return matchStartIndex.samePosition(in: string)
}
if matchIndex == haystack.endIndex {
// if we hit the end of the string before finding the end of the needle,
// we aren't going to find the needle after that.
return nil
}
if needle[needleIndex] == haystack[matchIndex] {
// keep advancing through both the string and search string on match
matchIndex = haystack.index(after: matchIndex)
needleIndex = haystack.index(after: needleIndex)
} else {
// no match, go back to finding a starting match in the string.
break
}
}
}
return nil
#endif
}
public func createTemporaryFile(
_ fileNamePrefix: String, _ fileNameSuffix: String, _ contents: String
) -> String {
#if _runtime(_ObjC)
let tempDir: NSString = NSTemporaryDirectory() as NSString
var fileName = tempDir.appendingPathComponent(
fileNamePrefix + "XXXXXX" + fileNameSuffix)
#else
var fileName = fileNamePrefix + "XXXXXX" + fileNameSuffix
#endif
let fd = _stdlib_mkstemps(
&fileName, CInt(fileNameSuffix.utf8.count))
if fd < 0 {
fatalError("mkstemps() returned an error")
}
var stream = _FDOutputStream(fd: fd)
stream.write(contents)
if close(fd) != 0 {
fatalError("close() return an error")
}
return fileName
}
public final class Box<T> {
public init(_ value: T) { self.value = value }
public var value: T
}
infix operator <=>
public func <=> <T: Comparable>(lhs: T, rhs: T) -> ExpectedComparisonResult {
return lhs < rhs
? .lt
: lhs > rhs ? .gt : .eq
}
public struct TypeIdentifier : Hashable, Comparable {
public init(_ value: Any.Type) {
self.value = value
}
public var hashValue: Int { return objectID.hashValue }
public var value: Any.Type
internal var objectID : ObjectIdentifier { return ObjectIdentifier(value) }
}
public func < (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool {
return lhs.objectID < rhs.objectID
}
public func == (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool {
return lhs.objectID == rhs.objectID
}
extension TypeIdentifier
: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return String(describing: value)
}
public var debugDescription: String {
return "TypeIdentifier(\(description))"
}
}
enum FormNextPermutationResult {
case success
case formedFirstPermutation
}
extension MutableCollection
where
Self : BidirectionalCollection,
Iterator.Element : Comparable
{
mutating func _reverseSubrange(_ subrange: Range<Index>) {
if subrange.isEmpty { return }
var f = subrange.lowerBound
var l = index(before: subrange.upperBound)
while f < l {
swap(&self[f], &self[l])
formIndex(after: &f)
formIndex(before: &l)
}
}
mutating func formNextPermutation() -> FormNextPermutationResult {
if isEmpty {
// There are 0 elements, only one permutation is possible.
return .formedFirstPermutation
}
do {
var i = startIndex
formIndex(after: &i)
if i == endIndex {
// There is only element, only one permutation is possible.
return .formedFirstPermutation
}
}
var i = endIndex
formIndex(before: &i)
var beforeI = i
formIndex(before: &beforeI)
var elementAtI = self[i]
var elementAtBeforeI = self[beforeI]
while true {
if elementAtBeforeI < elementAtI {
// Elements at `i..<endIndex` are in non-increasing order. To form the
// next permutation in lexicographical order we need to replace
// `self[i-1]` with the next larger element found in the tail, and
// reverse the tail. For example:
//
// i-1 i endIndex
// V V V
// 6 2 8 7 4 1 [ ] // Input.
// 6 (4) 8 7 (2) 1 [ ] // Exchanged self[i-1] with the
// ^--------^ // next larger element
// // from the tail.
// 6 4 (1)(2)(7)(8)[ ] // Reversed the tail.
// <-------->
var j = endIndex
repeat {
formIndex(before: &j)
} while !(elementAtBeforeI < self[j])
swap(&self[beforeI], &self[j])
_reverseSubrange(i..<endIndex)
return .success
}
if beforeI == startIndex {
// All elements are in non-increasing order. Reverse to form the first
// permutation, where all elements are sorted (in non-increasing order).
reverse()
return .formedFirstPermutation
}
i = beforeI
formIndex(before: &beforeI)
elementAtI = elementAtBeforeI
elementAtBeforeI = self[beforeI]
}
}
}
/// Generate all permutations.
public func forAllPermutations(_ size: Int, _ body: ([Int]) -> Void) {
var data = Array(0..<size)
repeat {
body(data)
} while data.formNextPermutation() != .formedFirstPermutation
}
/// Generate all permutations.
public func forAllPermutations<S : Sequence>(
_ sequence: S, _ body: ([S.Iterator.Element]) -> Void
) {
let data = Array(sequence)
forAllPermutations(data.count) {
(indices: [Int]) in
body(indices.map { data[$0] })
return ()
}
}
public func cartesianProduct<C1 : Collection, C2 : Collection>(
_ c1: C1, _ c2: C2
) -> [(C1.Iterator.Element, C2.Iterator.Element)] {
var result: [(C1.Iterator.Element, C2.Iterator.Element)] = []
for e1 in c1 {
for e2 in c2 {
result.append((e1, e2))
}
}
return result
}
| 25ee74de057fe1c88075a5eb9b4ca281 | 28.311741 | 81 | 0.632459 | false | false | false | false |
klemenkosir/SwiftExtensions | refs/heads/master | SwiftExtensions/SwiftExtensions/UIAlertControllerExtension.swift | mit | 1 | //
// UIAlertControllerExtension.swift
//
//
// Created by Klemen Kosir on 27/04/16.
// Copyright © 2016 Klemen Košir. All rights reserved.
//
import UIKit
private var alertWindowKey: UInt8 = 0
public extension UIAlertController {
private var alertWindow: UIWindow {
get {
return objc_getAssociatedObject(self, &alertWindowKey) as! UIWindow
}
set {
objc_setAssociatedObject(self, &alertWindowKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
static func showBasicPopup(_ title: String?, message: String?, autoDismiss: Bool, onViewController vc: UIViewController? = nil) {
guard let vc = vc else { return }
let popup = UIAlertController(title: title, message: message, preferredStyle: .alert)
if autoDismiss {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1*NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
popup.dismiss(animated: true, completion: nil)
})
}
else {
popup.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
}
if UIDevice.current.userInterfaceIdiom == .pad {
popup.popoverPresentationController?.sourceView = vc.view
popup.popoverPresentationController?.sourceRect = vc.view.bounds
}
vc.present(popup, animated: true, completion: nil)
}
static func showInfoPopup(_ title: String?, message: String?, autoDismiss: Bool, onViewController vc: UIViewController? = nil) -> UIAlertController? {
guard let vc = vc else { return nil }
let popup = UIAlertController(title: title, message: message, preferredStyle: .alert)
if autoDismiss {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1*NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
popup.dismiss(animated: true, completion: nil)
})
}
else {
popup.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
}
if UIDevice.current.userInterfaceIdiom == .pad {
popup.popoverPresentationController?.sourceView = vc.view
popup.popoverPresentationController?.sourceRect = vc.view.bounds
}
vc.present(popup, animated: true, completion: nil)
return popup
}
func show(_ animated: Bool = true, completion: (() -> Void)? = nil) {
alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.backgroundColor = .clear
alertWindow.windowLevel = UIWindowLevelAlert
let rootVC = UIViewController()
alertWindow.rootViewController = rootVC
alertWindow.makeKeyAndVisible()
rootVC.present(self, animated: animated, completion: completion)
}
func hide(_ animated: Bool = true) {
self.dismiss(animated: animated, completion: nil)
}
}
| caba649a5a0d18a229d95043211c2b31 | 33.210526 | 151 | 0.725769 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io | refs/heads/master | InfiniteScroll/InfiniteScroll/Animations/GSImageViewerController.swift | apache-2.0 | 1 | //
// GSImageViewerController.swift
// InfiniteScroll
//
// Created by Anirudh Das on 7/6/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import UIKit
/**
Scales up the image on tap, and scales back to original size on tap again.
*/
public struct GSImageInfo {
public enum ImageMode : Int {
case aspectFit = 1
case aspectFill = 2
}
public let image : UIImage
public let imageMode : ImageMode
public var imageHD : URL?
public var contentMode : UIViewContentMode {
return UIViewContentMode(rawValue: imageMode.rawValue)!
}
public init(image: UIImage, imageMode: ImageMode) {
self.image = image
self.imageMode = imageMode
}
public init(image: UIImage, imageMode: ImageMode, imageHD: URL?) {
self.init(image: image, imageMode: imageMode)
self.imageHD = imageHD
}
func calculateRect(_ size: CGSize) -> CGRect {
let widthRatio = size.width / image.size.width
let heightRatio = size.height / image.size.height
switch imageMode {
case .aspectFit:
return CGRect(origin: CGPoint.zero, size: size)
case .aspectFill:
return CGRect(
x : 0,
y : 0,
width : image.size.width * max(widthRatio, heightRatio),
height : image.size.height * max(widthRatio, heightRatio)
)
}
}
func calculateMaximumZoomScale(_ size: CGSize) -> CGFloat {
return max(2, max(
image.size.width / size.width,
image.size.height / size.height
))
}
}
open class GSTransitionInfo {
open var duration: TimeInterval = 0.35
open var canSwipe: Bool = true
public init(fromView: UIView) {
self.fromView = fromView
}
weak var fromView : UIView?
fileprivate var convertedRect : CGRect?
}
open class GSImageViewerController: UIViewController {
open let imageInfo : GSImageInfo
open var transitionInfo : GSTransitionInfo?
fileprivate let imageView = UIImageView()
fileprivate let scrollView = UIScrollView()
fileprivate lazy var session: URLSession = {
let configuration = URLSessionConfiguration.ephemeral
return URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
}()
// MARK: Initialization
public init(imageInfo: GSImageInfo) {
self.imageInfo = imageInfo
super.init(nibName: nil, bundle: nil)
}
public convenience init(imageInfo: GSImageInfo, transitionInfo: GSTransitionInfo) {
self.init(imageInfo: imageInfo)
self.transitionInfo = transitionInfo
if let fromView = transitionInfo.fromView, let referenceView = fromView.superview {
self.transitioningDelegate = self
self.modalPresentationStyle = .custom
transitionInfo.convertedRect = referenceView.convert(fromView.frame, to: nil)
}
}
public convenience init(image: UIImage, imageMode: UIViewContentMode, imageHD: URL?, fromView: UIView?) {
let imageInfo = GSImageInfo(image: image, imageMode: GSImageInfo.ImageMode(rawValue: imageMode.rawValue)!, imageHD: imageHD)
if let fromView = fromView {
self.init(imageInfo: imageInfo, transitionInfo: GSTransitionInfo(fromView: fromView))
} else {
self.init(imageInfo: imageInfo)
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Override
override open func viewDidLoad() {
super.viewDidLoad()
setupView()
setupScrollView()
setupImageView()
setupGesture()
setupImageHD()
edgesForExtendedLayout = UIRectEdge()
scrollView.contentInsetAdjustmentBehavior = .automatic //automaticallyAdjustsScrollViewInsets = false
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
imageView.frame = imageInfo.calculateRect(view.bounds.size)
scrollView.frame = view.bounds
scrollView.contentSize = imageView.bounds.size
scrollView.maximumZoomScale = imageInfo.calculateMaximumZoomScale(scrollView.bounds.size)
}
// MARK: Setups
fileprivate func setupView() {
view.backgroundColor = UIColor.black
}
fileprivate func setupScrollView() {
scrollView.delegate = self
scrollView.minimumZoomScale = 1.0
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
view.addSubview(scrollView)
}
fileprivate func setupImageView() {
imageView.image = imageInfo.image
imageView.contentMode = .scaleAspectFit
scrollView.addSubview(imageView)
}
fileprivate func setupGesture() {
let single = UITapGestureRecognizer(target: self, action: #selector(singleTap))
let double = UITapGestureRecognizer(target: self, action: #selector(doubleTap(_:)))
double.numberOfTapsRequired = 2
single.require(toFail: double)
scrollView.addGestureRecognizer(single)
scrollView.addGestureRecognizer(double)
if transitionInfo?.canSwipe == true {
let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(_:)))
pan.delegate = self
scrollView.addGestureRecognizer(pan)
}
}
fileprivate func setupImageHD() {
guard let imageHD = imageInfo.imageHD else { return }
let request = URLRequest(url: imageHD, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
guard let data = data else { return }
guard let image = UIImage(data: data) else { return }
self.imageView.image = image
self.view.layoutIfNeeded()
})
task.resume()
}
// MARK: Gesture
@objc fileprivate func singleTap() {
if navigationController == nil || (presentingViewController != nil && navigationController!.viewControllers.count <= 1) {
dismiss(animated: true, completion: nil)
}
}
@objc fileprivate func doubleTap(_ gesture: UITapGestureRecognizer) {
let point = gesture.location(in: scrollView)
if scrollView.zoomScale == 1.0 {
scrollView.zoom(to: CGRect(x: point.x-40, y: point.y-40, width: 80, height: 80), animated: true)
} else {
scrollView.setZoomScale(1.0, animated: true)
}
}
fileprivate var panViewOrigin : CGPoint?
fileprivate var panViewAlpha : CGFloat = 1
@objc fileprivate func pan(_ gesture: UIPanGestureRecognizer) {
func getProgress() -> CGFloat {
let origin = panViewOrigin!
let changeX = abs(scrollView.center.x - origin.x)
let changeY = abs(scrollView.center.y - origin.y)
let progressX = changeX / view.bounds.width
let progressY = changeY / view.bounds.height
return max(progressX, progressY)
}
func getChanged() -> CGPoint {
let origin = scrollView.center
let change = gesture.translation(in: view)
return CGPoint(x: origin.x + change.x, y: origin.y + change.y)
}
func getVelocity() -> CGFloat {
let vel = gesture.velocity(in: scrollView)
return sqrt(vel.x*vel.x + vel.y*vel.y)
}
switch gesture.state {
case .began:
panViewOrigin = scrollView.center
case .changed:
scrollView.center = getChanged()
panViewAlpha = 1 - getProgress()
view.backgroundColor = UIColor(white: 0.0, alpha: panViewAlpha)
gesture.setTranslation(CGPoint.zero, in: nil)
case .ended:
if getProgress() > 0.25 || getVelocity() > 1000 {
dismiss(animated: true, completion: nil)
} else {
fallthrough
}
default:
UIView.animate(withDuration: 0.3,
animations: {
self.scrollView.center = self.panViewOrigin!
self.view.backgroundColor = UIColor(white: 0.0, alpha: 1.0)
},
completion: { _ in
self.panViewOrigin = nil
self.panViewAlpha = 1.0
}
)
}
}
}
extension GSImageViewerController: UIScrollViewDelegate {
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
imageView.frame = imageInfo.calculateRect(scrollView.contentSize)
}
}
extension GSImageViewerController: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return GSImageViewerTransition(imageInfo: imageInfo, transitionInfo: transitionInfo!, transitionMode: .present)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return GSImageViewerTransition(imageInfo: imageInfo, transitionInfo: transitionInfo!, transitionMode: .dismiss)
}
}
class GSImageViewerTransition: NSObject, UIViewControllerAnimatedTransitioning {
let imageInfo : GSImageInfo
let transitionInfo : GSTransitionInfo
var transitionMode : TransitionMode
enum TransitionMode {
case present
case dismiss
}
init(imageInfo: GSImageInfo, transitionInfo: GSTransitionInfo, transitionMode: TransitionMode) {
self.imageInfo = imageInfo
self.transitionInfo = transitionInfo
self.transitionMode = transitionMode
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return transitionInfo.duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let tempMask = UIView()
tempMask.backgroundColor = UIColor.black
let tempImage = UIImageView(image: imageInfo.image)
tempImage.layer.cornerRadius = transitionInfo.fromView!.layer.cornerRadius
tempImage.layer.masksToBounds = true
tempImage.contentMode = imageInfo.contentMode
containerView.addSubview(tempMask)
containerView.addSubview(tempImage)
if transitionMode == .present {
transitionInfo.fromView!.alpha = 0
let imageViewer = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! GSImageViewerController
imageViewer.view.layoutIfNeeded()
tempMask.alpha = 0
tempMask.frame = imageViewer.view.bounds
tempImage.frame = transitionInfo.convertedRect!
UIView.animate(withDuration: transitionInfo.duration,
animations: {
tempMask.alpha = 1
tempImage.frame = imageViewer.imageView.frame
},
completion: { _ in
tempMask.removeFromSuperview()
tempImage.removeFromSuperview()
containerView.addSubview(imageViewer.view)
transitionContext.completeTransition(true)
}
)
}
if transitionMode == .dismiss {
let imageViewer = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! GSImageViewerController
imageViewer.view.removeFromSuperview()
tempMask.alpha = imageViewer.panViewAlpha
tempMask.frame = imageViewer.view.bounds
tempImage.frame = imageViewer.scrollView.frame
UIView.animate(withDuration: transitionInfo.duration,
animations: {
tempMask.alpha = 0
tempImage.frame = self.transitionInfo.convertedRect!
},
completion: { _ in
tempMask.removeFromSuperview()
imageViewer.view.removeFromSuperview()
self.transitionInfo.fromView!.alpha = 1
transitionContext.completeTransition(true)
}
)
}
}
}
extension GSImageViewerController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let pan = gestureRecognizer as? UIPanGestureRecognizer {
if scrollView.zoomScale != 1.0 {
return false
}
if imageInfo.imageMode == .aspectFill && (scrollView.contentOffset.x > 0 || pan.translation(in: view).x <= 0) {
return false
}
}
return true
}
}
| 095598546db23fdbac02940ab8e93deb | 32.87561 | 177 | 0.603931 | false | false | false | false |
ncalexan/firefox-ios | refs/heads/master | Extensions/Today/TodayViewController.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 NotificationCenter
import Shared
import SnapKit
import XCGLogger
private let log = Logger.browserLogger
struct TodayStrings {
static let NewPrivateTabButtonLabel = NSLocalizedString("TodayWidget.NewPrivateTabButtonLabel", tableName: "Today", value: "New Private Tab", comment: "New Private Tab button label")
static let NewTabButtonLabel = NSLocalizedString("TodayWidget.NewTabButtonLabel", tableName: "Today", value: "New Tab", comment: "New Tab button label")
static let GoToCopiedLinkLabel = NSLocalizedString("TodayWidget.GoToCopiedLinkLabel", tableName: "Today", value: "Go to copied link", comment: "Go to link on clipboard")
}
struct TodayUX {
static let privateBrowsingColor = UIColor(rgb: 0xCE6EFC)
static let backgroundHightlightColor = UIColor(white: 216.0/255.0, alpha: 44.0/255.0)
static let linkTextSize: CGFloat = 10.0
static let labelTextSize: CGFloat = 14.0
static let imageButtonTextSize: CGFloat = 14.0
static let copyLinkImageWidth: CGFloat = 23
static let margin: CGFloat = 8
static let buttonsHorizontalMarginPercentage: CGFloat = 0.1
static let iOS9LeftMargin: CGFloat = 40
}
@objc (TodayViewController)
class TodayViewController: UIViewController, NCWidgetProviding {
fileprivate lazy var newTabButton: ImageButtonWithLabel = {
let imageButton = ImageButtonWithLabel()
imageButton.addTarget(self, action: #selector(onPressNewTab), forControlEvents: .touchUpInside)
imageButton.label.text = TodayStrings.NewTabButtonLabel
let button = imageButton.button
button.setImage(UIImage(named: "new_tab_button_normal")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.setImage(UIImage(named: "new_tab_button_highlight")?.withRenderingMode(.alwaysTemplate), for: .highlighted)
let label = imageButton.label
label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize)
imageButton.sizeToFit()
return imageButton
}()
fileprivate lazy var newPrivateTabButton: ImageButtonWithLabel = {
let imageButton = ImageButtonWithLabel()
imageButton.addTarget(self, action: #selector(onPressNewPrivateTab), forControlEvents: .touchUpInside)
imageButton.label.text = TodayStrings.NewPrivateTabButtonLabel
let button = imageButton.button
button.setImage(UIImage(named: "new_private_tab_button_normal"), for: .normal)
button.setImage(UIImage(named: "new_private_tab_button_highlight"), for: .highlighted)
let label = imageButton.label
label.tintColor = TodayUX.privateBrowsingColor
label.textColor = TodayUX.privateBrowsingColor
label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize)
imageButton.sizeToFit()
return imageButton
}()
fileprivate lazy var openCopiedLinkButton: ButtonWithSublabel = {
let button = ButtonWithSublabel()
button.setTitle(TodayStrings.GoToCopiedLinkLabel, for: .normal)
button.addTarget(self, action: #selector(onPressOpenClibpoard), for: .touchUpInside)
// We need to set the background image/color for .Normal, so the whole button is tappable.
button.setBackgroundColor(UIColor.clear, forState: .normal)
button.setBackgroundColor(TodayUX.backgroundHightlightColor, forState: .highlighted)
button.setImage(UIImage(named: "copy_link_icon")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.label.font = UIFont.systemFont(ofSize: TodayUX.labelTextSize)
button.subtitleLabel.font = UIFont.systemFont(ofSize: TodayUX.linkTextSize)
return button
}()
fileprivate lazy var widgetStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = TodayUX.margin / 2
stackView.distribution = UIStackViewDistribution.fill
stackView.layoutMargins = UIEdgeInsets(top: TodayUX.margin, left: TodayUX.margin, bottom: TodayUX.margin, right: TodayUX.margin)
stackView.isLayoutMarginsRelativeArrangement = true
return stackView
}()
fileprivate lazy var buttonStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.spacing = 0
stackView.distribution = UIStackViewDistribution.fillEqually
let edge = self.view.frame.size.width * TodayUX.buttonsHorizontalMarginPercentage
stackView.layoutMargins = UIEdgeInsets(top: 0, left: edge, bottom: 0, right: edge)
stackView.isLayoutMarginsRelativeArrangement = true
return stackView
}()
fileprivate var scheme: String {
guard let string = Bundle.main.object(forInfoDictionaryKey: "MozInternalURLScheme") as? String else {
// Something went wrong/weird, but we should fallback to the public one.
return "firefox"
}
return string
}
override func viewDidLoad() {
super.viewDidLoad()
let widgetView: UIView!
self.extensionContext?.widgetLargestAvailableDisplayMode = .compact
let effectView = UIVisualEffectView(effect: UIVibrancyEffect.widgetPrimary())
self.view.addSubview(effectView)
effectView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
widgetView = effectView.contentView
buttonStackView.addArrangedSubview(newTabButton)
buttonStackView.addArrangedSubview(newPrivateTabButton)
widgetStackView.addArrangedSubview(buttonStackView)
widgetStackView.addArrangedSubview(openCopiedLinkButton)
widgetView.addSubview(widgetStackView)
widgetStackView.snp.makeConstraints { make in
make.edges.equalTo(widgetView)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateCopiedLink()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let edge = size.width * TodayUX.buttonsHorizontalMarginPercentage
buttonStackView.layoutMargins = UIEdgeInsets(top: 0, left: edge, bottom: 0, right: edge)
}
func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsets.zero
}
func updateCopiedLink() {
if let url = UIPasteboard.general.copiedURL {
self.openCopiedLinkButton.isHidden = false
self.openCopiedLinkButton.subtitleLabel.isHidden = SystemUtils.isDeviceLocked()
self.openCopiedLinkButton.subtitleLabel.text = url.absoluteString
} else {
self.openCopiedLinkButton.isHidden = true
}
}
// MARK: Button behaviour
@objc func onPressNewTab(_ view: UIView) {
openContainingApp()
}
@objc func onPressNewPrivateTab(_ view: UIView) {
openContainingApp("?private=true")
}
fileprivate func openContainingApp(_ urlSuffix: String = "") {
let urlString = "\(scheme)://open-url\(urlSuffix)"
self.extensionContext?.open(URL(string: urlString)!) { success in
log.info("Extension opened containing app: \(success)")
}
}
@objc func onPressOpenClibpoard(_ view: UIView) {
if let urlString = UIPasteboard.general.string,
let _ = URL(string: urlString) {
let encodedString =
urlString.escape()
openContainingApp("?url=\(encodedString)")
}
}
}
extension UIButton {
func setBackgroundColor(_ color: UIColor, forState state: UIControlState) {
let colorView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
colorView.backgroundColor = color
UIGraphicsBeginImageContext(colorView.bounds.size)
if let context = UIGraphicsGetCurrentContext() {
colorView.layer.render(in: context)
}
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: state)
}
}
class ImageButtonWithLabel: UIView {
lazy var button = UIButton()
lazy var label = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
performLayout()
}
func performLayout() {
addSubview(button)
addSubview(label)
button.snp.makeConstraints { make in
make.top.left.centerX.equalTo(self)
}
label.snp.makeConstraints { make in
make.top.equalTo(button.snp.bottom)
make.leading.trailing.bottom.equalTo(self)
}
label.numberOfLines = 1
label.lineBreakMode = .byWordWrapping
label.textAlignment = .center
label.textColor = UIColor.white
}
func addTarget(_ target: AnyObject?, action: Selector, forControlEvents events: UIControlEvents) {
button.addTarget(target, action: action, for: events)
}
}
class ButtonWithSublabel: UIButton {
lazy var subtitleLabel: UILabel = UILabel()
lazy var label: UILabel = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init() {
self.init(frame: CGRect.zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
performLayout()
}
fileprivate func performLayout() {
let titleLabel = self.label
self.titleLabel?.removeFromSuperview()
addSubview(titleLabel)
let imageView = self.imageView!
let subtitleLabel = self.subtitleLabel
subtitleLabel.textColor = UIColor.lightGray
self.addSubview(subtitleLabel)
imageView.snp.makeConstraints { make in
make.centerY.left.equalTo(self)
make.width.equalTo(TodayUX.copyLinkImageWidth)
}
titleLabel.snp.makeConstraints { make in
make.left.equalTo(imageView.snp.right).offset(TodayUX.margin)
make.trailing.top.equalTo(self)
}
subtitleLabel.lineBreakMode = .byTruncatingTail
subtitleLabel.snp.makeConstraints { make in
make.bottom.equalTo(self)
make.top.equalTo(titleLabel.snp.bottom)
make.leading.trailing.equalTo(titleLabel)
}
}
override func setTitle(_ text: String?, for state: UIControlState) {
self.label.text = text
super.setTitle(text, for: state)
}
}
| 68286b8e1e627a21a59c8cb980324d26 | 36.242321 | 186 | 0.684934 | false | false | false | false |
kaltura/playkit-ios | refs/heads/develop | Classes/FairPlayDRM/FPSUtils.swift | agpl-3.0 | 1 | // ===================================================================================================
// Copyright (C) 2018 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
public enum FPSError: Error {
// License response errors
case malformedServerResponse
case noCKCInResponse
case malformedCKCInResponse
case serverError(_ error: Error, _ url: URL)
case invalidLicenseDuration
// License requests errors (can't generate request)
case missingDRMParams
case invalidKeyRequest
case invalidMediaFormat
case persistenceNotSupported
case missingAssetId(_ url: URL)
}
protocol FPSLicenseRequest {
func getSPC(cert: Data, id: String, shouldPersist: Bool, callback: @escaping (Data?, Error?) -> Void)
func processContentKeyResponse(_ keyResponse: Data)
func processContentKeyResponseError(_ error: Error?)
func persistableContentKey(fromKeyVendorResponse keyVendorResponse: Data, options: [String : Any]?) throws -> Data
}
struct FPSParams {
let cert: Data
let url: URL
init?(_ pkParams: FairPlayDRMParams?) {
guard let params = pkParams else { return nil }
guard let cert = params.fpsCertificate else { PKLog.error("Missing FPS certificate"); return nil }
guard let url = params.licenseUri else { PKLog.error("Missing FPS license URL"); return nil }
self.cert = cert
self.url = url
}
}
class FPSLicense: Codable {
static let defaultExpiry: TimeInterval = 7*24*60*60
let expiryDate: Date?
var data: Data
init(ckc: Data, duration: TimeInterval) {
self.data = ckc
self.expiryDate = Date(timeIntervalSinceNow: duration)
}
init(legacyData: Data) {
self.data = legacyData
self.expiryDate = nil
}
func isExpired() -> Bool {
if let expiryDate = self.expiryDate {
return Date() > expiryDate
}
return false
}
}
extension LocalDataStore {
func fpsKey(_ assetId: String) -> String {
return assetId + ".fpskey"
}
func fpsKeyExists(_ assetId: String) -> Bool {
return exists(key: fpsKey(assetId))
}
func loadFPSKey(_ assetId: String) throws -> FPSLicense {
let obj = try load(key: fpsKey(assetId))
if let license = try? JSONDecoder().decode(FPSLicense.self, from: obj) {
return license
} else {
return FPSLicense(legacyData: obj)
}
}
func saveFPSKey(_ assetId: String, _ value: FPSLicense) throws {
let json = try JSONEncoder().encode(value)
try save(key: fpsKey(assetId), value: json)
}
func removeFPSKey(_ assetId: String) throws {
try remove(key: fpsKey(assetId))
}
}
@objc public class FPSExpirationInfo: NSObject {
@objc public let expirationDate: Date
init(date: Date) {
self.expirationDate = date
}
@objc public func isValid() -> Bool {
return self.expirationDate > Date()
}
}
class FPSUtils {
static let skdUrlPattern = try! NSRegularExpression(pattern: "URI=\"skd://([\\w-]+)\"", options: [])
static func findKeys(url: URL, isMaster: Bool, stopOnKey: Bool = true) -> [String]? {
let playlist: String
do {
playlist = try String(contentsOf: url)
} catch {
PKLog.error("Can't read playlist at \(url)");
return nil
}
var keys = [String]()
var lists = [URL]()
for line in playlist.components(separatedBy: .newlines) {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed.hasPrefix("#EXT-X-SESSION-KEY") || trimmed.hasPrefix("#EXT-X-KEY") {
// #EXT-X-SESSION-KEY:METHOD=SAMPLE-AES,URI="skd://entry-1_x14v3p06",KEYFORMAT="com.apple.streamingkeydelivery",KEYFORMATVERSIONS="1"
// - OR -
// #EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://entry-1_mq299xmb",KEYFORMAT="com.apple.streamingkeydelivery",KEYFORMATVERSIONS="1"
guard let match = skdUrlPattern.firstMatch(in: line, options: [], range: NSMakeRange(0, line.count)) else { continue }
if match.numberOfRanges < 2 { continue }
// Extract the actual assetId from the match (see pattern).
let assetIdRange = match.range(at: 1)
let start = line.index(line.startIndex, offsetBy: assetIdRange.location)
let end = line.index(line.startIndex, offsetBy: assetIdRange.location + assetIdRange.length - 1)
let assetId = String(line[start...end])
keys.append(assetId)
if stopOnKey {
break
}
} else if isMaster && !trimmed.isEmpty && !trimmed.hasPrefix("#") {
// Look for chunk lists too
guard let list = URL(string: trimmed, relativeTo: url) else {
PKLog.warning("Failed to create URL from \(url) and \(trimmed)")
continue
}
lists.append(list)
}
}
if keys.count > 0 {
return keys
}
if isMaster {
// If we're in a master playlist and there are chunklists, call this function
// recursively to find the keys in chunklists.
for list in lists {
if let keys = findKeys(url: list, isMaster: false) {
return keys
}
}
}
return nil
}
// Find the FairPlay assetId (also called keyId) for a downloaded asset.
static func extractAssetId(at location: URL) -> String? {
// Require a downloaded asset.
if !"file".equals(location.scheme) && !"localhost".equals(location.host) {
PKLog.error("Can only extract assetId from local resources")
return nil
}
guard let keys = findKeys(url: location, isMaster: true) else {
PKLog.error("No keys")
return nil
}
return keys[0] // if keys is not nil, there's at least one key.
}
static func removeOfflineLicense(for location: URL, dataStore: LocalDataStore) -> Bool {
guard let id = extractAssetId(at: location) else {return false}
do {
try dataStore.removeFPSKey(id)
return true
} catch {
return false
}
}
static func getLicenseExpirationInfo(for location: URL, dataStore: LocalDataStore) -> FPSExpirationInfo? {
guard let id = extractAssetId(at: location) else {return nil}
guard let lic = try? dataStore.loadFPSKey(id), let date = lic.expiryDate else {
return nil
}
return FPSExpirationInfo(date: date)
}
}
// MARK: Utility
extension PKMediaSource {
func isFairPlay() -> Bool {
return mediaFormat == .hls && drmData?.first?.scheme == .fairplay
}
func fairPlayParams() throws -> FairPlayDRMParams {
guard mediaFormat == .hls else { throw FPSError.invalidMediaFormat }
guard let fpsParams = drmData?.first as? FairPlayDRMParams else { throw FPSError.missingDRMParams }
guard fpsParams.fpsCertificate != nil && fpsParams.licenseUri != nil else { throw FPSError.missingDRMParams }
return fpsParams
}
func isWidevineClassic() -> Bool {
return mediaFormat == .wvm
}
}
extension String {
func equals(_ other: String?) -> Bool {
guard let other = other else {
return false // other is nil
}
return self == other
}
}
| 7739da40adf773f1482bf858b764c457 | 31.943548 | 149 | 0.571236 | false | false | false | false |
samodom/TestableUIKit | refs/heads/master | TestableUIKit/UIResponder/UIViewController/UIViewControllerPerformSegueSpy.swift | mit | 1 | //
// UIViewControllerPerformSegueSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/25/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import TestSwagger
import FoundationSwagger
public extension UIViewController {
private static let performSegueCalledString = UUIDKeyString()
private static let performSegueCalledKey = ObjectAssociationKey(performSegueCalledString)
private static let performSegueCalledReference = SpyEvidenceReference(key: performSegueCalledKey)
private static let performSegueIdentifierString = UUIDKeyString()
private static let performSegueIdentifierKey = ObjectAssociationKey(performSegueIdentifierString)
private static let performSegueIdentifierReference = SpyEvidenceReference(key: performSegueIdentifierKey)
private static let performSegueSenderString = UUIDKeyString()
private static let performSegueSenderKey = ObjectAssociationKey(performSegueSenderString)
private static let performSegueSenderReference = SpyEvidenceReference(key: performSegueSenderKey)
/// Spy controller for ensuring a controller has had its implementation of
/// `performSegue(withIdentifier:sender:)` invoked.
public enum PerformSegueSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UIViewController.self
public static let vector = SpyVector.direct
public static let coselectors = [
SpyCoselectors(
methodType: .instance,
original: #selector(UIViewController.performSegue(withIdentifier:sender:)),
spy: #selector(UIViewController.spy_performSegue(withIdentifier:sender:))
)
] as Set
public static let evidence = [
performSegueCalledReference,
performSegueIdentifierReference,
performSegueSenderReference
] as Set
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `performSegue(withIdentifier:sender:)`
public func spy_performSegue(withIdentifier identifier: String, sender: Any? = nil) {
performSegueCalled = true
performSegueIdentifier = identifier
performSegueSender = sender
spy_performSegue(withIdentifier: identifier, sender: sender)
}
/// Indicates whether the `performSegue(withIdentifier:sender:)` method has been
/// called on this object.
public final var performSegueCalled: Bool {
get {
return loadEvidence(with: UIViewController.performSegueCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: UIViewController.performSegueCalledReference)
}
}
/// Provides the segue identifier passed to `performSegue(withIdentifier:sender:)` if called.
public final var performSegueIdentifier: String? {
get {
return loadEvidence(with: UIViewController.performSegueIdentifierReference) as? String
}
set {
let reference = UIViewController.performSegueIdentifierReference
guard let identifier = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(identifier, with: reference)
}
}
/// Provides the sender passed to `performSegue(withIdentifier:sender:)` if called.
public final var performSegueSender: Any? {
get {
return loadEvidence(with: UIViewController.performSegueSenderReference)
}
set {
let reference = UIViewController.performSegueSenderReference
guard let sender = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(sender, with: reference)
}
}
}
| 9e69d5fe3c71dd98bbcdac9f63fb4b35 | 36.722772 | 109 | 0.698163 | false | false | false | false |
LYM-mg/MGDYZB | refs/heads/master | MGDYZB/MGDYZB/Class/Live/ViewModel/AllListViewModel.swift | mit | 1 | //
// AllListViewModel.swift
// MGDYZB
//
// Created by ming on 16/10/30.
// Copyright © 2016年 ming. All rights reserved.
import UIKit
class AllListViewModel: NSObject {
// 用于上下拉刷新
var currentPage = 0
var rooms: [RoomModel] = []
fileprivate let tagID: String = "0"
}
extension AllListViewModel {
func loadAllListData(_ finishedCallback: @escaping () -> ()) {
let parameters:[String : Any] = ["offset": 20*currentPage, "limit": 20, "time": String(format: "%.0f", Date().timeIntervalSince1970)]
let url = "http://capi.douyucdn.cn/api/v1/live/" + "\(tagID)?"
NetWorkTools.requestData(type: .get, urlString: url,parameters: parameters, succeed: { (result, err) in
// 1.获取到数据
guard let resultDict = result as? [String: Any] else { return }
guard let dataArray = resultDict["data"] as? [[String: Any]] else { return }
// debugPrint(dataArray)
// 2.字典转模型
for dict in dataArray {
self.rooms.append(RoomModel(dict: dict))
}
// 3.完成回调
finishedCallback()
}) { (err) in
finishedCallback()
}
NetWorkTools.requestData(type: .get, urlString: "http://www.douyu.com/api/v1/live/directory",parameters: nil, succeed: { (result, err) in
// 1.获取到数据
guard let resultDict = result as? [String: Any] else { return }
guard let dataArray = resultDict["data"] as? [[String: Any]] else { return }
debugPrint(dataArray)
// 2.字典转模型
for dict in dataArray {
self.rooms.append(RoomModel(dict: dict))
}
// 3.完成回调
finishedCallback()
}) { (err) in
finishedCallback()
}
}
}
| a714e188f72317a075238b9415b868e2 | 32.672727 | 145 | 0.544276 | false | false | false | false |
rsrose21/cluelist | refs/heads/master | ClueList/ClueList/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// ClueList
//
// Created by Ryan Rose on 10/12/15.
// Copyright © 2015 GE. All rights reserved.
//
import UIKit
import CoreData
import EventKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//store event store object so we don't request if multiple times
var eventStore: EKEventStore?
var sharedContext: NSManagedObjectContext {
return CoreDataManager.sharedInstance.managedObjectContext
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Change navigation bar color: https://coderwall.com/p/dyqrfa/customize-navigation-bar-appearance-with-swift
let navigationBarAppearace = UINavigationBar.appearance();
navigationBarAppearace.tintColor = UIColor(hexString: Constants.UIColors.WHITE)
navigationBarAppearace.barTintColor = UIColor(hexString: Constants.UIColors.NAVIGATION_BAR)
// change navigation item title color
navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName: UIColor(hexString: Constants.UIColors.WHITE)!]
//change status bar color
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
// set default list mode prior to any Core Data inserts
let defaults = NSUserDefaults.standardUserDefaults()
let mode = defaults.integerForKey(Constants.Data.APP_STATE)
if (ToDoListMode(rawValue: mode) != nil) {
ToDoListConfiguration.defaultConfiguration(sharedContext).listMode = ToDoListMode(rawValue: mode)!
} else {
ToDoListConfiguration.defaultConfiguration(sharedContext).listMode = .Simple
}
// register app to receive local notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)) // types are UIUserNotificationType members
// allow user to update ToDoItems from notifications bar
addActions(application)
if Constants.Data.SEED_DB {
//seed the Core Data database with sample ToDos
let dataHelper = DataHelper()
dataHelper.seedDataStore()
dataHelper.printAllToDos()
}
return true
}
func applicationDidEnterBackground(application: UIApplication) {
CoreDataManager.sharedInstance.saveContext()
}
func applicationWillTerminate(application: UIApplication) {
CoreDataManager.sharedInstance.saveContext()
}
// notify our listener when the ToDo list should be refreshed on application state change
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
NSNotificationCenter.defaultCenter().postNotificationName("TodoListShouldRefresh", object: self)
}
func applicationDidBecomeActive(application: UIApplication) {
NSNotificationCenter.defaultCenter().postNotificationName("TodoListShouldRefresh", object: self)
}
// badging the app icon for overdue ToDoItems
func applicationWillResignActive(application: UIApplication) { // fired when user quits the application
let todoItems: [ToDoItem] = ToDoList.sharedInstance.allItems() // retrieve list of all to-do items
let overdueItems = todoItems.filter({ (todoItem) -> Bool in
if (todoItem.deadline != nil) {
return todoItem.deadline!.compare(NSDate()) != .OrderedDescending
} else {
return false
}
})
UIApplication.sharedApplication().applicationIconBadgeNumber = overdueItems.count // set our badge number to number of overdue items
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
let dictionary: [String: AnyObject?] = ["deadline": notification.fireDate!, "text": notification.userInfo!["title"] as! String, "id": notification.userInfo!["UUID"] as! String!]
let toDoItem = ToDoItem(dictionary: dictionary, context: sharedContext)
CoreDataManager.sharedInstance.saveContext()
switch (identifier!) {
case "COMPLETE_TODO":
ToDoList.sharedInstance.removeItem(toDoItem)
toDoItem.completed = true
CoreDataManager.sharedInstance.saveContext()
case "REMIND":
ToDoList.sharedInstance.scheduleReminderforItem(toDoItem)
default: // switch statements must be exhaustive - this condition should never be met
NSLog("Error: unexpected notification action identifier!")
}
completionHandler() // per developer documentation, app will terminate if we fail to call this
}
// allow user to update ToDoItems from notifications bar: http://jamesonquave.com/blog/local-notifications-in-ios-8-with-swift-part-2/
func addActions(application: UIApplication) -> Bool {
let completeAction = UIMutableUserNotificationAction()
completeAction.identifier = "COMPLETE_TODO" // the unique identifier for this action
completeAction.title = "Complete" // title for the action button
completeAction.activationMode = .Background // UIUserNotificationActivationMode.Background - don't bring app to foreground
completeAction.authenticationRequired = false // don't require unlocking before performing action
completeAction.destructive = true // display action in red
let remindAction = UIMutableUserNotificationAction()
remindAction.identifier = "REMIND"
remindAction.title = "Remind in 30 minutes"
remindAction.activationMode = .Background
remindAction.destructive = false
let todoCategory = UIMutableUserNotificationCategory() // notification categories allow us to create groups of actions that we can associate with a notification
todoCategory.identifier = "TODO_CATEGORY"
todoCategory.setActions([remindAction, completeAction], forContext: .Default) // UIUserNotificationActionContext.Default (4 actions max)
todoCategory.setActions([completeAction, remindAction], forContext: .Minimal) // UIUserNotificationActionContext.Minimal - for when space is limited (2 actions max)
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: NSSet(array: [todoCategory]) as? Set<UIUserNotificationCategory>)) // we're now providing a set containing our category as an argument
return true
}
}
| 4b2bbdbfa6b05c2538014579053e1ddb | 49.496296 | 262 | 0.71131 | false | false | false | false |
shial4/api-loltracker | refs/heads/master | Sources/App/Models/Tracker.swift | mit | 1 | //
// Tracker.swift
// lolTracker-API
//
// Created by Shial on 13/01/2017.
//
//
import Foundation
import Vapor
import Fluent
final class Tracker: Model {
var exists: Bool = false
public var id: Node?
var summonerId: Node?
var date: String
init(date: String, summonerId: Node? = nil) {
self.id = nil
self.summonerId = summonerId
self.date = date
}
required init(node: Node, in context: Context) throws {
id = try node.extract("id")
date = try node.extract("date")
summonerId = try node.extract("summoner_id")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"date": date,
"summoner_id": summonerId
])
}
}
extension Tracker: Preparation {
static func prepare(_ database: Database) throws {
try database.create(entity, closure: { (tracks) in
tracks.id()
tracks.int("date")
tracks.parent(Summoner.self, optional: false)
})
}
static func revert(_ database: Database) throws {
try database.delete(entity)
}
}
extension Tracker {
func summoner() throws -> Summoner? {
return try parent(summonerId, nil, Summoner.self).get()
}
}
| 3887355b64633770e164b5f7154e3d0f | 21.491525 | 63 | 0.571213 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom/NCMainMenuViewController.swift | lgpl-2.1 | 2 | //
// NCMainMenuViewController.swift
// Neocom
//
// Created by Artem Shimanski on 04.12.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
import EVEAPI
import CoreData
import Futures
class NCMainMenuRow: DefaultTreeRow {
let scopes: Set<ESI.Scope>
let account: NCAccount?
let isEnabled: Bool
init(prototype: Prototype = Prototype.NCDefaultTableViewCell.default, nodeIdentifier: String, image: UIImage? = nil, title: String? = nil, route: Route? = nil, scopes: [ESI.Scope] = [], account: NCAccount? = nil) {
let scopes = Set(scopes)
self.scopes = scopes
self.account = account
let isEnabled: Bool = {
guard !scopes.isEmpty else {return true}
guard let currentScopes = account?.scopes?.compactMap({($0 as? NCScope)?.name}).compactMap ({ESI.Scope($0)}) else {return false}
return scopes.isSubset(of: currentScopes)
}()
self.isEnabled = isEnabled
super.init(prototype: prototype, nodeIdentifier: nodeIdentifier, image: image, title: title, accessoryType: .disclosureIndicator, route: isEnabled ? route : nil)
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = title
cell.iconView?.image = image
cell.accessoryType = .disclosureIndicator
if !isEnabled {
cell.titleLabel?.textColor = .lightText
cell.subtitleLabel?.text = NSLocalizedString("Please sign in again to unlock all features", comment: "")
}
else {
cell.titleLabel?.textColor = .white
cell.subtitleLabel?.text = nil
}
}
}
class NCAccountDataMenuRow<T>: NCMainMenuRow {
private var observer: NCManagedObjectObserver?
var isLoading = false
var result: CachedValue<T>? {
didSet {
if let cacheRecord = result?.cacheRecord(in: NCCache.sharedCache!.viewContext) {
self.observer = NCManagedObjectObserver(managedObject: cacheRecord) { [weak self] (_,_) in
guard let strongSelf = self else {return}
strongSelf.treeController?.reloadCells(for: [strongSelf], with: .none)
}
}
}
}
var error: Error?
}
class NCCharacterSheetMenuRow: NCAccountDataMenuRow<ESI.Skills.CharacterSkills> {
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
if let value = result?.value {
cell.subtitleLabel?.text = NCUnitFormatter.localizedString(from: value.totalSP, unit: .skillPoints, style: .full)
}
else if let error = error {
cell.subtitleLabel?.text = error.localizedDescription
}
else {
guard let account = account, !isLoading else {return}
isLoading = true
NCDataManager(account: account).skills().then(on: .main) { result in
self.result = result
self.error = nil
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
}
class NCJumpClonesMenuRow: NCAccountDataMenuRow<ESI.Clones.JumpClones> {
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
if let value = result?.value {
let t = 3600 * 24 + (value.lastCloneJumpDate ?? .distantPast).timeIntervalSinceNow
cell.subtitleLabel?.text = String(format: NSLocalizedString("Clone jump availability: %@", comment: ""), t > 0 ? NCTimeIntervalFormatter.localizedString(from: t, precision: .minutes) : NSLocalizedString("Now", comment: ""))
}
else if let error = error {
cell.subtitleLabel?.text = error.localizedDescription
}
else {
guard let account = account, !isLoading else {return}
isLoading = true
NCDataManager(account: account).clones().then(on: .main) { result in
self.result = result
self.error = nil
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
}
class NCSkillsMenuRow: NCAccountDataMenuRow<[ESI.Skills.SkillQueueItem]> {
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
if let value = result?.value {
let date = Date()
let skillQueue = value.filter {
guard let finishDate = $0.finishDate else {return false}
return finishDate >= date
}
if let skill = skillQueue.last,
let endTime = skill.finishDate {
cell.subtitleLabel?.text = String(format: NSLocalizedString("%d skills in queue (%@)", comment: ""), skillQueue.count, NCTimeIntervalFormatter.localizedString(from: endTime.timeIntervalSinceNow, precision: .minutes))
}
else {
cell.subtitleLabel?.text = NSLocalizedString("No skills in training", comment: "")
}
}
else if let error = error {
cell.subtitleLabel?.text = error.localizedDescription
}
else {
guard let account = account, !isLoading else {return}
isLoading = true
NCDataManager(account: account).skillQueue().then(on: .main) { result in
self.result = result
self.error = nil
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
}
class NCWealthMenuRow: NCAccountDataMenuRow<Double> {
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
if let value = result?.value {
cell.subtitleLabel?.text = NCUnitFormatter.localizedString(from: value, unit: .isk, style: .full)
}
else if let error = error {
cell.subtitleLabel?.text = error.localizedDescription
}
else {
guard let account = account, !isLoading else {return}
isLoading = true
NCDataManager(account: account).walletBalance().then(on: .main) { result in
self.result = result
self.error = nil
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
}
class NCServerStatusRow: NCAccountDataMenuRow<ESI.Status.ServerStatus> {
lazy var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "HH:mm:ss"
return dateFormatter
}()
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell, isEnabled else {return}
cell.accessoryType = .none
if let value = result?.value {
if value.players > 0 {
cell.titleLabel?.text = String(format: NSLocalizedString("Tranquility: online %@ players", comment: ""), NCUnitFormatter.localizedString(from: value.players, unit: .none, style: .full))
}
else {
cell.titleLabel?.text = NSLocalizedString("Tranquility: offline", comment: "")
}
cell.subtitleLabel?.text = NSLocalizedString("EVE Time: ", comment: "") + dateFormatter.string(from: Date())
}
else if let error = error {
cell.titleLabel?.text = NSLocalizedString("Tranquility", comment: "")
cell.subtitleLabel?.text = error.localizedDescription
}
else {
cell.titleLabel?.text = NSLocalizedString("Tranquility", comment: "")
cell.subtitleLabel?.text = NSLocalizedString("Updating...", comment: "")
guard !isLoading else {return}
isLoading = true
NCDataManager().serverStatus().then(on: .main) { result in
self.result = result
self.error = nil
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerTick(_:)), userInfo: nil, repeats: true)
}.catch(on: .main) { error in
self.result = nil
self.error = error
}.finally(on: .main) {
self.isLoading = false
self.treeController?.reloadCells(for: [self], with: .none)
}
}
}
deinit {
timer?.invalidate()
}
private var timer: Timer? {
didSet {
oldValue?.invalidate()
}
}
// override func willDisplay(cell: UITableViewCell) {
// timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerTick(_:)), userInfo: cell, repeats: true)
// }
@objc func timerTick(_ timer: Timer) {
guard let cell = treeController?.cell(for: self) as? NCDefaultTableViewCell else {return}
// guard let cell = timer.userInfo as? NCDefaultTableViewCell else {return}
cell.subtitleLabel?.text = NSLocalizedString("EVE Time: ", comment: "") + dateFormatter.string(from: Date())
}
// override func didEndDisplaying(cell: UITableViewCell) {
// if (timer?.userInfo as? UITableViewCell) == cell {
// timer = nil
// }
// }
}
class NCMainMenuViewController: NCTreeViewController {
override func viewDidLoad() {
super.viewDidLoad()
accountChangeAction = .update
tableView.register([Prototype.NCHeaderTableViewCell.default,
Prototype.NCDefaultTableViewCell.default,
Prototype.NCDefaultTableViewCell.noImage])
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let h = tableView.tableHeaderView?.bounds.height {
self.tableView.scrollIndicatorInsets.top = h
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if transitionCoordinator?.viewController(forKey: .to)?.parent == navigationController {
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
/*override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
DispatchQueue.main.async {
if let headerViewController = self.headerViewController {
self.headerMinHeight = headerViewController.view.systemLayoutSizeFitting(CGSize(width:self.view.bounds.size.width, height:0), withHorizontalFittingPriority:UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.defaultHigh).height
self.headerMaxHeight = headerViewController.view.systemLayoutSizeFitting(CGSize(width:self.view.bounds.size.width, height:0), withHorizontalFittingPriority:UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel).height
var rect = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.bounds.size.width, height: self.headerMaxHeight))
self.tableView?.tableHeaderView?.frame = rect
rect = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: max(self.headerMaxHeight - self.tableView.contentOffset.y, self.headerMinHeight))
headerViewController.view.frame = self.view.convert(rect, to:self.tableView)
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(rect.size.height, 0, 0, 0)
}
}
}*/
override func content() -> Future<TreeNode?> {
let account = NCAccount.current
var sections: [TreeNode] = [
DefaultTreeSection(nodeIdentifier: "Character", title: NSLocalizedString("Character", comment: "").uppercased(),
children: [
NCCharacterSheetMenuRow(nodeIdentifier: "CharacterSheet",
image: #imageLiteral(resourceName: "charactersheet"),
title: NSLocalizedString("Character Sheet", comment: ""),
route: Router.MainMenu.CharacterSheet(),
scopes: [.esiWalletReadCharacterWalletV1,
.esiSkillsReadSkillsV1,
.esiLocationReadLocationV1,
.esiLocationReadShipTypeV1,
.esiClonesReadImplantsV1],
account: account),
NCJumpClonesMenuRow(nodeIdentifier: "JumpClones",
image: #imageLiteral(resourceName: "jumpclones"),
title: NSLocalizedString("Jump Clones", comment: ""),
route: Router.MainMenu.JumpClones(),
scopes: [.esiClonesReadClonesV1,
.esiClonesReadImplantsV1],
account: account),
NCSkillsMenuRow(nodeIdentifier: "Skills",
image: #imageLiteral(resourceName: "skills"),
title: NSLocalizedString("Skills", comment: ""),
route: Router.MainMenu.Skills(),
scopes: [.esiSkillsReadSkillqueueV1,
.esiSkillsReadSkillsV1,
.esiClonesReadImplantsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "Mail",
image: #imageLiteral(resourceName: "evemail"),
title: NSLocalizedString("EVE Mail", comment: ""),
route: Router.MainMenu.Mail(),
scopes: [.esiMailReadMailV1,
.esiMailSendMailV1,
.esiMailOrganizeMailV1],
account: account),
NCMainMenuRow(nodeIdentifier: "Calendar",
image: #imageLiteral(resourceName: "calendar"),
title: NSLocalizedString("Calendar", comment: ""),
route: Router.MainMenu.Calendar(),
scopes: [.esiCalendarReadCalendarEventsV1,
.esiCalendarRespondCalendarEventsV1],
account: account),
NCWealthMenuRow(nodeIdentifier: "Wealth",
image: #imageLiteral(resourceName: "folder"),
title: NSLocalizedString("Wealth", comment: ""),
route: Router.MainMenu.Wealth(),
scopes: [.esiWalletReadCharacterWalletV1,
.esiAssetsReadAssetsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "LP",
image: #imageLiteral(resourceName: "lpstore"),
title: NSLocalizedString("Loyalty Points", comment: ""),
route: Router.MainMenu.LoyaltyPoints(),
scopes: [.esiCharactersReadLoyaltyV1],
account: account)
]),
DefaultTreeSection(nodeIdentifier: "Database", title: NSLocalizedString("Database", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "Database", image: #imageLiteral(resourceName: "items"), title: NSLocalizedString("Database", comment: ""), route: Router.MainMenu.Database()),
NCMainMenuRow(nodeIdentifier: "Certificates", image: #imageLiteral(resourceName: "certificates"), title: NSLocalizedString("Certificates", comment: ""), route: Router.MainMenu.Certificates()),
NCMainMenuRow(nodeIdentifier: "Market", image: #imageLiteral(resourceName: "market"), title: NSLocalizedString("Market", comment: ""), route: Router.MainMenu.Market()),
NCMainMenuRow(nodeIdentifier: "NPC", image: #imageLiteral(resourceName: "criminal"), title: NSLocalizedString("NPC", comment: ""), route: Router.MainMenu.NPC()),
NCMainMenuRow(nodeIdentifier: "Wormholes", image: #imageLiteral(resourceName: "terminate"), title: NSLocalizedString("Wormholes", comment: ""), route: Router.MainMenu.Wormholes()),
NCMainMenuRow(nodeIdentifier: "Incursions", image: #imageLiteral(resourceName: "incursions"), title: NSLocalizedString("Incursions", comment: ""), route: Router.MainMenu.Incursions())
]),
DefaultTreeSection(nodeIdentifier: "Fitting", title: NSLocalizedString("Fitting/Kills", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "Fitting", image: #imageLiteral(resourceName: "fitting"), title: NSLocalizedString("Fitting", comment: ""), route: Router.MainMenu.Fitting()),
NCMainMenuRow(nodeIdentifier: "KillReports",
image: #imageLiteral(resourceName: "killreport"),
title: NSLocalizedString("Kill Reports", comment: ""),
route: Router.MainMenu.KillReports(),
scopes: [.esiKillmailsReadKillmailsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "zKillboardReports", image: #imageLiteral(resourceName: "killrights"), title: NSLocalizedString("zKillboard Reports", comment: ""), route: Router.MainMenu.ZKillboardReports())
]),
DefaultTreeSection(nodeIdentifier: "Business", title: NSLocalizedString("Business", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "Assets",
image: #imageLiteral(resourceName: "assets"),
title: NSLocalizedString("Assets", comment: ""),
route: Router.MainMenu.Assets(owner: .character),
scopes: [.esiAssetsReadAssetsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "MarketOrders",
image: #imageLiteral(resourceName: "marketdeliveries"),
title: NSLocalizedString("Market Orders", comment: ""),
route: Router.MainMenu.MarketOrders(owner: .character),
scopes: [.esiMarketsReadCharacterOrdersV1],
account: account),
NCMainMenuRow(nodeIdentifier: "Contracts",
image: #imageLiteral(resourceName: "contracts"),
title: NSLocalizedString("Contracts", comment: ""),
route: Router.MainMenu.Contracts(),
scopes: [.esiContractsReadCharacterContractsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "WalletTransactions",
image: #imageLiteral(resourceName: "journal"),
title: NSLocalizedString("Wallet Transactions", comment: ""),
route: Router.MainMenu.WalletTransactions(owner: .character),
scopes: [.esiWalletReadCharacterWalletV1],
account: account),
NCMainMenuRow(nodeIdentifier: "WalletJournal",
image: #imageLiteral(resourceName: "wallet"),
title: NSLocalizedString("Wallet Journal", comment: ""),
route: Router.MainMenu.WalletJournal(owner: .character),
scopes: [.esiWalletReadCharacterWalletV1],
account: account),
NCMainMenuRow(nodeIdentifier: "IndustryJobs",
image: #imageLiteral(resourceName: "industry"),
title: NSLocalizedString("Industry Jobs", comment: ""),
route: Router.MainMenu.IndustryJobs(owner: .character),
scopes: [.esiIndustryReadCharacterJobsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "Planetaries",
image: #imageLiteral(resourceName: "planets"),
title: NSLocalizedString("Planetaries", comment: ""),
route: Router.MainMenu.Planetaries(),
scopes: [.esiPlanetsManagePlanetsV1],
account: account),
]),
DefaultTreeSection(nodeIdentifier: "Corporation", title: NSLocalizedString("Corporation", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "Assets",
image: #imageLiteral(resourceName: "assets"),
title: NSLocalizedString("Assets", comment: ""),
route: Router.MainMenu.Assets(owner: .corporation),
scopes: [.esiAssetsReadCorporationAssetsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "MarketOrders",
image: #imageLiteral(resourceName: "marketdeliveries"),
title: NSLocalizedString("Market Orders", comment: ""),
route: Router.MainMenu.MarketOrders(owner: .corporation),
scopes: [.esiMarketsReadCorporationOrdersV1],
account: account),
NCMainMenuRow(nodeIdentifier: "WalletTransactions",
image: #imageLiteral(resourceName: "journal"),
title: NSLocalizedString("Wallet Transactions", comment: ""),
route: Router.MainMenu.WalletTransactions(owner: .corporation),
scopes: [.esiWalletReadCorporationWalletsV1, .esiCorporationsReadDivisionsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "WalletJournal",
image: #imageLiteral(resourceName: "wallet"),
title: NSLocalizedString("Wallet Journal", comment: ""),
route: Router.MainMenu.WalletJournal(owner: .corporation),
scopes: [.esiWalletReadCorporationWalletsV1, .esiCorporationsReadDivisionsV1],
account: account),
NCMainMenuRow(nodeIdentifier: "IndustryJobs",
image: #imageLiteral(resourceName: "industry"),
title: NSLocalizedString("Industry Jobs", comment: ""),
route: Router.MainMenu.IndustryJobs(owner: .corporation),
scopes: [.esiIndustryReadCorporationJobsV1],
account: account)
]),
DefaultTreeSection(nodeIdentifier: "Info", title: NSLocalizedString("Info", comment: "").uppercased(),
children: [
NCMainMenuRow(nodeIdentifier: "News", image: #imageLiteral(resourceName: "newspost"), title: NSLocalizedString("News", comment: ""), route: Router.MainMenu.News()),
NCMainMenuRow(nodeIdentifier: "Settings", image: #imageLiteral(resourceName: "settings"), title: NSLocalizedString("Settings", comment: ""), route: Router.MainMenu.Settings()),
NCMainMenuRow(nodeIdentifier: "Subscription", image: #imageLiteral(resourceName: "votes"), title: NSLocalizedString("Remove Ads", comment: ""), route: Router.MainMenu.Subscription()),
NCMainMenuRow(nodeIdentifier: "BugReport", image: #imageLiteral(resourceName: "notepad"), title: NSLocalizedString("Report a Bug", comment: ""), route: Router.MainMenu.BugReport()),
NCMainMenuRow(nodeIdentifier: "About", image: #imageLiteral(resourceName: "info"), title: NSLocalizedString("About", comment: ""), route: Router.MainMenu.About())
])
]
// let currentScopes = Set((account?.scopes?.allObjects as? [NCScope])?.compactMap {return $0.name != nil ? ESI.Scope($0.name!) : nil} ?? [])
if (account?.scopes as? Set<NCScope>)?.compactMap({$0.name}).contains(ESI.Scope.esiAssetsReadCorporationAssetsV1.rawValue) == true {
sections[4].isExpanded = true
}
else {
sections[4].isExpanded = false
}
sections.forEach {$0.children = ($0.children as! [NCMainMenuRow]).filter({$0.scopes.isEmpty || account != nil})}
sections = sections.filter {!$0.children.isEmpty}
sections.insert(NCServerStatusRow(prototype: Prototype.NCDefaultTableViewCell.noImage,nodeIdentifier: "ServerStatus"), at: 0)
return .init(RootNode(sections, collapseIdentifier: "NCMainMenuViewController"))
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "NCAccountsViewController" {
segue.destination.transitioningDelegate = parent as? UIViewControllerTransitioningDelegate
}
}
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
if (node as? NCMainMenuRow)?.isEnabled == false {
ESI.performAuthorization(from: self)
}
}
/*
//MARK: UIScrollViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let row = self.mainMenu[indexPath.section][indexPath.row]
let isEnabled: Bool = {
guard let scopes = row["scopes"] as? [String] else {return true}
guard let currentScopes = currentScopes else {return false}
return Set(scopes).isSubset(of: currentScopes)
}()
if isEnabled {
if let segue = row["segueIdentifier"] as? String {
performSegue(withIdentifier: segue, sender: tableView.cellForRow(at: indexPath))
}
}
else {
let url = OAuth2.authURL(clientID: ESClientID, callbackURL: ESCallbackURL, scope: ESI.Scope.default, state: "esi")
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}*/
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let t: CGFloat
if #available(iOS 11, *) {
t = scrollView.safeAreaInsets.top + 70
}
else {
t = 70
}
if (scrollView.contentOffset.y < -t && self.transitionCoordinator == nil && scrollView.isTracking) {
// performSegue(withIdentifier: "NCAccountsViewController", sender: self)
}
}
}
| a9612cdabbab72507daeaaea23cfa4d3 | 43.020833 | 253 | 0.654046 | false | false | false | false |
sarvex/SwiftRecepies | refs/heads/master | Security/Authenticating the User with Touch ID/Authenticating the User with Touch ID/ViewController.swift | isc | 1 | //
// ViewController.swift
// Authenticating the User with Touch ID
//
// Created by Vandad Nahavandipoor on 7/7/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import LocalAuthentication
class ViewController: UIViewController {
@IBOutlet weak var buttonCheckTouchId: UIButton!
@IBOutlet weak var buttonUseTouchId: UIButton!
@IBAction func checkTouchIdAvailability(sender: AnyObject) {
let context = LAContext()
var error: NSError?
let isTouchIdAvailable = context.canEvaluatePolicy(
.DeviceOwnerAuthenticationWithBiometrics,
error: &error)
buttonUseTouchId.enabled = isTouchIdAvailable
/* Touch ID is not available */
if isTouchIdAvailable == false{
let alertController = UIAlertController(title: "Touch ID",
message: "Touch ID is not available",
preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK",
style: .Default,
handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
}
@IBAction func useTouchId(sender: AnyObject) {
/* We will code this soon */
let context = LAContext()
var error: NSError?
let reason = "Please authenticate with Touch ID " +
"to access your private information"
context.evaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics,
localizedReason: reason, reply: {(success: Bool, error: NSError!) in
if success{
/* The user was successfully authenticated */
} else {
/* The user could not be authenticated */
}
})
}
}
| 6ba097c06de2e3b5047406626e2ad3c5 | 29.195122 | 83 | 0.679321 | false | false | false | false |
daggmano/photo-management-studio | refs/heads/develop | src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/CollectionViewItem.swift | mit | 1 | //
// CollectionViewItem.swift
// Photo Management Studio
//
// Created by Darren Oster on 28/03/2016.
// Copyright © 2016 Criterion Software. All rights reserved.
//
import Cocoa
class CollectionViewItem: NSCollectionViewItem {
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var subTitleLabel: NSTextField!
private func updateView() {
super.viewWillAppear()
self.imageView?.image = NSImage(named: "placeholder")
titleLabel.stringValue = ""
subTitleLabel.stringValue = ""
view.toolTip = ""
if let item = self.importableItem {
titleLabel.stringValue = item.title
if let subTitle = item.subTitle {
subTitleLabel.stringValue = subTitle
self.view.toolTip = "\(item.title)\n\n\(subTitle)"
} else {
subTitleLabel.stringValue = ""
self.view.toolTip = item.title
}
if !item.imageUrl.containsString("http:") {
imageView?.image = NSImage(named: item.imageUrl)
} else {
var url: String;
if (item.imageUrl.containsString("?")) {
url = "\(item.imageUrl)&size=500"
} else {
url = "\(item.imageUrl)?size=500"
}
print(url)
let thumbName = "\(item.identifier!)_500x500.jpg"
ImageCache.getImage(url, thumbName: thumbName, useCache: true, callback: { (image) in
self.imageView?.image = image
self.imageView?.needsDisplay = true
})
}
// if let thumbUrl = item.thumbUrl {
// let url = "\(thumbUrl)&size=500"
// dispatch_async(dispatch_queue_create("getAsyncPhotosGDQueue", nil), { () -> Void in
// if let url = NSURL(string: url) {
// if let image = NSImage(contentsOfURL: url) {
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.imageView?.image = image
// self.imageView?.needsDisplay = true
// })
// }
// }
// })
// }
}
}
// MARK: properties
var importableItem: PhotoItem? {
return representedObject as? PhotoItem
}
override var representedObject: AnyObject? {
didSet {
super.representedObject = representedObject
if let _ = representedObject as? PhotoItem {
self.updateView()
}
}
}
override var selected: Bool {
didSet {
(self.view as! CollectionViewItemView).selected = selected
}
}
override var highlightState: NSCollectionViewItemHighlightState {
didSet {
(self.view as! CollectionViewItemView).highlightState = highlightState
}
}
// MARK: NSResponder
override func mouseDown(theEvent: NSEvent) {
if theEvent.clickCount == 2 {
// if let thumbUrl = importableItem?.thumbUrl {
// print("Double click \(importableItem!.fullPath)")
// Event.emit("display-preview", obj: thumbUrl)
// }
} else {
super.mouseDown(theEvent)
}
}
}
| 138836c3958b03c74afab453712c624b | 31.0625 | 101 | 0.494291 | false | false | false | false |
MichMich/HomeSensor | refs/heads/master | HomeSensor/Sensor.swift | apache-2.0 | 1 | //
// Sensor.swift
// HomeSensor
//
// Created by Michael Teeuw on 04/12/15.
// Copyright © 2015 Michael Teeuw. All rights reserved.
//
import Foundation
class Sensor {
var name: String
var identifier: String
var state:Bool = false {
didSet {
delegate?.sensorStateUpdate(self, state: state)
}
}
var timestamp:NSDate? {
didSet {
delegate?.sensorStateUpdate(self, state: state)
}
}
var publishNotificationSubscriptionChange = false
var notificationSubscription:NotificationType = .None {
didSet {
if notificationSubscription != oldValue {
delegate?.sensorNotificationSubscriptionChanged(self, notificationType: notificationSubscription)
}
}
}
var delegate:SensorDelegateProtocol?
init(name: String, identifier:String) {
self.name = name
self.identifier = identifier
}
func receivedNewValue(value:String) {
if let boolValue = value.toBool() {
state = boolValue
}
}
func receivedNewTimestamp(timeString:String) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
timestamp = dateFormatter.dateFromString(timeString)
}
}
protocol SensorDelegateProtocol {
func sensorStateUpdate(sensor:Sensor, state:Bool)
func sensorNotificationSubscriptionChanged(sensor:Sensor, notificationType:NotificationType)
}
extension String {
func toBool() -> Bool? {
switch self.lowercaseString {
case "true", "yes", "on", "1":
return true
case "false", "no", "off", "0":
return false
default:
return nil
}
}
} | d414a1f7c974b74b88ba143ab9ab8a6e | 20.507042 | 101 | 0.720183 | false | false | false | false |
mittenimraum/CVGenericDataSource | refs/heads/master | Example/CVGenericDataSourceExample/Classes/Coordination/StateCoordinator.swift | mit | 1 | //
// StateCoordinator.swift
// CVGenericDataSourceExample
//
// Created by Stephan Schulz on 11.04.17.
// Copyright © 2017 Stephan Schulz. All rights reserved.
//
import Foundation
import UIKit
import CVGenericDataSource
class StateCoordinator: NSObject, CoordinatorProtocol {
// MARK: - Variables <CoordinatorProtocol>
var parentCoordinator: CoordinatorProtocol?
var childCoordinators: [CoordinatorProtocol] = []
// MARK: - Variables
var navigationController: UINavigationController!
var stateViewController: StateViewController!
// MARK: - Init
init(parentCoordinator: CoordinatorProtocol?, navigationController: UINavigationController) {
super.init()
self.parentCoordinator = parentCoordinator
self.navigationController = navigationController
}
// MARK: - CoordinatorProtocol
func start() {
stateViewController = StateViewController(nibName: String(describing: StateViewController.self), bundle: nil)
stateViewController.viewModel = StateViewModel(coordinator: self)
navigationController.pushViewController(stateViewController, animated: true)
}
}
| 88fc414381a74d6d6a121ad3d31a62c3 | 26.714286 | 117 | 0.739691 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripeIdentity/StripeIdentity/Source/Analytics/IdentityAnalyticsClient.swift | mit | 1 | //
// IdentityAnalyticsClient.swift
// StripeIdentity
//
// Created by Mel Ludowise on 6/7/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
import UIKit
enum IdentityAnalyticsClientError: AnalyticLoggableError {
/// `startTrackingTimeToScreen` was called twice in a row without calling
/// `stopTrackingTimeToScreenAndLogIfNeeded`
case timeToScreenAlreadyStarted(
alreadyStartedForScreen: IdentityAnalyticsClient.ScreenName?,
requestedForScreen: IdentityAnalyticsClient.ScreenName?
)
func analyticLoggableSerializeForLogging() -> [String: Any] {
var payload: [String: Any] = [
"domain": (self as NSError).domain
]
switch self {
case .timeToScreenAlreadyStarted(let alreadyStartedForScreen, let requestedForScreen):
payload["type"] = "timeToScreenAlreadyStarted"
if let alreadyStartedForScreen = alreadyStartedForScreen {
payload["previous_tracked_screen"] = alreadyStartedForScreen.rawValue
}
if let requestedForScreen = requestedForScreen {
payload["new_tracked_screen"] = requestedForScreen.rawValue
}
}
return payload
}
}
/// Wrapper for AnalyticsClient that formats Identity-specific analytics
final class IdentityAnalyticsClient {
enum EventName: String {
// MARK: UI
case sheetPresented = "sheet_presented"
case sheetClosed = "sheet_closed"
case verificationFailed = "verification_failed"
case verificationCanceled = "verification_canceled"
case verificationSucceeded = "verification_succeeded"
case screenAppeared = "screen_presented"
case cameraError = "camera_error"
case cameraPermissionDenied = "camera_permission_denied"
case cameraPermissionGranted = "camera_permission_granted"
case documentCaptureTimeout = "document_timeout"
case selfieCaptureTimeout = "selfie_timeout"
// MARK: Performance
case averageFPS = "average_fps"
case modelPerformance = "model_performance"
case imageUpload = "image_upload"
case timeToScreen = "time_to_screen"
// MARK: Errors
case genericError = "generic_error"
}
enum ScreenName: String {
case biometricConsent = "consent"
case documentTypeSelect = "document_select"
case documentCapture = "live_capture"
case documentFileUpload = "file_upload"
case selfieCapture = "selfie"
case success = "confirmation"
case error = "error"
}
/// Name of the scanner logged in scanning performance events
enum ScannerName: String {
case document
case selfie
}
static let sharedAnalyticsClient = AnalyticsClientV2(
clientId: "mobile-identity-sdk",
origin: "stripe-identity-ios"
)
let verificationSessionId: String
let analyticsClient: AnalyticsClientV2Protocol
/// Total number of times the front of the document was attempted to be scanned.
private(set) var numDocumentFrontScanAttempts = 0
/// Total number of times the back of the document was attempted to be scanned.
private(set) var numDocumentBackScanAttempts = 0
/// Total number of times a selfie was attempted to be scanned.
private(set) var numSelfieScanAttempts = 0
/// Tracks the start time for `timeToScreen` analytic
private(set) var timeToScreenStartTime: Date?
/// The last screen transitioned to for `timeToScreen` analytic
private(set) var timeToScreenFromScreen: ScreenName?
init(
verificationSessionId: String,
analyticsClient: AnalyticsClientV2Protocol = IdentityAnalyticsClient.sharedAnalyticsClient
) {
self.verificationSessionId = verificationSessionId
self.analyticsClient = analyticsClient
}
// MARK: - UI Events
/// Increments the number of times a scan was initiated for the specified side of the document
func countDidStartDocumentScan(for side: DocumentSide) {
switch side {
case .front:
numDocumentFrontScanAttempts += 1
case .back:
numDocumentBackScanAttempts += 1
}
}
/// Increments the number of times a scan was initiated for a selfie
func countDidStartSelfieScan() {
numSelfieScanAttempts += 1
}
private func logAnalytic(
_ eventName: EventName,
metadata: [String: Any]
) {
analyticsClient.log(
eventName: eventName.rawValue,
parameters: [
"verification_session": verificationSessionId,
"event_metadata": metadata,
]
)
}
/// Logs an event when the verification sheet is presented
func logSheetPresented() {
logAnalytic(
.sheetPresented,
metadata: [:]
)
}
/// Logs a closed, failed, or canceled analytic events, depending on the result
func logSheetClosedFailedOrCanceled(
result: IdentityVerificationSheet.VerificationFlowResult,
sheetController: VerificationSheetControllerProtocol,
filePath: StaticString = #filePath,
line: UInt = #line
) {
switch result {
case .flowCompleted:
logSheetClosed(sessionResult: "flow_complete")
case .flowCanceled:
logVerificationCanceled(
sheetController: sheetController
)
logSheetClosed(sessionResult: "flow_canceled")
case .flowFailed(let error):
logVerificationFailed(
sheetController: sheetController,
error: error,
filePath: filePath,
line: line
)
}
}
/// Helper to create metadata common to both failed, canceled, and succeed analytic events
private func failedCanceledSucceededCommonMetadataPayload(
sheetController: VerificationSheetControllerProtocol
) -> [String: Any] {
var metadata: [String: Any] = [:]
if let idDocumentType = sheetController.collectedData.idDocumentType {
metadata["scan_type"] = idDocumentType.rawValue
}
if let verificationPage = try? sheetController.verificationPageResponse?.get() {
metadata["require_selfie"] = verificationPage.requirements.missing.contains(.face)
metadata["from_fallback_url"] = verificationPage.unsupportedClient
}
if let frontUploadMethod = sheetController.collectedData.idDocumentFront?.uploadMethod {
metadata["doc_front_upload_type"] = frontUploadMethod.rawValue
}
if let backUploadMethod = sheetController.collectedData.idDocumentBack?.uploadMethod {
metadata["doc_back_upload_type"] = backUploadMethod.rawValue
}
return metadata
}
/// Logs an event when the verification sheet is closed
private func logSheetClosed(sessionResult: String) {
logAnalytic(
.sheetClosed,
metadata: [
"session_result": sessionResult
]
)
}
/// Logs an event when verification sheet fails
private func logVerificationFailed(
sheetController: VerificationSheetControllerProtocol,
error: Error,
filePath: StaticString,
line: UInt
) {
var metadata = failedCanceledSucceededCommonMetadataPayload(
sheetController: sheetController
)
metadata["error"] = AnalyticsClientV2.serialize(
error: error,
filePath: filePath,
line: line
)
logAnalytic(.verificationFailed, metadata: metadata)
}
/// Logs an event when verification sheet is canceled
private func logVerificationCanceled(
sheetController: VerificationSheetControllerProtocol
) {
var metadata = failedCanceledSucceededCommonMetadataPayload(
sheetController: sheetController
)
if let lastScreen = sheetController.flowController.analyticsLastScreen {
metadata["last_screen_name"] = lastScreen.analyticsScreenName.rawValue
}
logAnalytic(.verificationCanceled, metadata: metadata)
}
/// Logs an event when verification sheet succeeds
func logVerificationSucceeded(
sheetController: VerificationSheetControllerProtocol
) {
var metadata = failedCanceledSucceededCommonMetadataPayload(
sheetController: sheetController
)
metadata["doc_front_retry_times"] = max(0, numDocumentFrontScanAttempts - 1)
metadata["doc_back_retry_times"] = max(0, numDocumentBackScanAttempts - 1)
metadata["selfie_retry_times"] = max(0, numSelfieScanAttempts - 1)
if let frontScore = sheetController.collectedData.frontDocumentScore {
metadata["doc_front_model_score"] = frontScore.value
}
if let backScore = sheetController.collectedData.idDocumentBack?.backScore {
metadata["doc_back_model_score"] = backScore.value
}
if let bestFaceScore = sheetController.collectedData.face?.bestFaceScore {
metadata["selfie_model_score"] = bestFaceScore.value
}
logAnalytic(.verificationSucceeded, metadata: metadata)
}
/// Logs an event when a screen is presented
func logScreenAppeared(
screenName: ScreenName,
sheetController: VerificationSheetControllerProtocol
) {
var metadata: [String: Any] = [
"screen_name": screenName.rawValue
]
if let idDocumentType = sheetController.collectedData.idDocumentType {
metadata["scan_type"] = idDocumentType.rawValue
}
logAnalytic(.screenAppeared, metadata: metadata)
}
/// Logs an event when a camera error occurs
func logCameraError(
sheetController: VerificationSheetControllerProtocol,
error: Error,
filePath: StaticString = #filePath,
line: UInt = #line
) {
var metadata: [String: Any] = [:]
if let idDocumentType = sheetController.collectedData.idDocumentType {
metadata["scan_type"] = idDocumentType.rawValue
}
metadata["error"] = AnalyticsClientV2.serialize(
error: error,
filePath: filePath,
line: line
)
logAnalytic(.cameraError, metadata: metadata)
}
/// Logs either a permission denied or granted event when the camera permissions are checked prior to starting a camera session
func logCameraPermissionsChecked(
sheetController: VerificationSheetControllerProtocol,
isGranted: Bool?
) {
var metadata: [String: Any] = [:]
if let idDocumentType = sheetController.collectedData.idDocumentType {
metadata["scan_type"] = idDocumentType.rawValue
}
let eventName: EventName =
(isGranted == true) ? .cameraPermissionGranted : .cameraPermissionDenied
logAnalytic(eventName, metadata: metadata)
}
/// Logs an event when document capture times out
func logDocumentCaptureTimeout(
idDocumentType: DocumentType,
documentSide: DocumentSide
) {
logAnalytic(
.documentCaptureTimeout,
metadata: [
"scan_type": idDocumentType.rawValue,
"side": documentSide.rawValue,
]
)
}
/// Logs an event when selfie capture times out
func logSelfieCaptureTimeout() {
logAnalytic(.selfieCaptureTimeout, metadata: [:])
}
// MARK: - Performance Events
/// Logs the a scan's average number of frames per seconds processed
func logAverageFramesPerSecond(
averageFPS: Double,
numFrames: Int,
scannerName: ScannerName
) {
logAnalytic(
.averageFPS,
metadata: [
"type": scannerName.rawValue,
"value": averageFPS,
"frames": numFrames,
]
)
}
/// Logs the average inference and post-processing times for every ML model used for one scan
func logModelPerformance(
mlModelMetricsTrackers: [MLDetectorMetricsTrackerProtocol]
) {
mlModelMetricsTrackers.forEach { metricsTracker in
// Cache values to avoid weakly capturing performanceTracker
let modelName = metricsTracker.modelName
metricsTracker.getPerformanceMetrics(completeOn: .main) { averageMetrics, numFrames in
guard numFrames > 0 else { return }
self.logModelPerformance(
modelName: modelName,
averageMetrics: averageMetrics,
numFrames: numFrames
)
}
}
}
/// Logs an ML model's average inference and post-process time during a scan
private func logModelPerformance(
modelName: String,
averageMetrics: MLDetectorMetricsTracker.Metrics,
numFrames: Int
) {
logAnalytic(
.modelPerformance,
metadata: [
"ml_model": modelName,
"inference": averageMetrics.inference.milliseconds,
"postprocess": averageMetrics.postProcess.milliseconds,
"frames": numFrames,
]
)
}
/// Logs the time it takes to upload an image along with its file size and compression quality
func logImageUpload(
idDocumentType: DocumentType?,
timeToUpload: TimeInterval,
compressionQuality: CGFloat,
fileId: String,
fileName: String,
fileSizeBytes: Int
) {
// NOTE: File size is logged in kB
var metadata: [String: Any] = [
"value": timeToUpload.milliseconds,
"id": fileId,
"compression_quality": compressionQuality,
"file_name": fileName,
"file_size": fileSizeBytes / 1024,
]
if let idDocumentType = idDocumentType {
metadata["scan_type"] = idDocumentType.rawValue
}
logAnalytic(.imageUpload, metadata: metadata)
}
/// Tracks the time when a user taps a button to continue to the next screen.
/// Should be followed by a call to `stopTrackingTimeToScreenAndLogIfNeeded`
/// when the next screen appears.
func startTrackingTimeToScreen(
from fromScreen: ScreenName?
) {
if timeToScreenStartTime != nil {
logGenericError(
error: IdentityAnalyticsClientError.timeToScreenAlreadyStarted(
alreadyStartedForScreen: timeToScreenFromScreen,
requestedForScreen: fromScreen
)
)
}
timeToScreenStartTime = Date()
timeToScreenFromScreen = fromScreen
}
/// Logs the time it takes for a screen to appear after the user takes an
/// action to proceed to the next screen in the flow.
/// If `startTrackingTimeToScreen` was not called before calling this method,
/// an analytic is not logged.
func stopTrackingTimeToScreenAndLogIfNeeded(to toScreen: ScreenName) {
let endTime = Date()
defer {
// Reset state properties
self.timeToScreenStartTime = nil
self.timeToScreenFromScreen = nil
}
// This method could be called unnecessarily from `viewDidAppear` in the
// case that the view controller was presenting another screen that was
// dismissed or the back button was used. Only log an analytic if there's
// `startTrackingTimeToScreen` was called.
guard let startTime = timeToScreenStartTime,
timeToScreenFromScreen != toScreen
else {
return
}
var metadata: [String: Any] = [
"value": endTime.timeIntervalSince(startTime).milliseconds,
"to_screen_name": toScreen.rawValue,
]
if let fromScreen = timeToScreenFromScreen {
metadata["from_screen_name"] = fromScreen.rawValue
}
logAnalytic(.timeToScreen, metadata: metadata)
}
// MARK: - Error Events
/// Logs when an error occurs.
func logGenericError(
error: Error,
filePath: StaticString = #filePath,
line: UInt = #line
) {
logAnalytic(
.genericError,
metadata: [
"error_details": AnalyticsClientV2.serialize(
error: error,
filePath: filePath,
line: line
)
]
)
}
}
| 7ec09d492e48eb6babf6b0e3914d3128 | 33.714286 | 131 | 0.631956 | false | false | false | false |
littlelightwang/firefox-ios | refs/heads/master | Extensions/ShareTo/InitialViewController.swift | mpl-2.0 | 2 | /* 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 Storage
let LastUsedShareDestinationsKey = "LastUsedShareDestinations"
@objc(InitialViewController)
class InitialViewController: UIViewController, ShareControllerDelegate
{
var shareDialogController: ShareDialogController!
var profile: Profile?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0.75, alpha: 0.65) // TODO: Is the correct color documented somewhere?
let accountManager = AccountProfileManager(loginCallback: { _ in () }, logoutCallback: { _ in () })
self.profile = accountManager.getAccount() // Or, eventually, a local-only one.
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in
if error == nil && item != nil {
dispatch_async(dispatch_get_main_queue()) {
self.presentShareDialog(item!)
}
} else {
self.extensionContext!.completeRequestReturningItems([], completionHandler: nil);
}
})
}
//
func shareControllerDidCancel(shareController: ShareDialogController)
{
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 0.0
}, completion: { (Bool) -> Void in
self.dismissShareDialog()
self.extensionContext!.completeRequestReturningItems([], completionHandler: nil);
})
}
func shareController(shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet)
{
setLastUsedShareDestinations(destinations)
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 0.0
}, completion: { (Bool) -> Void in
self.dismissShareDialog()
if destinations.containsObject(ShareDestinationReadingList) {
self.shareToReadingList(item)
}
if destinations.containsObject(ShareDestinationBookmarks) {
self.shareToBookmarks(item)
}
self.extensionContext!.completeRequestReturningItems([], completionHandler: nil);
})
}
//
func getLastUsedShareDestinations() -> NSSet {
if let destinations = NSUserDefaults.standardUserDefaults().objectForKey(LastUsedShareDestinationsKey) as? NSArray {
return NSSet(array: destinations)
}
return NSSet(object: ShareDestinationBookmarks)
}
func setLastUsedShareDestinations(destinations: NSSet) {
NSUserDefaults.standardUserDefaults().setObject(destinations.allObjects, forKey: LastUsedShareDestinationsKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
func presentShareDialog(item: ShareItem) {
shareDialogController = ShareDialogController()
shareDialogController.delegate = self
shareDialogController.item = item
shareDialogController.initialShareDestinations = getLastUsedShareDestinations()
self.addChildViewController(shareDialogController)
shareDialogController.view.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(shareDialogController.view)
// Setup constraints for the dialog. We keep the dialog centered with 16 points of padding on both
// sides. The dialog grows to max 380 points wide so that it does not look too big on landscape or
// iPad devices.
let views: NSDictionary = ["dialog": shareDialogController.view]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(16@751)-[dialog(<=380@1000)]-(16@751)-|",
options: NSLayoutFormatOptions.allZeros, metrics: nil, views: views))
let cx = NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)
cx.priority = 1000 // TODO: Why does UILayoutPriorityRequired give a linker error? SDK Bug?
view.addConstraint(cx)
view.addConstraint(NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
// Fade the dialog in
shareDialogController.view.alpha = 0.0
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 1.0
}, completion: nil)
}
func dismissShareDialog() {
shareDialogController.willMoveToParentViewController(nil)
shareDialogController.view.removeFromSuperview()
shareDialogController.removeFromParentViewController()
}
//
func shareToReadingList(item: ShareItem) {
// TODO: Discuss how to share to the (local) reading list
}
func shareToBookmarks(item: ShareItem) {
if profile != nil { // TODO: We need to properly deal with this.
profile!.bookmarks.shareItem(item)
}
}
}
| 810368624de3f98c8d41c70fc14169d6 | 40.384058 | 130 | 0.663456 | false | false | false | false |
firebase/firebase-ios-sdk | refs/heads/master | FirebaseSessions/Sources/Settings.swift | apache-2.0 | 1 | //
// Copyright 2022 Google LLC
//
// 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
/// Extends ApplicationInfoProtocol to string-format a combined appDisplayVersion and appBuildVersion
extension ApplicationInfoProtocol {
var synthesizedVersion: String { return "\(appDisplayVersion) (\(appBuildVersion))" }
}
/// Provides the APIs to access Settings and their configuration values
protocol SettingsProtocol {
func isCacheExpired(currentTime: Date) -> Bool
var sessionsEnabled: Bool { get }
var samplingRate: Double { get }
var sessionTimeout: TimeInterval { get }
}
class Settings: SettingsProtocol {
private static let cacheDurationSecondsDefault: TimeInterval = 60 * 60
private static let flagSessionsEnabled = "sessions_enabled"
private static let flagSamplingRate = "sampling_rate"
private static let flagSessionTimeout = "session_timeout"
private static let flagCacheDuration = "cache_duration"
private let cache: SettingsCacheClient
private let appInfo: ApplicationInfoProtocol
var sessionsEnabled: Bool {
guard let enabled = cache.cacheContent?[Settings.flagSessionsEnabled] as? Bool else {
return true
}
return enabled
}
var samplingRate: Double {
guard let rate = cache.cacheContent?[Settings.flagSamplingRate] as? Double else {
return 1.0
}
return rate
}
var sessionTimeout: TimeInterval {
guard let timeout = cache.cacheContent?[Settings.flagSessionTimeout] as? Double else {
return 30 * 60
}
return timeout
}
private var cacheDurationSeconds: TimeInterval {
guard let duration = cache.cacheContent?[Settings.flagCacheDuration] as? Double else {
return Settings.cacheDurationSecondsDefault
}
return duration
}
init(cache: SettingsCacheClient = SettingsCache(),
appInfo: ApplicationInfoProtocol) {
self.cache = cache
self.appInfo = appInfo
}
func isCacheExpired(currentTime: Date) -> Bool {
guard cache.cacheContent != nil else {
cache.removeCache()
return true
}
guard let cacheKey = cache.cacheKey else {
Logger.logError("[Settings] Could not load settings cache key")
cache.removeCache()
return true
}
guard cacheKey.googleAppID == appInfo.appID else {
Logger
.logDebug("[Settings] Cache expired because Google App ID changed")
cache.removeCache()
return true
}
if currentTime.timeIntervalSince(cacheKey.createdAt) > cacheDurationSeconds {
Logger.logDebug("[Settings] Cache TTL expired")
return true
}
if appInfo.synthesizedVersion != cacheKey.appVersion {
Logger.logDebug("[Settings] Cache expired because app version changed")
return true
}
return false
}
}
| b5e88bda0d342de5fe63342b5d09b212 | 31.68 | 101 | 0.723072 | false | false | false | false |
inacioferrarini/York | refs/heads/master | Classes/DeepLinkingNavigation/NavigationRouter.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// 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 JLRoutes
import UIKit
open class NavigationRouter: NSObject {
open let router: JLRoutes
open let schema: String
open let logger: Logger
public init(router: JLRoutes, schema: String, logger: Logger) {
self.router = router
self.schema = schema
self.logger = logger
super.init()
}
public convenience init(schema: String, logger: Logger) {
self.init(router: JLRoutes(forScheme: schema), schema: schema, logger: logger)
}
open func registerRoutes(_ appRoutes: [RoutingElement]) {
for r: RoutingElement in appRoutes {
self.router.addRoute(r.path.absoluteString(), handler: r.handler)
}
}
open func dispatch(_ url: URL) -> Bool {
let result = self.router.canRouteURL(url)
if result {
self.router.routeURL(url)
}
return result
}
open func navigateInternal(_ targetUrl: String) {
let completeUrl = URL(string: "\(self.schema):/\(targetUrl)")
if let url = completeUrl {
UIApplication.shared.openURL(url)
}
}
open func navigateExternal(_ targetUrl: String) {
let completeUrl = URL(string: targetUrl)
if let url = completeUrl {
UIApplication.shared.openURL(url)
}
}
}
| d94e1dd36d5008994986577a75191cac | 33.902778 | 86 | 0.665738 | false | false | false | false |
gardenm/SavageCanvas | refs/heads/master | SavageCanvas/SavageCanvas/Image.swift | mit | 1 | //
// Image.swift
// SavageCanvas
//
// Created by Matthew Garden on 2016-10-11.
// Copyright © 2016 Savagely Optimized. All rights reserved.
//
import Foundation
import ImageIO
import MobileCoreServices
extension Sequence where Iterator.Element == Renderable {
func renderToImage(size: CGSize) -> UIImage? {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
UIColor.clear.set()
UIRectFill(rect)
self.forEach { $0.render() }
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
public extension CanvasView {
public func renderToImage() -> UIImage? {
return self.drawableObjects.renderToImage(size: self.frame.size)
}
public func renderToImageSequence() -> [UIImage] {
let size = self.frame.size
var images: [UIImage] = []
for i in 0 ..< self.drawableObjects.count {
if let image = self.drawableObjects[0...i].renderToImage(size: size) {
images.append(image)
}
}
if !images.isEmpty, let blankImage = UIImage.image(color: .clear, size: size) {
images.insert(blankImage, at: 0)
}
return images
}
}
public extension UIImage {
internal class func image(color: UIColor, size: CGSize) -> UIImage? {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.set()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public func writeToTemporaryURL() throws -> URL {
let url = URL(fileURLWithPath: NSTemporaryDirectory())
return try self.write(toFileAtDirectoryURL: url)
}
public func write(toFileAtDirectoryURL url: URL) throws -> URL {
guard let fileName = (ProcessInfo.processInfo.globallyUniqueString as NSString).appendingPathExtension("png") else {
throw SavageCanvasError.imageCreation(url: url)
}
let fileURL = url.appendingPathComponent(fileName)
try self.write(to: fileURL)
return fileURL
}
public func write(to url: URL) throws {
let data = UIImagePNGRepresentation(self)
try data?.write(to: url)
}
}
public extension Collection where Iterator.Element == UIImage {
public func writeToTemporaryURL() throws -> URL {
let url = URL(fileURLWithPath: NSTemporaryDirectory())
return try self.write(toFileAtDirectoryURL: url)
}
public func write(toFileAtDirectoryURL url: URL) throws -> URL {
guard let fileName = (ProcessInfo.processInfo.globallyUniqueString as NSString).appendingPathExtension("png") else {
throw SavageCanvasError.imageCreation(url: url)
}
let fileURL = url.appendingPathComponent(fileName)
try self.write(to: fileURL)
return fileURL
}
public func write(to url: URL) throws {
let frameDelay: TimeInterval = 0.2
let innerFileProperties = [kCGImagePropertyAPNGLoopCount as String: 0 as NSNumber]
let fileProperties = [kCGImagePropertyPNGDictionary as String: innerFileProperties]
let innerFrameProperties = [kCGImagePropertyAPNGDelayTime as String: frameDelay as NSNumber]
let frameProperties = [kCGImagePropertyPNGDictionary as String: innerFrameProperties]
let count: Int = Int(self.count.toIntMax())
guard let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypePNG, count, nil) else {
throw SavageCanvasError.imageCreation(url: url)
}
CGImageDestinationSetProperties(destination, fileProperties as CFDictionary)
self.flatMap { $0.cgImage }.forEach {
CGImageDestinationAddImage(destination, $0, frameProperties as CFDictionary)
}
if !CGImageDestinationFinalize(destination) {
throw SavageCanvasError.imageFinalization
}
}
}
| 1ba764333583351e846d5d19ab071f1b | 29.217687 | 124 | 0.619541 | false | false | false | false |
tamasoszko/sandbox-ios | refs/heads/master | NetBank/NetBank/WebViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// NetBank
//
// Created by Oszkó Tamás on 29/03/15.
// Copyright (c) 2015 TamasO. All rights reserved.
//
import UIKit
import LocalAuthentication
class WebViewController: UIViewController, UIWebViewDelegate, WebView {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var backButton: UIBarButtonItem!
@IBOutlet weak var forwardButton: UIBarButtonItem!
@IBOutlet weak var refreshButton: UIBarButtonItem!
@IBOutlet weak var homeButton: UIBarButtonItem!
weak var appDelegate : AppDelegate!
weak var delegate : WebViewDelegate!
weak var controller : WebController!
let loginUrl = NSURL(string:"https://www.otpbank.hu/portal/hu/OTPdirekt/Belepes")
override func viewDidLoad() {
super.viewDidLoad()
self.webView.delegate = self
self.webView.scalesPageToFit = true
self.appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate!
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateUserInterface()
self.delegate.webViewWillAppear(self)
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
self.delegate.webView(self, willStarLoadingWithRequest: request)
return true
}
func webViewDidFinishLoad(webView: UIWebView) {
self.delegate.webViewDidFinishLoading(self)
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
self.delegate.webView(self, didFailLoading: error!)
}
// func isLoginPage() -> Bool {
// if self.lastRequest?.URL == loginUrl {
// return true
// }
// return false
// }
@IBAction func backButtonTapped(sender: AnyObject) {
self.webView.goBack()
}
@IBAction func forwardButtonTapped(sender: AnyObject) {
self.webView.goForward()
}
@IBAction func settingsButtonTapped(sender: AnyObject) {
self.appDelegate.workflow.startSettingsEdit()
}
@IBAction func reloadButtonTapped(sender: AnyObject) {
self.webView.reload()
}
@IBAction func homeButtonTapped(sender: AnyObject) {
self.controller.logout { () -> Void in
self.controller.loadLoginPage()
}
}
func fillAccountNumber(accountNumber: NSString) {
dispatch_async(dispatch_get_main_queue()) {
let ret = self.webView.stringByEvaluatingJavaScriptFromString("document.getElementById('hb_szamlaszam').value='\(accountNumber)'")
print("JS returned=\(ret)")
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showSettings" {
}
}
// MARK: - WebView
func load(url: NSURL) {
self.webView.loadRequest(NSURLRequest(URL: url))
}
func updateUserInterface() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = self.webView.loading
self.backButton.enabled = self.webView.canGoBack
self.forwardButton.enabled = self.webView.canGoForward
self.refreshButton.enabled = !self.webView.loading
self.homeButton.enabled = !self.webView.loading
if self.webView.loading {
self.title = self.controller.lastRequest?.URL!.absoluteString
} else {
if let title = self.webView.stringByEvaluatingJavaScriptFromString("document.title") {
self.title = title
} else {
self.title = ""
}
}
}
func goBack() {
self.webView.goBack()
}
func goForward() {
self.webView.goForward()
}
func reload() {
self.webView.reload()
}
func showError(error: NSError) {
guard error.code != NSURLError.Cancelled.rawValue else {
return
}
UIAlertView(title: error.localizedDescription, message: error.localizedRecoverySuggestion, delegate: nil, cancelButtonTitle: "OK").show()
}
func executeJavaSrcipt(javaSrcipt: String) -> String? {
return self.webView.stringByEvaluatingJavaScriptFromString(javaSrcipt)
}
}
| aa247b3e5bc798ab8229951b566e81a7 | 30.172662 | 145 | 0.646204 | false | false | false | false |
mikekavouras/Glowb-iOS | refs/heads/master | Glowb/Transforms/RubyDateTransform.swift | mit | 1 | //
// RubyDateTransform.swift
// Glowb
//
// Created by Michael Kavouras on 12/20/16.
// Copyright © 2016 Michael Kavouras. All rights reserved.
//
import ObjectMapper
struct RubyDateTransform: TransformType {
func transformFromJSON(_ value: Any?) -> Date? {
guard let date = value as? String else {
return nil
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
return formatter.date(from: date)
}
func transformToJSON(_ value: Date?) -> String? {
guard let date = value else { return nil }
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return formatter.string(from: date as Date)
}
}
| 10917d0cea5d6c377ef1c3582d6205c6 | 27.566667 | 65 | 0.612602 | false | false | false | false |
MozzazIncorporation/cordova-plugin-iosrtc | refs/heads/master | src/PluginRTCPeerConnectionConstraints.swift | mit | 1 | import Foundation
class PluginRTCPeerConnectionConstraints {
fileprivate var constraints: RTCMediaConstraints
init(pcConstraints: NSDictionary?) {
NSLog("PluginRTCPeerConnectionConstraints#init()")
if pcConstraints == nil {
self.constraints = RTCMediaConstraints()
return
}
var offerToReceiveAudio = pcConstraints?.object(forKey: "offerToReceiveAudio") as? Bool
var offerToReceiveVideo = pcConstraints?.object(forKey: "offerToReceiveVideo") as? Bool
if offerToReceiveAudio == nil && offerToReceiveVideo == nil {
self.constraints = RTCMediaConstraints()
return
}
if offerToReceiveAudio == nil {
offerToReceiveAudio = false
}
if offerToReceiveVideo == nil {
offerToReceiveVideo = false
}
NSLog("PluginRTCPeerConnectionConstraints#init() | [offerToReceiveAudio:%@, offerToReceiveVideo:%@]",
String(offerToReceiveAudio!), String(offerToReceiveVideo!))
self.constraints = RTCMediaConstraints(
mandatoryConstraints: [
RTCPair(key: "OfferToReceiveAudio", value: offerToReceiveAudio == true ? "true" : "false"),
RTCPair(key: "OfferToReceiveVideo", value: offerToReceiveVideo == true ? "true" : "false")
],
optionalConstraints: []
)
}
deinit {
NSLog("PluginRTCPeerConnectionConstraints#deinit()")
}
func getConstraints() -> RTCMediaConstraints {
NSLog("PluginRTCPeerConnectionConstraints#getConstraints()")
return self.constraints
}
}
| 2de3aae37439e9eb4a36ded935f68f1f | 24.836364 | 103 | 0.741027 | false | false | false | false |
newlix/swift-syncable-api | refs/heads/master | Tests/MergeTests.swift | mit | 1 | import XCTest
import LessMock
import SyncableAPI
class MergeTests: XCTestCase {
var mock:LessMock!
override func setUp() {
super.setUp()
mock = try! LessMock(URLString: lessMockServiceURLString)
clearBeforeTesting()
SyncableAPI.initialize(mock.URLString)
}
override func tearDown() {
super.tearDown()
}
func testMethodAndPath() {
try! mock.enqueueResponse(json: [[ "id": "fake" ]])
try! merge("Fake", objects: [[ "id": "fake" ]])
let request = try! mock.receivedRequests().first!
try! mock.verify()
XCTAssertEqual(request.path, "/Fake")
XCTAssertEqual(request.method, "POST")
}
func testPOSTBody() {
try! mock.enqueueResponse(json: [[ "id": "fake" ]])
try! merge("Fake", objects: [[ "id": "fake" ]])
let request = try! mock.receivedRequests().first!
try! mock.verify()
let objects = request.json as! [[String:AnyObject]]
let id = objects.first!["id"] as! String
XCTAssertEqual(id, "fake")
}
func testReturnUpdateds() {
try! mock.enqueueResponse(json: [[ "id": "fake", "up":"updated"]])
let updateds = try! merge("Fake", objects: [[ "id": "fake" ]])
try! mock.verify()
XCTAssertEqual((updateds.first!["up"] as! String), "updated")
}
func testInvalidReponseType() {
try! mock.enqueueResponse(json: ["bad1"])
do {
try merge("Fake", objects: [[ "id": "fake" ]])
XCTFail()
} catch {
}
}
func testHTTPError() {
try! mock.enqueueResponse(json: [], status: 500)
do {
try merge("Fake", objects: [[ "id": "fake" ]])
XCTFail()
} catch {
}
}
}
| bf28c293677f2605f6ab23c384b71af9 | 27.65625 | 74 | 0.535987 | false | true | false | false |
cassandrakane-minted/swipeFavoriteMintedArtMobileApp2 | refs/heads/master | Pod/Classes/KolodaView/KolodaView.swift | mit | 1 | //
// KolodaView.swift
// Koloda
//
// Created by Eugene Andreyev on 4/24/15.
// Copyright (c) 2015 Eugene Andreyev. All rights reserved.
//
import UIKit
import pop
//Default values
private let defaultCountOfVisibleCards = 3
private let defaultBackgroundCardsTopMargin: CGFloat = 4.0
private let defaultBackgroundCardsScalePercent: CGFloat = 0.95
private let defaultBackgroundCardsLeftMargin: CGFloat = 8.0
private let defaultBackgroundCardFrameAnimationDuration: NSTimeInterval = 0.2
//Opacity values
private let defaultAlphaValueOpaque: CGFloat = 1.0
private let defaultAlphaValueTransparent: CGFloat = 0.0
private let defaultAlphaValueSemiTransparent: CGFloat = 0.7
public protocol KolodaViewDataSource:class {
func kolodaNumberOfCards(koloda: KolodaView) -> UInt
func koloda(koloda: KolodaView, viewForCardAtIndex index: UInt) -> UIView
func koloda(koloda: KolodaView, viewForCardOverlayAtIndex index: UInt) -> OverlayView?
}
public extension KolodaViewDataSource {
func koloda(koloda: KolodaView, viewForCardOverlayAtIndex index: UInt) -> OverlayView? {
return nil
}
}
public protocol KolodaViewDelegate:class {
func koloda(koloda: KolodaView, allowedDirectionsForIndex index: UInt) -> [SwipeResultDirection]
func koloda(koloda: KolodaView, shouldSwipeCardAtIndex index: UInt, inDirection direction: SwipeResultDirection) -> Bool
func koloda(koloda: KolodaView, didSwipeCardAtIndex index: UInt, inDirection direction: SwipeResultDirection)
func kolodaDidRunOutOfCards(koloda: KolodaView)
func koloda(koloda: KolodaView, didSelectCardAtIndex index: UInt)
func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool
func kolodaShouldMoveBackgroundCard(koloda: KolodaView) -> Bool
func kolodaShouldTransparentizeNextCard(koloda: KolodaView) -> Bool
func koloda(koloda: KolodaView, draggedCardWithPercentage finishPercentage: CGFloat, inDirection direction: SwipeResultDirection)
func kolodaDidResetCard(koloda: KolodaView)
func kolodaSwipeThresholdRatioMargin(koloda: KolodaView) -> CGFloat?
func koloda(koloda: KolodaView, didShowCardAtIndex index: UInt)
func koloda(koloda: KolodaView, shouldDragCardAtIndex index: UInt ) -> Bool
}
public extension KolodaViewDelegate {
func koloda(koloda: KolodaView, shouldSwipeCardAtIndex index: UInt, inDirection direction: SwipeResultDirection) -> Bool { return true }
func koloda(koloda: KolodaView, allowedDirectionsForIndex index: UInt) -> [SwipeResultDirection] { return [.Left, .Right, .Up] }
func koloda(koloda: KolodaView, didSwipeCardAtIndex index: UInt, inDirection direction: SwipeResultDirection) {}
func kolodaDidRunOutOfCards(koloda: KolodaView) {}
func koloda(koloda: KolodaView, didSelectCardAtIndex index: UInt) {}
func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool { return true }
func kolodaShouldMoveBackgroundCard(koloda: KolodaView) -> Bool { return true }
func kolodaShouldTransparentizeNextCard(koloda: KolodaView) -> Bool { return true }
func koloda(koloda: KolodaView, draggedCardWithPercentage finishPercentage: CGFloat, inDirection direction: SwipeResultDirection) {}
func kolodaDidResetCard(koloda: KolodaView) {}
func kolodaSwipeThresholdRatioMargin(koloda: KolodaView) -> CGFloat? { return nil}
func koloda(koloda: KolodaView, didShowCardAtIndex index: UInt) {}
func koloda(koloda: KolodaView, shouldDragCardAtIndex index: UInt ) -> Bool { return true }
}
public class KolodaView: UIView, DraggableCardDelegate {
//Opacity values
public var alphaValueOpaque = defaultAlphaValueOpaque
public var alphaValueTransparent = defaultAlphaValueTransparent
public var alphaValueSemiTransparent = defaultAlphaValueSemiTransparent
public var shouldPassthroughTapsWhenNoVisibleCards = false
public weak var dataSource: KolodaViewDataSource? {
didSet {
setupDeck()
}
}
public weak var delegate: KolodaViewDelegate?
public lazy var animator: KolodaViewAnimator = {
return KolodaViewAnimator(koloda: self)
}()
internal var animating = false
internal var shouldTransparentizeNextCard: Bool {
return delegate?.kolodaShouldTransparentizeNextCard(self) ?? true
}
private(set) public var currentCardIndex = 0
private(set) public var countOfCards = 0
public var countOfVisibleCards = defaultCountOfVisibleCards
private var visibleCards = [DraggableCardView]()
override public func layoutSubviews() {
super.layoutSubviews()
if !animating {
layoutDeck()
}
}
//MARK: Configurations
private func setupDeck() {
if let dataSource = dataSource {
countOfCards = Int(dataSource.kolodaNumberOfCards(self))
if countOfCards - currentCardIndex > 0 {
let countOfNeededCards = min(countOfVisibleCards, countOfCards - currentCardIndex)
for index in 0..<countOfNeededCards {
let actualIndex = UInt(index + currentCardIndex)
let nextCardView = createCardAtIndex(actualIndex)
let isTop = index == 0
nextCardView.userInteractionEnabled = isTop
nextCardView.alpha = alphaValueOpaque
if shouldTransparentizeNextCard && !isTop {
nextCardView.alpha = 0
}
visibleCards.append(nextCardView)
isTop ? addSubview(nextCardView) : insertSubview(nextCardView, belowSubview: visibleCards[index - 1])
}
self.delegate?.koloda(self, didShowCardAtIndex: UInt(currentCardIndex))
}
}
}
public func layoutDeck() {
for (index, card) in visibleCards.enumerate() {
layoutCard(card, atIndex: UInt(index))
}
}
private func layoutCard(card: DraggableCardView, atIndex index: UInt) {
if index == 0 {
card.layer.transform = CATransform3DIdentity
card.frame = frameForTopCard()
} else {
let cardParameters = backgroundCardParametersForFrame(frameForCardAtIndex(UInt(index)))
let scale = cardParameters.scale
card.layer.transform = CATransform3DScale(CATransform3DIdentity, scale.width, scale.height, 1.0)
card.frame = cardParameters.frame
}
}
//MARK: Frames
public func frameForCardAtIndex(index: UInt) -> CGRect {
let bottomOffset:CGFloat = 0
let topOffset = defaultBackgroundCardsTopMargin * CGFloat(countOfVisibleCards - 1)
let scalePercent = defaultBackgroundCardsScalePercent
let width = CGRectGetWidth(self.frame) * pow(scalePercent, CGFloat(index))
let xOffset = (CGRectGetWidth(self.frame) - width) / 2
let height = (CGRectGetHeight(self.frame) - bottomOffset - topOffset) * pow(scalePercent, CGFloat(index))
let multiplier: CGFloat = index > 0 ? 1.0 : 0.0
let previousCardFrame = index > 0 ? frameForCardAtIndex(max(index - 1, 0)) : CGRectZero
let yOffset = (CGRectGetHeight(previousCardFrame) - height + previousCardFrame.origin.y + defaultBackgroundCardsTopMargin) * multiplier
let frame = CGRect(x: xOffset, y: yOffset, width: width, height: height)
return frame
}
internal func frameForTopCard() -> CGRect {
return frameForCardAtIndex(0)
}
internal func backgroundCardParametersForFrame(initialFrame: CGRect) -> (frame: CGRect, scale: CGSize) {
var finalFrame = frameForTopCard()
finalFrame.origin = initialFrame.origin
var scale = CGSize.zero
scale.width = initialFrame.width / finalFrame.width
scale.height = initialFrame.height / finalFrame.height
return (finalFrame, scale)
}
internal func moveOtherCardsWithPercentage(percentage: CGFloat) {
if visibleCards.count > 1 {
for index in 1..<visibleCards.count {
let previousCardFrame = frameForCardAtIndex(UInt(index - 1))
var frame = frameForCardAtIndex(UInt(index))
let fraction = percentage / 100
let distanceToMoveY: CGFloat = (frame.origin.y - previousCardFrame.origin.y) * fraction
frame.origin.y -= distanceToMoveY
let distanceToMoveX: CGFloat = (previousCardFrame.origin.x - frame.origin.x) * fraction
frame.origin.x += distanceToMoveX
let widthDelta = (previousCardFrame.size.width - frame.size.width) * fraction
let heightDelta = (previousCardFrame.size.height - frame.size.height) * fraction
frame.size.width += widthDelta
frame.size.height += heightDelta
let cardParameters = backgroundCardParametersForFrame(frame)
let scale = cardParameters.scale
let card = visibleCards[index]
card.layer.transform = CATransform3DScale(CATransform3DIdentity, scale.width, scale.height, 1.0)
card.frame = cardParameters.frame
//For fully visible next card, when moving top card
if shouldTransparentizeNextCard {
if index == 1 {
card.alpha = 0
}
}
}
}
}
//MARK: Animations
private func applyAppearAnimation() {
alpha = 0
userInteractionEnabled = false
animating = true
animator.animateAppearanceWithCompletion { [weak self] _ in
self?.userInteractionEnabled = true
self?.animating = false
}
}
public func applyAppearAnimationIfNeeded() {
if let shouldApply = delegate?.kolodaShouldApplyAppearAnimation(self) where shouldApply == true {
applyAppearAnimation()
}
}
//MARK: DraggableCardDelegate
func card(card: DraggableCardView, wasDraggedWithFinishPercentage percentage: CGFloat, inDirection direction: SwipeResultDirection) {
animating = true
if let shouldMove = delegate?.kolodaShouldMoveBackgroundCard(self) where shouldMove {
self.moveOtherCardsWithPercentage(percentage)
}
delegate?.koloda(self, draggedCardWithPercentage: percentage, inDirection: direction)
}
func card(card: DraggableCardView, shouldSwipeInDirection direction: SwipeResultDirection) -> Bool {
return delegate?.koloda(self, shouldSwipeCardAtIndex: UInt(self.currentCardIndex), inDirection: direction) ?? true
}
func card(cardAllowedDirections card: DraggableCardView) -> [SwipeResultDirection] {
let index = currentCardIndex + visibleCards.indexOf(card)!
return delegate?.koloda(self, allowedDirectionsForIndex: UInt(index)) ?? [.Left, .Right, .Up]
}
func card(card: DraggableCardView, wasSwipedInDirection direction: SwipeResultDirection) {
swipedAction(direction)
}
func card(cardWasReset card: DraggableCardView) {
if visibleCards.count > 1 {
animating = true
animator.resetBackgroundCardsWithCompletion { [weak self] _ in
guard let _self = self else {
return
}
_self.animating = false
for index in 1..<_self.visibleCards.count {
let card = _self.visibleCards[index]
if _self.shouldTransparentizeNextCard {
card.alpha = 0
}
}
}
} else {
animating = false
}
delegate?.kolodaDidResetCard(self)
}
func card(cardWasTapped card: DraggableCardView) {
guard let visibleIndex = visibleCards.indexOf(card) else { return }
let index = currentCardIndex + visibleIndex
delegate?.koloda(self, didSelectCardAtIndex: UInt(index))
}
func card(cardSwipeThresholdRatioMargin card: DraggableCardView) -> CGFloat? {
return delegate?.kolodaSwipeThresholdRatioMargin(self)
}
func card(cardShouldDrag card: DraggableCardView) -> Bool {
guard let visibleIndex = visibleCards.indexOf(card) else { return true}
let index = currentCardIndex + visibleIndex
return delegate?.koloda(self, shouldDragCardAtIndex: UInt(index)) ?? true
}
//MARK: Private
private func clear() {
currentCardIndex = 0
for card in visibleCards {
card.removeFromSuperview()
}
visibleCards.removeAll(keepCapacity: true)
}
//MARK: Actions
private func swipedAction(direction: SwipeResultDirection) {
animating = true
visibleCards.removeFirst()
currentCardIndex += 1
let shownCardsCount = currentCardIndex + countOfVisibleCards
if shownCardsCount - 1 < countOfCards {
loadNextCard()
}
if !visibleCards.isEmpty {
animateCardsAfterLoadingWithCompletion { [weak self] in
guard let _self = self else {
return
}
_self.visibleCards.last?.hidden = false
_self.animating = false
_self.delegate?.koloda(_self, didSwipeCardAtIndex: UInt(_self.currentCardIndex - 1), inDirection: direction)
_self.delegate?.koloda(_self, didShowCardAtIndex: UInt(_self.currentCardIndex))
}
} else {
animating = false
delegate?.koloda(self, didSwipeCardAtIndex: UInt(self.currentCardIndex - 1), inDirection: direction)
delegate?.kolodaDidRunOutOfCards(self)
}
}
private func loadNextCard() {
guard dataSource != nil else {
return
}
let cardParameters = backgroundCardParametersForFrame(frameForCardAtIndex(UInt(visibleCards.count)))
let lastCard = createCardAtIndex(UInt(currentCardIndex + countOfVisibleCards - 1), frame: cardParameters.frame)
let scale = cardParameters.scale
lastCard.layer.transform = CATransform3DScale(CATransform3DIdentity, scale.width, scale.height, 1)
lastCard.hidden = true
lastCard.userInteractionEnabled = true
if let card = visibleCards.last {
insertSubview(lastCard, belowSubview: card)
} else {
addSubview(lastCard)
}
visibleCards.append(lastCard)
}
private func animateCardsAfterLoadingWithCompletion(completion: (Void -> Void)? = nil) {
for (index, currentCard) in visibleCards.enumerate() {
currentCard.removeAnimations()
currentCard.userInteractionEnabled = index == 0
let cardParameters = backgroundCardParametersForFrame(frameForCardAtIndex(UInt(index)))
var animationCompletion: ((Bool) -> Void)? = nil
if index != 0 {
if shouldTransparentizeNextCard {
currentCard.alpha = 0
}
} else {
animationCompletion = { finished in
completion?()
}
if shouldTransparentizeNextCard {
animator.applyAlphaAnimation(currentCard, alpha: alphaValueOpaque)
} else {
currentCard.alpha = alphaValueOpaque
}
}
animator.applyScaleAnimation(
currentCard,
scale: cardParameters.scale,
frame: cardParameters.frame,
duration: defaultBackgroundCardFrameAnimationDuration,
completion: animationCompletion
)
}
}
public func revertAction() {
if currentCardIndex > 0 && !animating {
if countOfCards - currentCardIndex >= countOfVisibleCards {
if let lastCard = visibleCards.last {
lastCard.removeFromSuperview()
visibleCards.removeLast()
}
}
currentCardIndex -= 1
if dataSource != nil {
let firstCardView = createCardAtIndex(UInt(currentCardIndex), frame: frameForTopCard())
if shouldTransparentizeNextCard {
firstCardView.alpha = 0
}
firstCardView.delegate = self
addSubview(firstCardView)
visibleCards.insert(firstCardView, atIndex: 0)
animating = true
animator.applyReverseAnimation(firstCardView, completion: { [weak self] _ in
guard let _self = self else {
return
}
_self.animating = false
_self.delegate?.koloda(_self, didShowCardAtIndex: UInt(_self.currentCardIndex))
})
}
for (index, card) in visibleCards.dropFirst().enumerate() {
if shouldTransparentizeNextCard {
card.alpha = 0
}
card.userInteractionEnabled = false
let cardParameters = backgroundCardParametersForFrame(frameForCardAtIndex(UInt(index + 1)))
animator.applyScaleAnimation(
card,
scale: cardParameters.scale,
frame: cardParameters.frame,
duration: defaultBackgroundCardFrameAnimationDuration,
completion: nil
)
}
}
}
private func loadMissingCards(missingCardsCount: Int) {
if missingCardsCount > 0 {
let cardsToAdd = min(missingCardsCount, countOfCards - currentCardIndex)
let startIndex = visibleCards.count
let endIndex = startIndex + cardsToAdd - 1
for index in startIndex...endIndex {
let nextCardView = generateCard(frameForTopCard())
layoutCard(nextCardView, atIndex: UInt(index))
nextCardView.alpha = 0
visibleCards.append(nextCardView)
configureCard(nextCardView, atIndex: UInt(currentCardIndex + index))
insertSubview(nextCardView, belowSubview: visibleCards[index - 1])
}
}
}
private func reconfigureCards() {
if dataSource != nil {
for (index, card) in visibleCards.enumerate() {
let actualIndex = UInt(currentCardIndex + index)
configureCard(card, atIndex: actualIndex)
}
}
}
private func missingCardsCount() -> Int {
return min(countOfVisibleCards - visibleCards.count, countOfCards - (currentCardIndex + visibleCards.count))
}
// MARK: Public
public func reloadData() {
guard let numberOfCards = dataSource?.kolodaNumberOfCards(self) where numberOfCards > 0 else {
clear()
return
}
if currentCardIndex == 0 {
clear()
}
countOfCards = Int(numberOfCards)
if countOfCards - (currentCardIndex + visibleCards.count) > 0 {
if !visibleCards.isEmpty {
let missingCards = missingCardsCount()
loadMissingCards(missingCards)
} else {
setupDeck()
layoutDeck()
applyAppearAnimationIfNeeded()
}
} else {
reconfigureCards()
}
}
public func swipe(direction: SwipeResultDirection) {
let validDirection = delegate?.koloda(self, allowedDirectionsForIndex: UInt(currentCardIndex)).contains(direction) ?? true
guard validDirection else { return }
if !animating {
if let frontCard = visibleCards.first {
animating = true
if visibleCards.count > 1 {
let nextCard = visibleCards[1]
nextCard.alpha = 0
}
frontCard.swipe(direction)
frontCard.delegate = nil
}
}
}
public func resetCurrentCardIndex() {
clear()
reloadData()
}
public func viewForCardAtIndex(index: Int) -> UIView? {
if visibleCards.count + currentCardIndex > index && index >= currentCardIndex {
return visibleCards[index - currentCardIndex].contentView
} else {
return nil
}
}
public override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
if !shouldPassthroughTapsWhenNoVisibleCards {
return super.pointInside(point, withEvent: event)
}
return visibleCards.count > 0
}
// MARK: Cards managing - Insertion
private func insertVisibleCardsWithIndexes(visibleIndexes: [Int]) -> [DraggableCardView] {
var insertedCards: [DraggableCardView] = []
visibleIndexes.forEach { insertionIndex in
let card = createCardAtIndex(UInt(insertionIndex))
let visibleCardIndex = insertionIndex - currentCardIndex
visibleCards.insert(card, atIndex: visibleCardIndex)
if visibleCardIndex == 0 {
card.userInteractionEnabled = true
card.alpha = alphaValueOpaque
insertSubview(card, atIndex: visibleCards.count - 1)
} else {
card.userInteractionEnabled = false
card.alpha = 0
insertSubview(card, belowSubview: visibleCards[visibleCardIndex - 1])
}
layoutCard(card, atIndex: UInt(visibleCardIndex))
insertedCards.append(card)
}
return insertedCards
}
private func removeCards(cards: [DraggableCardView]) {
cards.forEach { card in
card.delegate = nil
card.removeFromSuperview()
}
}
private func removeCards(cards: [DraggableCardView], animated: Bool) {
visibleCards.removeLast()
if animated {
animator.applyRemovalAnimation(
cards,
completion: { _ in
self.removeCards(cards)
}
)
} else {
self.removeCards(cards)
}
}
public func insertCardAtIndexRange(indexRange: Range<Int>, animated: Bool = true) {
guard let dataSource = dataSource else {
return
}
let currentItemsCount = countOfCards
countOfCards = Int(dataSource.kolodaNumberOfCards(self))
let visibleIndexes = [Int](indexRange).filter { $0 >= currentCardIndex && $0 < currentCardIndex + countOfVisibleCards }
let insertedCards = insertVisibleCardsWithIndexes(visibleIndexes.sort())
let cardsToRemove = visibleCards.dropFirst(countOfVisibleCards).map { $0 }
removeCards(cardsToRemove, animated: animated)
animator.resetBackgroundCardsWithCompletion()
if animated {
animating = true
animator.applyInsertionAnimation(
insertedCards,
completion: { _ in
self.animating = false
}
)
}
assert(
currentItemsCount + indexRange.count == countOfCards,
"Cards count after update is not equal to data source count"
)
}
// MARK: Cards managing - Deletion
private func proceedDeletionInRange(range: Range<Int>) {
let deletionIndexes = [Int](range)
deletionIndexes.sort { $0 > $1 }.forEach { deletionIndex in
let visibleCardIndex = deletionIndex - currentCardIndex
let card = visibleCards[visibleCardIndex]
card.delegate = nil
card.swipe(.Right)
visibleCards.removeAtIndex(visibleCardIndex)
}
}
public func removeCardInIndexRange(indexRange: Range<Int>, animated: Bool) {
guard let dataSource = dataSource else {
return
}
animating = true
let currentItemsCount = countOfCards
countOfCards = Int(dataSource.kolodaNumberOfCards(self))
let visibleIndexes = [Int](indexRange).filter { $0 >= currentCardIndex && $0 < currentCardIndex + countOfVisibleCards }
if !visibleIndexes.isEmpty {
proceedDeletionInRange(visibleIndexes[0]...visibleIndexes[visibleIndexes.count - 1])
}
currentCardIndex -= Array(indexRange).filter { $0 < currentCardIndex }.count
loadMissingCards(missingCardsCount())
layoutDeck()
for (index, card) in visibleCards.enumerate() {
card.alpha = 0
card.userInteractionEnabled = index == 0
}
animating = false
assert(
currentItemsCount - indexRange.count == countOfCards,
"Cards count after update is not equal to data source count"
)
}
// MARK: Cards managing - Reloading
public func reloadCardsInIndexRange(indexRange: Range<Int>) {
guard dataSource != nil else {
return
}
let visibleIndexes = [Int](indexRange).filter { $0 >= currentCardIndex && $0 < currentCardIndex + countOfVisibleCards }
visibleIndexes.forEach { index in
let visibleCardIndex = index - currentCardIndex
if visibleCards.count > visibleCardIndex {
let card = visibleCards[visibleCardIndex]
configureCard(card, atIndex: UInt(index))
}
}
}
}
| ec3f392fd9d3ad394fd235d2ab24f1eb | 37.572052 | 143 | 0.603796 | false | false | false | false |
firebase/firebase-ios-sdk | refs/heads/master | FirebaseCombineSwift/Tests/Unit/Auth/SignInWithGameCenterTests.swift | apache-2.0 | 1 | // Copyright 2021 Google LLC
//
// 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 Combine
import XCTest
import FirebaseAuth
class SignInWithGameCenterTests: XCTestCase {
override class func setUp() {
FirebaseApp.configureForTests()
}
override class func tearDown() {
FirebaseApp.app()?.delete { success in
if success {
print("Shut down app successfully.")
} else {
print("💥 There was a problem when shutting down the app..")
}
}
}
fileprivate static let expectedAPIURL =
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/signInWithGameCenter?key=APIKEY"
fileprivate static let testAPI = "APIKEY"
fileprivate static let idTokenKey = "idToken"
fileprivate static let idToken = "IDTOKEN"
fileprivate static let refreshTokenKey = "refreshToken"
fileprivate static let refreshToken = "PUBLICKEYURL"
fileprivate static let localIDKey = "localId"
fileprivate static let localID = "LOCALID"
fileprivate static let playerIDKey = "playerId"
fileprivate static let playerID = "PLAYERID"
fileprivate static let approximateExpirationDateKey = "expiresIn"
fileprivate static let approximateExpirationDate = "3600"
fileprivate static let isNewUserKey = "isNewUser"
fileprivate static let isNewUser = true
fileprivate static let displayNameKey = "displayName"
fileprivate static let displayName = "DISPLAYNAME"
fileprivate static let publicKeyURLKey = "publicKeyUrl"
fileprivate static let publicKeyURL = "PUBLICKEYURL"
fileprivate static let signatureKey = "signature"
fileprivate static let signature = "AAAABBBBCCCC"
fileprivate static let saltKey = "salt"
fileprivate static let salt = "AAAA"
fileprivate static let timestampKey = "timestamp"
fileprivate static let timestamp: UInt64 = 12_345_678
fileprivate static let accessTokenKey = "idToken"
fileprivate static let accessToken = "ACCESSTOKEN"
class MockBackendRPCIssuer: NSObject, FIRAuthBackendRPCIssuer {
var requestURL: URL?
var requestData: Data?
var decodedRequest: [String: Any]?
var contentType: String?
var handler: FIRAuthBackendRPCIssuerCompletionHandler?
func asyncPostToURL(with requestConfiguration: FIRAuthRequestConfiguration, url URL: URL,
body: Data?, contentType: String,
completionHandler handler: @escaping FIRAuthBackendRPCIssuerCompletionHandler) {
requestURL = URL
if let body = body {
requestData = body
let json = try! JSONSerialization
.jsonObject(with: body, options: []) as! [String: Any]
decodedRequest = json
}
self.contentType = contentType
self.handler = handler
}
@discardableResult
func respond(withJSON JSON: [String: Any]) throws -> Data {
let data = try JSONSerialization.data(
withJSONObject: JSON,
options: JSONSerialization.WritingOptions.prettyPrinted
)
XCTAssertNotNil(handler)
handler?(data, nil)
return data
}
}
override func setUp() {
do {
try Auth.auth().signOut()
} catch {}
}
func testRequestResponseEncoding() {
// given
let RPCIssuer = MockBackendRPCIssuer()
FIRAuthBackend.setDefaultBackendImplementationWith(RPCIssuer)
let signature = Data(base64Encoded: Self.signature)!
let salt = Data(base64Encoded: Self.salt)!
let requestConfiguration = FIRAuthRequestConfiguration(apiKey: Self.testAPI, appID: "appID")!
let request = FIRSignInWithGameCenterRequest(
playerID: Self.playerID,
publicKeyURL: URL(string: Self.publicKeyURL)!,
signature: signature,
salt: salt,
timestamp: Self.timestamp,
displayName: Self.displayName,
requestConfiguration: requestConfiguration
)!
request.accessToken = Self.accessToken
var cancellables = Set<AnyCancellable>()
let signInWithGameCenterExpectation = expectation(description: "Sign in Game Center")
// when
FIRAuthBackend.signIn(withGameCenter: request)
.sink { completion in
switch completion {
case .finished:
print("Finished")
case let .failure(error):
XCTFail("💥 Something went wrong: \(error)")
}
} receiveValue: { response in
XCTAssertEqual(RPCIssuer.requestURL?.absoluteString, Self.expectedAPIURL)
XCTAssertNotNil(RPCIssuer.decodedRequest)
XCTAssertEqual(
RPCIssuer.decodedRequest?[Self.playerIDKey] as? String,
Self.playerID
)
XCTAssertEqual(
RPCIssuer.decodedRequest?[Self.publicKeyURLKey] as? String,
Self.publicKeyURL
)
XCTAssertEqual(
RPCIssuer.decodedRequest?[Self.signatureKey] as? String,
Self.signature
)
XCTAssertEqual(RPCIssuer.decodedRequest?[Self.saltKey] as? String, Self.salt)
XCTAssertEqual(
RPCIssuer.decodedRequest?[Self.timestampKey] as? UInt64,
Self.timestamp
)
XCTAssertEqual(
RPCIssuer.decodedRequest?[Self.accessTokenKey] as? String,
Self.accessToken
)
XCTAssertEqual(
RPCIssuer.decodedRequest?[Self.displayNameKey] as? String,
Self.displayName
)
XCTAssertNotNil(response)
XCTAssertEqual(response.idToken, Self.idToken)
XCTAssertEqual(response.refreshToken, Self.refreshToken)
XCTAssertEqual(response.localID, Self.localID)
XCTAssertEqual(response.playerID, Self.playerID)
XCTAssertEqual(response.isNewUser, Self.isNewUser)
XCTAssertEqual(response.displayName, Self.displayName)
signInWithGameCenterExpectation.fulfill()
}
.store(in: &cancellables)
let jsonDictionary: [String: Any] = [
"idToken": Self.idToken,
"refreshToken": Self.refreshToken,
"localId": Self.localID,
"playerId": Self.playerID,
"expiresIn": Self.approximateExpirationDate,
"isNewUser": Self.isNewUser,
"displayName": Self.displayName,
]
try! RPCIssuer.respond(withJSON: jsonDictionary)
// then
wait(for: [signInWithGameCenterExpectation], timeout: expectationTimeout)
}
}
| 357226cee455adc707d5d4761402026b | 34.240838 | 104 | 0.696479 | false | false | false | false |
zixun/ZXKit | refs/heads/master | Pod/Classes/core/ZXColor.swift | mit | 1 | //
// ZXColor.swift
// CocoaChinaPlus
//
// Created by user on 15/11/9.
// Copyright © 2015年 zixun. All rights reserved.
//
import Foundation
import UIKit
public func ZXColor(rgb:Int) -> UIColor {
return ZXColor(rgb, alpha: 1.0)
}
public func ZXColor(rgb:Int,alpha:CGFloat) ->UIColor {
let red: CGFloat = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
let green: CGFloat = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
let blue: CGFloat = CGFloat((rgb & 0x0000FF)) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
public func ZXColor(startColor:UIColor,endColor:UIColor,fraction:CGFloat) -> UIColor {
var startR: CGFloat = 0, startG: CGFloat = 0, startB: CGFloat = 0, startA: CGFloat = 0
startColor.getRed(&startR, green: &startG, blue: &startB, alpha: &startA)
var endR: CGFloat = 0, endG: CGFloat = 0, endB: CGFloat = 0, endA: CGFloat = 0
endColor.getRed(&endR, green: &endG, blue: &endB, alpha: &endA)
let resultA = startA + (endA - startA) * fraction
let resultR = startR + (endR - startR) * fraction
let resultG = startG + (endG - startG) * fraction
let resultB = startB + (endB - startB) * fraction
return UIColor(red: resultR, green: resultG, blue: resultB, alpha: resultA)
} | 7a29cd61434b4db4558d8697eb35b72d | 33.459459 | 90 | 0.655416 | false | false | false | false |
jubinjacob19/CustomCalendarSwift | refs/heads/master | SampleCalendar/NoteViewController.swift | mit | 1 | //
// NoteViewController.swift
// SampleCalendar
//
// Created by ram on 03/07/15.
// Copyright (c) 2015 XYZ. All rights reserved.
//
import UIKit
enum TagColors{
case Green
case Blue
case Red
case Gray
static let allColors : [TagColors] = [Green,Blue,Red,Gray]
var color : UIColor? {
get {
switch(self){
case .Green : return UIColor.greenColor()
case .Blue : return UIColor.blueColor()
case .Red : return UIColor.redColor()
case .Gray : return UIColor.grayColor()
}
}
}
}
class NoteViewController: UIViewController,UITextFieldDelegate,TagButtonDelegate,UITextViewDelegate {
var date : NSDate?
var selectedTag : TagButton?
private var discardedNote : Bool = false
private var selectedColor : UIColor?
private var selectedNote : Note?
private lazy var titleField : UITextField = {
var textField = UITextField()
textField.placeholder = "Title"
textField.setTranslatesAutoresizingMaskIntoConstraints(false)
textField.textColor = UIColor.brownColor()
textField.font = UIFont(name: "Helvetica-Bold", size: 16)
textField.delegate = self
return textField
}()
private var dateFormatter : NSDateFormatter = {
let dateFmtr = NSDateFormatter()
dateFmtr.dateFormat = "dd MMMM yyyy"
return dateFmtr
}()
private lazy var noteDescription : UITextView = {
var textView = UITextView()
textView.setTranslatesAutoresizingMaskIntoConstraints(false)
textView.textColor = UIColor.lightGrayColor()
textView.font = UIFont(name: "Helvetica", size: 14)
textView.text = "Note"
textView.delegate = self
return textView
}()
convenience init(date : NSDate){
self.init(nibName: nil, bundle: nil)
self.date = date
self.title = self.dateFormatter.stringFromDate(self.date!)
self.selectedNote = CoreDataManager.sharedInstance.getNote(self.date!).note
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder )
}
override func viewDidLoad() {
super.viewDidLoad()
let trashButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Trash, target: self, action: "discardNote")
self.navigationItem.rightBarButtonItem = trashButton
self.view.backgroundColor = UIColor.whiteColor()
self.addSubviews()
self.setLayoutConstraints()
// Do any additional setup after loading the view.
}
func addSubviews(){
self.view.addSubview(self.titleField)
self.view.addSubview(self.noteDescription)
self.titleField.becomeFirstResponder()
self.addTagOptions()
if(self.selectedNote != nil){
self.titleField.text = self.selectedNote?.title
self.noteDescription.text = self.selectedNote?.noteDescription
}
}
func setLayoutConstraints(){
self.view.addConstraint(NSLayoutConstraint(item: self.titleField, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 160))
self.view.addConstraint(NSLayoutConstraint(item: self.titleField, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 20))
self.view.addConstraint(NSLayoutConstraint(item: self.titleField, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 20))
self.view.addConstraint(NSLayoutConstraint(item: self.noteDescription, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.titleField, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10))
self.view.addConstraint(NSLayoutConstraint(item: self.noteDescription, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.titleField, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: -5))
self.view.addConstraint(NSLayoutConstraint(item: self.noteDescription, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.noteDescription, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 80))
}
func addTagOptions(){
for (index, value) in enumerate(TagColors.allColors){
var selected : Bool? = false
if(self.selectedNote == nil){
selected = (index == 0)
} else{
let color : UIColor = value.color!
var dbColor : UIColor? = self.selectedNote?.color as! UIColor!
selected = (color == dbColor)
}
let tagView : TagButton = TagButton(radius: 50, color: value.color!, isSelected: selected!, delegate : self)
if(selected == true){
self.selectedTag = tagView
self.selectedColor = value.color
}
self.view.addSubview(tagView)
self.view.addConstraint(NSLayoutConstraint(item: tagView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: CGFloat(50 * (index+1))))
self.view.addConstraint(NSLayoutConstraint(item: tagView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 80))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func selectedTagWthColor(color: UIColor, sender: TagButton) {
self.selectedTag?.markUnSelected()
self.selectedTag = sender
self.selectedColor = color
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return true
}
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
if(true){
textView.textColor = UIColor.blackColor()
textView.text = ""
}
return true
}
func textViewDidEndEditing(textView: UITextView) {
if(textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) == ""){
textView.textColor = UIColor.lightGrayColor()
textView.text = "Note"
}
}
func discardNote(){
self.discardedNote = true
self.navigationController?.popViewControllerAnimated(true)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if(self.isMovingFromParentViewController()){
if(!self.discardedNote){
if(self.selectedNote != nil){
CoreDataManager.sharedInstance.modifyNote(self.selectedNote!, title : self.titleField.text, noteDescripton: self.noteDescription.text, date: self.date!, color: self.selectedColor!)
}else{
if(!self.titleField.text.isEmpty){
CoreDataManager.sharedInstance.addNote(self.titleField.text, noteDescripton: self.noteDescription.text, date: self.date!, color: self.selectedColor!)
}
}
}else{
if(self.selectedNote != nil){
CoreDataManager.sharedInstance.deleteNote(self.selectedNote!)
}
}
}
}
}
| 542ba8bd47028382a05a27adcb827aa0 | 39.975845 | 250 | 0.647725 | false | false | false | false |
glwithu06/ReTodo | refs/heads/master | ReTodo/View/EditTaskViewController.swift | mit | 1 | //
// EditTaskViewController.swift
// ReTodo
//
// Created by Nate Kim on 13/07/2017.
// Copyright © 2017 NateKim. All rights reserved.
//
import UIKit
class EditTaskViewController: UIViewController {
var task: Task?
var dueDate:Date? {
didSet {
if let dueDate = dueDate {
dueDateDatePicker?.date = dueDate
unsetDueDateDateButton?.isEnabled = true
dueDateLabel?.text = dateFormatter.string(from: dueDate)
} else {
unsetDueDateDateButton?.isEnabled = false
dueDateLabel?.text = "-"
}
}
}
let dateFormatter:DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
return dateFormatter
}()
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var noteTextView: UITextView!
@IBOutlet weak var dueDateLabel: UILabel!
@IBOutlet weak var dueDateDatePicker: UIDatePicker!
@IBOutlet weak var unsetDueDateDateButton: UIButton!
@IBOutlet weak var deleteButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped))
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelTapped))
dueDateDatePicker.minimumDate = Date()
titleTextField.text = task?.title
noteTextView.text = task?.note
dueDate = task?.dueDate
deleteButton?.isHidden = (task == nil)
}
func doneTapped() {
if let title = titleTextField.text {
if let taskID = task?.id {
mainStore.dispatch(EditTaskAction(id: taskID, title: title, note: noteTextView.text, dueDate: dueDate))
} else {
mainStore.dispatch(AddTaskAction(title: title, note: noteTextView.text, dueDate: dueDate))
}
dismiss(animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Error", message: "A title is required.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
func cancelTapped() {
dismiss(animated: true, completion: nil)
}
@IBAction func unsetDueDateButtonTapped(_ sender: Any) {
dueDate = nil
}
@IBAction func datePickerChanged(_ sender: Any) {
dueDate = dueDateDatePicker.date
}
@IBAction func deleteButtonTapped(_ sender: Any) {
guard let taskID = task?.id else { return }
mainStore.dispatch(DeleteTaskAction(id: taskID))
self.dismiss(animated: true, completion: nil)
}
}
| 1a9fcad318956ef30c55e2e0eb3fcf95 | 34.488095 | 135 | 0.630661 | false | false | false | false |
0x4a616e/ArtlessEdit | refs/heads/master | ArtlessEdit/AppDelegate.swift | bsd-3-clause | 1 | //
// AppDelegate.swift
// ArtlessEdit
//
// Created by Jan Gassen on 21/12/14.
// Copyright (c) 2014 Jan Gassen. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var settingsWindow: NSWindow!
lazy var quickOpenController = SearchPopupController(windowNibName: "SearchPopup")
lazy var advancedSearchController = AdvancedSearchController(windowNibName: "AdvancedSearch")
lazy var defaultSettingsController = DefaultSettingsViewController(nibName: "DefaultSettings", bundle: nil)
lazy var externalToolsController = ExternalToolsViewController(nibName: "ExternalTools", bundle: nil)
func applicationDidFinishLaunching(aNotification: NSNotification) {
showDefaultSettings(self)
}
@IBAction func showAdvancesSearch(sender: AnyObject) {
advancedSearchController.showWindow(sender)
}
@IBAction func showDefaultSettings(sender: AnyObject) {
if let view = defaultSettingsController?.view {
settingsWindow.contentView = view
}
}
@IBAction func showExternalTools(sender: AnyObject) {
if let view = externalToolsController?.view {
settingsWindow.contentView = view
}
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
@IBAction func showQuickOpen(sender: AnyObject) {
quickOpenController.showWindow(sender, data: OpenFileData(), title: "Quick Open")
}
@IBAction func recentFileOpen(sender: AnyObject) {
quickOpenController.showWindow(sender, data: RecentFileData(), title: "Open Recent")
}
func createSubMenu(items: NSArray, targetMenu: NSMenuItem, selector: Selector) {
var subMenu = NSMenu()
for item in items {
var menuItem = NSMenuItem(title: item as String, action: selector, keyEquivalent: "")
menuItem.target = nil
subMenu.addItem(menuItem)
}
targetMenu.submenu = subMenu
}
}
| d7b683997f487fc37c218e70fc2b3fe6 | 30.835821 | 111 | 0.682138 | false | false | false | false |
WalletOne/P2P | refs/heads/master | P2PCore/Managers/NetworkManager.swift | mit | 1 | //
// NetworkManager.swift
// P2P_iOS
//
// Created by Vitaliy Kuzmenko on 20/07/2017.
// Copyright © 2017 Wallet One. All rights reserved.
//
import Foundation
import CryptoSwift
let kP2PErrorDomain = "com.walletone.ios.P2PCore.error"
public let P2PResponseStringKey = "P2PResponseStringKey"
public let P2PResponseErrorCodeKey = "P2PResponseErrorCodeKey"
extension NSError {
static let missingDataObject = NSError(domain: kP2PErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("MISSING_RESPONSE_DATA_OBJECT", comment: "")])
static let jsonParsingError = NSError(domain: kP2PErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("JSON_PARSING_ERROR", comment: "")])
static let dataStringError = NSError(domain: kP2PErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("DATA_STRING_ERROR", comment: "")])
class public func error(_ error: String) -> NSError {
return NSError(domain: kP2PErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: error])
}
}
extension Date {
var ISO8601TimeStamp: String {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return formatter.string(from: self)
}
}
class NetworkManager: Manager {
enum Method: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
let defaultSession = URLSession(configuration: .default)
var dataTasks: [URLSessionDataTask] = []
func makeSignature(url: String, timeStamp: String, requestBody: String) -> String {
let stringValue = String(format: "%@%@%@%@", url, timeStamp, requestBody, core.signatureKey)
let dataValue = stringValue.data(using: .utf8)!
let signatureEncoded = dataValue.sha256()
let base64 = signatureEncoded.base64EncodedString()
return base64
}
func makeSignatureForWeb(parameters: [(key: String, value: String)]) -> String {
let array = parameters.sorted(by: { (l, r) -> Bool in
return l.key < r.key
})
let stringValue = array.map({ $0.value }).joined() + core.signatureKey
P2PCore.printDebug(stringValue)
let dataValue = stringValue.data(using: .utf8)!
let signatureEncoded = dataValue.sha256()
let base64 = signatureEncoded.base64EncodedString()
return base64
}
func request<T: Mappable>(_ urlString: String, method: Method = .get, parameters: Any?, complete: @escaping ([T]?, Error?) -> Void) -> URLSessionDataTask {
return request(urlString, method: method, parameters: parameters, complete: { (JSON, error) in
if let error = error {
complete(nil, error)
} else if let JSON = JSON as? [[String: Any]] {
let array = JSON.map({ (_json) -> T in
return T(json: _json)
})
complete(array, nil)
}
})
}
func request<T: Mappable>(_ urlString: String, method: Method = .get, parameters: Any?, complete: @escaping (T?, Error?) -> Void) -> URLSessionDataTask {
return request(urlString, method: method, parameters: parameters, complete: { (JSON, error) in
if let error = error {
complete(nil, error)
} else if let JSON = JSON as? [String: Any] {
complete(T(json: JSON), nil)
}
})
}
func request(_ urlString: String, method: Method = .get, parameters: Any?, complete: @escaping (Error?) -> Void) -> URLSessionDataTask {
return request(urlString, method: method, parameters: parameters, complete: { (JSON, error) in
complete(error)
})
}
func request(_ urlString: String, method: Method = .get, parameters: Any?, complete: @escaping (Any?, Error?) -> Void) -> URLSessionDataTask {
let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
var bodyAsString = ""
let timeStamp = Date().ISO8601TimeStamp
if let parameters = parameters {
let body = try? JSONSerialization.data(withJSONObject: parameters, options: [])
bodyAsString = String(data: body ?? .init(), encoding: .utf8) ?? ""
request.httpBody = bodyAsString.data(using: .utf8)
}
let signature = makeSignature(url: urlString, timeStamp: timeStamp, requestBody: bodyAsString)
request.addValue(core.platformId, forHTTPHeaderField: "X-Wallet-PlatformId")
request.addValue(timeStamp, forHTTPHeaderField: "X-Wallet-Timestamp")
request.addValue(signature, forHTTPHeaderField: "X-Wallet-Signature")
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
P2PCore.printDebug("=======")
P2PCore.printDebug("BEGIN NEW REQUEST")
P2PCore.printDebug("\(request.httpMethod!) \(urlString)")
P2PCore.printDebug("BODY:\n\(bodyAsString)")
P2PCore.printDebug("Headers:\n\(String(describing: request.allHTTPHeaderFields ?? [:]))\n")
P2PCore.printDebug("END NEW REQUEST\n")
P2PCore.printDebug("=======")
return lowLevelRequest(request, complete: complete)
}
private func lowLevelRequest(_ request: URLRequest, complete: @escaping (Any?, Error?) -> Void) -> URLSessionDataTask {
let dataTask = defaultSession.dataTask(with: request) { data, response, error in
if let error = error {
complete(nil, error)
} else if let response = response {
DispatchQueue.main.async {
self.process(response: response, data: data, error: error, complete: complete)
}
}
}
dataTasks.append(dataTask)
dataTask.resume()
return dataTask
}
func process(response: URLResponse, data: Data?, error: Error?, complete: @escaping (Any?, Error?) -> Void) {
guard let response = response as? HTTPURLResponse else { return complete(nil, nil) }
guard let data = data else { return complete(nil, NSError.missingDataObject) }
guard let stringValue = String(data: data, encoding: .utf8) else { return complete(nil, NSError.dataStringError) }
let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
switch response.statusCode {
case 200...226:
complete(json ?? stringValue, nil)
default:
guard let errorJson = json as? [String: String] else {
let userInfo: [String: Any] = [
P2PResponseErrorCodeKey: "IS_NOT_NSDICTIONARY",
NSLocalizedDescriptionKey: NSLocalizedString("IS_NOT_NSDICTIONARY", comment: ""),
P2PResponseStringKey: stringValue
]
let error = NSError(domain: kP2PErrorDomain, code: 0, userInfo: userInfo)
return complete(nil, error)
}
let errorCode = errorJson["Error"] ?? "UNKNOWN"
let errorDescription = errorJson["ErrorDescription"] ?? errorJson["Message"] ?? "UNKNOWN"
let userInfo: [String: Any] = [
P2PResponseErrorCodeKey: errorCode,
NSLocalizedDescriptionKey: errorDescription,
P2PResponseStringKey: stringValue
]
complete(nil, NSError(domain: kP2PErrorDomain, code: 0, userInfo: userInfo))
}
}
}
| c5a4f8c27fb3775c164d2532e9ff734b | 41.411765 | 179 | 0.613416 | false | false | false | false |
telip007/ChatFire | refs/heads/master | ChatFire/Modals/Chat.swift | apache-2.0 | 1 | //
// Chat.swift
// ChatFire
//
// Created by Talip Göksu on 06.09.16.
// Copyright © 2016 ChatFire. All rights reserved.
//
import Foundation
import Firebase
class Chat: NSObject{
var user1: String?
var user2: String?
var chatId: String?
var lastMessage: String?
var lastDate: String?
var lastMessageDate: NSNumber?{
didSet{
getDate()
}
}
var partner: String?
override func setValuesForKeysWithDictionary(keyedValues: [String : AnyObject]) {
super.setValuesForKeysWithDictionary(keyedValues)
if self.user1! == currentUser?.uid{
self.partner = self.user2!
}
else{
self.partner = self.user1!
}
}
func getDate(){
if let date = self.lastMessageDate as? NSTimeInterval{
let createDate = NSDate(timeIntervalSince1970: date/1000)
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
self.lastDate = formatter.stringFromDate(createDate)
}
}
func getImage(imageUrl: (String) -> ()){
User.userFromId(self.partner!, user: { (user) in
imageUrl(user.profile_image!)
})
}
}
| 8e9935b8fce068487aee8cb7b29ad436 | 21.803571 | 85 | 0.571652 | false | false | false | false |
ManuelAurora/RxQuickbooksService | refs/heads/master | Carthage/Checkouts/OAuthSwift/Sources/OAuthSwiftURLHandlerType.swift | mit | 2 | //
// OAuthSwiftURLHandlerType.swift
// OAuthSwift
//
// Created by phimage on 11/05/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(watchOS)
import WatchKit
#elseif os(OSX)
import AppKit
#endif
@objc public protocol OAuthSwiftURLHandlerType {
func handle(_ url: URL)
}
// MARK: Open externally
open class OAuthSwiftOpenURLExternally: OAuthSwiftURLHandlerType {
public static var sharedInstance: OAuthSwiftOpenURLExternally = OAuthSwiftOpenURLExternally()
@objc open func handle(_ url: URL) {
#if os(iOS) || os(tvOS)
#if !OAUTH_APP_EXTENSIONS
UIApplication.shared.openURL(url)
#endif
#elseif os(watchOS)
// WATCHOS: not implemented
#elseif os(OSX)
NSWorkspace.shared().open(url)
#endif
}
}
// MARK: Open SFSafariViewController
#if os(iOS)
import SafariServices
@available(iOS 9.0, *)
open class SafariURLHandler: NSObject, OAuthSwiftURLHandlerType, SFSafariViewControllerDelegate {
public typealias UITransion = (_ controller: SFSafariViewController, _ handler: SafariURLHandler) -> Void
open let oauthSwift: OAuthSwift
open var present: UITransion
open var dismiss: UITransion
// retains observers
var observers = [String: NSObjectProtocol]()
open var factory: (_ URL: URL) -> SFSafariViewController = {URL in
return SFSafariViewController(url: URL)
}
// delegates
open weak var delegate: SFSafariViewControllerDelegate?
// configure default presentation and dismissal code
open var animated: Bool = true
open var presentCompletion: (() -> Void)?
open var dismissCompletion: (() -> Void)?
open var delay: UInt32? = 1
// init
public init(viewController: UIViewController, oauthSwift: OAuthSwift) {
self.oauthSwift = oauthSwift
self.present = { controller, handler in
viewController.present(controller, animated: handler.animated, completion: handler.presentCompletion)
}
self.dismiss = { controller, handler in
viewController.dismiss(animated: handler.animated, completion: handler.dismissCompletion)
}
}
public init(present: @escaping UITransion, dismiss: @escaping UITransion, oauthSwift: OAuthSwift) {
self.oauthSwift = oauthSwift
self.present = present
self.dismiss = dismiss
}
@objc open func handle(_ url: URL) {
let controller = factory(url)
controller.delegate = self
// present controller in main thread
OAuthSwift.main { [weak self] in
guard let this = self else {
return
}
if let delay = this.delay { // sometimes safari show a blank view..
sleep(delay)
}
this.present(controller, this)
}
let key = UUID().uuidString
observers[key] = OAuthSwift.notificationCenter.addObserver(
forName: NSNotification.Name.OAuthSwiftHandleCallbackURL,
object: nil,
queue: OperationQueue.main,
using: { [weak self] _ in
guard let this = self else {
return
}
if let observer = this.observers[key] {
OAuthSwift.notificationCenter.removeObserver(observer)
this.observers.removeValue(forKey: key)
}
OAuthSwift.main {
this.dismiss(controller, this)
}
}
)
}
// Clear internal observers on authentification flow
open func clearObservers() {
clearLocalObservers()
self.oauthSwift.removeCallbackNotificationObserver()
}
open func clearLocalObservers() {
for (_, observer) in observers {
OAuthSwift.notificationCenter.removeObserver(observer)
}
observers.removeAll()
}
// SFSafariViewControllerDelegate
public func safariViewController(_ controller: SFSafariViewController, activityItemsFor URL: Foundation.URL, title: String?) -> [UIActivity] {
return self.delegate?.safariViewController?(controller, activityItemsFor: URL, title: title) ?? []
}
public func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
// "Done" pressed
self.clearObservers()
self.delegate?.safariViewControllerDidFinish?(controller)
}
public func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
self.delegate?.safariViewController?(controller, didCompleteInitialLoad: didLoadSuccessfully)
}
}
#endif
// MARK: Open url using NSExtensionContext
open class ExtensionContextURLHandler: OAuthSwiftURLHandlerType {
fileprivate var extensionContext: NSExtensionContext
public init(extensionContext: NSExtensionContext) {
self.extensionContext = extensionContext
}
@objc open func handle(_ url: URL) {
extensionContext.open(url, completionHandler: nil)
}
}
| 72313f6b18a3cc51e32ed89bbb7942d8 | 32.125749 | 150 | 0.609544 | false | false | false | false |
fei1990/PageScaledScroll | refs/heads/master | ScaledPageView/ScaledPageView/sliding/ScaledScrollView.swift | mit | 1 | //
// ScaledScrollView.swift
// PageScaledScrollView
//
// Created by wangfei on 16/6/23.
// Copyright © 2016年 fei.wang. All rights reserved.
//
import UIKit
import EZSwiftExtensions
let MAXSCALE_FACTOR = CGFloat(1.0)
let MINSCALE_FACTOR = CGFloat(0.8)
class ScaledScrollView: UIScrollView {
weak internal var scrollViewDataSource:ScaledViewDataSource!
weak internal var scrollViewDelegate:ScaledViewDelegate!
private var numsOfItems:Int = 0
private var pageView:UIView!
private var pageViewArr:Array<UIView>!
private var currentPageView:UIView? //当前屏幕中间显示的pageView
private var nextSlidePageView:UIView? //下一个滑入屏幕中间的pageView
override init(frame: CGRect) {
super.init(frame: frame)
self.clipsToBounds = false
self.pagingEnabled = true
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
self.alwaysBounceHorizontal = false
self.decelerationRate = UIScrollViewDecelerationRateFast
self.delegate = self
self.addGestureRecognizer(self.tapGesture())
pageViewArr = Array()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func reloadData() {
self.removeSubviews()
self.contentSize = CGSizeMake(0, 0)
self.pageViewArr.removeAll()
numsOfItems = (scrollViewDataSource?.numbersOfPageInScaledView(self))!
assert(numsOfItems > 0, "pageView的数量必须大于零")
for i in 0...numsOfItems {
if i == numsOfItems {
pageView = scrollViewDataSource?.pageViewInScrollView(self, pageIndex: 0)
}else {
pageView = scrollViewDataSource?.pageViewInScrollView(self, pageIndex: i)
}
setPageViewFrameAndCenter(pageView: pageView, withIndex: i)
pageViewArr.append(pageView)
self.addSubview(pageView!)
}
pageView = scrollViewDataSource?.pageViewInScrollView(self, pageIndex: numsOfItems - 1)
pageViewArr.insert(pageView, atIndex: 0)
setPageViewFrameAndCenter(pageView: pageView, withIndex: -1)
self.addSubview(pageView)
self.contentSize = CGSize(width: scrollViewWidth * CGFloat(numsOfItems + 2), height: scrollViewHeight)
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(0.05 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
// self.contentOffset = CGPointMake(self.scrollViewWidth, 0)
// }
self.performSelector(#selector(ScaledScrollView.scrollToSpecifiedPoint), withObject: nil, afterDelay: 0.0, inModes: [NSRunLoopCommonModes])
}
func tapGesture() -> UITapGestureRecognizer {
let tap = UITapGestureRecognizer(target: self, action: #selector(ScaledScrollView.tappedAction(_:)))
tap.numberOfTapsRequired = 1;
return tap
}
func tappedAction(tap:UITapGestureRecognizer) {
let point = tap.locationInView(tap.view)
let convertPoint = tap.view?.convertPoint(point, toView: self.superview) //转换point点
let touchIndex:Int = touchPageViewIndexOfPoint(point.x)
if selectedCenterPageViewOfConvertPoint(convertPoint!) { //点击中间的cell
let indexPath:Int = pageViewIndexOfPoint(touchPVIndex: CGFloat(touchIndex))
scrollViewDelegate?.didSelectPageView?(self, pageIndex: indexPath)
}
if selectedLeftRightPageViewOfPoint(convertPoint!, index: touchIndex) { //点击两侧的cell //或传入point 对应的条件要变
self.setContentOffset(CGPointMake(scrollViewWidth * CGFloat(touchIndex), 0), animated: true)
}
}
private func touchPageViewIndexOfPoint(pointX:CGFloat) ->Int {
return Int(pointX / (pageViewWidth + leftRightMargin * 2))
}
private func pageViewIndexOfPoint(touchPVIndex tIndex:CGFloat) -> Int {
let index = tIndex - 1
if index < 0 {
return numsOfItems - 1
}
if index == CGFloat(numsOfItems) {
return 0
}
return Int(index)
}
private func selectedCenterPageViewOfConvertPoint(convertPoint:CGPoint) -> Bool {
return convertPoint.x >= scrollViewX && convertPoint.x <= (scrollViewX + scrollViewWidth) && convertPoint.y >= scrollViewY && convertPoint.y <= (scrollViewY + scrollViewHeight)
// return (convertPoint.x >= (leftRightMargin + scrollViewX) && convertPoint.x <= (pageViewWidth + leftRightMargin + scrollViewX)) && (convertPoint.y >= (topBottomMargin + scrollViewY) && convertPoint.y <= (pageVieweHeight + topBottomMargin + scrollViewY))
}
private func selectedLeftRightPageViewOfPoint(point:CGPoint, index:Int) ->Bool {
return (point.x <= scrollViewX - leftRightMargin || point.x >= scrollViewX + scrollViewWidth + leftRightMargin) && point.y >= topBottomMargin && point.y <= (topBottomMargin + pageVieweHeight)
// return point.x >= leftRightMargin + scrollViewWidth * CGFloat(index) && point.y >= topBottomMargin && point.y <= (topBottomMargin + pageVieweHeight)
}
private func setPageViewFrameAndCenter(pageView pageView:UIView, withIndex index:Int) {
self.pageView.frame = CGRectMake(0, 0, self.scrollViewWidth, self.scrollViewHeight)
self.pageView.center = CGPointMake(self.scrollViewWidth * (0.5 + CGFloat(index + 1)), self.scrollViewHeight/2)
self.pageView.layer.masksToBounds = true
self.pageView.layer.cornerRadius = 4
self.pageView.layer.borderWidth = 1
self.pageView.layer.borderColor = UIColor(colorLiteralRed: 230.0/255, green: 230.0/255, blue: 230.0/255, alpha: 1.0).CGColor
}
//MARK: - scroll to specified index
func scrollToSpecifiedPoint() {
self.contentOffset = CGPointMake(self.scrollViewWidth, 0)
}
}
extension ScaledScrollView {
private var pageViewWidth:CGFloat {
get{
return CGRectGetWidth(pageView.frame)
}
}
private var pageVieweHeight:CGFloat {
get{
return CGRectGetHeight(pageView.frame)
}
}
private var leftRightMargin:CGFloat {
get{
return (CGRectGetWidth(self.frame) - CGRectGetWidth(pageView.frame))/2
}
}
private var topBottomMargin:CGFloat {
get {
return (CGRectGetHeight(self.frame) - CGRectGetHeight(pageView.frame))/2
}
}
private var scrollViewWidth:CGFloat {
get{
return CGRectGetWidth(self.frame)
}
}
private var scrollViewHeight:CGFloat {
get {
return CGRectGetHeight(self.frame)
}
}
private var scrollViewX:CGFloat {
get{
return CGRectGetMinX(self.frame)
}
}
private var scrollViewY:CGFloat {
get{
return CGRectGetMinY(self.frame)
}
}
}
extension ScaledScrollView:UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
currentPageView?.transform = CGAffineTransformMakeScale(MINSCALE_FACTOR, MINSCALE_FACTOR)
nextSlidePageView?.transform = CGAffineTransformMakeScale(MINSCALE_FACTOR, MINSCALE_FACTOR)
let scale = scrollView.contentOffset.x/scrollViewWidth //滑动时的缩放比例
let indexOfPage = Int(scale)
if Int(scrollView.contentOffset.x/scrollViewWidth) == numsOfItems + 1 { //滑到最后一个
scrollView.setContentOffset(CGPointMake(scrollViewWidth, 0), animated: false)
nextSlidePageView = self.pageViewArr.first
// nextSlidePageView?.layer.transform = CATransform3DMakeScale(MINSCALE_FACTOR, MINSCALE_FACTOR, MINSCALE_FACTOR)
nextSlidePageView?.transform = CGAffineTransformMakeScale(MINSCALE_FACTOR, MINSCALE_FACTOR)
return
}
if CGFloat(scrollView.contentOffset.x/scrollViewWidth) <= 0 { //滑到第一个
scrollView.setContentOffset(CGPointMake(scrollViewWidth * CGFloat(numsOfItems), 0), animated: false)
nextSlidePageView = self.pageViewArr.last
// nextSlidePageView?.layer.transform = CATransform3DMakeScale(MINSCALE_FACTOR, MINSCALE_FACTOR, MINSCALE_FACTOR)
nextSlidePageView?.transform = CGAffineTransformMakeScale(MINSCALE_FACTOR, MINSCALE_FACTOR)
return
}
if indexOfPage < self.pageViewArr.count - 1 {
currentPageView = self.pageViewArr[indexOfPage]
if indexOfPage < self.pageViewArr.count - 1 {
nextSlidePageView = self.pageViewArr[indexOfPage + 1]
}else {
nextSlidePageView = self.pageViewArr[1]
}
// currentPageView?.layer.transform = CATransform3DMakeScale(MAXSCALE_FACTOR - (CGFloat(scale) - CGFloat(indexOfPage))/5, MAXSCALE_FACTOR - (CGFloat(scale) - CGFloat(indexOfPage))/5, MAXSCALE_FACTOR - (CGFloat(scale) - CGFloat(indexOfPage))/5)
// nextSlidePageView?.layer.transform = CATransform3DMakeScale(MINSCALE_FACTOR + (CGFloat(scale) - CGFloat(indexOfPage))/5, MINSCALE_FACTOR + (CGFloat(scale) - CGFloat(indexOfPage))/5, MINSCALE_FACTOR + (CGFloat(scale) - CGFloat(indexOfPage))/5)
currentPageView?.transform = CGAffineTransformMakeScale(MAXSCALE_FACTOR - (CGFloat(scale) - CGFloat(indexOfPage))/5, MAXSCALE_FACTOR - (CGFloat(scale) - CGFloat(indexOfPage))/5)
nextSlidePageView?.transform = CGAffineTransformMakeScale(MINSCALE_FACTOR + (CGFloat(scale) - CGFloat(indexOfPage))/5, MINSCALE_FACTOR + (CGFloat(scale) - CGFloat(indexOfPage))/5)
}
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
}
}
| 62e8a1704d13361dae3ffc0ca4f9d6ca | 41.604348 | 263 | 0.664354 | false | false | false | false |
etataurov/ImageLoaderSwift | refs/heads/master | ImageLoader/ImageLoader.swift | mit | 1 | //
// ImageLoader.swift
// ImageLoader
//
// Created by Hirohisa Kawasaki on 10/16/14.
// Copyright (c) 2014 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
public protocol URLLiteralConvertible {
var URL: NSURL { get }
}
extension NSURL: URLLiteralConvertible {
public var URL: NSURL {
return self
}
}
extension String: URLLiteralConvertible {
public var URL: NSURL {
return NSURL(string: self)!
}
}
// MARK: Optimize image
extension CGBitmapInfo {
private var alphaInfo: CGImageAlphaInfo? {
let info = self & .AlphaInfoMask
return CGImageAlphaInfo(rawValue: info.rawValue)
}
}
extension UIImage {
private func inflated() -> UIImage {
let scale = UIScreen.mainScreen().scale
let width = CGImageGetWidth(CGImage)
let height = CGImageGetHeight(CGImage)
if !(width > 0 && height > 0) {
return self
}
let bitsPerComponent = CGImageGetBitsPerComponent(CGImage)
if (bitsPerComponent > 8) {
return self
}
var bitmapInfo = CGImageGetBitmapInfo(CGImage)
var alphaInfo = CGImageGetAlphaInfo(CGImage)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colorSpaceModel = CGColorSpaceGetModel(colorSpace)
switch (colorSpaceModel.value) {
case kCGColorSpaceModelRGB.value:
// Reference: http://stackoverflow.com/questions/23723564/which-cgimagealphainfo-should-we-use
var info = CGImageAlphaInfo.PremultipliedFirst
switch alphaInfo {
case .None:
info = CGImageAlphaInfo.NoneSkipFirst
default:
break
}
bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGBitmapInfo(info.rawValue)
default:
break
}
let context = CGBitmapContextCreate(
nil,
width,
height,
bitsPerComponent,
0,
colorSpace,
bitmapInfo
)
let frame = CGRect(x: 0, y: 0, width: Int(width), height: Int(height))
CGContextDrawImage(context, frame, CGImage)
let inflatedImageRef = CGBitmapContextCreateImage(context)
if let inflatedImage = UIImage(CGImage: inflatedImageRef, scale: scale, orientation: imageOrientation) {
return inflatedImage
}
return self
}
}
// MARK: Cache
/**
Cache for `ImageLoader` have to implement methods.
fetch image by cache before sending a request and set image into cache after receiving image data.
*/
public protocol ImageCache: NSObjectProtocol {
subscript (aKey: NSURL) -> UIImage? {
get
set
}
}
internal typealias CompletionHandler = (NSURL, UIImage?, NSError?) -> ()
internal class Block: NSObject {
let completionHandler: CompletionHandler
init(completionHandler: CompletionHandler) {
self.completionHandler = completionHandler
}
}
/**
Use to check state of loaders that manager has.
Ready: The manager have no loaders
Running: The manager has loaders, and they are running
Suspended: The manager has loaders, and their states are all suspended
*/
public enum State {
case Ready
case Running
case Suspended
}
/**
Responsible for creating and managing `Loader` objects and controlling of `NSURLSession` and `ImageCache`
*/
public class LoaderManager {
let session: NSURLSession
let cache: ImageCache
let delegate: SessionDataDelegate = SessionDataDelegate()
public var inflatesImage: Bool = true
// MARK: singleton instance
public class var sharedInstance: LoaderManager {
struct Singleton {
static let instance = LoaderManager()
}
return Singleton.instance
}
init(configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
cache: ImageCache = Diskcached()
) {
session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
self.cache = cache
}
// MARK: state
var state: State {
var status: State = .Ready
for loader: Loader in delegate.loaders.values {
switch loader.state {
case .Running:
status = .Running
case .Suspended:
if status == .Ready {
status = .Suspended
}
default:
break
}
}
return status
}
// MARK: loading
internal func load(URL: URLLiteralConvertible) -> Loader {
let URL = URL.URL
if let loader = delegate[URL] {
loader.resume()
return loader
}
let request = NSMutableURLRequest(URL: URL)
request.setValue("image/*", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request)
let loader = Loader(task: task, delegate: self)
delegate[URL] = loader
return loader
}
internal func suspend(URL: URLLiteralConvertible) -> Loader? {
let URL = URL.URL
if let loader = delegate[URL] {
loader.suspend()
return loader
}
return nil
}
internal func cancel(URL: URLLiteralConvertible, block: Block? = nil) -> Loader? {
let URL = URL.URL
if let loader = delegate[URL] {
if let block = block {
loader.remove(block)
}
if loader.blocks.count == 0 || block == nil {
loader.cancel()
delegate.remove(URL)
}
return loader
}
return nil
}
class SessionDataDelegate: NSObject, NSURLSessionDataDelegate {
private let _queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
private var loaders: [NSURL: Loader] = [NSURL: Loader]()
subscript (URL: NSURL) -> Loader? {
get {
var loader : Loader?
dispatch_sync(_queue) {
loader = self.loaders[URL]
}
return loader
}
set {
dispatch_barrier_async(_queue) {
self.loaders[URL] = newValue!
}
}
}
private func remove(URL: NSURL) -> Loader? {
if let loader = self[URL] {
loaders.removeValueForKey(URL)
return loader
}
return nil
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
// TODO: status code 3xx
if let URL = dataTask.originalRequest.URL, let loader = self[URL] {
loader.receive(data)
}
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
completionHandler(.Allow)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
// TODO: status code 3xx
// loader completion, and store remove loader
if let URL = task.originalRequest.URL, let loader = self[URL] {
loader.complete(error)
remove(URL)
}
}
}
}
/**
Responsible for sending a request and receiving the response and calling blocks for the request.
*/
public class Loader {
let delegate: LoaderManager
let task: NSURLSessionDataTask
var receivedData: NSMutableData = NSMutableData()
let inflatesImage: Bool
internal var blocks: [Block] = []
init (task: NSURLSessionDataTask, delegate: LoaderManager) {
self.task = task
self.delegate = delegate
self.inflatesImage = delegate.inflatesImage
self.resume()
}
var state: NSURLSessionTaskState {
return task.state
}
public func completionHandler(completionHandler: (NSURL, UIImage?, NSError?) -> ()) -> Self {
let block = Block(completionHandler: completionHandler)
blocks.append(block)
return self
}
// MARK: task
public func suspend() {
task.suspend()
}
public func resume() {
task.resume()
}
public func cancel() {
task.cancel()
}
private func remove(block: Block) {
// needs to queue with sync
var newBlocks: [Block] = []
for b: Block in blocks {
if !b.isEqual(block) {
newBlocks.append(b)
}
}
blocks = newBlocks
}
private func receive(data: NSData) {
receivedData.appendData(data)
}
private func complete(error: NSError?) {
var image: UIImage?
if let URL = task.originalRequest.URL {
if error == nil {
image = UIImage(data: receivedData)
_toCache(URL, image: image)
}
for block: Block in blocks {
block.completionHandler(URL, image, error)
}
blocks = []
}
}
private func _toCache(URL: NSURL, image _image: UIImage?) {
var image = _image
if inflatesImage {
image = image?.inflated()
}
if let image = image {
delegate.cache[URL] = image
}
}
}
/**
Creates `Loader` object using the shared LoaderManager instance for the specified URL.
*/
public func load(URL: URLLiteralConvertible) -> Loader {
return LoaderManager.sharedInstance.load(URL)
}
/**
Suspends `Loader` object using the shared LoaderManager instance for the specified URL.
*/
public func suspend(URL: URLLiteralConvertible) -> Loader? {
return LoaderManager.sharedInstance.suspend(URL)
}
/**
Cancels `Loader` object using the shared LoaderManager instance for the specified URL.
*/
public func cancel(URL: URLLiteralConvertible) -> Loader? {
return LoaderManager.sharedInstance.cancel(URL)
}
/**
Fetches the image using the shared LoaderManager instance's `ImageCache` object for the specified URL.
*/
public func cache(URL: URLLiteralConvertible) -> UIImage? {
let URL = URL.URL
return LoaderManager.sharedInstance.cache[URL]
}
public var state: State {
return LoaderManager.sharedInstance.state
}
| 28d906e2e9fe51a3f89da06bd9337f7e | 24.933824 | 186 | 0.596163 | false | false | false | false |
hyperoslo/CalendarKit | refs/heads/master | CalendarKitDemo/CalendarApp/CustomCalendarExampleController.swift | mit | 1 | import UIKit
import CalendarKit
class CustomCalendarExampleController: DayViewController {
var data = [["Breakfast at Tiffany's",
"New York, 5th avenue"],
["Workout",
"Tufteparken"],
["Meeting with Alex",
"Home",
"Oslo, Tjuvholmen"],
["Beach Volleyball",
"Ipanema Beach",
"Rio De Janeiro"],
["WWDC",
"Moscone West Convention Center",
"747 Howard St"],
["Google I/O",
"Shoreline Amphitheatre",
"One Amphitheatre Parkway"],
["✈️️ to Svalbard ❄️️❄️️❄️️❤️️",
"Oslo Gardermoen"],
["💻📲 Developing CalendarKit",
"🌍 Worldwide"],
["Software Development Lecture",
"Mikpoli MB310",
"Craig Federighi"],
]
var generatedEvents = [EventDescriptor]()
var alreadyGeneratedSet = Set<Date>()
var colors = [UIColor.blue,
UIColor.yellow,
UIColor.green,
UIColor.red]
private lazy var rangeFormatter: DateIntervalFormatter = {
let fmt = DateIntervalFormatter()
fmt.dateStyle = .none
fmt.timeStyle = .short
return fmt
}()
override func loadView() {
calendar.timeZone = TimeZone(identifier: "Europe/Paris")!
dayView = DayView(calendar: calendar)
view = dayView
}
override func viewDidLoad() {
super.viewDidLoad()
title = "CalendarKit Demo"
navigationController?.navigationBar.isTranslucent = false
dayView.autoScrollToFirstEvent = true
reloadData()
}
// MARK: EventDataSource
override func eventsForDate(_ date: Date) -> [EventDescriptor] {
if !alreadyGeneratedSet.contains(date) {
alreadyGeneratedSet.insert(date)
generatedEvents.append(contentsOf: generateEventsForDate(date))
}
return generatedEvents
}
private func generateEventsForDate(_ date: Date) -> [EventDescriptor] {
var workingDate = Calendar.current.date(byAdding: .hour, value: Int.random(in: 1...15), to: date)!
var events = [Event]()
for i in 0...4 {
let event = Event()
let duration = Int.random(in: 60 ... 160)
event.startDate = workingDate
event.endDate = Calendar.current.date(byAdding: .minute, value: duration, to: workingDate)!
var info = data[Int(arc4random_uniform(UInt32(data.count)))]
let timezone = dayView.calendar.timeZone
print(timezone)
info.append(rangeFormatter.string(from: event.startDate, to: event.endDate))
event.text = info.reduce("", {$0 + $1 + "\n"})
event.color = colors[Int(arc4random_uniform(UInt32(colors.count)))]
event.isAllDay = Int(arc4random_uniform(2)) % 2 == 0
event.lineBreakMode = .byTruncatingTail
// Event styles are updated independently from CalendarStyle
// hence the need to specify exact colors in case of Dark style
if #available(iOS 12.0, *) {
if traitCollection.userInterfaceStyle == .dark {
event.textColor = textColorForEventInDarkTheme(baseColor: event.color)
event.backgroundColor = event.color.withAlphaComponent(0.6)
}
}
events.append(event)
let nextOffset = Int.random(in: 40 ... 250)
workingDate = Calendar.current.date(byAdding: .minute, value: nextOffset, to: workingDate)!
event.userInfo = String(i)
}
print("Events for \(date)")
return events
}
private func textColorForEventInDarkTheme(baseColor: UIColor) -> UIColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
baseColor.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return UIColor(hue: h, saturation: s * 0.3, brightness: b, alpha: a)
}
// MARK: DayViewDelegate
private var createdEvent: EventDescriptor?
override func dayViewDidSelectEventView(_ eventView: EventView) {
guard let descriptor = eventView.descriptor as? Event else {
return
}
print("Event has been selected: \(descriptor) \(String(describing: descriptor.userInfo))")
}
override func dayViewDidLongPressEventView(_ eventView: EventView) {
guard let descriptor = eventView.descriptor as? Event else {
return
}
endEventEditing()
print("Event has been longPressed: \(descriptor) \(String(describing: descriptor.userInfo))")
beginEditing(event: descriptor, animated: true)
print(Date())
}
override func dayView(dayView: DayView, didTapTimelineAt date: Date) {
endEventEditing()
print("Did Tap at date: \(date)")
}
override func dayViewDidBeginDragging(dayView: DayView) {
endEventEditing()
print("DayView did begin dragging")
}
override func dayView(dayView: DayView, willMoveTo date: Date) {
print("DayView = \(dayView) will move to: \(date)")
}
override func dayView(dayView: DayView, didMoveTo date: Date) {
print("DayView = \(dayView) did move to: \(date)")
}
override func dayView(dayView: DayView, didLongPressTimelineAt date: Date) {
print("Did long press timeline at date \(date)")
// Cancel editing current event and start creating a new one
endEventEditing()
let event = generateEventNearDate(date)
print("Creating a new event")
create(event: event, animated: true)
createdEvent = event
}
private func generateEventNearDate(_ date: Date) -> EventDescriptor {
let duration = Int(arc4random_uniform(160) + 60)
let startDate = Calendar.current.date(byAdding: .minute, value: -Int(CGFloat(duration) / 2), to: date)!
let event = Event()
event.startDate = startDate
event.endDate = Calendar.current.date(byAdding: .minute, value: duration, to: startDate)!
var info = data[Int(arc4random_uniform(UInt32(data.count)))]
info.append(rangeFormatter.string(from: event.startDate, to: event.endDate))
event.text = info.reduce("", {$0 + $1 + "\n"})
event.color = colors[Int(arc4random_uniform(UInt32(colors.count)))]
event.editedEvent = event
// Event styles are updated independently from CalendarStyle
// hence the need to specify exact colors in case of Dark style
if #available(iOS 12.0, *) {
if traitCollection.userInterfaceStyle == .dark {
event.textColor = textColorForEventInDarkTheme(baseColor: event.color)
event.backgroundColor = event.color.withAlphaComponent(0.6)
}
}
return event
}
override func dayView(dayView: DayView, didUpdate event: EventDescriptor) {
print("did finish editing \(event)")
print("new startDate: \(event.startDate) new endDate: \(event.endDate)")
if let _ = event.editedEvent {
event.commitEditing()
}
if let createdEvent = createdEvent {
createdEvent.editedEvent = nil
generatedEvents.append(createdEvent)
self.createdEvent = nil
endEventEditing()
}
reloadData()
}
}
| 6fba678d96a53d8624a2b847db83d3b3 | 31.411765 | 107 | 0.625436 | false | false | false | false |
djwbrown/swift | refs/heads/master | test/IRGen/builtins.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-stdlib -primary-file %s -emit-ir -o - -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
// REQUIRES: executable_test
// REQUIRES: CPU=x86_64
import Swift
// CHECK-DAG: [[REFCOUNT:%swift.refcounted.*]] = type
// CHECK-DAG: [[X:%T8builtins1XC]] = type
// CHECK-DAG: [[Y:%T8builtins1YC]] = type
typealias Int = Builtin.Int32
typealias Bool = Builtin.Int1
infix operator * {
associativity left
precedence 200
}
infix operator / {
associativity left
precedence 200
}
infix operator % {
associativity left
precedence 200
}
infix operator + {
associativity left
precedence 190
}
infix operator - {
associativity left
precedence 190
}
infix operator << {
associativity none
precedence 180
}
infix operator >> {
associativity none
precedence 180
}
infix operator ... {
associativity none
precedence 175
}
infix operator < {
associativity none
precedence 170
}
infix operator <= {
associativity none
precedence 170
}
infix operator > {
associativity none
precedence 170
}
infix operator >= {
associativity none
precedence 170
}
infix operator == {
associativity none
precedence 160
}
infix operator != {
associativity none
precedence 160
}
func * (lhs: Int, rhs: Int) -> Int {
return Builtin.mul_Int32(lhs, rhs)
// CHECK: mul i32
}
func / (lhs: Int, rhs: Int) -> Int {
return Builtin.sdiv_Int32(lhs, rhs)
// CHECK: sdiv i32
}
func % (lhs: Int, rhs: Int) -> Int {
return Builtin.srem_Int32(lhs, rhs)
// CHECK: srem i32
}
func + (lhs: Int, rhs: Int) -> Int {
return Builtin.add_Int32(lhs, rhs)
// CHECK: add i32
}
func - (lhs: Int, rhs: Int) -> Int {
return Builtin.sub_Int32(lhs, rhs)
// CHECK: sub i32
}
// In C, 180 is <<, >>
func < (lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_slt_Int32(lhs, rhs)
// CHECK: icmp slt i32
}
func > (lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sgt_Int32(lhs, rhs)
// CHECK: icmp sgt i32
}
func <=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sle_Int32(lhs, rhs)
// CHECK: icmp sle i32
}
func >=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sge_Int32(lhs, rhs)
// CHECK: icmp sge i32
}
func ==(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_eq_Int32(lhs, rhs)
// CHECK: icmp eq i32
}
func !=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_ne_Int32(lhs, rhs)
// CHECK: icmp ne i32
}
func gepRaw_test(_ ptr: Builtin.RawPointer, offset: Builtin.Int64)
-> Builtin.RawPointer {
return Builtin.gepRaw_Int64(ptr, offset)
// CHECK: getelementptr inbounds i8, i8*
}
// CHECK: define hidden {{.*}}i64 @_T08builtins9load_test{{[_0-9a-zA-Z]*}}F
func load_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64*
// CHECK-NEXT: load i64, i64* [[CASTPTR]]
// CHECK: ret
return Builtin.load(ptr)
}
// CHECK: define hidden {{.*}}i64 @_T08builtins13load_raw_test{{[_0-9a-zA-Z]*}}F
func load_raw_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64*
// CHECK-NEXT: load i64, i64* [[CASTPTR]]
// CHECK: ret
return Builtin.loadRaw(ptr)
}
// CHECK: define hidden {{.*}}void @_T08builtins11assign_test{{[_0-9a-zA-Z]*}}F
func assign_test(_ value: Builtin.Int64, ptr: Builtin.RawPointer) {
Builtin.assign(value, ptr)
// CHECK: ret
}
// CHECK: define hidden {{.*}}%swift.refcounted* @_T08builtins16load_object_test{{[_0-9a-zA-Z]*}}F
func load_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]**
// CHECK: call void @swift_rt_swift_retain([[REFCOUNT]]* [[T0]])
// CHECK: ret [[REFCOUNT]]* [[T0]]
return Builtin.load(ptr)
}
// CHECK: define hidden {{.*}}%swift.refcounted* @_T08builtins20load_raw_object_test{{[_0-9a-zA-Z]*}}F
func load_raw_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]**
// CHECK: call void @swift_rt_swift_retain([[REFCOUNT]]* [[T0]])
// CHECK: ret [[REFCOUNT]]* [[T0]]
return Builtin.loadRaw(ptr)
}
// CHECK: define hidden {{.*}}void @_T08builtins18assign_object_test{{[_0-9a-zA-Z]*}}F
func assign_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) {
Builtin.assign(value, ptr)
}
// CHECK: define hidden {{.*}}void @_T08builtins16init_object_test{{[_0-9a-zA-Z]*}}F
func init_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) {
// CHECK: [[DEST:%.*]] = bitcast i8* {{%.*}} to %swift.refcounted**
// CHECK-NEXT: store [[REFCOUNT]]* {{%.*}}, [[REFCOUNT]]** [[DEST]]
Builtin.initialize(value, ptr)
}
func cast_test(_ ptr: inout Builtin.RawPointer, i8: inout Builtin.Int8,
i64: inout Builtin.Int64, f: inout Builtin.FPIEEE32,
d: inout Builtin.FPIEEE64
) {
// CHECK: cast_test
i8 = Builtin.trunc_Int64_Int8(i64) // CHECK: trunc
i64 = Builtin.zext_Int8_Int64(i8) // CHECK: zext
i64 = Builtin.sext_Int8_Int64(i8) // CHECK: sext
i64 = Builtin.ptrtoint_Int64(ptr) // CHECK: ptrtoint
ptr = Builtin.inttoptr_Int64(i64) // CHECK: inttoptr
i64 = Builtin.fptoui_FPIEEE64_Int64(d) // CHECK: fptoui
i64 = Builtin.fptosi_FPIEEE64_Int64(d) // CHECK: fptosi
d = Builtin.uitofp_Int64_FPIEEE64(i64) // CHECK: uitofp
d = Builtin.sitofp_Int64_FPIEEE64(i64) // CHECK: sitofp
d = Builtin.fpext_FPIEEE32_FPIEEE64(f) // CHECK: fpext
f = Builtin.fptrunc_FPIEEE64_FPIEEE32(d) // CHECK: fptrunc
i64 = Builtin.bitcast_FPIEEE64_Int64(d) // CHECK: bitcast
d = Builtin.bitcast_Int64_FPIEEE64(i64) // CHECK: bitcast
}
func intrinsic_test(_ i32: inout Builtin.Int32, i16: inout Builtin.Int16) {
i32 = Builtin.int_bswap_Int32(i32) // CHECK: llvm.bswap.i32(
i16 = Builtin.int_bswap_Int16(i16) // CHECK: llvm.bswap.i16(
var x = Builtin.int_sadd_with_overflow_Int16(i16, i16) // CHECK: call { i16, i1 } @llvm.sadd.with.overflow.i16(
Builtin.int_trap() // CHECK: llvm.trap()
}
// CHECK: define hidden {{.*}}void @_T08builtins19sizeof_alignof_testyyF()
func sizeof_alignof_test() {
// CHECK: store i64 4, i64*
var xs = Builtin.sizeof(Int.self)
// CHECK: store i64 4, i64*
var xa = Builtin.alignof(Int.self)
// CHECK: store i64 1, i64*
var ys = Builtin.sizeof(Bool.self)
// CHECK: store i64 1, i64*
var ya = Builtin.alignof(Bool.self)
}
// CHECK: define hidden {{.*}}void @_T08builtins27generic_sizeof_alignof_testyxlF(
func generic_sizeof_alignof_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 11
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[SIZE:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: store i64 [[SIZE]], i64* [[S:%.*]]
var s = Builtin.sizeof(T.self)
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 12
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[T2:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: [[T3:%.*]] = and i64 [[T2]], 65535
// CHECK-NEXT: [[ALIGN:%.*]] = add i64 [[T3]], 1
// CHECK-NEXT: store i64 [[ALIGN]], i64* [[A:%.*]]
var a = Builtin.alignof(T.self)
}
// CHECK: define hidden {{.*}}void @_T08builtins21generic_strideof_testyxlF(
func generic_strideof_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 13
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[STRIDE:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: store i64 [[STRIDE]], i64* [[S:%.*]]
var s = Builtin.strideof(T.self)
}
class X {}
class Y {}
func move(_ ptr: Builtin.RawPointer) {
var temp : Y = Builtin.take(ptr)
// CHECK: define hidden {{.*}}void @_T08builtins4move{{[_0-9a-zA-Z]*}}F
// CHECK: [[SRC:%.*]] = bitcast i8* {{%.*}} to [[Y]]**
// CHECK-NEXT: [[VAL:%.*]] = load [[Y]]*, [[Y]]** [[SRC]]
// CHECK-NEXT: store [[Y]]* [[VAL]], [[Y]]** {{%.*}}
}
func allocDealloc(_ size: Builtin.Word, align: Builtin.Word) {
var ptr = Builtin.allocRaw(size, align)
Builtin.deallocRaw(ptr, size, align)
}
func fence_test() {
// CHECK: fence acquire
Builtin.fence_acquire()
// CHECK: fence singlethread acq_rel
Builtin.fence_acqrel_singlethread()
}
func cmpxchg_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32, b: Builtin.Int32) {
// rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers
// CHECK: [[Z_RES:%.*]] = cmpxchg i32* {{.*}}, i32 {{.*}}, i32 {{.*}} acquire acquire
// CHECK: [[Z_VAL:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 0
// CHECK: [[Z_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 1
// CHECK: store i32 [[Z_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[Z_SUCCESS]], i1* {{.*}}, align 1
var (z, zSuccess) = Builtin.cmpxchg_acquire_acquire_Int32(ptr, a, b)
// CHECK: [[Y_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} monotonic monotonic
// CHECK: [[Y_VAL:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 0
// CHECK: [[Y_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 1
// CHECK: store i32 [[Y_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[Y_SUCCESS]], i1* {{.*}}, align 1
var (y, ySuccess) = Builtin.cmpxchg_monotonic_monotonic_volatile_Int32(ptr, a, b)
// CHECK: [[X_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} singlethread acquire monotonic
// CHECK: [[X_VAL:%.*]] = extractvalue { i32, i1 } [[X_RES]], 0
// CHECK: [[X_SUCCESS:%.*]] = extractvalue { i32, i1 } [[X_RES]], 1
// CHECK: store i32 [[X_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[X_SUCCESS]], i1* {{.*}}, align 1
var (x, xSuccess) = Builtin.cmpxchg_acquire_monotonic_volatile_singlethread_Int32(ptr, a, b)
// CHECK: [[W_RES:%.*]] = cmpxchg volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst
// CHECK: [[W_VAL:%.*]] = extractvalue { i64, i1 } [[W_RES]], 0
// CHECK: [[W_SUCCESS:%.*]] = extractvalue { i64, i1 } [[W_RES]], 1
// CHECK: [[W_VAL_PTR:%.*]] = inttoptr i64 [[W_VAL]] to i8*
// CHECK: store i8* [[W_VAL_PTR]], i8** {{.*}}, align 8
// CHECK: store i1 [[W_SUCCESS]], i1* {{.*}}, align 1
var (w, wSuccess) = Builtin.cmpxchg_seqcst_seqcst_volatile_singlethread_RawPointer(ptr, ptr, ptr)
// CHECK: [[V_RES:%.*]] = cmpxchg weak volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst
// CHECK: [[V_VAL:%.*]] = extractvalue { i64, i1 } [[V_RES]], 0
// CHECK: [[V_SUCCESS:%.*]] = extractvalue { i64, i1 } [[V_RES]], 1
// CHECK: [[V_VAL_PTR:%.*]] = inttoptr i64 [[V_VAL]] to i8*
// CHECK: store i8* [[V_VAL_PTR]], i8** {{.*}}, align 8
// CHECK: store i1 [[V_SUCCESS]], i1* {{.*}}, align 1
var (v, vSuccess) = Builtin.cmpxchg_seqcst_seqcst_weak_volatile_singlethread_RawPointer(ptr, ptr, ptr)
}
func atomicrmw_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32,
ptr2: Builtin.RawPointer) {
// CHECK: atomicrmw add i32* {{.*}}, i32 {{.*}} acquire
var z = Builtin.atomicrmw_add_acquire_Int32(ptr, a)
// CHECK: atomicrmw volatile max i32* {{.*}}, i32 {{.*}} monotonic
var y = Builtin.atomicrmw_max_monotonic_volatile_Int32(ptr, a)
// CHECK: atomicrmw volatile xchg i32* {{.*}}, i32 {{.*}} singlethread acquire
var x = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_Int32(ptr, a)
// rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers
// CHECK: atomicrmw volatile xchg i64* {{.*}}, i64 {{.*}} singlethread acquire
var w = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_RawPointer(ptr, ptr2)
}
func addressof_test(_ a: inout Int, b: inout Bool) {
// CHECK: bitcast i32* {{.*}} to i8*
var ap : Builtin.RawPointer = Builtin.addressof(&a)
// CHECK: bitcast i1* {{.*}} to i8*
var bp : Builtin.RawPointer = Builtin.addressof(&b)
}
func fneg_test(_ half: Builtin.FPIEEE16,
single: Builtin.FPIEEE32,
double: Builtin.FPIEEE64)
-> (Builtin.FPIEEE16, Builtin.FPIEEE32, Builtin.FPIEEE64)
{
// CHECK: fsub half 0xH8000, {{%.*}}
// CHECK: fsub float -0.000000e+00, {{%.*}}
// CHECK: fsub double -0.000000e+00, {{%.*}}
return (Builtin.fneg_FPIEEE16(half),
Builtin.fneg_FPIEEE32(single),
Builtin.fneg_FPIEEE64(double))
}
// The call to the builtins should get removed before we reach IRGen.
func testStaticReport(_ b: Bool, ptr: Builtin.RawPointer) -> () {
Builtin.staticReport(b, b, ptr);
return Builtin.staticReport(b, b, ptr);
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins12testCondFail{{[_0-9a-zA-Z]*}}F(i1, i1)
func testCondFail(_ b: Bool, c: Bool) {
// CHECK: br i1 %0, label %[[FAIL:.*]], label %[[CONT:.*]]
Builtin.condfail(b)
// CHECK: <label>:[[CONT]]
// CHECK: br i1 %1, label %[[FAIL2:.*]], label %[[CONT:.*]]
Builtin.condfail(c)
// CHECK: <label>:[[CONT]]
// CHECK: ret void
// CHECK: <label>:[[FAIL]]
// CHECK: call void @llvm.trap()
// CHECK: unreachable
// CHECK: <label>:[[FAIL2]]
// CHECK: call void @llvm.trap()
// CHECK: unreachable
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins8testOnce{{[_0-9a-zA-Z]*}}F(i8*, i8*) {{.*}} {
// CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]*
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: br i1 [[IS_DONE]], label %[[DONE:.*]], label %[[NOT_DONE:.*]]
// CHECK-objc: [[NOT_DONE]]:
// CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* undef)
// CHECK-objc: br label %[[DONE]]
// CHECK-objc: [[DONE]]:
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]])
func testOnce(_ p: Builtin.RawPointer, f: @escaping @convention(thin) () -> ()) {
Builtin.once(p, f)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins19testOnceWithContext{{[_0-9a-zA-Z]*}}F(i8*, i8*, i8*) {{.*}} {
// CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]*
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: br i1 [[IS_DONE]], label %[[DONE:.*]], label %[[NOT_DONE:.*]]
// CHECK-objc: [[NOT_DONE]]:
// CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* %2)
// CHECK-objc: br label %[[DONE]]
// CHECK-objc: [[DONE]]:
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]])
func testOnceWithContext(_ p: Builtin.RawPointer, f: @escaping @convention(thin) (Builtin.RawPointer) -> (), k: Builtin.RawPointer) {
Builtin.onceWithContext(p, f, k)
}
class C {}
struct S {}
@objc class O {}
@objc protocol OP1 {}
@objc protocol OP2 {}
protocol P {}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins10canBeClass{{[_0-9a-zA-Z]*}}F
func canBeClass<T>(_ f: @escaping (Builtin.Int8) -> (), _: T) {
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(O.self))
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(OP1.self))
typealias ObjCCompo = OP1 & OP2
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(ObjCCompo.self))
// CHECK: call {{.*}}void {{%.*}}(i8 0
f(Builtin.canBeClass(S.self))
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(C.self))
// CHECK: call {{.*}}void {{%.*}}(i8 0
f(Builtin.canBeClass(P.self))
typealias MixedCompo = OP1 & P
// CHECK: call {{.*}}void {{%.*}}(i8 0
f(Builtin.canBeClass(MixedCompo.self))
// CHECK: call {{.*}}void {{%.*}}(i8 2
f(Builtin.canBeClass(T.self))
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15destroyPODArray{{[_0-9a-zA-Z]*}}F(i8*, i64)
// CHECK-NOT: loop:
// CHECK: ret void
func destroyPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) {
Builtin.destroyArray(Int.self, array, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins18destroyNonPODArray{{[_0-9a-zA-Z]*}}F(i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: call {{.*}} @swift_rt_swift_release
// CHECK: br label %iter
func destroyNonPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) {
Builtin.destroyArray(C.self, array, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15destroyGenArrayyBp_Bw5countxtlF(i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
// CHECK-NOT: loop:
// CHECK: call void %destroyArray
func destroyGenArray<T>(_ array: Builtin.RawPointer, count: Builtin.Word, _: T) {
Builtin.destroyArray(T.self, array, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins12copyPODArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
func copyPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(Int.self, dest, src, count)
Builtin.takeArrayFrontToBack(Int.self, dest, src, count)
Builtin.takeArrayBackToFront(Int.self, dest, src, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins11copyBTArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: call {{.*}} @swift_rt_swift_retain
// CHECK: br label %iter
// CHECK: mul nuw i64 8, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 8, i1 false)
// CHECK: mul nuw i64 8, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 8, i1 false)
func copyBTArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(C.self, dest, src, count)
Builtin.takeArrayFrontToBack(C.self, dest, src, count)
Builtin.takeArrayBackToFront(C.self, dest, src, count)
}
struct W { weak var c: C? }
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15copyNonPODArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: swift_weakCopyInit
// CHECK: iter{{.*}}:
// CHECK: loop{{.*}}:
// CHECK: swift_weakTakeInit
// CHECK: iter{{.*}}:
// CHECK: loop{{.*}}:
// CHECK: swift_weakTakeInit
func copyNonPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(W.self, dest, src, count)
Builtin.takeArrayFrontToBack(W.self, dest, src, count)
Builtin.takeArrayBackToFront(W.self, dest, src, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins12copyGenArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithCopy
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithTakeFrontToBack
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithTakeBackToFront
func copyGenArray<T>(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word, _: T) {
Builtin.copyArray(T.self, dest, src, count)
Builtin.takeArrayFrontToBack(T.self, dest, src, count)
Builtin.takeArrayBackToFront(T.self, dest, src, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins24conditionallyUnreachableyyF
// CHECK-NEXT: entry
// CHECK-NEXT: unreachable
func conditionallyUnreachable() {
Builtin.conditionallyUnreachable()
}
struct Abc {
var value : Builtin.Word
}
// CHECK-LABEL: define hidden {{.*}}@_T08builtins22assumeNonNegative_testBwAA3AbcVzF
func assumeNonNegative_test(_ x: inout Abc) -> Builtin.Word {
// CHECK: load {{.*}}, !range ![[R:[0-9]+]]
return Builtin.assumeNonNegative_Word(x.value)
}
@inline(never)
func return_word(_ x: Builtin.Word) -> Builtin.Word {
return x
}
// CHECK-LABEL: define hidden {{.*}}@_T08builtins23assumeNonNegative_test2BwBwF
func assumeNonNegative_test2(_ x: Builtin.Word) -> Builtin.Word {
// CHECK: call {{.*}}, !range ![[R]]
return Builtin.assumeNonNegative_Word(return_word(x))
}
struct Empty {}
struct Pair { var i: Int, b: Bool }
// CHECK-LABEL: define hidden {{.*}}i64 @_T08builtins15zeroInitializerAA5EmptyV_AA4PairVtyF() {{.*}} {
// CHECK: [[ALLOCA:%.*]] = alloca { i64 }
// CHECK: bitcast
// CHECK: lifetime.start
// CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]]
// CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0
// CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0
// CHECK: store i32 0, i32* [[FLDI]]
// CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1
// CHECK: store i1 false, i1* [[FLDB]]
// CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0
// CHECK: [[RES:%.*]] = load i64, i64* [[RET]]
// CHECK: ret i64 [[RES]]
func zeroInitializer() -> (Empty, Pair) {
return (Builtin.zeroInitializer(), Builtin.zeroInitializer())
}
// CHECK-LABEL: define hidden {{.*}}i64 @_T08builtins20zeroInitializerTupleAA5EmptyV_AA4PairVtyF() {{.*}} {
// CHECK: [[ALLOCA:%.*]] = alloca { i64 }
// CHECK: bitcast
// CHECK: lifetime.start
// CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]]
// CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0
// CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0
// CHECK: store i32 0, i32* [[FLDI]]
// CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1
// CHECK: store i1 false, i1* [[FLDB]]
// CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0
// CHECK: [[RES:%.*]] = load i64, i64* [[RET]]
// CHECK: ret i64 [[RES]]
func zeroInitializerTuple() -> (Empty, Pair) {
return Builtin.zeroInitializer()
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins20zeroInitializerEmptyyyF() {{.*}} {
// CHECK: ret void
func zeroInitializerEmpty() {
return Builtin.zeroInitializer()
}
// ----------------------------------------------------------------------------
// isUnique variants
// ----------------------------------------------------------------------------
// CHECK: define hidden {{.*}}void @_T08builtins26acceptsBuiltinNativeObjectyBoSgzF([[BUILTIN_NATIVE_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
func acceptsBuiltinNativeObject(_ ref: inout Builtin.NativeObject?) {}
// native
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool {
return Builtin.isUnique(&ref)
}
// native nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.NativeObject) -> Bool {
return Builtin.isUnique(&ref)
}
// native pinned
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// native pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native(%swift.refcounted* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// CHECK: define hidden {{.*}}void @_T08builtins27acceptsBuiltinUnknownObjectyBOSgzF([[BUILTIN_UNKNOWN_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
func acceptsBuiltinUnknownObject(_ ref: inout Builtin.UnknownObject?) {}
// ObjC
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BOSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_UNKNOWN_OBJECT_TY]]* %0 to [[UNKNOWN_OBJECT:%objc_object|%swift\.refcounted]]**
// CHECK-NEXT: load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** %1
// CHECK-objc-NEXT: call i1 @swift_isUniquelyReferencedNonObjC([[UNKNOWN_OBJECT]]* %2)
// CHECK-native-NEXT: call i1 @swift_isUniquelyReferenced_native([[UNKNOWN_OBJECT]]* %2)
// CHECK-NEXT: ret i1 %3
func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool {
return Builtin.isUnique(&ref)
}
// ObjC nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BOzF
// CHECK-SAME: ([[UNKNOWN_OBJECT]]** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** %0
// CHECK-objc-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull([[UNKNOWN_OBJECT]]* %1)
// CHECK-native-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native([[UNKNOWN_OBJECT]]* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool {
return Builtin.isUnique(&ref)
}
// ObjC pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BOzF
// CHECK-SAME: ([[UNKNOWN_OBJECT]]** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** %0
// CHECK-native-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native([[UNKNOWN_OBJECT]]* %1)
// CHECK-objc-NEXT: call i1 @swift_isUniquelyReferencedOrPinnedNonObjC_nonNull([[UNKNOWN_OBJECT]]* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// BridgeObject nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUnique(&ref)
}
// Bridge pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedOrPinnedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// BridgeObject nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins15isUnique_nativeBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUnique_native(&ref)
}
// Bridge pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins23isUniqueOrPinned_nativeBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUniqueOrPinned_native(&ref)
}
// ImplicitlyUnwrappedOptional argument to isUnique.
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins11isUniqueIUOBi1_BoSgzF(%{{.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted*
// CHECK: ret i1
func isUniqueIUO(_ ref: inout Builtin.NativeObject?) -> Bool {
var iuo : Builtin.NativeObject! = ref
return Builtin.isUnique(&iuo)
}
// CHECK-LABEL: define {{.*}} @{{.*}}generic_ispod_test
func generic_ispod_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 12
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[FLAGS:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: [[ISNOTPOD:%.*]] = and i64 [[FLAGS]], 65536
// CHECK-NEXT: [[ISPOD:%.*]] = icmp eq i64 [[ISNOTPOD]], 0
// CHECK-NEXT: store i1 [[ISPOD]], i1* [[S:%.*]]
var s = Builtin.ispod(T.self)
}
// CHECK-LABEL: define {{.*}} @{{.*}}ispod_test
func ispod_test() {
// CHECK: store i1 true, i1*
// CHECK: store i1 false, i1*
var t = Builtin.ispod(Int.self)
var f = Builtin.ispod(Builtin.NativeObject)
}
// CHECK-LABEL: define {{.*}} @{{.*}}is_same_metatype
func is_same_metatype_test(_ t1: Any.Type, _ t2: Any.Type) {
// CHECK: [[MT1_AS_PTR:%.*]] = bitcast %swift.type* %0 to i8*
// CHECK: [[MT2_AS_PTR:%.*]] = bitcast %swift.type* %1 to i8*
// CHECK: icmp eq i8* [[MT1_AS_PTR]], [[MT2_AS_PTR]]
var t = Builtin.is_same_metatype(t1, t2)
}
// CHECK-LABEL: define {{.*}} @{{.*}}generic_unsafeGuaranteed_test
// CHECK: call void @{{.*}}swift_{{.*}}etain({{.*}}* %0)
// CHECK: call void @{{.*}}swift_{{.*}}elease({{.*}}* %0)
// CHECK: ret {{.*}}* %0
func generic_unsafeGuaranteed_test<T: AnyObject>(_ t : T) -> T {
let (g, _) = Builtin.unsafeGuaranteed(t)
return g
}
// CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteed_test
// CHECK: [[LOCAL:%.*]] = alloca %swift.refcounted*
// CHECK: call void @swift_rt_swift_retain(%swift.refcounted* %0)
// CHECK: store %swift.refcounted* %0, %swift.refcounted** [[LOCAL]]
// CHECK: call void @swift_rt_swift_release(%swift.refcounted* %0)
// CHECK: ret %swift.refcounted* %0
func unsafeGuaranteed_test(_ x: Builtin.NativeObject) -> Builtin.NativeObject {
var (g,t) = Builtin.unsafeGuaranteed(x)
Builtin.unsafeGuaranteedEnd(t)
return g
}
// CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteedEnd_test
// CHECK-NEXT: {{.*}}:
// CHECK-NEXT: ret void
func unsafeGuaranteedEnd_test(_ x: Builtin.Int8) {
Builtin.unsafeGuaranteedEnd(x)
}
// CHECK-LABEL: define {{.*}} @{{.*}}atomicload
func atomicload(_ p: Builtin.RawPointer) {
// CHECK: [[A:%.*]] = load atomic i8*, i8** {{%.*}} unordered, align 8
let a: Builtin.RawPointer = Builtin.atomicload_unordered_RawPointer(p)
// CHECK: [[B:%.*]] = load atomic i32, i32* {{%.*}} singlethread monotonic, align 4
let b: Builtin.Int32 = Builtin.atomicload_monotonic_singlethread_Int32(p)
// CHECK: [[C:%.*]] = load atomic volatile i64, i64* {{%.*}} singlethread acquire, align 8
let c: Builtin.Int64 =
Builtin.atomicload_acquire_volatile_singlethread_Int64(p)
// CHECK: [[D0:%.*]] = load atomic volatile i32, i32* {{%.*}} seq_cst, align 4
// CHECK: [[D:%.*]] = bitcast i32 [[D0]] to float
let d: Builtin.FPIEEE32 = Builtin.atomicload_seqcst_volatile_FPIEEE32(p)
// CHECK: store atomic i8* [[A]], i8** {{%.*}} unordered, align 8
Builtin.atomicstore_unordered_RawPointer(p, a)
// CHECK: store atomic i32 [[B]], i32* {{%.*}} singlethread monotonic, align 4
Builtin.atomicstore_monotonic_singlethread_Int32(p, b)
// CHECK: store atomic volatile i64 [[C]], i64* {{%.*}} singlethread release, align 8
Builtin.atomicstore_release_volatile_singlethread_Int64(p, c)
// CHECK: [[D1:%.*]] = bitcast float [[D]] to i32
// CHECK: store atomic volatile i32 [[D1]], i32* {{.*}} seq_cst, align 4
Builtin.atomicstore_seqcst_volatile_FPIEEE32(p, d)
}
// CHECK: ![[R]] = !{i64 0, i64 9223372036854775807}
| 69b499415cb57644ef634a1df891282b | 39.391892 | 237 | 0.627391 | false | true | false | false |
saturnboy/learning_spritekit_swift | refs/heads/master | LearningSpriteKit/LearningSpriteKit/GameScene3.swift | mit | 1 | //
// GameScene3.swift
// LearningSpriteKit
//
// Created by Justin on 12/1/14.
// Copyright (c) 2014 SaturnBoy. All rights reserved.
//
import SpriteKit
class GameScene3: SKScene {
let alien = SKSpriteNode(imageNamed: "alien1")
let hit = SKAction.playSoundFileNamed("fire.caf", waitForCompletion: false)
let miss = SKAction.playSoundFileNamed("miss.caf", waitForCompletion: false)
override func didMoveToView(view: SKView) {
println("GameScene3: \(view.frame.size)")
self.backgroundColor = UIColor(red: 0.3, green: 0.1, blue: 0.1, alpha: 1.0)
self.alien.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(self.alien)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if let touch: AnyObject = touches.anyObject() {
let loc = touch.locationInNode(self)
println("touch: \(loc)")
if self.alien.containsPoint(loc) {
println("HIT!")
self.runAction(self.hit)
//compute the new position
let center = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
let newPos = CGPoint(x: center.x + CGFloat(arc4random_uniform(201)) - 100.0,
y: center.y + CGFloat(arc4random_uniform(201)) - 100.0)
//1. Instead of the above, how could you adjust positioning for iPhone vs iPad
let fadeOut = SKAction.fadeOutWithDuration(0.2)
let fadeIn = SKAction.fadeInWithDuration(0.2)
let move = SKAction.moveTo(newPos, duration:0.2)
self.alien.runAction(SKAction.sequence([fadeOut, move, fadeIn]))
} else {
println("miss")
self.runAction(self.miss)
}
}
}
override func update(currentTime: CFTimeInterval) {
//pass
}
}
| 8f36cb610b0957d10a4d84c087c67a74 | 35.350877 | 97 | 0.567085 | false | false | false | false |
AaronMT/firefox-ios | refs/heads/main | Storage/Rust/RustPlaces.swift | mpl-2.0 | 7 | /* 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
@_exported import MozillaAppServices
private let log = Logger.syncLogger
public class RustPlaces {
let databasePath: String
let writerQueue: DispatchQueue
let readerQueue: DispatchQueue
var api: PlacesAPI?
var writer: PlacesWriteConnection?
var reader: PlacesReadConnection?
public fileprivate(set) var isOpen: Bool = false
private var didAttemptToMoveToBackup = false
public init(databasePath: String) {
self.databasePath = databasePath
self.writerQueue = DispatchQueue(label: "RustPlaces writer queue: \(databasePath)", attributes: [])
self.readerQueue = DispatchQueue(label: "RustPlaces reader queue: \(databasePath)", attributes: [])
}
private func open() -> NSError? {
do {
api = try PlacesAPI(path: databasePath)
isOpen = true
return nil
} catch let err as NSError {
if let placesError = err as? PlacesError {
switch placesError {
case .panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when opening Rust Places database", tag: SentryTag.rustPlaces, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when opening Rust Places database", tag: SentryTag.rustPlaces, severity: .error, description: placesError.localizedDescription)
}
} else {
Sentry.shared.sendWithStacktrace(message: "Unknown error when opening Rust Places database", tag: SentryTag.rustPlaces, severity: .error, description: err.localizedDescription)
}
return err
}
}
private func close() -> NSError? {
api = nil
writer = nil
reader = nil
isOpen = false
return nil
}
private func withWriter<T>(_ callback: @escaping(_ connection: PlacesWriteConnection) throws -> T) -> Deferred<Maybe<T>> {
let deferred = Deferred<Maybe<T>>()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
return
}
if self.writer == nil {
self.writer = self.api?.getWriter()
}
if let writer = self.writer {
do {
let result = try callback(writer)
deferred.fill(Maybe(success: result))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
} else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
}
}
return deferred
}
private func withReader<T>(_ callback: @escaping(_ connection: PlacesReadConnection) throws -> T) -> Deferred<Maybe<T>> {
let deferred = Deferred<Maybe<T>>()
readerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
return
}
if self.reader == nil {
do {
self.reader = try self.api?.openReader()
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
}
if let reader = self.reader {
do {
let result = try callback(reader)
deferred.fill(Maybe(success: result))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
} else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
}
}
return deferred
}
public func migrateBookmarksIfNeeded(fromBrowserDB browserDB: BrowserDB) {
// Since we use the existence of places.db as an indication that we've
// already migrated bookmarks, assert that places.db is not open here.
assert(!isOpen, "Shouldn't attempt to migrate bookmarks after opening Rust places.db")
// We only need to migrate bookmarks here if the old browser.db file
// already exists AND the new Rust places.db file does NOT exist yet.
// This is to ensure that we only ever run this migration ONCE. In
// addition, it is the caller's (Profile.swift) responsibility to NOT
// use this migration API for users signed into a Firefox Account.
// Those users will automatically get all their bookmarks on next Sync.
guard FileManager.default.fileExists(atPath: browserDB.databasePath),
!FileManager.default.fileExists(atPath: databasePath) else {
return
}
// Ensure that the old BrowserDB schema is up-to-date before migrating.
_ = browserDB.touch().value
// Open the Rust places.db now for the first time.
_ = reopenIfClosed()
do {
try api?.migrateBookmarksFromBrowserDb(path: browserDB.databasePath)
} catch let err as NSError {
Sentry.shared.sendWithStacktrace(message: "Error encountered while migrating bookmarks from BrowserDB", tag: SentryTag.rustPlaces, severity: .error, description: err.localizedDescription)
}
}
public func getBookmarksTree(rootGUID: GUID, recursive: Bool) -> Deferred<Maybe<BookmarkNode?>> {
return withReader { connection in
return try connection.getBookmarksTree(rootGUID: rootGUID, recursive: recursive)
}
}
public func getBookmark(guid: GUID) -> Deferred<Maybe<BookmarkNode?>> {
return withReader { connection in
return try connection.getBookmark(guid: guid)
}
}
public func getRecentBookmarks(limit: UInt) -> Deferred<Maybe<[BookmarkItem]>> {
return withReader { connection in
return try connection.getRecentBookmarks(limit: limit)
}
}
public func getBookmarkURLForKeyword(keyword: String) -> Deferred<Maybe<String?>> {
return withReader { connection in
return try connection.getBookmarkURLForKeyword(keyword: keyword)
}
}
public func getBookmarksWithURL(url: String) -> Deferred<Maybe<[BookmarkItem]>> {
return withReader { connection in
return try connection.getBookmarksWithURL(url: url)
}
}
public func isBookmarked(url: String) -> Deferred<Maybe<Bool>> {
return getBookmarksWithURL(url: url).bind { result in
guard let bookmarks = result.successValue else {
return deferMaybe(false)
}
return deferMaybe(!bookmarks.isEmpty)
}
}
public func searchBookmarks(query: String, limit: UInt) -> Deferred<Maybe<[BookmarkItem]>> {
return withReader { connection in
return try connection.searchBookmarks(query: query, limit: limit)
}
}
public func interruptWriter() {
writer?.interrupt()
}
public func interruptReader() {
reader?.interrupt()
}
public func runMaintenance() {
_ = withWriter { connection in
try connection.runMaintenance()
}
}
public func deleteBookmarkNode(guid: GUID) -> Success {
return withWriter { connection in
let result = try connection.deleteBookmarkNode(guid: guid)
if !result {
log.debug("Bookmark with GUID \(guid) does not exist.")
}
}
}
public func deleteBookmarksWithURL(url: String) -> Success {
return getBookmarksWithURL(url: url) >>== { bookmarks in
let deferreds = bookmarks.map({ self.deleteBookmarkNode(guid: $0.guid) })
return all(deferreds).bind { results in
if let error = results.find({ $0.isFailure })?.failureValue {
return deferMaybe(error)
}
return succeed()
}
}
}
public func createFolder(parentGUID: GUID, title: String, position: UInt32? = nil) -> Deferred<Maybe<GUID>> {
return withWriter { connection in
return try connection.createFolder(parentGUID: parentGUID, title: title, position: position)
}
}
public func createSeparator(parentGUID: GUID, position: UInt32? = nil) -> Deferred<Maybe<GUID>> {
return withWriter { connection in
return try connection.createSeparator(parentGUID: parentGUID, position: position)
}
}
@discardableResult
public func createBookmark(parentGUID: GUID, url: String, title: String?, position: UInt32? = nil) -> Deferred<Maybe<GUID>> {
return withWriter { connection in
return try connection.createBookmark(parentGUID: parentGUID, url: url, title: title, position: position)
}
}
public func updateBookmarkNode(guid: GUID, parentGUID: GUID? = nil, position: UInt32? = nil, title: String? = nil, url: String? = nil) -> Success {
return withWriter { connection in
return try connection.updateBookmarkNode(guid: guid, parentGUID: parentGUID, position: position, title: title, url: url)
}
}
public func reopenIfClosed() -> NSError? {
var error: NSError? = nil
writerQueue.sync {
guard !isOpen else { return }
error = open()
}
return error
}
public func interrupt() {
api?.interrupt()
}
public func forceClose() -> NSError? {
var error: NSError? = nil
api?.interrupt()
writerQueue.sync {
guard isOpen else { return }
error = close()
}
return error
}
public func syncBookmarks(unlockInfo: SyncUnlockInfo) -> Success {
let deferred = Success()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
return
}
do {
try _ = self.api?.syncBookmarks(unlockInfo: unlockInfo)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
if let placesError = err as? PlacesError {
switch placesError {
case .panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when syncing Places database", tag: SentryTag.rustPlaces, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when syncing Places database", tag: SentryTag.rustPlaces, severity: .error, description: placesError.localizedDescription)
}
}
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func resetBookmarksMetadata() -> Success {
let deferred = Success()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesError.connUseAfterAPIClosed as MaybeErrorType))
return
}
do {
try self.api?.resetBookmarkSyncMetadata()
deferred.fill(Maybe(success: ()))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
}
return deferred
}
}
| 7b616a53ec04e6e57f61c471bcd8dc25 | 34.391691 | 217 | 0.598223 | false | false | false | false |
hanhailong/practice-swift | refs/heads/master | CoreMotion/Ball/Ball/ViewController.swift | mit | 2 | //
// ViewController.swift
// Ball
//
// Created by Domenico on 02/05/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
import CoreMotion
class ViewController: UIViewController {
private let updateInterval = 1.0/60.0
private let motionManager = CMMotionManager()
private let queue = NSOperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
motionManager.deviceMotionUpdateInterval = updateInterval
motionManager.startDeviceMotionUpdatesToQueue(queue,
withHandler: {
(motionData: CMDeviceMotion!, error: NSError!) -> Void in
let ballView = self.view as! BallView
ballView.acceleration = motionData.gravity
dispatch_async(dispatch_get_main_queue(), {
ballView.update()
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| eec7679cdc84e8e7738871a4f63cd045 | 25.948718 | 73 | 0.624167 | false | false | false | false |
limsangjin12/Hero | refs/heads/master | Sources/Animator/HeroDefaultAnimator.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// 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
internal extension UIView {
func optimizedDuration(targetState: HeroTargetState) -> TimeInterval {
return optimizedDurationTo(position: targetState.position, size: targetState.size, transform: targetState.transform)
}
func optimizedDurationTo(position: CGPoint?, size: CGSize?, transform: CATransform3D?) -> TimeInterval {
let fromPos = (layer.presentation() ?? layer).position
let toPos = position ?? fromPos
let fromSize = (layer.presentation() ?? layer).bounds.size
let toSize = size ?? fromSize
let fromTransform = (layer.presentation() ?? layer).transform
let toTransform = transform ?? fromTransform
let realFromPos = CGPoint.zero.transform(fromTransform) + fromPos
let realToPos = CGPoint.zero.transform(toTransform) + toPos
let realFromSize = fromSize.transform(fromTransform)
let realToSize = toSize.transform(toTransform)
let movePoints = (realFromPos.distance(realToPos) + realFromSize.point.distance(realToSize.point))
// duration is 0.2 @ 0 to 0.375 @ 500
let duration = 0.208 + Double(movePoints.clamp(0, 500)) / 3000
return duration
}
}
internal class HeroDefaultAnimator<ViewContext>: HeroAnimator where ViewContext: HeroAnimatorViewContext {
weak public var context: HeroContext!
var viewContexts: [UIView: ViewContext] = [:]
public func seekTo(timePassed: TimeInterval) {
for viewContext in viewContexts.values {
viewContext.seek(timePassed: timePassed)
}
}
public func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval {
var duration: TimeInterval = 0
for (_, context) in viewContexts {
context.resume(timePassed: timePassed, reverse: reverse)
duration = max(duration, context.duration)
}
return duration
}
public func apply(state: HeroTargetState, to view: UIView) {
if let context = viewContexts[view] {
context.apply(state:state)
}
}
public func canAnimate(view: UIView, appearing: Bool) -> Bool {
guard let state = context[view] else { return false }
return ViewContext.canAnimate(view: view, state: state, appearing: appearing)
}
public func animate(fromViews: [UIView], toViews: [UIView]) -> TimeInterval {
var duration: TimeInterval = 0
// animate
for v in fromViews { animate(view: v, appearing: false) }
for v in toViews { animate(view: v, appearing: true) }
// infinite duration means matching the duration of the longest animation
var infiniteDurationViewContexts = [ViewContext]()
for viewContext in viewContexts.values {
if viewContext.duration == .infinity {
infiniteDurationViewContexts.append(viewContext)
} else {
duration = max(duration, viewContext.duration)
}
}
for viewContext in infiniteDurationViewContexts {
duration = max(duration, viewContext.snapshot.optimizedDuration(targetState: viewContext.targetState))
}
for viewContext in infiniteDurationViewContexts {
viewContext.apply(state: [.duration(duration)])
}
return duration
}
func animate(view: UIView, appearing: Bool) {
let snapshot = context.snapshotView(for: view)
let viewContext = ViewContext(animator:self, snapshot: snapshot, targetState: context[view]!)
viewContexts[view] = viewContext
viewContext.startAnimations(appearing: appearing)
}
public func clean() {
for vc in viewContexts.values {
vc.clean()
}
viewContexts.removeAll()
}
}
| c47c4fd3017cc12e990dc8ec3929972b | 36.691057 | 120 | 0.723253 | false | false | false | false |
oasisweng/DWActionsMenu | refs/heads/master | DWActionsMenu/ActionsMenuConstants.swift | mit | 1 | //
// ActionsMenuConstants.swift
// DWActionsMenu
//
// Created by Dingzhong Weng on 24/12/2014.
// Copyright (c) 2014 Dingzhong Weng. All rights reserved.
//
import UIKit
import Foundation
struct Constants{
let kRESIZECONTROLHEIGHT : CGFloat = 16.0
let kBUTTONSIZE : CGFloat = 44.0
let kBUTTONIMAGESIZE : CGFloat = 32.0
let kBUTTONINSET : CGFloat = 6.0
let kMENUHEIGHT : CGFloat = 44.0
} | 309788d119b172994c2308e3828ae0c6 | 22.055556 | 59 | 0.700483 | false | false | false | false |
a2/RxSwift | refs/heads/master | RxTests/RxSwiftTests/TestImplementations/Mocks/PrimitiveHotObservable.swift | mit | 13 | //
// PrimitiveHotObservable.swift
// RxTests
//
// Created by Krunoslav Zaher on 6/4/15.
//
//
import Foundation
import RxSwift
let SubscribedToHotObservable = Subscription(0)
let UnsunscribedFromHotObservable = Subscription(0, 0)
class PrimitiveHotObservable<ElementType : Equatable> : Observable<ElementType>, ObserverType {
typealias Events = Recorded<E>
typealias Observer = ObserverOf<E>
var subscriptions: [Subscription]
var observers: Bag<ObserverOf<E>>
override init() {
self.subscriptions = []
self.observers = Bag()
super.init()
}
func on(event: Event<E>) {
observers.forEach { $0.on(event) }
}
override func subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable {
let key = observers.insert(ObserverOf(observer))
subscriptions.append(SubscribedToHotObservable)
let i = self.subscriptions.count - 1
return AnonymousDisposable {
let removed = self.observers.removeKey(key)
assert(removed != nil)
self.subscriptions[i] = UnsunscribedFromHotObservable
}
}
}
| 90e6957e45023be55d52424a67c6ac40 | 24.468085 | 95 | 0.629908 | false | false | false | false |
wyz5120/DrinkClock | refs/heads/master | DrinkClock/DrinkClock/Classes/RemindTableViewController.swift | mit | 1 | //
// RemindTableViewController.swift
// DrinkClock
//
// Created by wyz on 16/4/19.
// Copyright © 2016年 wyz. All rights reserved.
//
import UIKit
private let remindCellIdentifier = "remindCellIdentifier"
let dataSourceDidChangeNotification = "dataSourceDidChangeNotification"
class RemindTableViewController: UIViewController {
var dataSource:NSMutableArray?
var isAnimating = false
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
view.addSubview(tableView)
view.addSubview(coverView)
tableView.backgroundColor = UIColor.clearColor()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RemindTableViewController.refresh), name: didAddReminderNotification, object: nil)
tableView.snp_makeConstraints { (make) in
make.edges.equalTo(self.view)
}
coverView.snp_makeConstraints { (make) in
make.edges.equalTo(self.view)
}
coverView.hidden = true
refresh()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
tableView.dataSource = self
tableView.delegate = self
tableView.registerClass(RemindCell.self, forCellReuseIdentifier: remindCellIdentifier)
tableView.rowHeight = 60
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.showsVerticalScrollIndicator = false
return tableView
}()
private lazy var coverView:UIView = {
let view = CoverView()
view.addReminderColoure = {[weak self]() -> Void in
self!.addReminderPlan()
}
return view
}()
func addReminderPlan() {
let plan = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("drinkInfo", ofType: "plist")!)!
let existed = NSFileManager.defaultManager().fileExistsAtPath(path)
var array = NSMutableArray()
if existed {
array = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as! NSMutableArray
}
loop: for i in 0..<8 {
let dict = plan[i] as! NSDictionary
let r = Reminder()
r.time = (dict.valueForKey("time") as! String)
r.uuid = "\(i)"
r.remind = true
r.repeatMode = ReminderRepeatMode.OneDay.rawValue
r.sound = RemindSound()
r.isDone = false
r.tipString = (dict.valueForKey("tip") as! String)
for re in array {
if re.uuid == r.uuid {
continue loop
}
}
array.addObject(r)
}
NSKeyedArchiver.archiveRootObject(array, toFile: path)
NSNotificationCenter.defaultCenter().postNotificationName(didAddReminderNotification, object: nil)
NotificationManager.addLoacalNotification()
let alert = UIAlertController(title: "成功添加到提醒", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
func refresh() {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "a hh:mm"
dateFormatter.locale = NSLocale(localeIdentifier: "zh_CN")
dataSource = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? NSMutableArray
if dataSource?.count >= 2 {
dataSource!.sortUsingComparator({ (r1, r2) -> NSComparisonResult in
let reminder1 = r1 as! Reminder
let reminder2 = r2 as! Reminder
let d1 = dateFormatter.dateFromString(reminder1.time)
let d2 = dateFormatter.dateFromString(reminder2.time)
return d1!.compare(d2!)
})
}
if dataSource == nil {
coverView.hidden = false
} else {
coverView.hidden = dataSource?.count != 0
}
NSNotificationCenter.defaultCenter().postNotificationName(dataSourceDidChangeNotification, object: nil)
tableView.reloadData()
}
func updateData(reminder:Reminder) {
let array = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as! NSMutableArray
for i in 0..<array.count {
let r = array[i] as! Reminder
if r.uuid == reminder.uuid {
array.replaceObjectAtIndex(i, withObject: reminder)
break
}
}
NSKeyedArchiver.archiveRootObject(array, toFile: path)
self.refresh()
}
}
extension RemindTableViewController:UITableViewDataSource,UITableViewDelegate {
// MARK: - Table view data source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows = 0
if let list = dataSource {
rows = list.count
}
return rows
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(remindCellIdentifier) as! RemindCell
let reminder = dataSource![indexPath.row] as! Reminder
cell.reminder = reminder
cell.remindButtonClickClosure = {[weak self]()->Void in
reminder.remind = !reminder.remind
self!.updateData(reminder)
self!.isAnimating = false
if reminder.remind {
NotificationManager.addNotifationWithReminder(reminder)
} else {
NotificationManager.cancelNotifationWithReminder(reminder)
}
}
cell.doneButtonClickClosure = {[weak self]()->Void in
reminder.isDone = !reminder.isDone
self!.updateData(reminder)
self!.isAnimating = false
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let addReminderVc = AddReminderViewController()
addReminderVc.reminder = dataSource![indexPath.row] as? Reminder
let navigationVc = NavigationController(rootViewController: addReminderVc)
presentViewController(navigationVc, animated: true, completion: nil)
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if !isAnimating {
return
}
let tranformScale = CGAffineTransformMakeScale(0.6, 0.8)
let tranformTranslate = CGAffineTransformMakeTranslation(0.6,0.8)
cell.transform = CGAffineTransformConcat(tranformScale, tranformTranslate)
tableView .bringSubviewToFront(cell)
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
cell.transform = CGAffineTransformIdentity
}, completion: nil)
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
isAnimating = true
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
isAnimating = false
}
}
class CoverView:UIView {
var addReminderColoure:(()->Void)?
override init(frame: CGRect) {
super.init(frame: frame)
layer.cornerRadius = 10
layer.masksToBounds = true
addSubview(visualEffectView)
addSubview(textLabel)
addSubview(addButton)
visualEffectView.snp_makeConstraints { (make) in
make.edges.equalTo(self)
}
textLabel.snp_makeConstraints { (make) in
make.centerX.equalTo(self)
make.bottom.equalTo(self.snp_centerY).offset(-20)
}
addButton.snp_makeConstraints { (make) in
make.centerX.equalTo(self)
make.top.equalTo(self.snp_centerY).offset(10)
make.width.equalTo(screenWidth * 0.5)
make.height.equalTo(44)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var textLabel:UILabel = {
let label = UILabel()
label.textColor = UIColor.cyanColor()
label.font = UIFont(name: "GloberSemiBold", size: scaleFromIphone5Width(17))
label.text = "还没添加提醒呢"
label.numberOfLines = 0;
label.textAlignment = NSTextAlignment.Center
return label
}()
private lazy var addButton:UIButton = {
let button = UIButton()
button.setTitleColor(UIColor(red: 64/255.0, green: 228/255.0, blue: 165/255.0, alpha: 1.0), forState: UIControlState.Normal)
button.setTitle("添加推荐时间", forState: UIControlState.Normal)
button.backgroundColor = UIColor.clearColor()
button.layer.masksToBounds = true
button.layer.cornerRadius = 22
button.layer.borderWidth = 2
button.layer.borderColor = UIColor(red: 64/255.0, green: 228/255.0, blue: 165/255.0, alpha: 1.0).CGColor
button.sizeToFit()
button.addTarget(self, action:#selector(CoverView.addPlanAction), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
private lazy var visualEffectView: UIVisualEffectView = {
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark))
visualEffectView.alpha = 1.0
visualEffectView.layer.cornerRadius = 10
visualEffectView.layer.masksToBounds = true
visualEffectView.userInteractionEnabled = false
return visualEffectView
}()
func addPlanAction() {
if addReminderColoure != nil {
addReminderColoure!()
}
}
}
| df01f2f94a26bee803cecde48e5838e1 | 35.750916 | 165 | 0.633908 | false | false | false | false |
marty-suzuki/QiitaWithFluxSample | refs/heads/master | Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSignup/DefaultImplementations.swift | mit | 5 | //
// DefaultImplementations.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !RX_NO_MODULE
import RxSwift
#endif
import struct Foundation.CharacterSet
import struct Foundation.URL
import struct Foundation.URLRequest
import struct Foundation.NSRange
import class Foundation.URLSession
import func Foundation.arc4random
class GitHubDefaultValidationService: GitHubValidationService {
let API: GitHubAPI
static let sharedValidationService = GitHubDefaultValidationService(API: GitHubDefaultAPI.sharedAPI)
init (API: GitHubAPI) {
self.API = API
}
// validation
let minPasswordCount = 5
func validateUsername(_ username: String) -> Observable<ValidationResult> {
if username.characters.count == 0 {
return .just(.empty)
}
// this obviously won't be
if username.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) != nil {
return .just(.failed(message: "Username can only contain numbers or digits"))
}
let loadingValue = ValidationResult.validating
return API
.usernameAvailable(username)
.map { available in
if available {
return .ok(message: "Username available")
}
else {
return .failed(message: "Username already taken")
}
}
.startWith(loadingValue)
}
func validatePassword(_ password: String) -> ValidationResult {
let numberOfCharacters = password.characters.count
if numberOfCharacters == 0 {
return .empty
}
if numberOfCharacters < minPasswordCount {
return .failed(message: "Password must be at least \(minPasswordCount) characters")
}
return .ok(message: "Password acceptable")
}
func validateRepeatedPassword(_ password: String, repeatedPassword: String) -> ValidationResult {
if repeatedPassword.characters.count == 0 {
return .empty
}
if repeatedPassword == password {
return .ok(message: "Password repeated")
}
else {
return .failed(message: "Password different")
}
}
}
class GitHubDefaultAPI : GitHubAPI {
let URLSession: Foundation.URLSession
static let sharedAPI = GitHubDefaultAPI(
URLSession: Foundation.URLSession.shared
)
init(URLSession: Foundation.URLSession) {
self.URLSession = URLSession
}
func usernameAvailable(_ username: String) -> Observable<Bool> {
// this is ofc just mock, but good enough
let url = URL(string: "https://github.com/\(username.URLEscaped)")!
let request = URLRequest(url: url)
return self.URLSession.rx.response(request: request)
.map { pair in
return pair.response.statusCode == 404
}
.catchErrorJustReturn(false)
}
func signup(_ username: String, password: String) -> Observable<Bool> {
// this is also just a mock
let signupResult = arc4random() % 5 == 0 ? false : true
return Observable.just(signupResult)
.delay(1.0, scheduler: MainScheduler.instance)
}
}
| e88c797eef15bc3d05e5e8dae7335cb1 | 28.324786 | 104 | 0.610026 | false | false | false | false |
twoefay/ios-client | refs/heads/master | Twoefay/Controller/HomePageViewController.swift | gpl-3.0 | 1 | //
// HomePageViewController.swift
// Twoefay
//
// Created by Bruin OnLine on 5/5/16.
// Copyright © 2016 Twoefay. All rights reserved.
//
import UIKit
import LocalAuthentication
class HomePageViewController: UIViewController {
@IBOutlet weak var statusLabel: UILabel!
let context = LAContext()
let policy = LAPolicy.DeviceOwnerAuthenticationWithBiometrics
let error: NSErrorPointer = nil
override func viewDidLoad() {
super.viewDidLoad()
statusLabel.text = ""
}
func touchIDNotAvailable(){
statusLabel.text = "TouchID not available on this device."
}
func authenticationSucceeded(){
dispatch_async(dispatch_get_main_queue()) {
self.statusLabel.text = "Authentication successful"
}
}
func authenticationFailed(error: NSError){
dispatch_async(dispatch_get_main_queue()) {
self.statusLabel.text = "Error occurred: \(error.localizedDescription)"
}
}
@IBAction func buttonTapped(sender: AnyObject) {
if context.canEvaluatePolicy(policy, error: error){
context.evaluatePolicy(policy, localizedReason: "Pleace authenticate using TouchID"){ status, error in
status ? self.authenticationSucceeded() : self.authenticationFailed(error!)
}
} else {
touchIDNotAvailable()
}
}
}
| 9c0ce188ec6105a9f26a6b06b4fae661 | 26.862745 | 114 | 0.641802 | false | false | false | false |
btanner/Eureka | refs/heads/master | Source/Core/NavigationAccessoryView.swift | mit | 1 | // NavigationAccessoryView.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public protocol NavigationAccessory {
var doneClosure: (() -> ())? { get set }
var nextClosure: (() -> ())? { get set }
var previousClosure: (() -> ())? { get set }
var previousEnabled: Bool { get set }
var nextEnabled: Bool { get set }
}
/// Class for the navigation accessory view used in FormViewController
@objc(EurekaNavigationAccessoryView)
open class NavigationAccessoryView: UIToolbar, NavigationAccessory {
open var previousButton: UIBarButtonItem!
open var nextButton: UIBarButtonItem!
open var doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(didTapDone))
private var fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
private var flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
public override init(frame: CGRect) {
super.init(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 44.0))
autoresizingMask = .flexibleWidth
fixedSpace.width = 22.0
initializeChevrons()
setItems([previousButton, fixedSpace, nextButton, flexibleSpace, doneButton], animated: false)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func drawChevron(pointingRight: Bool) -> UIImage? {
// Hardcoded chevron size
let width = 12
let height = 20
// Begin the image context, with which we are going to draw a chevron
UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0.0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
defer {
UIGraphicsEndImageContext()
}
// The chevron looks like > or <. This can be drawn with 3 points; the Y coordinates of the points
// are independant of whether it is to be pointing left or right; the X coordinates will depend, as follows.
// The 1s are to ensure that the point of the chevron does not sit exactly on the edge of the frame, which
// would slightly truncate the point.
let chevronPointXCoordinate, chevronTailsXCoordinate: Int
if pointingRight {
chevronPointXCoordinate = width - 1
chevronTailsXCoordinate = 1
} else {
chevronPointXCoordinate = 1
chevronTailsXCoordinate = width - 1
}
// Draw the lines and return the image
context.setLineWidth(1.5)
context.setLineCap(.square)
context.strokeLineSegments(between: [
CGPoint(x: chevronTailsXCoordinate, y: 0),
CGPoint(x: chevronPointXCoordinate, y: height / 2),
CGPoint(x: chevronPointXCoordinate, y: height / 2),
CGPoint(x: chevronTailsXCoordinate, y: height)
])
return UIGraphicsGetImageFromCurrentImageContext()
}
private func initializeChevrons() {
var imageLeftChevron, imageRightChevron: UIImage?
if #available(iOS 13.0, *) {
// If we have access to SFSymbols, use the system chevron images, rather than faffing around with our own
imageLeftChevron = UIImage(systemName: "chevron.left")
imageRightChevron = UIImage(systemName: "chevron.right")
} else {
imageLeftChevron = drawChevron(pointingRight: false)
imageRightChevron = drawChevron(pointingRight: true)
}
// RTL language support
imageLeftChevron = imageLeftChevron?.imageFlippedForRightToLeftLayoutDirection()
imageRightChevron = imageRightChevron?.imageFlippedForRightToLeftLayoutDirection()
previousButton = UIBarButtonItem(image: imageLeftChevron, style: .plain, target: self, action: #selector(didTapPrevious))
nextButton = UIBarButtonItem(image: imageRightChevron, style: .plain, target: self, action: #selector(didTapNext))
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {}
public var doneClosure: (() -> ())?
public var nextClosure: (() -> ())?
public var previousClosure: (() -> ())?
@objc private func didTapDone() {
doneClosure?()
}
@objc private func didTapNext() {
nextClosure?()
}
@objc private func didTapPrevious() {
previousClosure?()
}
public var previousEnabled: Bool {
get {
return previousButton.isEnabled
}
set {
previousButton.isEnabled = newValue
}
}
public var nextEnabled: Bool {
get {
return nextButton.isEnabled
}
set {
nextButton.isEnabled = newValue
}
}
}
| 529a214858ddc1e9c45cc4da179de5b7 | 38.993333 | 129 | 0.672779 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/interval-list-intersections.swift | mit | 2 | /**
* https://leetcode.com/problems/interval-list-intersections/
*
*
*/
// Date: Sat May 23 13:24:00 PDT 2020
class Solution {
/// Two pointers track on the indices of 2 arrays.
func intervalIntersection(_ A: [[Int]], _ B: [[Int]]) -> [[Int]] {
var ret: [[Int]] = []
var index1 = 0
var index2 = 0
while index1 < A.count, index2 < B.count {
if A[index1][1] < B[index2][0] {
index1 += 1
} else if B[index2][1] < A[index1][0] {
index2 += 1
} else if A[index1][1] <= B[index2][1], A[index1][0] >= B[index2][0] {
ret.append(A[index1])
index1 += 1
} else if B[index2][1] <= A[index1][1], B[index2][0] >= A[index1][0] {
ret.append(B[index2])
index2 += 1
} else if A[index1][1] <= B[index2][1], A[index1][0] <= B[index2][0] {
ret.append([B[index2][0], A[index1][1]])
index1 += 1
} else if B[index2][1] <= A[index1][1], B[index2][0] <= A[index1][0] {
ret.append([A[index1][0], B[index2][1]])
index2 += 1
}
}
return ret
}
}
| 72f528f26e7756f8ef2b1cb4dab264ef | 34.257143 | 82 | 0.439222 | false | false | false | false |
mownier/pyrobase | refs/heads/master | PyrobaseTests/RequestTest.swift | mit | 1 | //
// RequestTest.swift
// Pyrobase
//
// Created by Mounir Ybanez on 02/05/2017.
// Copyright © 2017 Ner. All rights reserved.
//
import XCTest
@testable import Pyrobase
class RequestTest: XCTestCase {
func testRead() {
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testRead")
request.read(path: "https://foo.firebaseio.com/users/12345/name.json?access_token=accessToken", query: [:]) { result in
switch result {
case .failed:
XCTFail()
case .succeeded(let data):
XCTAssertTrue(data is String)
XCTAssertEqual(data as! String, "Luche")
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testReadWithInt() {
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testRead")
request.read(path: "https://foo.firebaseio.com/users/12345/int.json?access_token=accessToken", query: [:]) { result in
switch result {
case .failed:
XCTFail()
case .succeeded(let data):
XCTAssertTrue(data is String)
let number = Int(data as! String)
XCTAssertNotNil(number)
XCTAssertEqual(number, 101)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testReadWithDouble() {
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testRead")
request.read(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", query: [:]) { result in
switch result {
case .failed:
XCTFail()
case .succeeded(let data):
XCTAssertTrue(data is String)
let number = Double(data as! String)
XCTAssertNotNil(number)
XCTAssertEqual(number, 101.12345)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testReadWithInvalidURL() {
let request = Request.create()
let expectation1 = expectation(description: "testRead")
request.read(path: "", query: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let error):
XCTAssertTrue(error is RequestError)
let errorInfo = error as! RequestError
XCTAssertTrue(errorInfo == RequestError.invalidURL)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testReadWithError() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testRead")
taskResult.error = URLSessionDataTaskMock.TaskMockError.mockError1
session.expectedDataTaskResult = taskResult
request.read(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", query: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let error):
XCTAssertTrue(error is URLSessionDataTaskMock.TaskMockError)
let errorInfo = error as! URLSessionDataTaskMock.TaskMockError
XCTAssertTrue(errorInfo == URLSessionDataTaskMock.TaskMockError.mockError1)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testReadWithNoURLResponse() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testRead")
taskResult.response = nil
session.expectedDataTaskResult = taskResult
request.read(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", query: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let error):
XCTAssertTrue(error is RequestError)
let errorInfo = error as! RequestError
XCTAssertTrue(errorInfo == RequestError.noURLResponse)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testReadWithNilData() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testRead")
taskResult.response = HTTPURLResponse()
session.expectedDataTaskResult = taskResult
request.read(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", query: [:]) { result in
switch result {
case .failed:
XCTFail()
case .succeeded(let info):
XCTAssertTrue(info is [AnyHashable: Any])
let resultInfo = info as! [AnyHashable: Any]
XCTAssertTrue(resultInfo.isEmpty)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testReadWithErrorParsingData() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = RequestOperationMock()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testRead")
taskResult.response = HTTPURLResponse()
taskResult.data = Data(bytes: [1,2,3])
session.expectedDataTaskResult = taskResult
request.read(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", query: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestOperationMock.MockError)
let errorInfo = info as! RequestOperationMock.MockError
XCTAssertTrue(errorInfo == RequestOperationMock.MockError.failedToParse)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testReadWithJSONNull() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testRead")
taskResult.response = HTTPURLResponse()
taskResult.data = "null".data(using: .utf8)
session.expectedDataTaskResult = taskResult
request.read(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", query: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestError)
let resultInfo = info as! RequestError
XCTAssertTrue(resultInfo == RequestError.nullJSON)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testWriteWithInvalidURL() {
let request = Request.create()
let expectation1 = expectation(description: "testWrite")
request.write(path: "", method: .post, data: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let error):
XCTAssertTrue(error is RequestError)
let errorInfo = error as! RequestError
XCTAssertTrue(errorInfo == RequestError.invalidURL)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testWriteWithError() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testWrite")
taskResult.error = URLSessionDataTaskMock.TaskMockError.mockError1
session.expectedDataTaskResult = taskResult
request.write(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", method: .post, data: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let error):
XCTAssertTrue(error is URLSessionDataTaskMock.TaskMockError)
let errorInfo = error as! URLSessionDataTaskMock.TaskMockError
XCTAssertTrue(errorInfo == URLSessionDataTaskMock.TaskMockError.mockError1)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testWriteWithNoURLResponse() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testWrite")
taskResult.response = nil
session.expectedDataTaskResult = taskResult
request.write(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", method: .post, data: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let error):
XCTAssertTrue(error is RequestError)
let errorInfo = error as! RequestError
XCTAssertTrue(errorInfo == RequestError.noURLResponse)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testWriteWithNilData() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testWrite")
taskResult.response = HTTPURLResponse()
session.expectedDataTaskResult = taskResult
request.write(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", method: .post, data: [:]) { result in
switch result {
case .failed:
XCTFail()
case .succeeded(let info):
XCTAssertTrue(info is [AnyHashable: Any])
let resultInfo = info as! [AnyHashable: Any]
XCTAssertTrue(resultInfo.isEmpty)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testWriteWithErrorParsingData() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = RequestOperationMock()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testWrite")
taskResult.response = HTTPURLResponse()
taskResult.data = Data(bytes: [1,2,3])
session.expectedDataTaskResult = taskResult
request.write(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", method: .post, data: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestOperationMock.MockError)
let errorInfo = info as! RequestOperationMock.MockError
XCTAssertTrue(errorInfo == RequestOperationMock.MockError.failedToParse)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testDeleteWithInvalidURL() {
let request = Request.create()
let expectation1 = expectation(description: "testDelete")
request.delete(path: "") { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let error):
XCTAssertTrue(error is RequestError)
let errorInfo = error as! RequestError
XCTAssertTrue(errorInfo == RequestError.invalidURL)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testDeleteWithError() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testDelete")
taskResult.error = URLSessionDataTaskMock.TaskMockError.mockError1
session.expectedDataTaskResult = taskResult
request.delete(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken") { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let error):
XCTAssertTrue(error is URLSessionDataTaskMock.TaskMockError)
let errorInfo = error as! URLSessionDataTaskMock.TaskMockError
XCTAssertTrue(errorInfo == URLSessionDataTaskMock.TaskMockError.mockError1)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testDeleteWithNoURLResponse() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testDelete")
taskResult.response = nil
session.expectedDataTaskResult = taskResult
request.delete(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken") { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let error):
XCTAssertTrue(error is RequestError)
let errorInfo = error as! RequestError
XCTAssertTrue(errorInfo == RequestError.noURLResponse)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testDeleteNilData() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testDelete")
taskResult.response = HTTPURLResponse()
session.expectedDataTaskResult = taskResult
request.delete(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken") { result in
switch result {
case .failed:
XCTFail()
case .succeeded(let info):
XCTAssertTrue(info is [AnyHashable: Any])
let resultInfo = info as! [AnyHashable: Any]
XCTAssertTrue(resultInfo.isEmpty)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testDeleteWithErrorParsingData() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = RequestOperationMock()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testDelete")
taskResult.response = HTTPURLResponse()
taskResult.data = Data(bytes: [1,2,3])
session.expectedDataTaskResult = taskResult
request.delete(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken") { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestOperationMock.MockError)
let errorInfo = info as! RequestOperationMock.MockError
XCTAssertTrue(errorInfo == RequestOperationMock.MockError.failedToParse)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testDeleteWithJSONNull() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testDelete")
taskResult.response = HTTPURLResponse()
taskResult.data = "null".data(using: .utf8)
session.expectedDataTaskResult = taskResult
request.delete(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken") { result in
switch result {
case .failed:
XCTFail()
case .succeeded(let info):
XCTAssertTrue(info is String)
let resultInfo = info as! String
XCTAssertEqual(resultInfo.lowercased(), "null")
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testWriteHavingPOSTWithJSONNull() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testWritePOST")
taskResult.response = HTTPURLResponse()
taskResult.data = "null".data(using: .utf8)
session.expectedDataTaskResult = taskResult
request.write(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", method: .post, data: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestError)
let resultInfo = info as! RequestError
XCTAssertTrue(resultInfo == RequestError.nullJSON)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testWriteHavingPUTWithJSONNull() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testWritePUT")
taskResult.response = HTTPURLResponse()
taskResult.data = "null".data(using: .utf8)
session.expectedDataTaskResult = taskResult
request.write(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", method: .put, data: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestError)
let resultInfo = info as! RequestError
XCTAssertTrue(resultInfo == RequestError.nullJSON)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testWriteHavingPATCHWithJSONNull() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testWritePATCH")
taskResult.response = HTTPURLResponse()
taskResult.data = "null".data(using: .utf8)
session.expectedDataTaskResult = taskResult
request.write(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", method: .patch, data: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestError)
let resultInfo = info as! RequestError
XCTAssertTrue(resultInfo == RequestError.nullJSON)
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testReadShouldReturnErroneous() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testRead")
taskResult.response = HTTPURLResponse(url: URL(string: "https://sampleio.com")!, statusCode: 400, httpVersion: nil, headerFields: nil)
session.expectedDataTaskResult = taskResult
request.read(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", query: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestError)
let resultInfo = info as! RequestError
XCTAssertTrue(resultInfo == .badRequest(""))
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testWriteShouldReturnErroneous() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = RequestOperationMock()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testWrite")
taskResult.response = HTTPURLResponse(url: URL(string: "https://sampleio.com")!, statusCode: 500, httpVersion: nil, headerFields: nil)
session.expectedDataTaskResult = taskResult
request.write(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken", method: .post, data: [:]) { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestError)
let errorInfo = info as! RequestError
XCTAssertTrue(errorInfo == .internalServiceError(""))
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testDeleteShouldReturnErroneous() {
let taskResult = URLSessionDataTaskMock.Result()
let session = URLSessionMock()
let operation = RequestOperationMock()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
let expectation1 = expectation(description: "testDelete")
taskResult.response = HTTPURLResponse(url: URL(string: "https://sampleio.com")!, statusCode: 404, httpVersion: nil, headerFields: nil)
session.expectedDataTaskResult = taskResult
request.delete(path: "https://foo.firebaseio.com/users/12345/double.json?access_token=accessToken") { result in
switch result {
case .succeeded:
XCTFail()
case .failed(let info):
XCTAssertTrue(info is RequestError)
let errorInfo = info as! RequestError
XCTAssertTrue(errorInfo == .notFound(""))
}
expectation1.fulfill()
}
waitForExpectations(timeout: 1)
}
func testBuildURLforGETWithNonEmptyData() {
let request = Request.create()
var path = "https://foo.firebaseio.com/posts"
var url = request.buildURL(path, .get, ["orderBy": "\"$key\"", "limitToFirst": 1])
XCTAssertNotNil(url)
XCTAssertEqual(url!.absoluteString, "\(path)?orderBy=%22$key%22&limitToFirst=1")
let accessToken = "accessToken"
path = "https://foo.firebaseio.com/posts.json?auth=\(accessToken)"
url = request.buildURL(path, .get, ["orderBy": "\"$key\"", "limitToFirst": 1])
XCTAssertNotNil(url)
XCTAssertEqual(url!.absoluteString, "\(path)&orderBy=%22$key%22&limitToFirst=1")
url = request.buildURL("", .get, ["orderBy": "\"$key\"", "limitToFirst": 1])
XCTAssertNil(url)
}
}
| b5e6f04ca074e7cd7fd41dd5d0004871 | 39.841716 | 145 | 0.600167 | false | true | false | false |
thelowlypeon/bikeshare-kit | refs/heads/master | BikeshareKit/BikeshareKit/Common/NSDateExtension.swift | mit | 1 | //
// NSDateExtension.swift
// BikeshareKit
//
// Created by Peter Compernolle on 12/19/15.
// Copyright © 2015 Out of Something, LLC. All rights reserved.
//
import Foundation
private var APIDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.timeZone = TimeZone(identifier: "UTC")
return formatter
}()
extension Date {
public static func fromAPIString(_ string: String?) -> Date? {
return string != nil ? APIDateFormatter.date(from: string!) : nil
}
}
| e6e4dc6e21bd1f3ab79e8970bec617aa | 24.818182 | 73 | 0.684859 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | Stripe/STPEphemeralKey.swift | mit | 1 | //
// STPEphemeralKey.swift
// StripeiOS
//
// Created by Ben Guo on 5/4/17.
// Copyright © 2017 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripePayments
class STPEphemeralKey: NSObject, STPAPIResponseDecodable {
private(set) var stripeID: String
private(set) var created: Date
private(set) var livemode = false
private(set) var secret: String
private(set) var expires: Date
private(set) var customerID: String?
private(set) var issuingCardID: String?
/// You cannot directly instantiate an `STPEphemeralKey`. You should instead use
/// `decodedObjectFromAPIResponse:` to create a key from a JSON response.
required init(
stripeID: String,
created: Date,
secret: String,
expires: Date
) {
self.stripeID = stripeID
self.created = created
self.secret = secret
self.expires = expires
super.init()
}
private(set) var allResponseFields: [AnyHashable: Any] = [:]
class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? {
guard let response = response else {
return nil
}
let dict = response.stp_dictionaryByRemovingNulls()
// required fields
guard
let stripeId = dict.stp_string(forKey: "id"),
let created = dict.stp_date(forKey: "created"),
let secret = dict.stp_string(forKey: "secret"),
let expires = dict.stp_date(forKey: "expires"),
let associatedObjects = dict.stp_array(forKey: "associated_objects"),
dict["livemode"] != nil
else {
return nil
}
var customerID: String?
var issuingCardID: String?
for obj in associatedObjects {
if let obj = obj as? [AnyHashable: Any] {
let type = obj.stp_string(forKey: "type")
if type == "customer" {
customerID = obj.stp_string(forKey: "id")
}
if type == "issuing.card" {
issuingCardID = obj.stp_string(forKey: "id")
}
}
}
if customerID == nil && issuingCardID == nil {
return nil
}
let key = self.init(stripeID: stripeId, created: created, secret: secret, expires: expires)
key.customerID = customerID
key.issuingCardID = issuingCardID
key.stripeID = stripeId
key.livemode = dict.stp_bool(forKey: "livemode", or: true)
key.created = created
key.secret = secret
key.expires = expires
key.allResponseFields = response
return key
}
override var hash: Int {
return stripeID.hash
}
override func isEqual(_ object: Any?) -> Bool {
if self === (object as? STPEphemeralKey) {
return true
}
if object == nil || !(object is STPEphemeralKey) {
return false
}
if let object = object as? STPEphemeralKey {
return isEqual(to: object)
}
return false
}
func isEqual(to other: STPEphemeralKey) -> Bool {
return stripeID == other.stripeID
}
}
| ae34af89589a4edff24d98cacd50f12e | 30.076923 | 99 | 0.575804 | false | false | false | false |
Nocookieleft/Jump-r-Drop | refs/heads/master | Tower/Tower/Platform.swift | gpl-3.0 | 1 |
//
// Platform.swift
// Tower
//
// Created by Evil Cookie on 05/06/15.
// Copyright (c) 2015 Evil Cookie. All rights reserved.
//
import Foundation
import SpriteKit
class Platform: SKSpriteNode {
var isMoving = false
init(size: CGSize) {
// render the platforms by sprite from the image assets
let platformTexture = SKTexture(imageNamed: "floor")
super.init(texture: platformTexture, color: nil, size: size)
self.name = "platform"
// use physicsbody to simulate gravity, should not happen for platforms
// self.physicsBody = SKPhysicsBody(edgeLoopFromRect: CGRect(x: 0, y: 0, width: size.width, height: size.height))
self.physicsBody = SKPhysicsBody(rectangleOfSize: size)
self.physicsBody?.categoryBitMask = platformCategory
self.physicsBody?.contactTestBitMask = playerCategory | rockBottomCategory
self.physicsBody?.collisionBitMask = platformCategory
self.physicsBody?.affectedByGravity = false
self.physicsBody?.dynamic = false
}
// start moving platform down the screen
func startMoving(){
let moveDown = SKAction.moveByX(0, y: -kDefaultSpeed , duration: 1.0)
runAction(SKAction.repeatActionForever(moveDown))
isMoving = true
}
// stop platform from moving
func stopMoving(){
if self.hasActions()
{
self.removeAllActions()
isMoving = false
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| a6bac242847c07e387180d47526e7a62 | 25.629032 | 120 | 0.631738 | false | false | false | false |
blg-andreasbraun/Operations | refs/heads/development | Tests/Location/ReverseGeocodeProcedureTests.swift | mit | 2 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import XCTest
import CoreLocation
import MapKit
import ProcedureKit
import TestingProcedureKit
@testable import ProcedureKitLocation
class ReverseGeocodeProcedureTests: LocationProcedureTestCase {
func test__geocoder_starts() {
geocoder.placemarks = [placemark]
let procedure = ReverseGeocodeProcedure(location: location)
procedure.geocoder = geocoder
wait(for: procedure)
XCTAssertProcedureFinishedWithoutErrors(procedure)
XCTAssertEqual(geocoder.didReverseGeocodeLocation, location)
}
func test__geocoder_returns_error_finishes_with_error() {
geocoder.error = TestError()
let procedure = ReverseGeocodeProcedure(location: location)
procedure.geocoder = geocoder
wait(for: procedure)
XCTAssertProcedureFinishedWithErrors(procedure, count: 1)
XCTAssertEqual(geocoder.didReverseGeocodeLocation, location)
}
func test__geocoder_cancels_when_cancelled() {
let procedure = ReverseGeocodeProcedure(location: location)
procedure.geocoder = geocoder
check(procedure: procedure) { $0.cancel() }
XCTAssertTrue(geocoder.didCancel)
}
func test__result_is_set() {
geocoder.placemarks = [placemark]
let procedure = ReverseGeocodeProcedure(location: location)
procedure.geocoder = geocoder
wait(for: procedure)
XCTAssertProcedureFinishedWithoutErrors(procedure)
XCTAssertNotNil(procedure.output.success)
XCTAssertEqual(procedure.output.success, geocoder.placemarks?.first)
}
func test__completion_is_executed_and_receives_placemark() {
weak var exp = expectation(description: "Test: \(#function)")
var didReceivePlacemark: CLPlacemark? = nil
geocoder.placemarks = [placemark]
let procedure = ReverseGeocodeProcedure(location: location) { placemark in
didReceivePlacemark = placemark
exp?.fulfill()
}
procedure.geocoder = geocoder
wait(for: procedure)
XCTAssertProcedureFinishedWithoutErrors(procedure)
XCTAssertNotNil(didReceivePlacemark)
XCTAssertEqual(didReceivePlacemark, geocoder.placemarks?.first)
}
func test__completion_is_executed_on_main_queue() {
weak var exp = expectation(description: "Test: \(#function)")
var didRunCompletionBlockOnMainQueue = false
geocoder.placemarks = [placemark]
let procedure = ReverseGeocodeProcedure(location: location) { _ in
didRunCompletionBlockOnMainQueue = DispatchQueue.isMainDispatchQueue
exp?.fulfill()
}
procedure.geocoder = geocoder
wait(for: procedure)
XCTAssertProcedureFinishedWithoutErrors(procedure)
XCTAssertTrue(didRunCompletionBlockOnMainQueue)
}
}
| 7a44e657022171e45e0aa56c5295e8be | 34.987654 | 82 | 0.699485 | false | true | false | false |
jegumhon/URMovingTransitionAnimator | refs/heads/master | Example/URExampleMovingTransition/URExampleDetailViewController.swift | mit | 1 | //
// URExampleDetailViewController.swift
// URExampleMovingTransition
//
// Created by DongSoo Lee on 2017. 3. 14..
// Copyright © 2017년 zigbang. All rights reserved.
//
import UIKit
import URMovingTransitionAnimator
class URExampleDetailViewController: UIViewController, URMovingTransitionReceivable {
@IBOutlet var imgView: UIImageView!
@IBOutlet var lbText: UILabel!
var image: UIImage!
var text: String!
var transitionView: UIView?
override func viewDidLoad() {
super.viewDidLoad()
self.imgView.image = self.image
self.lbText.text = self.text
self.imgView.contentMode = .scaleAspectFit
}
func transitionFinishingFrame(startingFrame: CGRect) -> CGRect {
self.imgView.layoutIfNeeded()
let frame = self.imgView.frame
let finishingFrame = CGRect(origin: CGPoint(x: 0, y: 64), size: frame.size)
return finishingFrame
}
@IBAction func changImg(_ sender: Any) {
let anim = CABasicAnimation(keyPath: "contents")
anim.fromValue = #imageLiteral(resourceName: "suzy1").cgImage
anim.toValue = #imageLiteral(resourceName: "sulhyun1").cgImage
anim.duration = 0.5
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
anim.fillMode = kCAFillModeForwards
anim.isRemovedOnCompletion = false
self.imgView.layer.add(anim, forKey: nil)
}
}
| 75c3b81ede3ef699a3de715e668f390c | 28.958333 | 88 | 0.690542 | false | false | false | false |
Stitch7/Instapod | refs/heads/master | Instapod/EnumIteratable.swift | mit | 1 | //
// EnumIteratable.swift
// Instapod
//
// Created by Christopher Reitz on 06.09.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import Foundation
protocol EnumIteratable {
associatedtype Enum: Hashable, RawRepresentable = Self
static func values() -> [Enum]
static func rawValues() -> [Enum.RawValue]
}
extension EnumIteratable {
static func values() -> [Enum] {
var retval = [Enum]()
for item in iterateEnum(Enum.self) {
retval.append(item)
}
return retval
}
static func rawValues() -> [Enum.RawValue] {
return values().map { (item: Enum) -> Enum.RawValue in item.rawValue }
}
}
func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafePointer(to: &i) {
$0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee }
}
if next.hashValue != i { return nil }
i += 1
return next
}
}
| da462d5493d534cf30ed2b2a198bef89 | 23.071429 | 78 | 0.59545 | false | false | false | false |
AckeeCZ/ACKReactiveExtensions | refs/heads/master | ACKReactiveExtensions/Realm/RealmObjectExtensions.swift | mit | 1 | //
// RealmObjectExtensions.swift
// Realm
//
// Created by Jakub Olejník on 06/02/2018.
//
//
//import RealmSwift
//import ReactiveSwift
//
//extension Reactive where Base: Object {
// /// Signal with object changes
// ///
// /// Make sure not to subscribe to this signal inside Realm transaction
// var changes: Signal<Base?, RealmError> {
// return Signal { [weak base = base] observer, lifetime in
// guard let base = base else { observer.sendInterrupted(); return }
//
// var notificationToken: NotificationToken? = base.observe { change in
// switch change {
// case .error(let e): observer.send(error: RealmError(underlyingError: e))
// case .deleted:
// observer.send(value: nil)
// observer.sendCompleted()
// case .change: observer.send(value: base)
// }
// }
//
// lifetime.observeEnded {
// _ = notificationToken // silence Xcode warning, token needs to be held strongly
// notificationToken = nil
// }
// }
// }
//
// /// Property with current object state
// ///
// /// Make sure not to create this property inside Realm transaction
// var property: ReactiveSwift.Property<Base?> {
// return Property(initial: base, then: changes.flatMapError { _ in SignalProducer(value: nil) })
// }
//}
| 61adcf72060cd6d2ade0329794c49c1f | 33.642857 | 104 | 0.569759 | false | false | false | false |
saketh93/SlideMenu | refs/heads/master | SlideMenu/Extensions.swift | mit | 1 | //
// Extensions.swift
// SlideMenu
//
// Created by Saketh Manemala on 28/06/17.
// Copyright © 2017 Saketh. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func imageWithImage(_ image:UIImage,scaledToSize newSize:CGSize)->UIImage{
UIGraphicsBeginImageContext( newSize )
image.draw(in: CGRect(x: 0,y: 0,width: newSize.width,height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!.withRenderingMode(.alwaysTemplate)
}
}
extension HomeViewController : MenuViewControllerDelegate {
// func configureFirstText(_ textField: UITextField!)
// {
// if let aTextField = textField {
// // aTextField.backgroundColor = UIColor.clearColor()
// aTextField.placeholder = " Address"
// aTextField.borderStyle = UITextBorderStyle.roundedRect
// }
// }
func forSideMenuCollapse() {
delegate?.collapseSidePanels()
}
}
| f349f592c53f1594eda24987169b3d48 | 28.083333 | 85 | 0.673352 | false | false | false | false |
skylib/SnapImagePicker | refs/heads/master | SnapImagePicker_Unit_Tests/TestDoubles/PhotoLoaderSpy.swift | bsd-3-clause | 1 | import Photos
@testable import SnapImagePicker
class PhotoLoaderSpy: ImageLoaderProtocol, AlbumLoaderProtocol {
var loadImageFromAssetCount = 0
var loadImageFromAssetAsset: PHAsset?
var loadImageFromAssetIsPreview: Bool?
var loadImageFromAssetPreviewSize: CGSize?
var loadImageFromAssetHandler: ((SnapImagePickerImage) -> ())?
var loadImagesFromAssetsCount = 0
var loadImagesFromAssetsAssets: [Int: PHAsset]?
var loadImagesFromAssetsSize: CGSize?
var loadImagesFromAssetsHandler: (([Int: SnapImagePickerImage]) -> ())?
var fetchAssetsFromCollectionWithTypeCount = 0
var fetchAssetsFromCollectionWithTypeType: AlbumType?
var fetchAllPhotosPreviewsCount = 0
var fetchAllPhotosPreviewsTargetSize: CGSize?
var fetchAllPhotosPreviewsHandler: ((Album) -> Void)?
var fetchFavoritesPreviewsCount = 0
var fetchFavoritesPreviewsTargetSize: CGSize?
var fetchFavoritesPreviewsHandler: ((Album) -> Void)?
var fetchUserAlbumPreviewsCount = 0
var fetchUserAlbumPreviewsTargetSize: CGSize?
var fetchUserAlbumPreviewsHandler: ((Album) -> Void)?
var fetchSmartAlbumPreviewsCount = 0
var fetchSmartAlbumPreviewsTargetSize: CGSize?
var fetchSmartAlbumPreviewsHandler: ((Album) -> Void)?
func loadImageFromAsset(_ asset: PHAsset, isPreview: Bool, withPreviewSize previewSize: CGSize , handler: @escaping (SnapImagePickerImage) -> ()) -> PHImageRequestID {
loadImageFromAssetCount += 1
loadImageFromAssetAsset = asset
loadImageFromAssetIsPreview = isPreview
loadImageFromAssetPreviewSize = previewSize
loadImageFromAssetHandler = handler
return PHImageRequestID()
}
func loadImagesFromAssets(_ assets: [Int: PHAsset], withTargetSize targetSize: CGSize, handler: @escaping ([Int: SnapImagePickerImage]) -> ()) -> [Int: PHImageRequestID] {
loadImagesFromAssetsCount += 1
loadImagesFromAssetsAssets = assets
loadImagesFromAssetsSize = targetSize
loadImagesFromAssetsHandler = handler
return [Int: PHImageRequestID]()
}
func fetchAssetsFromCollectionWithType(_ type: AlbumType) -> PHFetchResult<PHAsset>? {
fetchAssetsFromCollectionWithTypeCount += 1
fetchAssetsFromCollectionWithTypeType = type
return nil
}
func fetchAllPhotosPreview(_ targetSize: CGSize, handler: @escaping (Album) -> Void) {
fetchAllPhotosPreviewsCount += 1
fetchAllPhotosPreviewsTargetSize = targetSize
fetchAllPhotosPreviewsHandler = handler
}
func fetchFavoritesPreview(_ targetSize: CGSize, handler: @escaping (Album) -> Void) {
fetchFavoritesPreviewsCount += 1
fetchFavoritesPreviewsTargetSize = targetSize
fetchFavoritesPreviewsHandler = handler
}
func fetchAllUserAlbumPreviews(_ targetSize: CGSize, handler: @escaping (Album) -> Void) {
fetchUserAlbumPreviewsCount += 1
fetchUserAlbumPreviewsTargetSize = targetSize
fetchUserAlbumPreviewsHandler = handler
}
func fetchAllSmartAlbumPreviews(_ targetSize: CGSize, handler: @escaping (Album) -> Void) {
fetchSmartAlbumPreviewsCount += 1
fetchSmartAlbumPreviewsTargetSize = targetSize
fetchSmartAlbumPreviewsHandler = handler
}
func loadImageWithLocalIdentifier(_ identifier: String, handler: @escaping ((SnapImagePickerImage) -> Void)) {}
func deleteRequests(_ requestIds: [PHImageRequestID]) {}
}
| 054d453edcd7b0bdc320d9a901c4bc59 | 39.781609 | 175 | 0.719842 | false | false | false | false |
wangxin20111/WXWeiBo | refs/heads/master | WXWeibo/WXWeibo/Classes/NewFeature/WXWelcomeController.swift | mit | 1 | //
// WXWelcomeController.swift
// WXWeibo
//
// Created by 王鑫 on 16/7/16.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
import PureLayout
import SDWebImage
class WXWelcomeController: UIViewController {
//MARK: - 基本属性
let kWXImageIconHeight: CGFloat = 80.0
var headViewToSupTopConstr:NSLayoutConstraint?
//MARK: - 懒加载对象
//背景图片
lazy var bgView: UIImageView = {
let bg = UIImageView()
bg.image = UIImage(named:"ad_background")
bg.frame = UIScreen.mainScreen().bounds
return bg
}()
//头像
lazy var headIcon: UIImageView = {
let head = UIImageView()
head.image = UIImage(named:"avatar_default_big")
return head
}()
//姓名
lazy var titleLab: UILabel = {
let t = UILabel()
t.text = "名字"
t.alpha = 0.0
return t
}()
//MARK: - 对外提供的对象方法
//MARK: - 对外提供的类方法
//MARK: - Vc的生命周期函数
override func viewDidLoad() {
super.viewDidLoad()
//添加子控件
setupSubViews()
//更新头像
let user = WXUser.fetchUserInfo()
if user?.avatorImage != nil
{
let str = user!.avatorImage! as String
headIcon.sd_setImageWithURL(NSURL(string:str))
titleLab.text = user!.screenName
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//创建完之后,开始执行动画
headViewToSupTopConstr?.constant = 100
headIcon.alpha = 0.0
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.7, options: UIViewAnimationOptions(rawValue:0), animations: {
self.view.layoutIfNeeded()
self.headIcon.alpha = 1.0
}) { (_) in
UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue:0), animations: {
self.titleLab.alpha = 1.0
}, completion: { (_) in
//应该过几秒发送通知的
WXNotificationCenter.postNotificationName(WXChangeRootViewControllerNotification, object: true)
})
}
}
//MARK: - 私有方法
private func setupSubViews(){
view.addSubview(bgView)
view.addSubview(titleLab)
view.addSubview(headIcon)
headIcon.layer.cornerRadius = kWXImageIconHeight * 0.5
headIcon.layer.masksToBounds = true
//更新UI布局
setupContrs()
}
//设置布局
private func setupContrs(){
headViewToSupTopConstr = headIcon.autoPinEdgeToSuperviewEdge(ALEdge.Top, withInset: 450)
headIcon.autoAlignAxisToSuperviewAxis(ALAxis.Vertical)
headIcon.autoSetDimensionsToSize(CGSize(width: kWXImageIconHeight,height: kWXImageIconHeight))
//姓名
titleLab.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: headIcon, withOffset: 20)
titleLab.autoAlignAxisToSuperviewAxis(ALAxis.Vertical)
}
}
| a73812b6a4103c8c636a0afd04134f40 | 30.206186 | 171 | 0.613479 | false | false | false | false |
AnnMic/FestivalArchitect | refs/heads/master | FestivalArchitect/Classes/Systems/MoveSystem.swift | mit | 1 | //
// Move.swift
// FestivalTycoon
//
// Created by Ann Michelsen on 25/09/14.
// Copyright (c) 2014 Ann Michelsen. All rights reserved.
//
import Foundation
class MoveSystem : System {
let environment:Environment
init (env:Environment) {
environment = env
}
func update(dt:Float) {
let matcher = All(types:[MoveComponent.self, RenderComponent.self])
let movable:[Entity] = environment.entitiesMatching(matcher)
for entity in movable {
let move = entity.component(MoveComponent)!
let render = entity.component(RenderComponent)!
var newPosition = ccpAdd(render.sprite.position, ccpMult(move.velocity, CGFloat(dt)))
let winSize = CCDirector.sharedDirector().view.frame
newPosition.x = max(min(newPosition.x, winSize.width), 0)
newPosition.y = max(min(newPosition.y, winSize.height), 0)
render.sprite.position = newPosition
// entity.setComponent(newPosition, overwrite: true)
}
}
}
| 262a8cd4c802a2da6923eda59ce105bd | 27.325 | 97 | 0.593998 | false | false | false | false |
esttorhe/SwiftSSH2 | refs/heads/swift-2.0 | SwiftSSH2/FileHandle.swift | mit | 1 |
public typealias SFTP_Handle = COpaquePointer
public struct FileHandle {
private var handle: SFTP_Handle?
private let path: String?
private let session: SSH2Client?
public init(fileHandle _handle: SFTP_Handle, session _session: SSH2Client, path _path: String) {
handle = _handle
session = _session
path = _path
}
public func write(buffer: UnsafePointer<Int8>, maxLength: Int) -> Int {
if let handle = handle {
return libssh2_sftp_write(handle, buffer, maxLength)
} else {
return 0
}
}
public func writeData(data: NSData) throws -> Int {
var offset = 0
var remainder = data.length
// while remainder != 0 {
// let bytes: UnsafePointer<()> = data.bytes
// let bytesWritten = self.write(UnsafePointer<Int8>(bytes+offset), maxLength: remainder)
// if bytesWritten < 0 {
// if let session = session {
// if let path = path {
// if let error = session.sessionError(path: path) {
// return Result<Int, NSError>.failure(error)
// }
// }
// }
//
// return Result<Int, NSError>.failure(NSError(domain: "es.estebantorr.SwiftSSH2", code: -666, userInfo: [NSLocalizedDescriptionKey: "Unable to write data"]))
// } else {
// offset+=bytesWritten
// remainder-=bytesWritten
// }
// }
return 0
}
} | bfb7ad1d8d452e0bcc49b1592ae0a3f9 | 28.083333 | 165 | 0.602151 | false | false | false | false |
PierrePerrin/ShadowView | refs/heads/master | ShadowViewExample/ExampleProgViewController.swift | mit | 1 | //
// ExampleProgViewController.swift
// ShadowView
//
// Created by Pierre Perrin on 26/07/2017.
// Copyright © 2017 Pierreperrin. All rights reserved.
//
import UIKit
class ExampleProgViewController: UIViewController {
let exampleShadowContainerView = ShadowView()
let imageView = UIImageView(image: #imageLiteral(resourceName: "sample.jpg"))
override func loadView() {
super.loadView()
exampleShadowContainerView.frame = self.view.bounds
exampleShadowContainerView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
exampleShadowContainerView.shadowOffset = CGSize(width: 0, height: 10)
exampleShadowContainerView.shadowRadius = 20
imageView.frame.size = CGSize(width: 200, height: 200)
imageView.center = exampleShadowContainerView.center
self.view.addSubview(exampleShadowContainerView)
self.exampleShadowContainerView.addSubview(imageView)
}
override func viewDidLoad() {
super.viewDidLoad()
self.exampleShadowContainerView.updateShadow()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// self.exampleShadowContainerView.updateShadow()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.imageView.center = exampleShadowContainerView.center
self.exampleShadowContainerView.updateShadow()
}
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.
}
*/
}
| 7e86e88f5e3a99b907735dee44609418 | 30.5 | 106 | 0.688988 | false | false | false | false |
WWITDC/Underchess | refs/heads/master | QCMethod.swift | unlicense | 1 | //
// QCMethod.swift
//
// Version 1.2
//
// www.quartzcodeapp.com
//
#if os(iOS)
import UIKit
#else
import Cocoa
#endif
class QCMethod
{
class func reverseAnimation(_ anim : CAAnimation, totalDuration : CFTimeInterval) -> CAAnimation{
var duration :CFTimeInterval = anim.duration + (anim.autoreverses ? anim.duration : 0)
if anim.repeatCount > 1 {
duration = duration * CFTimeInterval(anim.repeatCount)
}
let endTime = anim.beginTime + duration
let reverseStartTime = totalDuration - endTime
var newAnim : CAAnimation!
//Reverse timing function closure
let reverseTimingFunction =
{
(theAnim:CAAnimation) -> Void in
let timingFunction = theAnim.timingFunction;
if timingFunction != nil{
var first : [Float] = [0,0]
var second : [Float] = [0,0]
timingFunction?.getControlPoint(at: 1, values: &first)
timingFunction?.getControlPoint(at: 2, values: &second)
theAnim.timingFunction = CAMediaTimingFunction(controlPoints: 1-second[0], 1-second[1], 1-first[0], 1-first[1])
}
}
//Reverse animation values appropriately
if let basicAnim = anim as? CABasicAnimation{
if !anim.autoreverses{
basicAnim.toValue = basicAnim.fromValue
basicAnim.fromValue = basicAnim.toValue
reverseTimingFunction(basicAnim)
}
basicAnim.beginTime = CFTimeInterval(reverseStartTime)
if reverseStartTime > 0 {
let groupAnim = CAAnimationGroup()
groupAnim.animations = [basicAnim]
groupAnim.duration = maxDurationFromAnimations(groupAnim.animations! as [CAAnimation])
_ = groupAnim.animations?.map{$0.setValue(kCAFillModeBoth, forKey: "fillMode")}
newAnim = groupAnim
}
else{
newAnim = basicAnim
}
}
else if let keyAnim = anim as? CAKeyframeAnimation{
if !anim.autoreverses{
let values : [AnyObject] = keyAnim.values!.reversed() as [AnyObject]
keyAnim.values = values;
reverseTimingFunction(keyAnim)
}
keyAnim.beginTime = CFTimeInterval(reverseStartTime)
if reverseStartTime > 0 {
let groupAnim = CAAnimationGroup()
groupAnim.animations = [keyAnim]
groupAnim.duration = maxDurationFromAnimations(groupAnim.animations! as [CAAnimation])
_ = groupAnim.animations?.map{$0.setValue(kCAFillModeBoth, forKey: "fillMode")}
newAnim = groupAnim
}else{
newAnim = keyAnim
}
}
else if let groupAnim = anim as? CAAnimationGroup{
var newSubAnims : [CAAnimation] = []
for subAnim in groupAnim.animations! as [CAAnimation] {
let newSubAnim = reverseAnimation(subAnim, totalDuration: totalDuration)
newSubAnims.append(newSubAnim)
}
groupAnim.animations = newSubAnims
_ = groupAnim.animations?.map{$0.setValue(kCAFillModeBoth, forKey: "fillMod")}
groupAnim.duration = maxDurationFromAnimations(newSubAnims)
newAnim = groupAnim
}else{
newAnim = anim
}
return newAnim
}
class func groupAnimations(_ animations : [CAAnimation], fillMode : String!, forEffectLayer : Bool, sublayersCount : NSInteger) -> CAAnimationGroup!{
let groupAnimation = CAAnimationGroup()
groupAnimation.animations = animations
if (fillMode != nil){
if let animations = groupAnimation.animations {
for anim in animations {
anim.fillMode = fillMode
}
}
groupAnimation.fillMode = fillMode
groupAnimation.isRemovedOnCompletion = false
}
if forEffectLayer{
groupAnimation.duration = QCMethod.maxDurationOfEffectAnimation(groupAnimation, sublayersCount: sublayersCount)
}else{
groupAnimation.duration = QCMethod.maxDurationFromAnimations(animations)
}
return groupAnimation
}
class func groupAnimations(_ animations : [CAAnimation], fillMode : String!) -> CAAnimationGroup!{
return groupAnimations(animations, fillMode: fillMode, forEffectLayer: false, sublayersCount: 0)
}
class func maxDurationFromAnimations(_ anims : [CAAnimation]) -> CFTimeInterval{
var maxDuration: CGFloat = 0;
for anim in anims {
maxDuration = max(CGFloat(anim.beginTime + anim.duration) * CGFloat(anim.repeatCount == 0 ? 1.0 : anim.repeatCount) * (anim.autoreverses ? 2.0 : 1.0), maxDuration);
}
if maxDuration.isInfinite { return TimeInterval(NSIntegerMax)}
return CFTimeInterval(maxDuration);
}
class func maxDurationOfEffectAnimation(_ anim : CAAnimation, sublayersCount : NSInteger) -> CFTimeInterval{
var maxDuration : CGFloat = 0
if let groupAnim = anim as? CAAnimationGroup{
for subAnim in groupAnim.animations! as [CAAnimation]{
var delay : CGFloat = 0
let instDelay = (subAnim.value(forKey: "instanceDelay") as AnyObject).floatValue;
if (instDelay != nil) {
delay = CGFloat(instDelay!) * CGFloat(sublayersCount - 1);
}
var repeatCountDuration : CGFloat = 0;
if subAnim.repeatCount > 1 {
repeatCountDuration = CGFloat(subAnim.duration) * CGFloat(subAnim.repeatCount-1);
}
var duration : CGFloat = 0;
duration = CGFloat(subAnim.beginTime) + (subAnim.autoreverses ? CGFloat(subAnim.duration) : CGFloat(0)) + delay + CGFloat(subAnim.duration) + CGFloat(repeatCountDuration);
maxDuration = max(duration, maxDuration);
}
}
if maxDuration.isInfinite{
maxDuration = 1000
}
return CFTimeInterval(maxDuration);
}
class func updateValueFromAnimationsForLayers(_ layers : [CALayer]){
CATransaction.begin()
CATransaction.setDisableActions(true)
for aLayer in layers{
if let keys = aLayer.animationKeys() as [String]!{
for animKey in keys{
let anim = aLayer.animation(forKey: animKey)
updateValueForAnimation(anim!, theLayer: aLayer);
}
}
}
CATransaction.commit()
}
class func updateValueForAnimation(_ anim : CAAnimation, theLayer : CALayer){
if let basicAnim = anim as? CABasicAnimation{
if (!basicAnim.autoreverses) {
theLayer.setValue(basicAnim.toValue, forKeyPath: basicAnim.keyPath!)
}
}else if let keyAnim = anim as? CAKeyframeAnimation{
if (!keyAnim.autoreverses) {
theLayer.setValue(keyAnim.values?.last, forKeyPath: keyAnim.keyPath!)
}
}else if let groupAnim = anim as? CAAnimationGroup{
for subAnim in groupAnim.animations! as [CAAnimation]{
updateValueForAnimation(subAnim, theLayer: theLayer)
}
}
}
class func updateValueFromPresentationLayerForAnimation(_ anim : CAAnimation!, theLayer : CALayer){
if let basicAnim = anim as? CABasicAnimation{
theLayer.setValue(theLayer.presentation()?.value(forKeyPath: basicAnim.keyPath!), forKeyPath: basicAnim.keyPath!)
}else if let keyAnim = anim as? CAKeyframeAnimation{
theLayer.setValue(theLayer.presentation()?.value(forKeyPath: keyAnim.keyPath!), forKeyPath: keyAnim.keyPath!)
}else if let groupAnim = anim as? CAAnimationGroup{
for subAnim in groupAnim.animations! as [CAAnimation]{
updateValueFromPresentationLayerForAnimation(subAnim, theLayer: theLayer)
}
}
}
class func addSublayersAnimation(_ anim : CAAnimation, key : String, layer : CALayer){
return addSublayersAnimationNeedReverse(anim, key: key, layer: layer, reverseAnimation: false, totalDuration: 0)
}
class func addSublayersAnimationNeedReverse(_ anim : CAAnimation, key : String, layer : CALayer, reverseAnimation : Bool, totalDuration : CFTimeInterval){
let sublayers = layer.sublayers
let sublayersCount = sublayers!.count
let setBeginTime =
{
(subAnim:CAAnimation, sublayerIdx:NSInteger) -> Void in
if let instDelay = (subAnim.value(forKey: "instanceDelay") as AnyObject).floatValue,
let orderType = subAnim.value(forKey: "instanceOrder") as? NSInteger {
let instanceDelay = CGFloat(instDelay)
switch (orderType) {
case 0: subAnim.beginTime = CFTimeInterval(CGFloat(subAnim.beginTime) + CGFloat(sublayerIdx) * instanceDelay)
case 1: subAnim.beginTime = CFTimeInterval(CGFloat(subAnim.beginTime) + CGFloat(sublayersCount - sublayerIdx - 1) * instanceDelay)
case 2:
let middleIdx = sublayersCount/2
let begin = CGFloat(abs(middleIdx - sublayerIdx)) * instanceDelay
subAnim.beginTime += CFTimeInterval(begin)
case 3:
let middleIdx = sublayersCount/2
let begin = CGFloat(middleIdx - abs((middleIdx - sublayerIdx))) * instanceDelay
subAnim.beginTime += CFTimeInterval(begin)
default:
break
}
}
}
for (idx, sublayer) in sublayers!.enumerated() {
if let groupAnim = anim.copy() as? CAAnimationGroup{
var newSubAnimations : [CAAnimation] = []
for subAnim in groupAnim.animations!{
newSubAnimations.append(subAnim.copy() as! CAAnimation)
}
groupAnim.animations = newSubAnimations
let animations = groupAnim.animations
for sub in animations! as [CAAnimation]{
setBeginTime(sub, idx)
//Reverse animation if needed
if reverseAnimation {
_ = self.reverseAnimation(sub, totalDuration: totalDuration)
}
}
sublayer.add(groupAnim, forKey: key)
}
else{
let copiedAnim = anim.copy() as! CAAnimation
setBeginTime(copiedAnim, idx)
sublayer.add(copiedAnim, forKey: key)
}
}
}
#if os(iOS)
class func alignToBottomPath(_ path : UIBezierPath, layer: CALayer) -> UIBezierPath{
let diff = layer.bounds.maxY - path.bounds.maxY
let transform = CGAffineTransform.identity.translatedBy(x: 0, y: diff)
path.apply(transform)
return path
}
class func offsetPath(_ path : UIBezierPath, offset : CGPoint) -> UIBezierPath{
let affineTransform = CGAffineTransform.identity.translatedBy(x: offset.x, y: offset.y)
path.apply(affineTransform)
return path
}
#else
class func offsetPath(path : NSBezierPath, offset : CGPoint) -> NSBezierPath{
let xfm = NSAffineTransform()
xfm.translateXBy(offset.x, yBy:offset.y)
path.transformUsingAffineTransform(xfm)
return path
}
#endif
}
#if os(iOS)
#else
extension NSBezierPath {
var quartzPath: CGPathRef {
get {
return self.transformToCGPath()
}
}
/// Transforms the NSBezierPath into a CGPathRef
///
/// :returns: The transformed NSBezierPath
private func transformToCGPath() -> CGPathRef {
// Create path
var path = CGPathCreateMutable()
var points = UnsafeMutablePointer<NSPoint>.alloc(3)
let numElements = self.elementCount
if numElements > 0 {
var didClosePath = true
for index in 0..<numElements {
let pathType = self.elementAtIndex(index, associatedPoints: points)
switch pathType {
case .MoveToBezierPathElement:
CGPathMoveToPoint(path, nil, points[0].x, points[0].y)
case .LineToBezierPathElement:
CGPathAddLineToPoint(path, nil, points[0].x, points[0].y)
didClosePath = false
case .CurveToBezierPathElement:
CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y)
didClosePath = false
case .ClosePathBezierPathElement:
CGPathCloseSubpath(path)
didClosePath = true
}
}
//if !didClosePath { CGPathCloseSubpath(path) }
}
points.dealloc(3)
return path
}
}
extension NSImage{
func cgImage() -> CGImageRef{
let data = self.TIFFRepresentation
var imageRef : CGImageRef!
var sourceRef : CGImageSourceRef!
sourceRef = CGImageSourceCreateWithData(data, nil)
if (sourceRef != nil) {
imageRef = CGImageSourceCreateImageAtIndex(sourceRef, 0, nil)
}
return imageRef
}
}
#endif
| b513dfd5ecfa046cf265104e6b83bf27 | 37.337875 | 187 | 0.572779 | false | false | false | false |
mrdepth/EVEOnlineAPI | refs/heads/master | EVEAPI/EVEAPI/EVEAssetList.swift | mit | 1 | //
// EVEAssetList.swift
// EVEAPI
//
// Created by Artem Shimanski on 29.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
public class EVEAssetListItem: EVEObject {
public var itemID: Int64 = 0
public var locationID: Int64 = 0
public var typeID: Int = 0
public var quantity: Int64 = 0
public var rawQuantity: Int64 = 0
public var flag: EVEInventoryFlag = .none
public var singleton: Bool = false
public var contents:[EVEAssetListItem] = []
public weak var parent:EVEAssetListItem? = nil
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
for item in contents {
item.parent = self
}
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
for item in contents {
item.parent = self
}
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"itemID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"locationID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"typeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"quantity":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"rawQuantity":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"flag":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"singleton":EVESchemeElementType.Bool(elementName:nil, transformer:nil),
"contents":EVESchemeElementType.Rowset(elementName: nil, type: EVEAssetListItem.self, transformer: nil)
]
}
}
public class EVEAssetList: EVEResult {
public var assets: [EVEAssetListItem] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"assets":EVESchemeElementType.Rowset(elementName: nil, type: EVEAssetListItem.self, transformer: nil)
]
}
}
| 7f4a6670856c3091ae8fb799051165f9 | 29.121212 | 106 | 0.738934 | false | false | false | false |
powerytg/Accented | refs/heads/master | Accented/UI/Home/Themes/Default/Renderers/DefaultStreamInitialLoadingCell.swift | mit | 1 | //
// StreamInitialLoadingCell.swift
// Accented
//
// Created by You, Tiangong on 5/4/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
class DefaultStreamInitialLoadingCell: UICollectionViewCell {
@IBOutlet weak var loadingIndicator: InlineLoadingView!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var retryButton: PushButton!
private let duration = 0.2
// Reference to the stream view model
weak var streamViewModel : StreamViewModel?
override func awakeFromNib() {
super.awakeFromNib()
// By default, hide the ending symbol and the retry button
retryButton.alpha = 0
messageLabel.alpha = 0
loadingIndicator.loadingIndicator.image = UIImage(named: "DarkLoadingIndicatorLarge")
}
func showRetryState(_ errorMessage : String) {
loadingIndicator.stopLoadingAnimation()
messageLabel.text = errorMessage
UIView.animate(withDuration: duration) { [weak self] in
self?.loadingIndicator.alpha = 0
self?.messageLabel.alpha = 1
self?.retryButton.alpha = 1
}
}
func showLoadingState() {
loadingIndicator.startLoadingAnimation()
UIView.animate(withDuration: duration) { [weak self] in
self?.loadingIndicator.alpha = 1
self?.messageLabel.alpha = 0
self?.retryButton.alpha = 0
}
}
@IBAction func retryButtonDidTouch(_ sender: AnyObject) {
showLoadingState()
if let viewModel = streamViewModel {
viewModel.loadNextPage()
}
}
}
| 17e3312cbb9936ddf68ed237acdf2302 | 27.40678 | 93 | 0.634248 | false | false | false | false |
fousa/trackkit | refs/heads/master | Sources/Classes/Parser/NMEA/Extensions/Point+NMEA.swift | mit | 1 | //
// Point+NMEA.swift
// Pods
//
// Created by Jelle Vandebeeck on 03/06/2017.
//
//
import CoreLocation
extension Point {
convenience init?(nmea line: [String]) {
guard let parser = NMEAParser(line: line) else {
return nil
}
self.init()
recordType = parser.recordType
name = parser.name
time = parser.time
coordinate = parser.coordinate
gpsQuality = parser.gpsQuality
navigationReceiverWarning = parser.navigationReceiverWarning
numberOfSatellites = parser.numberOfSatellites
horizontalDilutionOfPrecision = parser.horizontalDilutionOfPrecision
elevation = parser.elevation
heightOfGeoid = parser.heightOfGeoid
timeSinceLastUpdate = parser.timeSinceLastUpdate
speed = parser.speed
magneticVariation = parser.magneticVariation
trackAngle = parser.trackAngle
stationId = parser.stationId
}
}
| 2a08e7bdd8f2eec7543e2ef91e7fc71e | 25.777778 | 76 | 0.6639 | false | false | false | false |
lukejmann/FBLA2017 | refs/heads/master | Pods/Instructions/Sources/Helpers/CoachMarkInnerLayoutHelper.swift | mit | 1 | // CoachMarkInnerLayoutHelper.swift
//
// Copyright (c) 2016 Frédéric Maquin <[email protected]>
//
// 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
class CoachMarkInnerLayoutHelper {
func horizontalArrowConstraints(for coachMarkViews: CoachMarkViews,
withPosition position: ArrowPosition,
horizontalOffset: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint(
item: coachMarkViews.arrowView, attribute: .centerX, relatedBy: .equal,
toItem: coachMarkViews.bodyView, attribute: position.layoutAttribute,
multiplier: 1, constant: adaptedOffset(for: position, offset: horizontalOffset)
)
}
func horizontalConstraints(forBody body: UIView) -> [NSLayoutConstraint] {
if body.superview == nil {
print("Body's superview was found nil, returned array of constraint will be empty.")
return []
}
return NSLayoutConstraint.constraints(
withVisualFormat: "H:|[bodyView]|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: ["bodyView": body]
)
}
func verticalConstraints(for coachMarkViews: CoachMarkViews, in parentView: UIView,
withProperties properties: CoachMarkViewProperties)
-> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
let verticalArrowOffset = properties.verticalArrowOffset
if properties.orientation == .top {
constraints = topOrientationConstraints(for: coachMarkViews, in: parentView,
verticalArrowOffset: verticalArrowOffset)
} else if properties.orientation == .bottom {
constraints = bottomOrientationConstraints(for: coachMarkViews, in: parentView,
verticalArrowOffset: verticalArrowOffset)
}
return constraints
}
func topConstraint(forBody body: UIView, in parent: UIView) -> NSLayoutConstraint {
return NSLayoutConstraint(
item: parent, attribute: .top, relatedBy: .equal,
toItem: body, attribute: .top,
multiplier: 1, constant: 0
)
}
func bottomConstraint(forBody body: UIView, in parent: UIView) -> NSLayoutConstraint {
return NSLayoutConstraint(
item: parent, attribute: .bottom, relatedBy: .equal,
toItem: body, attribute: .bottom,
multiplier: 1, constant: 0
)
}
private func topOrientationConstraints(for coachMarkViews: CoachMarkViews,
in parentView: UIView, verticalArrowOffset: CGFloat)
-> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(
item: parentView, attribute: .top, relatedBy: .equal,
toItem: coachMarkViews.arrowView, attribute: .top,
multiplier: 1, constant: 0
))
constraints.append(NSLayoutConstraint(
item: coachMarkViews.arrowView, attribute: .bottom, relatedBy: .equal,
toItem: coachMarkViews.bodyView, attribute: .top,
multiplier: 1, constant: adaptedOffset(for: .top, offset: verticalArrowOffset)
))
constraints.append(bottomConstraint(forBody: coachMarkViews.bodyView, in: parentView))
return constraints
}
private func bottomOrientationConstraints(for coachMarkViews: CoachMarkViews,
in parentView: UIView, verticalArrowOffset: CGFloat)
-> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(
item: parentView, attribute: .bottom, relatedBy: .equal,
toItem: coachMarkViews.arrowView, attribute: .bottom,
multiplier: 1, constant: 0
))
constraints.append(NSLayoutConstraint(
item: coachMarkViews.arrowView, attribute: .top, relatedBy: .equal,
toItem: coachMarkViews.bodyView, attribute: .bottom,
multiplier: 1, constant: adaptedOffset(for: .bottom, offset: verticalArrowOffset)
))
constraints.append(topConstraint(forBody: coachMarkViews.bodyView, in: parentView))
return constraints
}
private func adaptedOffset(for arrowPosition: ArrowPosition, offset: CGFloat) -> CGFloat {
switch arrowPosition {
case .leading: return offset
case .center: return -offset
case .trailing: return -offset
}
}
private func adaptedOffset(for arrowOrientation: CoachMarkArrowOrientation,
offset: CGFloat) -> CGFloat {
switch arrowOrientation {
case .top: return offset
case .bottom: return -offset
}
}
}
typealias CoachMarkViews = (bodyView: UIView, arrowView: UIView)
typealias CoachMarkViewProperties = (orientation: CoachMarkArrowOrientation,
verticalArrowOffset: CGFloat)
| 851e75eb8f2bc27d57790c818c9d37d9 | 41.578231 | 98 | 0.644991 | false | false | false | false |
Mioke/PlanB | refs/heads/master | PlanB/PlanB/Base/KMViewController/UIViewController+TaskManager.swift | gpl-3.0 | 1 | //
// UIViewController+TaskManager.swift
// swiftArchitecture
//
// Created by Klein Mioke on 15/11/27.
// Copyright © 2015年 KleinMioke. All rights reserved.
//
import UIKit
extension UIViewController: sender, receiver {
typealias receiveDataType = AnyObject
func doTask(task: () throws -> receiveDataType, identifier: String) {
let block = {
do {
let result = try task()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.finishTaskWithReuslt(result, identifier: identifier)
})
} catch let e {
if let error = e as? ErrorResultType {
self.taskCancelledWithError(error, identifier: identifier)
} else {
Log.debugPrintln("Undefined error")
}
}
}
dispatch_async(dispatch_get_global_queue(0, 0), block)
}
@available(*, deprecated, message="尽量不要使用block回调,保证结构统一性。To make sure the unitarity of callback ,don't use this except neccesary")
func doTask(task: () throws -> receiveDataType, callBack: (receiveDataType) -> Void, failure: (ErrorResultType) -> Void) {
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
do {
let result = try task()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
callBack(result)
})
} catch let e {
if let error = e as? ErrorResultType {
failure(error)
} else {
Log.debugPrintln("Undefined error")
}
}
}
}
func taskCancelledWithError(error: ErrorResultType, identifier: String) {
NetworkManager.dealError(error)
}
/**
Task's callback. 任务的回调函数
- parameter result: Task execution's result. 任务执行返回的结果
- parameter identifier: Task's identifier. 任务的标识
*/
func finishTaskWithReuslt(result: receiveDataType, identifier: String) {
}
}
| 3e97010d52eb36f83b42cf0ad11fd332 | 30.333333 | 134 | 0.541628 | false | false | false | false |
Kalito98/Find-me-a-band | refs/heads/master | Find me a band/Find me a band/ViewControllers/AddBandViewController.swift | mit | 1 | //
// AddBandViewController.swift
// Find me a band
//
// Created by Kaloyan Yanev on 3/25/17.
// Copyright © 2017 Kaloyan Yanev. All rights reserved.
//
import UIKit
import SwiftSpinner
import Toaster
class AddBandViewController: UIViewController, BandsDataDelegate {
@IBOutlet weak var textFieldBandName: UITextField!
@IBOutlet weak var textFieldBandEmail: UITextField!
@IBOutlet weak var textFieldBandPhone: UITextField!
@IBOutlet weak var textFieldGenere: UITextField!
var url: String {
get{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return "\(appDelegate.baseUrl)"
}
}
var sessionManager: SessionManager?
var bandsData: BandsData?
override func viewDidLoad() {
super.viewDidLoad()
sessionManager = SessionManager()
bandsData = BandsData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func createBand(_ sender: UIButton) {
SwiftSpinner.show("Creating Band")
let bandName = textFieldBandName.text
let bandEmail = textFieldBandEmail.text
let bandPhone = textFieldBandPhone.text
let genere = textFieldGenere.text
let bandCreator = sessionManager?.getUsername()
print(bandCreator!)
let bandJson = [
"name": bandName!,
"contactPhone": bandPhone!,
"contactEmail": bandEmail!,
"bandMembers": [],
"creator": bandCreator! as String,
"genre": genere!
] as [String : Any]
self.bandsData?.delegate = self
self.bandsData?.createBand(band: bandJson)
}
func clearTextFields() {
weak var weakSelf = self
DispatchQueue.main.async {
weakSelf?.textFieldBandName.text = ""
weakSelf?.textFieldBandEmail.text = ""
weakSelf?.textFieldBandPhone.text = ""
weakSelf?.textFieldGenere.text = ""
}
}
func didReceiveBandsData(bandsData: Any) {
clearTextFields()
SwiftSpinner.hide()
Toast(text: "Successfully created band", duration: Delay.short).show()
}
func didReceiveBandsError(error: HttpError) {
SwiftSpinner.hide()
Toast(text: "Error creating band", duration: Delay.short).show()
}
}
| e5cf32588f79cd7acc837d4a89ba2b9b | 27.034483 | 78 | 0.615826 | false | false | false | false |
DeeptanshuM/MHacks9 | refs/heads/master | MHacks9/GoogleCloudVisionAPI.swift | apache-2.0 | 1 | //
// GoogleCloudVisionAPI.swift
// MHacks9
//
// Created by Ryuji Mano on 3/25/17.
// Copyright © 2017 DeeptanhuRyujiKenanAvi. All rights reserved.
//
import UIKit
import SwiftyJSON
class GoogleCloudVisionAPI: NSObject {
static let apiKey = "API_KEY"
static let googleURL = "https://vision.googleapis.com/v1/images:annotate?key=\(apiKey)"
static let session = URLSession.shared
static var recognizedText = ""
class func getText(from image: UIImage) {
var data = UIImagePNGRepresentation(image)
// Resize the image if it exceeds the 2MB API limit
if ((data?.count)! > 2097152) {
let old: CGSize = image.size
let new: CGSize = CGSize(width: 800, height: old.height / old.width * 800)
data = resizeImage(new, image: image)
}
getText(with: data!.base64EncodedString(options: .endLineWithCarriageReturn))
}
class func resizeImage(_ imageSize: CGSize, image: UIImage) -> Data {
UIGraphicsBeginImageContext(imageSize)
image.draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
let resizedImage = UIImagePNGRepresentation(newImage!)
UIGraphicsEndImageContext()
return resizedImage!
}
class func getText(with image: String) {
var request = URLRequest(url: URL(string: googleURL)!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// Build our API request
let jsonRequest = [
"requests": [
"image": [
"content": image
],
"features": [
[
"type": "TEXT_DETECTION"
]
]
]
]
let jsonObject = JSON(jsonDictionary: jsonRequest)
// Serialize the JSON
guard let data = try? jsonObject.rawData() else {
return
}
request.httpBody = data
// Run the request on a background thread
let semaphore = DispatchSemaphore(value: 0)
let task: URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "")
return
}
let json = JSON(data)
recognizedText = json["responses"][0]["fullTextAnnotation"]["text"].string!
semaphore.signal()
}
task.resume()
_ = semaphore.wait(timeout: .distantFuture)
}
}
| 1b6ada46707437dd1bbb71eedd9a6b8b | 30.651685 | 99 | 0.559815 | false | false | false | false |
oskarpearson/rileylink_ios | refs/heads/master | MinimedKit/PumpEvents/ResultDailyTotalPumpEvent.swift | mit | 1 | //
// ResultDailyTotalPumpEvent.swift
// RileyLink
//
// Created by Pete Schwamb on 3/8/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct ResultDailyTotalPumpEvent: PumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public init?(availableData: Data, pumpModel: PumpModel) {
if pumpModel.larger {
length = 10
} else {
length = 7
}
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
timestamp = DateComponents(pumpEventBytes: availableData.subdata(in: 5..<7))
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "ResultDailyTotal",
"validDate": String(format: "%04d-%02d-%02d", timestamp.year!, timestamp.month!, timestamp.day!),
]
}
}
| 2e8cb4122698d95cf255f1bcca500797 | 24.487179 | 109 | 0.598592 | false | false | false | false |
Meru-Interactive/iOSC | refs/heads/master | swiftOSC/Elements/OSCMessage.swift | mit | 1 | import Foundation
public class OSCMessage: OSCElement, CustomStringConvertible {
//MARK: Properties
public var address: OSCAddressPattern
public var arguments:[OSCType?] = []
public var data: Data {
get {
var data = Data()
//add address
data.append(self.address.string.toDataBase32())
//create type list
var types = ","
for argument in self.arguments {
if let argument = argument {
types += argument.tag
} else {
//add null tag if nil argument
types += "N"
}
}
data.append(types.toDataBase32())
//get arguments data
for argument in arguments {
if let argument = argument {
data.append(argument.data)
}
}
return data
}
}
public var description: String {
var description = "OSCMessage [Address<\(self.address.string)>"
for argument in self.arguments {
if let int = argument as? Int {
description += " Int<\(int)>"
}
if let float = argument as? Float {
description += " Float<\(float)>"
}
if let float = argument as? Double {
description += " Float<\(float)>"
}
if let string = argument as? String {
description += " String<\(string)>"
}
if let blob = argument as? Blob {
description += " Blob\(blob)"
}
if let bool = argument as? Bool {
description += " <\(bool)>"
}
if argument == nil {
description += " <null>"
}
if argument is Impulse {
description += " <impulse>"
}
if let timetag = argument as? Timetag {
description += " Timetag<\(timetag)>"
}
}
description += "]"
return description
}
//MARK: Initializers
public init(_ address: OSCAddressPattern){
self.address = address
}
public init(_ address: OSCAddressPattern,_ arguments:OSCType?...){
self.address = address
self.arguments = arguments
}
public func add(){
self.arguments.append(nil)
}
//MARK: Methods
public func add(_ arguments: OSCType?...){
self.arguments += arguments
}
}
| 0b05180204e91741b713d950d5d5f8fa | 28.274725 | 71 | 0.458333 | false | false | false | false |
gpr321/ScrollViewRefresh | refs/heads/master | ScrollViewRefresh/ScrollViewRefresh/ScrollViewRefresh/BaseView.swift | mit | 1 | //
// BaseView.swift
// ScrollViewRefresh
//
// Created by mac on 15/3/13.
// Copyright (c) 2015年 gpr. All rights reserved.
//
import UIKit
class BaseView: UIView {
static let HEADER_HEIGHT: CGFloat = 44
static let FOOTER_HEIGHT: CGFloat = 44
static var originOffset = CGPointZero
static var originInset = UIEdgeInsetsZero
weak var newSuperview: UIScrollView?
var isSetUpObserve: Bool = false
override init() {
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
setUpSubViews()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
self.removeFromSuperview()
assert(newSuperview is UIScrollView, "父控件必须继承 UIScrollView ")
self.newSuperview = newSuperview as? UIScrollView
}
func setUpViewFrame() {
var frame = self.frame
frame.size.width = newSuperview!.bounds.size.width
frame.origin.x = 0
if self is HeaderView {
frame.size.height = BaseView.HEADER_HEIGHT
frame.origin.y = -BaseView.HEADER_HEIGHT
} else if self is FooterView {
frame.size.height = BaseView.FOOTER_HEIGHT
frame.origin.y = newSuperview!.contentSize.height
}
self.frame = frame
}
override func layoutSubviews() {
super.layoutSubviews()
setUpViewFrame()
if !isSetUpObserve {
setUpObserver()
isSetUpObserve = true
BaseView.originInset = newSuperview!.contentInset
BaseView.originOffset = newSuperview!.contentOffset
}
}
// MARK: 子类初始化子控件的函数
func setUpSubViews() {
}
func setUpObserver() {
}
}
| cf201c936a371a1d1f9c8215d5bdafd5 | 24.078947 | 69 | 0.60808 | false | false | false | false |
luoziyong/firefox-ios | refs/heads/master | Client/Frontend/Browser/LoginsHelper.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 Foundation
import Shared
import Storage
import XCGLogger
import WebKit
import Deferred
import SwiftyJSON
private let log = Logger.browserLogger
class LoginsHelper: TabHelper {
fileprivate weak var tab: Tab?
fileprivate let profile: Profile
fileprivate var snackBar: SnackBar?
// Exposed for mocking purposes
var logins: BrowserLogins {
return profile.logins
}
class func name() -> String {
return "LoginsHelper"
}
required init(tab: Tab, profile: Profile) {
self.tab = tab
self.profile = profile
if let path = Bundle.main.path(forResource: "LoginsHelper", ofType: "js"), let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
tab.webView!.configuration.userContentController.addUserScript(userScript)
}
}
func scriptMessageHandlerName() -> String? {
return "loginsManagerMessageHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard var res = message.body as? [String: AnyObject] else { return }
guard let type = res["type"] as? String else { return }
// Check to see that we're in the foreground before trying to check the logins. We want to
// make sure we don't try accessing the logins database while we're backgrounded to avoid
// the system from terminating our app due to background disk access.
//
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1307822 for details.
guard UIApplication.shared.applicationState == .active && !profile.isShutdown else {
return
}
// We don't use the WKWebView's URL since the page can spoof the URL by using document.location
// right before requesting login data. See bug 1194567 for more context.
if let url = message.frameInfo.request.url {
// Since responses go to the main frame, make sure we only listen for main frame requests
// to avoid XSS attacks.
if message.frameInfo.isMainFrame && type == "request" {
res["username"] = "" as AnyObject?
res["password"] = "" as AnyObject?
if let login = Login.fromScript(url, script: res),
let requestId = res["requestId"] as? String {
requestLogins(login, requestId: requestId)
}
} else if type == "submit" {
if self.profile.prefs.boolForKey("saveLogins") ?? true {
if let login = Login.fromScript(url, script: res) {
setCredentials(login)
}
}
}
}
}
class func replace(_ base: String, keys: [String], replacements: [String]) -> NSMutableAttributedString {
var ranges = [NSRange]()
var string = base
for (index, key) in keys.enumerated() {
let replace = replacements[index]
let range = string.range(of: key,
options: NSString.CompareOptions.literal,
range: nil,
locale: nil)!
string.replaceSubrange(range, with: replace)
let nsRange = NSRange(location: string.characters.distance(from: string.startIndex, to: range.lowerBound),
length: replace.characters.count)
ranges.append(nsRange)
}
var attributes = [String: AnyObject]()
attributes[NSFontAttributeName] = UIFont.systemFont(ofSize: 13, weight: UIFontWeightRegular)
attributes[NSForegroundColorAttributeName] = UIColor.darkGray
let attr = NSMutableAttributedString(string: string, attributes: attributes)
let font: UIFont = UIFont.systemFont(ofSize: 13, weight: UIFontWeightMedium)
for range in ranges {
attr.addAttribute(NSFontAttributeName, value: font, range: range)
}
return attr
}
func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
return profile.logins.getLoginsForProtectionSpace(protectionSpace)
}
func updateLoginByGUID(_ guid: GUID, new: LoginData, significant: Bool) -> Success {
return profile.logins.updateLoginByGUID(guid, new: new, significant: significant)
}
func removeLoginsWithGUIDs(_ guids: [GUID]) -> Success {
return profile.logins.removeLoginsWithGUIDs(guids)
}
func setCredentials(_ login: LoginData) {
if login.password.isEmpty {
log.debug("Empty password")
return
}
profile.logins
.getLoginsForProtectionSpace(login.protectionSpace, withUsername: login.username)
.uponQueue(DispatchQueue.main) { res in
if let data = res.successValue {
log.debug("Found \(data.count) logins.")
for saved in data {
if let saved = saved {
if saved.password == login.password {
self.profile.logins.addUseOfLoginByGUID(saved.guid)
return
}
self.promptUpdateFromLogin(login: saved, toLogin: login)
return
}
}
}
self.promptSave(login)
}
}
fileprivate func promptSave(_ login: LoginData) {
guard login.isValid.isSuccess else {
return
}
let promptMessage: NSAttributedString
if let username = login.username {
let promptStringFormat = NSLocalizedString("LoginsHelper.PromptSaveLogin.Title", value: "Save login %@ for %@?", comment: "Prompt for saving a login. The first parameter is the username being saved. The second parameter is the hostname of the site.")
promptMessage = NSAttributedString(string: String(format: promptStringFormat, username, login.hostname))
} else {
let promptStringFormat = NSLocalizedString("LoginsHelper.PromptSavePassword.Title", value: "Save password for %@?", comment: "Prompt for saving a password with no username. The parameter is the hostname of the site.")
promptMessage = NSAttributedString(string: String(format: promptStringFormat, login.hostname))
}
if snackBar != nil {
tab?.removeSnackbar(snackBar!)
}
snackBar = TimerSnackBar(attrText: promptMessage,
img: UIImage(named: "key"),
buttons: [
SnackButton(title: Strings.LoginsHelperDontSaveButtonTitle, accessibilityIdentifier: "SaveLoginPrompt.dontSaveButton", callback: { (bar: SnackBar) -> Void in
self.tab?.removeSnackbar(bar)
self.snackBar = nil
return
}),
SnackButton(title: Strings.LoginsHelperSaveLoginButtonTitle, accessibilityIdentifier: "SaveLoginPrompt.saveLoginButton", callback: { (bar: SnackBar) -> Void in
self.tab?.removeSnackbar(bar)
self.snackBar = nil
self.profile.logins.addLogin(login)
LeanplumIntegration.sharedInstance.track(eventName: .savedLoginAndPassword)
})
])
tab?.addSnackbar(snackBar!)
}
fileprivate func promptUpdateFromLogin(login old: LoginData, toLogin new: LoginData) {
guard new.isValid.isSuccess else {
return
}
let guid = old.guid
let formatted: String
if let username = new.username {
let promptStringFormat = NSLocalizedString("LoginsHelper.PromptUpdateLogin.Title", value: "Update login %@ for %@?", comment: "Prompt for updating a login. The first parameter is the username for which the password will be updated for. The second parameter is the hostname of the site.")
formatted = String(format: promptStringFormat, username, new.hostname)
} else {
let promptStringFormat = NSLocalizedString("LoginsHelper.PromptUpdatePassword.Title", value: "Update password for %@?", comment: "Prompt for updating a password with no username. The parameter is the hostname of the site.")
formatted = String(format: promptStringFormat, new.hostname)
}
let promptMessage = NSAttributedString(string: formatted)
if snackBar != nil {
tab?.removeSnackbar(snackBar!)
}
snackBar = TimerSnackBar(attrText: promptMessage,
img: UIImage(named: "key"),
buttons: [
SnackButton(title: Strings.LoginsHelperDontSaveButtonTitle, accessibilityIdentifier: "UpdateLoginPrompt.dontSaveButton", callback: { (bar: SnackBar) -> Void in
self.tab?.removeSnackbar(bar)
self.snackBar = nil
return
}),
SnackButton(title: Strings.LoginsHelperUpdateButtonTitle, accessibilityIdentifier: "UpdateLoginPrompt.updateButton", callback: { (bar: SnackBar) -> Void in
self.tab?.removeSnackbar(bar)
self.snackBar = nil
self.profile.logins.updateLoginByGUID(guid, new: new,
significant: new.isSignificantlyDifferentFrom(old))
})
])
tab?.addSnackbar(snackBar!)
}
fileprivate func requestLogins(_ login: LoginData, requestId: String) {
profile.logins.getLoginsForProtectionSpace(login.protectionSpace).uponQueue(DispatchQueue.main) { res in
var jsonObj = [String: Any]()
if let cursor = res.successValue {
log.debug("Found \(cursor.count) logins.")
jsonObj["requestId"] = requestId
jsonObj["name"] = "RemoteLogins:loginsFound"
jsonObj["logins"] = cursor.map { $0!.toDict() }
}
let json = JSON(jsonObj)
let src = "window.__firefox__.logins.inject(\(json.stringValue()!))"
self.tab?.webView?.evaluateJavaScript(src, completionHandler: { (obj, err) -> Void in
})
}
}
}
| 05f59b2510fa1553ed2d76ba428f30a5 | 43.844538 | 299 | 0.613698 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | refs/heads/master | companion-iPad/Venue-companion/Models/LeaderboardUser.swift | epl-1.0 | 1 | //
// LeaderboardUser.swift
// Venue-companion
//
// Created by Kyle Craig on 10/1/15.
// Copyright © 2015 IBM MIL. All rights reserved.
//
import UIKit
class LeaderboardUser: NSObject {
let id: Int
let firstName: String
let lastName: String
var name: String {return firstName + " " + lastName}
var initials: String {return String(firstName[firstName.startIndex]) + String(lastName[lastName.startIndex])}
let pictureURL: String
let score: Int
init(dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] as? Int,
let firstName = dictionary["first_name"] as? String,
let lastName = dictionary["last_name"] as? String,
let pictureURL = dictionary["avatar"] as? String,
let score = dictionary["score"] as? Int else {
abort()
}
self.id = id
self.firstName = firstName
self.lastName = lastName
self.pictureURL = pictureURL
self.score = score
}
}
| 3c2aa0245449cd562ddeab2d708ac124 | 26.447368 | 113 | 0.600192 | false | false | false | false |
ArnavChawla/InteliChat | refs/heads/master | Carthage/Checkouts/ios-sdk/Source/VisualRecognitionV3/Models/Collection.swift | apache-2.0 | 3 | /**
* Copyright IBM Corporation 2016
*
* 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 RestKit
/** A collection of images to search. */
public struct Collection: JSONDecodable {
/// The unique ID of the collection.
public let collectionID: String
/// The name of the collection.
public let name: String
/// The date the collection was created.
public let created: String
/// The number of images in the collection.
public let images: Int
/// The status of the collection. Returns 'available' when images can be added
/// to the collection. Returns 'unavailable' when the collection is being created
/// or trained.
public let status: String
/// The number of images possible in the collection. Each collection can contain
/// 1000000 images.
public let capacity: String
/// Used internally to initialize a 'Collection' model from JSON.
public init(json: JSON) throws {
collectionID = try json.getString(at: "collection_id")
name = try json.getString(at: "name")
created = try json.getString(at: "created")
images = try json.getInt(at: "images")
status = try json.getString(at: "status")
capacity = try json.getString(at: "capacity")
}
}
| 8af3826bf0363da82ba74f8c836e3e19 | 32.888889 | 85 | 0.682514 | false | false | false | false |
AdaptiveMe/adaptive-arp-darwin | refs/heads/master | adaptive-arp-rt/AdaptiveArpRtiOS/ViewController.swift | apache-2.0 | 1 | /*
* =| ADAPTIVE RUNTIME PLATFORM |=======================================================================================
*
* (C) Copyright 2013-2014 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
*
* 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.
*
* Original author:
*
* * Carlos Lozano Diez
* <http://github.com/carloslozano>
* <http://twitter.com/adaptivecoder>
* <mailto:[email protected]>
*
* Contributors:
*
* * Ferran Vila Conesa
* <http://github.com/fnva>
* <http://twitter.com/ferran_vila>
* <mailto:[email protected]>
*
* =====================================================================================================================
*/
import UIKit
import AdaptiveArpApi
class ViewController: BaseViewController {
/// Webview
@IBOutlet weak var webView: UIWebView!
/// The view controller calls this method when its view property is requested but is currently nil. This method loads or creates a view and assigns it to the view property.
override func loadView() {
super.loadView()
}
internal required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
/// This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadView method.
override func viewDidLoad() {
super.viewDidLoad()
(AppRegistryBridge.sharedInstance.getPlatformContextWeb().getDelegate()! as! AppContextWebviewDelegate).setWebviewPrimary(self.webView!)
let req = NSURLRequest(URL: NSURL(string: "https://adaptiveapp/index.html")!)
(self.webView! as UIWebView).loadRequest(req)
// MARK: Waiting on Bug fix to support NSProtocol
/*if (NSClassFromString("WKWebView") != nil) {
(self.webView! as WKWebView).loadRequest(req)
} else {
(self.webView! as UIWebView).loadRequest(req)
}*/
self.navigationController?.view.backgroundColor = self.view.backgroundColor
//self.navigationController?.navigationBar.backgroundColor = self.view.backgroundColor
}
var tested : Bool = false;
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
/// Sent to the view controller when the app receives a memory warning.
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return super.supportedInterfaceOrientations()
}
override func shouldAutorotate() -> Bool {
return super.shouldAutorotate()
}
}
| bda413ccd6ea1859dc5802bb972de655 | 35.742268 | 240 | 0.630752 | false | false | false | false |
johnlui/Swift-MMP | refs/heads/master | Swift-MMP/Common/NowPlayingInfoCenter.swift | mit | 1 | //
// NowPlayingInfoCenter.swift
// Swift-MMP
//
// Created by John Lui on 2017/9/13.
// Copyright © 2017年 John Lui. All rights reserved.
//
import MediaPlayer
class NowPlayingInfoCenter: NSObject {
var mprcPlay, mprcPause, mprcPrevious, mprcNext: MPRemoteCommand!
var musicPlayerVC: PlayerViewController!
func setNowPlayingInfo(_ asset: AVURLAsset) {
var info = [String: AnyObject]()
for i in asset.metadata {
if let key = i.commonKey {
switch key {
case AVMetadataKey.commonKeyArtwork:
info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: UIImage(data: i.value as! Data)!)
case AVMetadataKey.commonKeyArtist:
info[MPMediaItemPropertyArtist] = i.value?.description as AnyObject?
case AVMetadataKey.id3MetadataKeyAlbumTitle:
info[MPMediaItemPropertyAlbumTitle] = i.value?.description as AnyObject?
case AVMetadataKey.commonKeyTitle:
info[MPMediaItemPropertyTitle] = i.value?.description as AnyObject?
default:
break
}
}
}
info[MPMediaItemPropertyPlaybackDuration] = self.musicPlayerVC.streamer.duration as AnyObject?
info[MPNowPlayingInfoPropertyPlaybackRate] = 1 as AnyObject?
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
self.mprcPlay = MPRemoteCommandCenter.shared().playCommand
self.mprcPlay.removeTarget(self)
self.mprcPlay.addTarget (handler: { (event) -> MPRemoteCommandHandlerStatus in
return .success
})
self.mprcPlay.addTarget(self, action: #selector(play(_:)))
self.mprcPause = MPRemoteCommandCenter.shared().pauseCommand
self.mprcPause.removeTarget(self)
self.mprcPause.addTarget (handler: { (event) -> MPRemoteCommandHandlerStatus in
return .success
})
self.mprcPause.addTarget(self, action: #selector(pause(_:)))
self.mprcPrevious = MPRemoteCommandCenter.shared().previousTrackCommand
self.mprcPrevious.removeTarget(self)
self.mprcPrevious.addTarget (handler: { (event) -> MPRemoteCommandHandlerStatus in
return .success
})
self.mprcPrevious.addTarget(self, action: #selector(previous(_:)))
self.mprcNext = MPRemoteCommandCenter.shared().nextTrackCommand
self.mprcNext.removeTarget(self)
self.mprcNext.addTarget (handler: { (event) -> MPRemoteCommandHandlerStatus in
return .success
})
self.mprcNext.addTarget(self, action: #selector(next(_:)))
}
@objc func play(_ event: MPRemoteCommandEvent) {
if self.musicPlayerVC.streamer == nil {
return
}
self.musicPlayerVC.streamer.play()
}
@objc func pause(_ event: MPRemoteCommandEvent) {
if self.musicPlayerVC.streamer == nil {
return
}
self.musicPlayerVC.streamer.pause()
}
@objc func previous(_ event: MPRemoteCommandEvent) {
if self.musicPlayerVC.streamer == nil {
return
}
self.musicPlayerVC.prevButtonBeTapped(self)
}
@objc func next(_ event: MPRemoteCommandEvent) {
if self.musicPlayerVC.streamer == nil {
return
}
self.musicPlayerVC.nextButtonBeTapped(self)
}
}
| 014c84adb11292a03c398579dd79b98a | 36.37234 | 114 | 0.621691 | false | false | false | false |
Takanu/Pelican | refs/heads/master | Sources/Pelican/Session/Modules/API Request/Async/MethodRequestAsync.swift | mit | 1 | //
// MethodRequestAsync.swift
// Pelican
//
// Created by Ido Constantine on 18/03/2018.
//
import Foundation
/**
A delegate for creating and sending TelegramRequest types in a synchronous manner,
where your code execution will continue immediately after the request is made and sent.
Use this if you don't need to handle the response immediately after making the request or don't need to know
the result of a request.
*/
public struct MethodRequestAsync {
public typealias CallbackBoolean = ((Bool) -> ())?
public typealias CallbackString = ((String?) -> ())?
/// The tag of the session that this request instance belongs to.
var tag: SessionTag
public init(tag: SessionTag) {
self.tag = tag
}
/**
Allows you to make a custom request to Telegram, using a method name and set of arguments as a dictionary.
Use this if Pelican hasn't yet implemented a new API method, but also submit an issue [right about here](https://github.com/Takanu/Pelican)
here so I can add it 👌👍.
*/
func customRequest(methodName: String, queries: [String: Codable], file: MessageFile?, callback: ((TelegramResponse?) -> ())? ) {
let request = TelegramRequest()
request.method = methodName
request.query = queries
request.file = file
tag.sendAsyncRequest(request) { response in
if callback != nil {
callback!(response)
}
}
}
}
| bcd5d10bf34deee1d92b7bc739b74cd0 | 26.34 | 140 | 0.712509 | false | false | false | false |
welbesw/easypost-swift | refs/heads/master | Example/EasyPostApi/DefaultsManager.swift | mit | 1 | //
// DefaultsManager.swift
// BigcommerceApi
//
// Created by William Welbes on 7/7/15.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import UIKit
open class DefaultsManager: NSObject {
//Define a shared instance method to return a singleton of the manager
public static var sharedInstance = DefaultsManager()
let userDefaults = UserDefaults.standard
var orderStatusIdFilter: Int? = nil //Allows the user to filter based on a specific order status
var apiToken: String? {
get {
return userDefaults.string(forKey: "ApiToken")
}
set(newValue) {
userDefaults.setValue(newValue, forKey: "ApiToken")
}
}
var apiBaseUrl: String? {
get {
return userDefaults.string(forKey: "ApiBaseUrl")
}
set(newValue) {
userDefaults.setValue(newValue, forKey: "ApiBaseUrl")
}
}
var apiCredentialsAreSet: Bool {
get {
return self.apiToken != nil && self.apiBaseUrl != nil
}
}
}
| 7dd9e1ad7dd5e05e0a34350734e3b9ed | 23.590909 | 100 | 0.603512 | false | false | false | false |
timd/ProiOSTableCollectionViews | refs/heads/master | Ch09/InCellDelegate/InCellTV/ViewController.swift | mit | 1 | //
// ViewController.swift
// InCellTV
//
// Created by Tim on 07/11/15.
// Copyright © 2015 Tim Duckett. All rights reserved.
//
import UIKit
protocol InCellButtonProtocol {
func didTapButtonInCell(cell: ButtonCell)
}
class ViewController: UIViewController, InCellButtonProtocol {
@IBOutlet var tableView: UITableView!
var tableData = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func setupData() {
for index in 0...125 {
tableData.append(index)
}
}
func didTapButtonInCell(cell: ButtonCell) {
let indexPathAtTap = tableView.indexPathForCell(cell)
let alert = UIAlertController(title: "Something happened!", message: "A button was tapped at row \(indexPathAtTap!.row)", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
}
extension ViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as! ButtonCell
cell.textLabel?.text = "Row \(tableData[indexPath.row])"
if cell.delegate == nil {
cell.delegate = self
}
return cell
}
}
| bfbe67734c7b8649619d28e4d14c5e3a | 23.95122 | 153 | 0.644673 | false | false | false | false |
chrisdoc/hubber | refs/heads/master | hubberTests/UserTests.swift | mit | 1 |
import XCTest
@testable import Hubber
class UserTests: XCTestCase {
var userDictionary: [String: Any]!
var usersDictionary: [String: Any]!
override func setUp() {
super.setUp()
userDictionary = [ "login": "chrisdoc", "id": 9047291, "avatar_url": "https://avatars.githubusercontent.com/u/9047291?v=3", "gravatar_id": "", "url": "https://api.github.com/users/chrisdoc"] as [String : Any]
let users = [userDictionary, userDictionary, userDictionary]
usersDictionary = ["items": users]
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testUserDeserializationWithValidData() {
if let user = User.parseUser(userDictionary) {
XCTAssertEqual(user.username, "chrisdoc")
XCTAssertEqual(user.avatar, "https://avatars.githubusercontent.com/u/9047291?v=3")
} else {
XCTFail("could not parse user")
}
}
func testUserDeserializationWithInvalidData() {
XCTAssertNil(User.parseUser(["user": "chrisdoc"]))
}
func testUsersDeserializationWithValidData() {
let users = User.parseUsers(usersDictionary)
XCTAssertEqual(users.count, 3)
XCTAssertEqual(users[2].username, "chrisdoc")
XCTAssertEqual(users[2].avatar, "https://avatars.githubusercontent.com/u/9047291?v=3")
}
func testUsersDeserializationWithInvalidDataReturnsEmptyArray() {
let users = User.parseUsers(["Items":[userDictionary, userDictionary]])
XCTAssertEqual(users.count, 0)
}
}
| 36722fd37b549fbd39ae268a7f36d3ac | 37.382979 | 216 | 0.65133 | false | true | false | false |
airbnb/lottie-ios | refs/heads/master | Tests/ValueProvidersTests.swift | apache-2.0 | 2 | //
// ValueProvidersTests.swift
// LottieTests
//
// Created by Marcelo Fabri on 5/5/22.
//
import Lottie
import XCTest
@MainActor
final class ValueProvidersTests: XCTestCase {
func testGetValue() async throws {
let optionalAnimationView = await SnapshotConfiguration.makeAnimationView(
for: "HamburgerArrow",
configuration: .init(renderingEngine: .mainThread))
let animationView = try XCTUnwrap(optionalAnimationView)
let keypath = AnimationKeypath(keypath: "A1.Shape 1.Stroke 1.Color")
animationView.setValueProvider(ColorValueProvider(.red), keypath: keypath)
let updatedColor = try XCTUnwrap(animationView.getValue(for: keypath, atFrame: 0) as? LottieColor)
XCTAssertEqual(updatedColor, .red)
let originalColor = try XCTUnwrap(animationView.getOriginalValue(for: keypath, atFrame: 0) as? LottieColor)
XCTAssertEqual(originalColor, LottieColor(r: 0.4, g: 0.16, b: 0.7, a: 1))
}
}
| 211c12de74fc0e23cef5447bd88b8bd0 | 30.366667 | 111 | 0.742827 | false | true | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom/ContractInfoInteractor.swift | lgpl-2.1 | 2 | //
// ContractInfoInteractor.swift
// Neocom
//
// Created by Artem Shimanski on 11/12/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
import CloudData
import EVEAPI
class ContractInfoInteractor: TreeInteractor {
typealias Presenter = ContractInfoPresenter
typealias Content = ESI.Result<Value>
weak var presenter: Presenter?
required init(presenter: Presenter) {
self.presenter = presenter
}
struct Value {
var contract: ESI.Contracts.Contract
var bids: [ESI.Contracts.Bid]?
var items: [ESI.Contracts.Item]?
var locations: [Int64: EVELocation]?
var contacts: [Int64: Contact]?
}
var api = Services.api.current
func load(cachePolicy: URLRequest.CachePolicy) -> Future<Content> {
guard let contract = presenter?.view?.input else {return .init(.failure(NCError.invalidInput(type: type(of: self))))}
let progress = Progress(totalUnitCount: 4)
let api = self.api
return Services.sde.performBackgroundTask { context -> Content in
let bids = try? progress.performAsCurrent(withPendingUnitCount: 1) {api.contractBids(contractID: Int64(contract.contractID), cachePolicy: cachePolicy)}.get()
let items = try? progress.performAsCurrent(withPendingUnitCount: 1) {api.contractItems(contractID: Int64(contract.contractID), cachePolicy: cachePolicy)}.get()
let locationIDs = [contract.startLocationID, contract.endLocationID].compactMap {$0}
let contactIDs = ([contract.acceptorID, contract.assigneeID, contract.issuerID] + (bids?.value.map {$0.bidderID} ?? []))
.filter{$0 > 0}
.map{Int64($0)}
let locations = try? progress.performAsCurrent(withPendingUnitCount: 1) {api.locations(with: Set(locationIDs))}.get()
let contacts = try? progress.performAsCurrent(withPendingUnitCount: 1) {api.contacts(with: Set(contactIDs))}.get()
let value = Value(contract: contract,
bids: bids?.value,
items: items?.value,
locations: locations,
contacts: contacts)
let expires = [bids?.expires, items?.expires].compactMap{$0}.min()
return ESI.Result(value: value, expires: expires, metadata: nil)
}
}
private var didChangeAccountObserver: NotificationObserver?
func configure() {
didChangeAccountObserver = NotificationCenter.default.addNotificationObserver(forName: .didChangeAccount, object: nil, queue: .main) { [weak self] _ in
_ = self?.presenter?.reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { presentation in
self?.presenter?.view?.present(presentation, animated: true)
}
}
}
}
| 45133ff876f335d52bbfa39c9571b043 | 37.328358 | 162 | 0.728583 | false | false | false | false |
Rapid-SDK/ios | refs/heads/master | Examples/RapiDO - ToDo list/RapiDO iOS/TaskViewController.swift | mit | 1 | //
// AddTaskViewController.swift
// ExampleApp
//
// Created by Jan on 08/05/2017.
// Copyright © 2017 Rapid. All rights reserved.
//
import UIKit
import Rapid
class TaskViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var titleTextView: TitleTextView!
@IBOutlet weak var descriptionTextView: DescriptionTextView!
@IBOutlet weak var tagsTableView: TagsTableView!
@IBOutlet weak var priorityView: PriorityView!
@IBOutlet weak var actionButton: UIButton! {
didSet {
actionButton.clipsToBounds = true
actionButton.backgroundColor = .appRed
actionButton.setTitleColor(.white, for: .normal)
actionButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
actionButton.layer.cornerRadius = 4
}
}
@IBOutlet weak var completedCheckbox: BEMCheckBox! {
didSet {
completedCheckbox.tintColor = .appSeparator
completedCheckbox.onTintColor = .appRed
completedCheckbox.onCheckColor = .appRed
}
}
@IBOutlet weak var titleTextFieldTop: NSLayoutConstraint!
var task: Task?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerForKeyboardFrameChangeNotifications()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Actions
@IBAction func saveTask(_ sender: Any) {
let title: String
if let text = titleTextView.text, !text.isEmpty {
title = text
}
else {
title = "Task"
}
let description: Any
if let text = descriptionTextView.text, !text.isEmpty {
description = text
}
else {
description = NSNull()
}
let priority = priorityView.priority.rawValue
let tags = tagsTableView.selectedTags.map({$0.rawValue})
// Create task dictionary
let task: [String: Any] = [
Task.titleAttributeName: title,
Task.descriptionAttributeName: description,
Task.createdAttributeName: self.task?.createdAt.isoString ?? Date().isoString,
Task.priorityAttributeName: priority,
Task.tagsAttributeName: tags,
Task.completedAttributeName: completedCheckbox.on
]
if let existingTask = self.task {
// Update an existing task
existingTask.update(withValue: task)
}
else {
// Create a new task
Task.create(withValue: task)
}
dismissController()
}
@objc func cancel(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
func dismissController() {
if navigationController?.viewControllers.first == self {
dismiss(animated: true, completion: nil)
}
else {
navigationController?.popViewController(animated: true)
}
}
@objc func hideKeyboard(_ sender: AnyObject) {
priorityView.collapse()
view.endEditing(true)
}
}
fileprivate extension TaskViewController {
func setupUI() {
navigationItem.largeTitleDisplayMode = .never
descriptionTextView.layer.borderColor = UIColor(red: 0.783922, green: 0.780392, blue: 0.8, alpha: 1).cgColor
descriptionTextView.layer.borderWidth = 0.5
let tap = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboard(_:)))
tap.cancelsTouchesInView = false
scrollView.addGestureRecognizer(tap)
if let task = task {
title = "Edit task"
actionButton.setTitle("Save", for: .normal)
titleTextFieldTop.constant = 102
completedCheckbox.isHidden = false
completedCheckbox.on = task.completed
titleTextView.text = task.title
descriptionTextView.text = task.description
priorityView.setPriority(task.priority)
tagsTableView.selectTags(task.tags)
}
else {
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.cancel(_:)))
navigationItem.leftBarButtonItem = cancelButton
title = "New task"
actionButton.setTitle("Create", for: .normal)
titleTextFieldTop.constant = 20
completedCheckbox.isHidden = true
completedCheckbox.on = false
titleTextView.text = ""
descriptionTextView.text = ""
priorityView.setPriority(Priority.low)
tagsTableView.selectTags([])
}
}
}
// MARK: - Adjust to keyboard
extension TaskViewController: AdjustsToKeyboard {
func animateWithKeyboard(height: CGFloat) {
additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: height, right: 0)
}
}
class PriorityView: UIView, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var titleLabel: UILabel! {
didSet {
titleLabel.textColor = .appPlaceholderText
titleLabel.font = UIFont.systemFont(ofSize: 12)
titleLabel.text = "PRIORITY"
}
}
@IBOutlet weak var valueLabel: UILabel! {
didSet {
valueLabel.textColor = .appText
valueLabel.font = UIFont.systemFont(ofSize: 15)
}
}
@IBOutlet weak var priorityPicker: UIPickerView! {
didSet {
priorityPicker.delegate = self
priorityPicker.dataSource = self
priorityPicker.alpha = 0
priorityPicker.isUserInteractionEnabled = false
}
}
@IBOutlet weak var heightConstraint: NSLayoutConstraint! {
didSet {
heightConstraint.constant = 60
}
}
fileprivate(set) var priority: Priority = .low
fileprivate var selected: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
func setPriority(_ priority: Priority) {
self.priority = priority
priorityPicker.selectRow(priority.rawValue, inComponent: 0, animated: false)
valueLabel.text = priority.title
}
fileprivate func setupUI() {
clipsToBounds = true
isUserInteractionEnabled = true
layer.borderColor = UIColor.appSeparator.cgColor
layer.borderWidth = 1
layer.cornerRadius = 4
let tap = UITapGestureRecognizer(target: self, action: #selector(self.didTap(_:)))
tap.cancelsTouchesInView = false
addGestureRecognizer(tap)
}
func collapse() {
selected = false
animateChange()
}
@objc func didTap(_ sender: Any) {
selected = !selected
animateChange()
}
func animateChange() {
isUserInteractionEnabled = false
superview?.layoutIfNeeded()
UIView.animate(withDuration: 0.3, animations: {
self.heightConstraint.constant = self.selected ? 120 : 60
self.valueLabel.alpha = self.selected ? 0 : 1
self.priorityPicker.alpha = self.selected ? 1 : 0
self.superview?.layoutIfNeeded()
}) { _ in
self.isUserInteractionEnabled = true
self.priorityPicker.isUserInteractionEnabled = self.selected
}
}
// MARK: Picker
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Priority.allValues.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Priority.allValues[row].title
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
priority = Priority.allValues[row]
valueLabel.text = priority.title
}
}
class TextView: UIView, UITextViewDelegate {
@IBOutlet weak var titleLabel: UILabel! {
didSet {
titleLabel.textColor = .appPlaceholderText
titleLabel.font = UIFont.systemFont(ofSize: 12)
}
}
@IBOutlet private weak var textView: UITextView! {
didSet {
textView.textColor = .appText
textView.font = UIFont.systemFont(ofSize: 15)
textView.tintColor = .appRed
textView.isScrollEnabled = false
textView.delegate = self
}
}
@IBOutlet weak var heightConstraint: NSLayoutConstraint! {
didSet {
heightConstraint.constant = 51
}
}
@IBOutlet weak var titleTopConstraint: NSLayoutConstraint!
var text: String! {
get {
return textView.text
}
set {
textView.text = newValue
updateHeight(collapse: !textView.isFirstResponder)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
func updateHeight(collapse: Bool) {
superview?.layoutIfNeeded()
let height: CGFloat
if collapse && textView.text?.isEmpty ?? true {
height = 50
}
else {
let textViewSize = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
height = textViewSize.height + 30
}
guard height != frame.height else {
return
}
UIView.animate(withDuration: 0.3, animations: {
self.heightConstraint.constant = height
self.titleTopConstraint.constant = height <= 50 ? 18 : 9
self.superview?.layoutIfNeeded()
})
}
fileprivate func setupUI() {
clipsToBounds = true
isUserInteractionEnabled = true
layer.borderColor = UIColor.appSeparator.cgColor
layer.borderWidth = 1
layer.cornerRadius = 4
let tap = UITapGestureRecognizer(target: self, action: #selector(self.didTap(_:)))
tap.cancelsTouchesInView = false
addGestureRecognizer(tap)
}
@objc func didTap(_ sender: Any) {
if textView.isFirstResponder {
textView.resignFirstResponder()
}
else {
textView.becomeFirstResponder()
}
}
// MARK: Text view delegate
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.text.isEmpty {
updateHeight(collapse: false)
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
updateHeight(collapse: true)
}
}
func textViewDidChange(_ textView: UITextView) {
updateHeight(collapse: false)
}
}
class TitleTextView: TextView {
override weak var titleLabel: UILabel! {
didSet {
titleLabel.text = "TITLE"
}
}
}
class DescriptionTextView: TextView {
override weak var titleLabel: UILabel! {
didSet {
titleLabel.text = "DESCRIPTION"
}
}
}
| 316b3d2107b96306592f40bec3ed953b | 27.804878 | 135 | 0.591025 | false | false | false | false |
bvankuik/Spinner | refs/heads/master | Spinner/VIToastView.swift | mit | 1 | //
// VIToastView.swift
// Spinner
//
// Created by Bart van Kuik on 29/05/2017.
// Copyright © 2017 DutchVirtual. All rights reserved.
//
public class VIToastView: VIStatusBaseView {
static let shared = VIToastView()
private let label = UILabel()
private var constraintsInstalled = false
private let minimumHeight: CGFloat = 50.0
private let minimumWidth: CGFloat = 150.0
private let margin: CGFloat = 20.0
// MARK: - Public functions
public static func show(text: String, in containingView: UIView) {
let toastView = VIToastView.shared
toastView.label.text = text
VIStatusBaseView.showBaseView(baseView: toastView, in: containingView)
}
// MARK: - Layout
override public func layoutSubviews() {
if !self.constraintsInstalled {
self.constraintsInstalled = true
let constraints = [
self.label.centerYAnchor.constraint(equalTo: self.centerYAnchor),
self.widthAnchor.constraint(greaterThanOrEqualToConstant: self.minimumWidth),
self.heightAnchor.constraint(greaterThanOrEqualToConstant: self.minimumHeight),
self.label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: self.margin),
self.label.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -self.margin),
self.heightAnchor.constraint(greaterThanOrEqualTo: self.label.heightAnchor, multiplier: 1.0, constant: self.margin)
]
self.addConstraints(constraints)
}
super.layoutSubviews()
}
// MARK: - Life cycle
override init(frame: CGRect) {
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.white
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
super.init(frame: frame)
self.addSubview(label)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("Unsupported")
}
}
| 85195d789552cf3e7d1909310cfb796f | 31.328125 | 131 | 0.665539 | false | false | false | false |
koehlermichael/focus | refs/heads/master | Blockzilla/SearchEngine.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 Foundation
class SearchEngine {
private lazy var template: String = {
let enginesPath = Bundle.main.path(forResource: "SearchEngines", ofType: "plist")!
let engines = NSDictionary(contentsOfFile: enginesPath) as! [String: String]
var components = Locale.preferredLanguages.first!.components(separatedBy: "-")
if components.count == 3 {
components.remove(at: 1)
}
return engines[components.joined(separator: "-")] ?? engines[components[0]] ?? engines["default"]!
}()
func urlForQuery(_ query: String) -> URL? {
guard let escaped = query.addingPercentEncoding(withAllowedCharacters: .urlQueryParameterAllowed),
let url = URL(string: template.replacingOccurrences(of: "{searchTerms}", with: escaped)) else {
assertionFailure("Invalid search URL")
return nil
}
return url
}
}
| 48894be5840da6aedcafe9c07bc1acf1 | 37.896552 | 109 | 0.652482 | false | false | false | false |
Jamol/Nutil | refs/heads/master | Sources/http/v2/Http2Response.swift | mit | 1 | //
// Http2Response.swift
// Nutil
//
// Created by Jamol Bao on 12/25/16.
// Copyright © 2016 Jamol Bao. All rights reserved.
// Contact: [email protected]
//
import Foundation
let kColon = UInt8(ascii: ":")
class Http2Response : HttpHeader, HttpResponse {
fileprivate var stream: H2Stream?
fileprivate var bodyBytesSent = 0
fileprivate var reqHeaders: [String: String] = [:]
fileprivate var reqMethod = ""
fileprivate var reqPath = ""
fileprivate var version = "HTTP/2.0"
fileprivate var cbData: DataCallback?
fileprivate var cbHeader: EventCallback?
fileprivate var cbRequest: EventCallback?
fileprivate var cbComplete: EventCallback?
fileprivate var cbError: ErrorCallback?
fileprivate var cbSend: EventCallback?
enum State: Int, Comparable {
case idle
case receivingRequest
case waitForResponse
case sendingHeader
case sendingBody
case completed
case error
case closed
}
fileprivate var state = State.idle
fileprivate func setState(_ state: State) {
self.state = state
}
fileprivate func cleanup() {
if let stream = self.stream {
stream.close()
self.stream = nil
}
}
func setSslFlags(_ flags: UInt32) {
}
func attachFd(_ fd: SOCKET_FD, _ initData: UnsafeRawPointer?, _ initSize: Int) -> KMError {
return .unsupport
}
func attachStream(_ conn: H2Connection, _ streamId: UInt32) -> KMError {
stream = conn.getStream(streamId)
if stream == nil {
return .invalidParam
}
stream!.onHeaders(onHeaders)
.onData(onData)
.onRSTStream(onRSTStream)
.onWrite(onWrite)
return .noError
}
override func addHeader(_ name: String, _ value: String) {
if name.caseInsensitiveCompare(kTransferEncoding) == .orderedSame
&& value.caseInsensitiveCompare("chunked") == .orderedSame {
isChunked = true
return
}
super.addHeader(name, value)
}
func sendResponse(_ statusCode: Int, _ desc: String?) -> KMError {
infoTrace("sendResponse, statusCode=\(statusCode)")
guard let stream = self.stream else {
return .invalidState
}
setState(.sendingHeader)
let hdrInfo = buildHeaders(statusCode)
let endStream = contentLength != nil && contentLength! == 0
let ret = stream.sendHeaders(hdrInfo.headers, hdrInfo.size, endStream)
if ret == .noError {
if (endStream) {
setState(.completed)
notifyComplete()
} else {
setState(.sendingBody)
onWrite() // should queue in event loop rather than call onWrite directly?
}
}
return ret
}
func sendData(_ data: UnsafeRawPointer?, _ len: Int) -> Int {
if state != .sendingBody {
return 0
}
guard let stream = self.stream else {
return 0
}
var ret = 0
if let dbuf = data, len > 0 {
var slen = len
if let clen = contentLength {
if bodyBytesSent + slen > clen {
slen = clen - bodyBytesSent
}
}
ret = stream.sendData(dbuf, slen, false)
if (ret > 0) {
bodyBytesSent += ret
}
}
let endStream = (data == nil) || (contentLength != nil && bodyBytesSent >= contentLength!)
if endStream {
_ = stream.sendData(nil, 0, true)
setState(.completed)
notifyComplete()
}
return ret
}
func sendString(_ str: String) -> Int {
return sendData(UnsafePointer<UInt8>(str), str.utf8.count)
}
fileprivate func checkHeaders() {
}
fileprivate func buildHeaders(_ statusCode: Int) -> (headers: NameValueArray, size: Int) {
processHeader(statusCode)
var hdrSize = 0
var hdrList: [KeyValuePair] = []
let strCode = "\(statusCode)"
hdrList.append((kH2HeaderStatus, strCode))
hdrSize += kH2HeaderStatus.utf8.count + strCode.utf8.count
for hdr in headers {
hdrList.append((hdr.key, hdr.value))
hdrSize += hdr.key.utf8.count + hdr.value.utf8.count
}
return (hdrList, hdrSize)
}
fileprivate func onHeaders(headers: NameValueArray, endStream: Bool) {
if headers.isEmpty {
return
}
var cookie = ""
for kv in headers {
if kv.name.isEmpty {
continue
}
if UInt8(kv.name.utf8CString[0]) == kColon { // pseudo header
if kv.name.compare(kH2HeaderMethod) == .orderedSame {
reqMethod = kv.value
} else if kv.name.compare(kH2HeaderAuthority) == .orderedSame {
super.headers["host"] = kv.value
} else if kv.name.compare(kH2HeaderPath) == .orderedSame {
reqPath = kv.value
}
} else if kv.name.compare(kH2HeaderCookie) == .orderedSame {
if !cookie.isEmpty {
cookie += "; "
}
cookie += kv.value
} else {
super.headers[kv.name] = kv.value
}
}
if !cookie.isEmpty {
super.headers["Cookie"] = cookie
}
cbHeader?()
if endStream {
setState(.waitForResponse)
cbRequest?()
}
}
fileprivate func onData(data: UnsafeMutableRawPointer?, len: Int, endStream: Bool) {
if let d = data, len > 0 {
cbData?(d, len)
}
if endStream {
setState(.waitForResponse)
cbRequest?()
}
}
fileprivate func onRSTStream(err: Int) {
onError(.failed)
}
fileprivate func onWrite() {
cbSend?()
}
fileprivate func onError(_ err: KMError) {
cbError?(err)
}
fileprivate func notifyComplete() {
cbComplete?()
}
override func reset() {
super.reset()
}
func close() {
infoTrace("Http2Response.close")
cleanup()
setState(.closed)
}
}
extension Http2Response {
@discardableResult func onData(_ cb: @escaping (UnsafeMutableRawPointer, Int) -> Void) -> Self {
cbData = cb
return self
}
@discardableResult func onHeaderComplete(_ cb: @escaping () -> Void) -> Self {
cbHeader = cb
return self
}
@discardableResult func onRequestComplete(_ cb: @escaping () -> Void) -> Self {
cbRequest = cb
return self
}
@discardableResult func onResponseComplete(_ cb: @escaping () -> Void) -> Self {
cbComplete = cb
return self
}
@discardableResult func onError(_ cb: @escaping (KMError) -> Void) -> Self {
cbError = cb
return self
}
@discardableResult func onSend(_ cb: @escaping () -> Void) -> Self {
cbSend = cb
return self
}
func getMethod() -> String {
return reqMethod
}
func getPath() -> String {
return reqPath
}
func getVersion() -> String {
return version
}
func getHeader(_ name: String) -> String? {
return reqHeaders[name]
}
func getParam(_ name: String) -> String? {
return nil
}
}
| d9a330a04d079880b0f6e55f5e92645c | 26.614286 | 100 | 0.53492 | false | false | false | false |
masahiko24/CRToastSwift | refs/heads/master | CRToastSwift/UserInteraction.swift | mit | 2 | //
// UserInteraction.swift
// CRToastSwift
//
// Copyright (c) 2015 Masahiko Tsujita <[email protected]>
//
// 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 CRToast
/// Represents an user interaction
public struct UserInteraction: OptionSetType {
public typealias RawValue = CRToastInteractionType.RawValue
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
public let rawValue: RawValue
public static let Tap = UserInteraction(rawValue: CRToastInteractionType.TapOnce.rawValue)
public static let DoubleTap = UserInteraction(rawValue: CRToastInteractionType.TapTwice.rawValue)
public static let TwoFingerTap = UserInteraction(rawValue: CRToastInteractionType.TwoFingerTapOnce.rawValue)
public static let TwoFingerDoubleTap = UserInteraction(rawValue: CRToastInteractionType.TwoFingerTapTwice.rawValue)
public static let SwipeUp = UserInteraction(rawValue: CRToastInteractionType.SwipeUp.rawValue)
public static let SwipeLeft = UserInteraction(rawValue: CRToastInteractionType.SwipeLeft.rawValue)
public static let SwipeDown = UserInteraction(rawValue: CRToastInteractionType.SwipeDown.rawValue)
public static let SwipeRight = UserInteraction(rawValue: CRToastInteractionType.SwipeRight.rawValue)
public static let AnyTap = UserInteraction(rawValue: CRToastInteractionType.Tap.rawValue)
public static let AnySwipe = UserInteraction(rawValue: CRToastInteractionType.Swipe.rawValue)
public static let Any = UserInteraction(rawValue: CRToastInteractionType.All.rawValue)
}
| 09ed39aaf0d26b4cf93eca65552f42f1 | 51.566038 | 122 | 0.737258 | false | false | false | false |
recruit-lifestyle/Sidebox | refs/heads/master | Pod/Classes/View/SBIconView.swift | mit | 1 | //
// SBIconView.swift
// Pods
//
// Created by Nonchalant on 2015/07/31.
// Copyright (c) 2015 Nonchalant. All rights reserved.
//
import UIKit
class SBIconView: SBRootView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(frame: CGRect, data: SBDataObject) {
super.init(frame: frame)
let iv = UIImageView(image: data.icon)
iv.frame = CGRectMake(7.5, 7.5, 45.0, 45.0)
self.addSubview(iv)
let tapGesture = UITapGestureRecognizer(target: self, action: "tapped:")
tapGesture.delegate = self
self.addGestureRecognizer(tapGesture)
}
// MARK: UIGestureMethod
override final func panDragEnd() {
if (self.frame.origin.x + absOrigin!.x + self.frame.size.width < 0.0) {
if let id = obj.id { SBDataModel.sharedInstance.sbDataRemove(id) }
}
}
// MARK: UIGestureRecognizer
final func tapped(sender: UITapGestureRecognizer) {
NSNotificationCenter.defaultCenter().postNotificationName("sbTap", object: nil, userInfo: ["Object": obj])
}
// MARK: - TouchAction
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.backgroundColor = .lightGrayColor()
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
self.backgroundColor = .clearColor()
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
self.backgroundColor = .clearColor()
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
self.backgroundColor = .clearColor()
}
}
| 6b3ae718d8f69dc1a8dee5636914b072 | 27.796875 | 114 | 0.629409 | false | false | false | false |
Ferrari-lee/firefox-ios | refs/heads/autocomplete-highlight | Account/HawkHelper.swift | mpl-2.0 | 33 | /* 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 FxA
import Shared
public class HawkHelper {
private let NonceLengthInBytes: UInt = 8
let id: String
let key: NSData
public init(id: String, key: NSData) {
self.id = id
self.key = key
}
// Produce a HAWK value suitable for an "Authorization: value" header, timestamped now.
public func getAuthorizationValueFor(request: NSURLRequest) -> String {
let timestampInSeconds: Int64 = Int64(NSDate().timeIntervalSince1970)
return getAuthorizationValueFor(request, at: timestampInSeconds)
}
// Produce a HAWK value suitable for an "Authorization: value" header.
func getAuthorizationValueFor(request: NSURLRequest, at timestampInSeconds: Int64) -> String {
let nonce = NSData.randomOfLength(NonceLengthInBytes)!.base64EncodedString
let extra = ""
return getAuthorizationValueFor(request, at: timestampInSeconds, nonce: nonce, extra: extra)
}
func getAuthorizationValueFor(request: NSURLRequest, at timestampInSeconds: Int64, nonce: String, extra: String) -> String {
let timestampString = String(timestampInSeconds)
let hashString = HawkHelper.getPayloadHashFor(request)
let requestString = HawkHelper.getRequestStringFor(request, timestampString: timestampString, nonce: nonce, hash: hashString, extra: extra)
let macString = HawkHelper.getSignatureFor(requestString.utf8EncodedData!, key: self.key)
let s = NSMutableString(string: "Hawk ")
func append(key: String, value: String) -> Void {
s.appendString(key)
s.appendString("=\"")
s.appendString(value)
s.appendString("\", ")
}
append("id", value: id)
append("ts", value: timestampString)
append("nonce", value: nonce)
if !hashString.isEmpty {
append("hash", value: hashString)
}
if !extra.isEmpty {
append("ext", value: HawkHelper.escapeExtraHeaderAttribute(extra))
}
append("mac", value: macString)
// Drop the trailing "\",".
return s.substringToIndex(s.length - 2)
}
class func getSignatureFor(input: NSData, key: NSData) -> String {
return input.hmacSha256WithKey(key).base64EncodedString
}
class func getRequestStringFor(request: NSURLRequest, timestampString: String, nonce: String, hash: String, extra: String) -> String {
let s = NSMutableString(string: "hawk.1.header\n")
func append(line: String) -> Void {
s.appendString(line)
s.appendString("\n")
}
append(timestampString)
append(nonce)
append(request.HTTPMethod?.uppercaseString ?? "GET")
let url = request.URL!
s.appendString(url.path!)
if let query = url.query {
s.appendString("?")
s.appendString(query)
}
if let fragment = url.fragment {
s.appendString("#")
s.appendString(fragment)
}
s.appendString("\n")
append(url.host!)
if let port = url.port {
append(port.stringValue)
} else {
if url.scheme.lowercaseString == "https" {
append("443")
} else {
append("80")
}
}
append(hash)
if !extra.isEmpty {
append(HawkHelper.escapeExtraString(extra))
} else {
append("")
}
return s as String
}
class func getPayloadHashFor(request: NSURLRequest) -> String {
if let body = request.HTTPBody {
let d = NSMutableData()
func append(s: String) {
let data = s.utf8EncodedData!
d.appendBytes(data.bytes, length: data.length)
}
append("hawk.1.payload\n")
append(getBaseContentTypeFor(request.valueForHTTPHeaderField("Content-Type")))
append("\n") // Trailing newline is specified by Hawk.
d.appendBytes(body.bytes, length: body.length)
append("\n") // Trailing newline is specified by Hawk.
return d.sha256.base64EncodedString
} else {
return ""
}
}
class func getBaseContentTypeFor(contentType: String?) -> String {
if let contentType = contentType {
if let index = contentType.characters.indexOf(";") {
return contentType.substringToIndex(index).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
} else {
return contentType.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
} else {
return "text/plain"
}
}
class func escapeExtraHeaderAttribute(extra: String) -> String {
return extra.stringByReplacingOccurrencesOfString("\\", withString: "\\\\").stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
}
class func escapeExtraString(extra: String) -> String {
return extra.stringByReplacingOccurrencesOfString("\\", withString: "\\\\").stringByReplacingOccurrencesOfString("\n", withString: "\\n")
}
}
| 7e791f03138a5da46dd0969d9d98d96b | 37.714286 | 147 | 0.616974 | false | false | false | false |
linchanlau/Swift-PM25 | refs/heads/master | PM25/ViewController.swift | mit | 3 | //
// ViewController.swift
// PM25
//
// Created by scott on 14-6-7.
// Copyright (c) 2014年 scott. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
let indexSet = ["A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","W","X","Y","Z"]
let dataSet = [
["鞍山","安阳"],
["保定","宝鸡","包头","北海","北京","本溪","滨州"],
["沧州","长春","常德","长沙","常熟","长治","常州","潮州","承德","成都","赤峰","重庆"],
["大连","丹东","大庆","大同","德阳","德州","东莞","东营"],
["鄂尔多斯"],
["佛山","抚顺","富阳","福州"],
["广州","桂林","贵阳"],
["哈尔滨","海口","海门","邯郸","杭州","合肥","衡水","河源","菏泽","淮安","呼和浩特","惠州","葫芦岛","湖州"],
["江门","江阴","胶南","胶州","焦作","嘉兴","嘉峪关","揭阳","吉林","即墨","济南","金昌","荆州","金华","济宁","金坛","锦州","九江","句容"],
["开封","克拉玛依","库尔勒","昆明","昆山"],
["莱芜","莱西","莱州","廊坊","兰州","拉萨","连云港","聊城","临安","临汾","临沂","丽水","柳州","溧阳","洛阳","泸州"],
["马鞍山","茂名","梅州","绵阳","牡丹江"],
["南昌","南充","南京","南宁","南通","宁波"],
["盘锦","攀枝花","蓬莱","平顶山","平度"],
["青岛","清远","秦皇岛","齐齐哈尔","泉州","曲靖","衢州"],
["日照","荣成","乳山"],
["三门峡","三亚","上海","汕头","汕尾","韶关","绍兴","沈阳","深圳","石家庄","石嘴山","寿光","宿迁","苏州"],
["泰安","太仓","太原","台州","泰州","唐山","天津","铜川"],
["瓦房店","潍坊","威海","渭南","文登","温州","武汉","芜湖","吴江","乌鲁木齐","无锡"],
["厦门","西安","湘潭","咸阳","邢台","西宁","徐州"],
["延安","盐城","阳江","阳泉","扬州","烟台","宜宾","宜昌","银川","营口","义乌","宜兴","岳阳","云浮","玉溪"],
["枣庄","张家港","张家界","张家口","章丘","湛江","肇庆","招远","郑州","镇江","中山","舟山","珠海","诸暨","株洲","淄博","自贡","遵义"]
]
override func viewDidLoad() {
super.viewDidLoad()
//设置导航栏名称
//self.navigationItem.title="全国主要城市PM2.5"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//导航栏关于按钮
@IBAction func about(sender : AnyObject) {
SCLAlertView().showInfo(self,title: "关于", subTitle: "该应用数据来源于pm25.in。仅供学习交流,请勿用于商业用途!\nQQ:184675420")
}
// #pragma mark - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return indexSet.count
}
// #pragma mark - UITableViewDataSource
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]!{
return indexSet
}
// #pragma mark - UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return dataSet[section].count
}
// #pragma mark - UITableViewDataSource
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String{
return indexSet[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let reuseIdentifier = "Cell"
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as UITableViewCell
// if cell == nil {
// cell = UITableViewCell(style:.Default,reuseIdentifier:reuseIdentifier)
// }
cell.textLabel!.text = dataSet[indexPath.section][indexPath.row]
return cell
}
// #pragma mark - UITableViewDelegate
// override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
//
// 显示DetailsViewController
//
// let detailsViewController:DetailsViewController = DetailsViewController()
//
// detailsViewController.city = tableData[indexPath.row] as String
//
// self.navigationController.pushViewController(detailsViewController, animated: true)
//
// }
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){
if segue.identifier == "Detail" {
if segue.destinationViewController is DetailsViewController {
var detailsViewController:DetailsViewController = segue.destinationViewController as DetailsViewController
var index = self.tableView.indexPathForSelectedRow()
detailsViewController.city = dataSet[index!.section][index!.row] as String
}
}
}
}
| 170f3839d2737f682c628902596f36e0 | 32.075188 | 122 | 0.535122 | false | false | false | false |
dvor/Antidote | refs/heads/master | Antidote/AppCoordinator.swift | mit | 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 AppCoordinator {
fileprivate let window: UIWindow
fileprivate var activeCoordinator: TopCoordinatorProtocol!
fileprivate var theme: Theme
init(window: UIWindow) {
self.window = window
let filepath = Bundle.main.path(forResource: "default-theme", ofType: "yaml")!
let yamlString = try! NSString(contentsOfFile:filepath, encoding:String.Encoding.utf8.rawValue) as String
theme = try! Theme(yamlString: yamlString)
applyTheme(theme)
}
}
// MARK: CoordinatorProtocol
extension AppCoordinator: TopCoordinatorProtocol {
func startWithOptions(_ options: CoordinatorOptions?) {
let storyboard = UIStoryboard(name: "LaunchPlaceholderBoard", bundle: Bundle.main)
window.rootViewController = storyboard.instantiateViewController(withIdentifier: "LaunchPlaceholderController")
recreateActiveCoordinator(options: options)
}
func handleLocalNotification(_ notification: UILocalNotification) {
activeCoordinator.handleLocalNotification(notification)
}
func handleInboxURL(_ url: URL) {
activeCoordinator.handleInboxURL(url)
}
}
extension AppCoordinator: RunningCoordinatorDelegate {
func runningCoordinatorDidLogout(_ coordinator: RunningCoordinator, importToxProfileFromURL: URL?) {
KeychainManager().deleteActiveAccountData()
recreateActiveCoordinator()
if let url = importToxProfileFromURL,
let coordinator = activeCoordinator as? LoginCoordinator {
coordinator.handleInboxURL(url)
}
}
func runningCoordinatorDeleteProfile(_ coordinator: RunningCoordinator) {
let userDefaults = UserDefaultsManager()
let profileManager = ProfileManager()
let name = userDefaults.lastActiveProfile!
do {
try profileManager.deleteProfileWithName(name)
KeychainManager().deleteActiveAccountData()
userDefaults.lastActiveProfile = nil
recreateActiveCoordinator()
}
catch let error as NSError {
handleErrorWithType(.deleteProfile, error: error)
}
}
func runningCoordinatorRecreateCoordinatorsStack(_ coordinator: RunningCoordinator, options: CoordinatorOptions) {
recreateActiveCoordinator(options: options, skipAuthorizationChallenge: true)
}
}
extension AppCoordinator: LoginCoordinatorDelegate {
func loginCoordinatorDidLogin(_ coordinator: LoginCoordinator, manager: OCTManager, password: String) {
KeychainManager().toxPasswordForActiveAccount = password
recreateActiveCoordinator(manager: manager, skipAuthorizationChallenge: true)
}
}
// MARK: Private
private extension AppCoordinator {
func applyTheme(_ theme: Theme) {
let linkTextColor = theme.colorForType(.LinkText)
UIButton.appearance().tintColor = linkTextColor
UISwitch.appearance().onTintColor = linkTextColor
UINavigationBar.appearance().tintColor = linkTextColor
}
func recreateActiveCoordinator(options: CoordinatorOptions? = nil,
manager: OCTManager? = nil,
skipAuthorizationChallenge: Bool = false) {
if let password = KeychainManager().toxPasswordForActiveAccount {
let successBlock: (OCTManager) -> Void = { [unowned self] manager -> Void in
self.activeCoordinator = self.createRunningCoordinatorWithManager(manager,
options: options,
skipAuthorizationChallenge: skipAuthorizationChallenge)
}
if let manager = manager {
successBlock(manager)
}
else {
let deleteActiveAccountAndRetry: (Void) -> Void = { [unowned self] in
KeychainManager().deleteActiveAccountData()
self.recreateActiveCoordinator(options: options,
manager: manager,
skipAuthorizationChallenge: skipAuthorizationChallenge)
}
guard let profileName = UserDefaultsManager().lastActiveProfile else {
deleteActiveAccountAndRetry()
return
}
let path = ProfileManager().pathForProfileWithName(profileName)
guard let configuration = OCTManagerConfiguration.configurationWithBaseDirectory(path) else {
deleteActiveAccountAndRetry()
return
}
ToxFactory.createToxWithConfiguration(configuration,
encryptPassword: password,
successBlock: successBlock,
failureBlock: { _ in
log("Cannot create tox with configuration \(configuration)")
deleteActiveAccountAndRetry()
})
}
}
else {
activeCoordinator = createLoginCoordinator(options)
}
}
func createRunningCoordinatorWithManager(_ manager: OCTManager,
options: CoordinatorOptions?,
skipAuthorizationChallenge: Bool) -> RunningCoordinator {
let coordinator = RunningCoordinator(theme: theme,
window: window,
toxManager: manager,
skipAuthorizationChallenge: skipAuthorizationChallenge)
coordinator.delegate = self
coordinator.startWithOptions(options)
return coordinator
}
func createLoginCoordinator(_ options: CoordinatorOptions?) -> LoginCoordinator {
let coordinator = LoginCoordinator(theme: theme, window: window)
coordinator.delegate = self
coordinator.startWithOptions(options)
return coordinator
}
}
| 1f15e3af5da6cad20f81521158bfa150 | 38.595092 | 137 | 0.609544 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.